Upstream changes for NetworkQualityProvider
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blob7c83d6c0e4905799b15bba24d582807e6c2f61ea
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/metrics/histogram_macros.h"
73 #include "base/single_thread_task_runner.h"
74 #include "base/stl_util.h"
75 #include "base/strings/string_number_conversions.h"
76 #include "base/strings/string_util.h"
77 #include "base/strings/stringprintf.h"
78 #include "base/thread_task_runner_handle.h"
79 #include "base/threading/thread_restrictions.h"
80 #include "base/values.h"
81 #include "crypto/ec_private_key.h"
82 #include "crypto/nss_util.h"
83 #include "crypto/nss_util_internal.h"
84 #include "crypto/rsa_private_key.h"
85 #include "crypto/scoped_nss_types.h"
86 #include "net/base/address_list.h"
87 #include "net/base/dns_util.h"
88 #include "net/base/io_buffer.h"
89 #include "net/base/net_errors.h"
90 #include "net/cert/asn1_util.h"
91 #include "net/cert/cert_policy_enforcer.h"
92 #include "net/cert/cert_status_flags.h"
93 #include "net/cert/cert_verifier.h"
94 #include "net/cert/ct_ev_whitelist.h"
95 #include "net/cert/ct_verifier.h"
96 #include "net/cert/ct_verify_result.h"
97 #include "net/cert/scoped_nss_types.h"
98 #include "net/cert/sct_status_flags.h"
99 #include "net/cert/x509_certificate_net_log_param.h"
100 #include "net/cert/x509_util.h"
101 #include "net/cert_net/nss_ocsp.h"
102 #include "net/http/transport_security_state.h"
103 #include "net/log/net_log.h"
104 #include "net/socket/client_socket_handle.h"
105 #include "net/socket/nss_ssl_util.h"
106 #include "net/ssl/ssl_cert_request_info.h"
107 #include "net/ssl/ssl_cipher_suite_names.h"
108 #include "net/ssl/ssl_connection_status_flags.h"
109 #include "net/ssl/ssl_failure_state.h"
110 #include "net/ssl/ssl_info.h"
112 #if defined(USE_NSS_CERTS)
113 #include <dlfcn.h>
114 #endif
116 namespace net {
118 // State machines are easier to debug if you log state transitions.
119 // Enable these if you want to see what's going on.
120 #if 1
121 #define EnterFunction(x)
122 #define LeaveFunction(x)
123 #define GotoState(s) next_handshake_state_ = s
124 #else
125 #define EnterFunction(x)\
126 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
127 << "; next_handshake_state " << next_handshake_state_
128 #define LeaveFunction(x)\
129 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
130 << "; next_handshake_state " << next_handshake_state_
131 #define GotoState(s)\
132 do {\
133 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
134 next_handshake_state_ = s;\
135 } while (0)
136 #endif
138 #if !defined(CKM_AES_GCM)
139 #define CKM_AES_GCM 0x00001087
140 #endif
142 #if !defined(CKM_NSS_CHACHA20_POLY1305)
143 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
144 #endif
146 namespace {
148 // SSL plaintext fragments are shorter than 16KB. Although the record layer
149 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
150 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
151 // entire SSL record.
152 const int kRecvBufferSize = 17 * 1024;
153 const int kSendBufferSize = 17 * 1024;
155 // Used by SSLClientSocketNSS::Core to indicate there is no read result
156 // obtained by a previous operation waiting to be returned to the caller.
157 // This constant can be any non-negative/non-zero value (eg: it does not
158 // overlap with any value of the net::Error range, including net::OK).
159 const int kNoPendingReadResult = 1;
161 // Helper functions to make it possible to log events from within the
162 // SSLClientSocketNSS::Core.
163 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
164 NetLog::EventType event_type) {
165 if (!net_log)
166 return;
167 net_log->AddEvent(event_type);
170 // Helper function to make it possible to log events from within the
171 // SSLClientSocketNSS::Core.
172 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
173 NetLog::EventType event_type,
174 const NetLog::ParametersCallback& callback) {
175 if (!net_log)
176 return;
177 net_log->AddEvent(event_type, callback);
180 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
181 // from within the SSLClientSocketNSS::Core.
182 // AddByteTransferEvent expects to receive a const char*, which within the
183 // Core is backed by an IOBuffer. If the "const char*" is bound via
184 // base::Bind and posted to another thread, and the IOBuffer that backs that
185 // pointer then goes out of scope on the origin thread, this would result in
186 // an invalid read of a stale pointer.
187 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
188 // to the owning IOBuffer can be bound to the Callback. This ensures that the
189 // IOBuffer will stay alive long enough to cross threads if needed.
190 void LogByteTransferEvent(
191 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
192 int len, IOBuffer* buffer) {
193 if (!net_log)
194 return;
195 net_log->AddByteTransferEvent(event_type, len, buffer->data());
198 // PeerCertificateChain is a helper object which extracts the certificate
199 // chain, as given by the server, from an NSS socket and performs the needed
200 // resource management. The first element of the chain is the leaf certificate
201 // and the other elements are in the order given by the server.
202 class PeerCertificateChain {
203 public:
204 PeerCertificateChain() {}
205 PeerCertificateChain(const PeerCertificateChain& other);
206 ~PeerCertificateChain();
207 PeerCertificateChain& operator=(const PeerCertificateChain& other);
209 // Resets the current chain, freeing any resources, and updates the current
210 // chain to be a copy of the chain stored in |nss_fd|.
211 // If |nss_fd| is NULL, then the current certificate chain will be freed.
212 void Reset(PRFileDesc* nss_fd);
214 // Returns the current certificate chain as a vector of DER-encoded
215 // base::StringPieces. The returned vector remains valid until Reset is
216 // called.
217 std::vector<base::StringPiece> AsStringPieceVector() const;
219 bool empty() const { return certs_.empty(); }
221 CERTCertificate* operator[](size_t index) const {
222 DCHECK_LT(index, certs_.size());
223 return certs_[index];
226 private:
227 std::vector<CERTCertificate*> certs_;
230 PeerCertificateChain::PeerCertificateChain(
231 const PeerCertificateChain& other) {
232 *this = other;
235 PeerCertificateChain::~PeerCertificateChain() {
236 Reset(NULL);
239 PeerCertificateChain& PeerCertificateChain::operator=(
240 const PeerCertificateChain& other) {
241 if (this == &other)
242 return *this;
244 Reset(NULL);
245 certs_.reserve(other.certs_.size());
246 for (size_t i = 0; i < other.certs_.size(); ++i)
247 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
249 return *this;
252 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
253 for (size_t i = 0; i < certs_.size(); ++i)
254 CERT_DestroyCertificate(certs_[i]);
255 certs_.clear();
257 if (nss_fd == NULL)
258 return;
260 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
261 // The handshake on |nss_fd| may not have completed.
262 if (list == NULL)
263 return;
265 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
266 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
267 certs_.push_back(CERT_DupCertificate(node->cert));
269 CERT_DestroyCertList(list);
272 std::vector<base::StringPiece>
273 PeerCertificateChain::AsStringPieceVector() const {
274 std::vector<base::StringPiece> v(certs_.size());
275 for (unsigned i = 0; i < certs_.size(); i++) {
276 v[i] = base::StringPiece(
277 reinterpret_cast<const char*>(certs_[i]->derCert.data),
278 certs_[i]->derCert.len);
281 return v;
284 // HandshakeState is a helper struct used to pass handshake state between
285 // the NSS task runner and the network task runner.
287 // It contains members that may be read or written on the NSS task runner,
288 // but which also need to be read from the network task runner. The NSS task
289 // runner will notify the network task runner whenever this state changes, so
290 // that the network task runner can safely make a copy, which avoids the need
291 // for locking.
292 struct HandshakeState {
293 HandshakeState() { Reset(); }
295 void Reset() {
296 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
297 next_proto.clear();
298 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
299 channel_id_sent = false;
300 server_cert_chain.Reset(NULL);
301 server_cert = NULL;
302 sct_list_from_tls_extension.clear();
303 stapled_ocsp_response.clear();
304 resumed_handshake = false;
305 ssl_connection_status = 0;
308 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
309 // negotiated protocol stored in |next_proto|.
310 SSLClientSocket::NextProtoStatus next_proto_status;
311 std::string next_proto;
313 // TLS extension used for protocol negotiation.
314 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
316 // True if a channel ID was sent.
317 bool channel_id_sent;
319 // List of DER-encoded X.509 DistinguishedName of certificate authorities
320 // allowed by the server.
321 std::vector<std::string> cert_authorities;
323 // Set when the handshake fully completes.
325 // The server certificate is first received from NSS as an NSS certificate
326 // chain (|server_cert_chain|) and then converted into a platform-specific
327 // X509Certificate object (|server_cert|). It's possible for some
328 // certificates to be successfully parsed by NSS, and not by the platform
329 // libraries (i.e.: when running within a sandbox, different parsing
330 // algorithms, etc), so it's not safe to assume that |server_cert| will
331 // always be non-NULL.
332 PeerCertificateChain server_cert_chain;
333 scoped_refptr<X509Certificate> server_cert;
334 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
335 std::string sct_list_from_tls_extension;
336 // Stapled OCSP response received.
337 std::string stapled_ocsp_response;
339 // True if the current handshake was the result of TLS session resumption.
340 bool resumed_handshake;
342 // The negotiated security parameters (TLS version, cipher, extensions) of
343 // the SSL connection.
344 int ssl_connection_status;
347 // Client-side error mapping functions.
349 // Map NSS error code to network error code.
350 int MapNSSClientError(PRErrorCode err) {
351 switch (err) {
352 case SSL_ERROR_BAD_CERT_ALERT:
353 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
354 case SSL_ERROR_REVOKED_CERT_ALERT:
355 case SSL_ERROR_EXPIRED_CERT_ALERT:
356 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
357 case SSL_ERROR_UNKNOWN_CA_ALERT:
358 case SSL_ERROR_ACCESS_DENIED_ALERT:
359 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
360 default:
361 return MapNSSError(err);
365 } // namespace
367 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
368 // able to marshal data between NSS functions and an underlying transport
369 // socket.
371 // All public functions are meant to be called from the network task runner,
372 // and any callbacks supplied will be invoked there as well, provided that
373 // Detach() has not been called yet.
375 /////////////////////////////////////////////////////////////////////////////
377 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
379 // Because NSS may block on either hardware or user input during operations
380 // such as signing, creating certificates, or locating private keys, the Core
381 // handles all of the interactions with the underlying NSS SSL socket, so
382 // that these blocking calls can be executed on a dedicated task runner.
384 // Note that the network task runner and the NSS task runner may be executing
385 // on the same thread. If that happens, then it's more performant to try to
386 // complete as much work as possible synchronously, even if it might block,
387 // rather than continually PostTask-ing to the same thread.
389 // Because NSS functions should only be called on the NSS task runner, while
390 // I/O resources should only be accessed on the network task runner, most
391 // public functions are implemented via three methods, each with different
392 // task runner affinities.
394 // In the single-threaded mode (where the network and NSS task runners run on
395 // the same thread), these are all attempted synchronously, while in the
396 // multi-threaded mode, message passing is used.
398 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
399 // DoHandshake)
400 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
401 // (BufferRecv, BufferSend)
402 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
403 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
404 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
405 // data from the network task runner back to NSS (BufferRecvComplete,
406 // BufferSendComplete, OnHandshakeIOComplete)
408 /////////////////////////////////////////////////////////////////////////////
409 // Single-threaded example
411 // |--------------------------Network Task Runner--------------------------|
412 // SSLClientSocketNSS Core (Transport Socket)
413 // Read()
414 // |-------------------------V
415 // Read()
416 // |
417 // DoPayloadRead()
418 // |
419 // BufferRecv()
420 // |
421 // DoBufferRecv()
422 // |-------------------------V
423 // Read()
424 // V-------------------------|
425 // BufferRecvComplete()
426 // |
427 // PostOrRunCallback()
428 // V-------------------------|
429 // (Read Callback)
431 /////////////////////////////////////////////////////////////////////////////
432 // Multi-threaded example:
434 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
435 // SSLClientSocketNSS Core Socket Core
436 // Read()
437 // |---------------------V
438 // Read()
439 // |-------------------------------V
440 // Read()
441 // |
442 // DoPayloadRead()
443 // |
444 // BufferRecv
445 // V-------------------------------|
446 // DoBufferRecv
447 // |----------------V
448 // Read()
449 // V----------------|
450 // BufferRecvComplete()
451 // |-------------------------------V
452 // BufferRecvComplete()
453 // |
454 // PostOrRunCallback()
455 // V-------------------------------|
456 // PostOrRunCallback()
457 // V---------------------|
458 // (Read Callback)
460 /////////////////////////////////////////////////////////////////////////////
461 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
462 public:
463 // Creates a new Core.
465 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
466 // that need to operate on the underlying transport, net log, or server
467 // bound certificate fetching will happen on the |network_task_runner|, so
468 // that their lifetimes match that of the owning SSLClientSocketNSS.
470 // The caller retains ownership of |transport|, |net_log|, and
471 // |channel_id_service|, and they will not be accessed once Detach()
472 // has been called.
473 Core(base::SequencedTaskRunner* network_task_runner,
474 base::SequencedTaskRunner* nss_task_runner,
475 ClientSocketHandle* transport,
476 const HostPortPair& host_and_port,
477 const SSLConfig& ssl_config,
478 BoundNetLog* net_log,
479 ChannelIDService* channel_id_service);
481 // Called on the network task runner.
482 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
483 // underlying memio implementation, to the Core. Returns true if the Core
484 // was successfully registered with the socket.
485 bool Init(PRFileDesc* socket, memio_Private* buffers);
487 // Called on the network task runner.
489 // Attempts to perform an SSL handshake. If the handshake cannot be
490 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
491 // the network task runner once the handshake has completed. Otherwise,
492 // returns OK on success or a network error code on failure.
493 int Connect(const CompletionCallback& callback);
495 // Called on the network task runner.
496 // Signals that the resources owned by the network task runner are going
497 // away. No further callbacks will be invoked on the network task runner.
498 // May be called at any time.
499 void Detach();
501 // Called on the network task runner.
502 // Returns the current state of the underlying SSL socket. May be called at
503 // any time.
504 const HandshakeState& state() const { return network_handshake_state_; }
506 // Called on the network task runner.
507 // Read() and Write() mirror the net::Socket functions of the same name.
508 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
509 // task runner at a later point, unless the caller calls Detach().
510 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
511 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
513 // Called on the network task runner.
514 bool IsConnected() const;
515 bool HasPendingAsyncOperation() const;
516 bool HasUnhandledReceivedData() const;
517 bool WasEverUsed() const;
519 // Called on the network task runner.
520 // Causes the associated SSL/TLS session ID to be added to NSS's session
521 // cache, but only if the connection has not been False Started.
523 // This should only be called after the server's certificate has been
524 // verified, and may not be called within an NSS callback.
525 void CacheSessionIfNecessary();
527 private:
528 friend class base::RefCountedThreadSafe<Core>;
529 ~Core();
531 enum State {
532 STATE_NONE,
533 STATE_HANDSHAKE,
534 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
537 bool OnNSSTaskRunner() const;
538 bool OnNetworkTaskRunner() const;
540 ////////////////////////////////////////////////////////////////////////////
541 // Methods that are ONLY called on the NSS task runner:
542 ////////////////////////////////////////////////////////////////////////////
544 // Called by NSS during full handshakes to allow the application to
545 // verify the certificate. Instead of verifying the certificate in the midst
546 // of the handshake, SECSuccess is always returned and the peer's certificate
547 // is verified afterwards.
548 // This behaviour is an artifact of the original SSLClientSocketWin
549 // implementation, which could not verify the peer's certificate until after
550 // the handshake had completed, as well as bugs in NSS that prevent
551 // SSL_RestartHandshakeAfterCertReq from working.
552 static SECStatus OwnAuthCertHandler(void* arg,
553 PRFileDesc* socket,
554 PRBool checksig,
555 PRBool is_server);
557 // Callbacks called by NSS when the peer requests client certificate
558 // authentication.
559 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
560 // the arguments.
561 static SECStatus ClientAuthHandler(void* arg,
562 PRFileDesc* socket,
563 CERTDistNames* ca_names,
564 CERTCertificate** result_certificate,
565 SECKEYPrivateKey** result_private_key);
567 // Called by NSS to determine if we can False Start.
568 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
569 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
570 void* arg,
571 PRBool* can_false_start);
573 // Called by NSS each time a handshake completely finishes.
574 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
575 static void HandshakeCallback(PRFileDesc* socket, void* arg);
577 // Called once for each successful handshake. If the initial handshake false
578 // starts, it is called when it false starts and not when it completely
579 // finishes. is_initial is true if this is the initial handshake.
580 void HandshakeSucceeded(bool is_initial);
582 // Handles an NSS error generated while handshaking or performing IO.
583 // Returns a network error code mapped from the original NSS error.
584 int HandleNSSError(PRErrorCode error);
586 int DoHandshakeLoop(int last_io_result);
587 int DoReadLoop(int result);
588 int DoWriteLoop(int result);
590 int DoHandshake();
591 int DoGetDBCertComplete(int result);
593 int DoPayloadRead();
594 int DoPayloadWrite();
596 bool DoTransportIO();
597 int BufferRecv();
598 int BufferSend();
600 void OnRecvComplete(int result);
601 void OnSendComplete(int result);
603 void DoConnectCallback(int result);
604 void DoReadCallback(int result);
605 void DoWriteCallback(int result);
607 // Client channel ID handler.
608 static SECStatus ClientChannelIDHandler(
609 void* arg,
610 PRFileDesc* socket,
611 SECKEYPublicKey **out_public_key,
612 SECKEYPrivateKey **out_private_key);
614 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
615 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
616 // and an error code otherwise.
617 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
618 // set by a call to ChannelIDService->GetChannelID. The caller
619 // takes ownership of the |*cert| and |*key|.
620 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
622 // Updates the NSS and platform specific certificates.
623 void UpdateServerCert();
624 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
625 // received in the handshake via a TLS extension.
626 void UpdateSignedCertTimestamps();
627 // Update the OCSP response cache with the stapled response received in the
628 // handshake, and update nss_handshake_state_ with
629 // the SignedCertificateTimestampList received in the stapled OCSP response.
630 void UpdateStapledOCSPResponse();
631 // Updates the nss_handshake_state_ with the negotiated security parameters.
632 void UpdateConnectionStatus();
633 // Record histograms for channel id support during full handshakes - resumed
634 // handshakes are ignored.
635 void RecordChannelIDSupportOnNSSTaskRunner();
636 // UpdateNextProto gets any application-layer protocol that may have been
637 // negotiated by the TLS connection.
638 void UpdateNextProto();
639 // Record TLS extension used for protocol negotiation (NPN or ALPN).
640 void UpdateExtensionUsed();
642 // Returns true if renegotiations are allowed.
643 bool IsRenegotiationAllowed() const;
645 ////////////////////////////////////////////////////////////////////////////
646 // Methods that are ONLY called on the network task runner:
647 ////////////////////////////////////////////////////////////////////////////
648 int DoBufferRecv(IOBuffer* buffer, int len);
649 int DoBufferSend(IOBuffer* buffer, int len);
650 int DoGetChannelID(const std::string& host);
652 void OnGetChannelIDComplete(int result);
653 void OnHandshakeStateUpdated(const HandshakeState& state);
654 void OnNSSBufferUpdated(int amount_in_read_buffer);
655 void DidNSSRead(int result);
656 void DidNSSWrite(int result);
657 void RecordChannelIDSupportOnNetworkTaskRunner(
658 bool negotiated_channel_id,
659 bool channel_id_enabled,
660 bool supports_ecc) const;
662 ////////////////////////////////////////////////////////////////////////////
663 // Methods that are called on both the network task runner and the NSS
664 // task runner.
665 ////////////////////////////////////////////////////////////////////////////
666 void OnHandshakeIOComplete(int result);
667 void BufferRecvComplete(IOBuffer* buffer, int result);
668 void BufferSendComplete(int result);
670 // PostOrRunCallback is a helper function to ensure that |callback| is
671 // invoked on the network task runner, but only if Detach() has not yet
672 // been called.
673 void PostOrRunCallback(const tracked_objects::Location& location,
674 const base::Closure& callback);
676 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
677 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
678 void AddCertProvidedEvent(int cert_count);
680 // Sets the handshake state |channel_id_sent| flag and logs the
681 // SSL_CHANNEL_ID_PROVIDED event.
682 void SetChannelIDProvided();
684 ////////////////////////////////////////////////////////////////////////////
685 // Members that are ONLY accessed on the network task runner:
686 ////////////////////////////////////////////////////////////////////////////
688 // True if the owning SSLClientSocketNSS has called Detach(). No further
689 // callbacks will be invoked nor access to members owned by the network
690 // task runner.
691 bool detached_;
693 // The underlying transport to use for network IO.
694 ClientSocketHandle* transport_;
695 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
697 // The current handshake state. Mirrors |nss_handshake_state_|.
698 HandshakeState network_handshake_state_;
700 // The service for retrieving Channel ID keys. May be NULL.
701 ChannelIDService* channel_id_service_;
702 ChannelIDService::Request channel_id_request_;
704 // The information about NSS task runner.
705 int unhandled_buffer_size_;
706 bool nss_waiting_read_;
707 bool nss_waiting_write_;
708 bool nss_is_closed_;
710 // Set when Read() or Write() successfully reads or writes data to or from the
711 // network.
712 bool was_ever_used_;
714 ////////////////////////////////////////////////////////////////////////////
715 // Members that are ONLY accessed on the NSS task runner:
716 ////////////////////////////////////////////////////////////////////////////
717 HostPortPair host_and_port_;
718 SSLConfig ssl_config_;
720 // NSS SSL socket.
721 PRFileDesc* nss_fd_;
723 // Buffers for the network end of the SSL state machine
724 memio_Private* nss_bufs_;
726 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
727 // as much data as possible, without blocking.
728 // If DoPayloadRead() encounters an error after having read some data, stores
729 // the results to return on the *next* call to DoPayloadRead(). A value of
730 // kNoPendingReadResult indicates there is no pending result, otherwise 0
731 // indicates EOF and < 0 indicates an error.
732 int pending_read_result_;
733 // Contains the previously observed NSS error. Only valid when
734 // pending_read_result_ != kNoPendingReadResult.
735 PRErrorCode pending_read_nss_error_;
737 // The certificate chain, in DER form, that is expected to be received from
738 // the server.
739 std::vector<std::string> predicted_certs_;
741 State next_handshake_state_;
743 // True if channel ID extension was negotiated.
744 bool channel_id_xtn_negotiated_;
745 // True if the handshake state machine was interrupted for channel ID.
746 bool channel_id_needed_;
747 // True if the handshake state machine was interrupted for client auth.
748 bool client_auth_cert_needed_;
749 // True if NSS has False Started in the initial handshake, but the initial
750 // handshake has not yet completely finished..
751 bool false_started_;
752 // True if NSS has called HandshakeCallback.
753 bool handshake_callback_called_;
755 HandshakeState nss_handshake_state_;
757 bool transport_recv_busy_;
758 bool transport_recv_eof_;
759 bool transport_send_busy_;
761 // Used by Read function.
762 scoped_refptr<IOBuffer> user_read_buf_;
763 int user_read_buf_len_;
765 // Used by Write function.
766 scoped_refptr<IOBuffer> user_write_buf_;
767 int user_write_buf_len_;
769 CompletionCallback user_connect_callback_;
770 CompletionCallback user_read_callback_;
771 CompletionCallback user_write_callback_;
773 ////////////////////////////////////////////////////////////////////////////
774 // Members that are accessed on both the network task runner and the NSS
775 // task runner.
776 ////////////////////////////////////////////////////////////////////////////
777 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
778 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
780 // Dereferenced only on the network task runner, but bound to tasks destined
781 // for the network task runner from the NSS task runner.
782 base::WeakPtr<BoundNetLog> weak_net_log_;
784 // Written on the network task runner by the |channel_id_service_|,
785 // prior to invoking OnHandshakeIOComplete.
786 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
787 // on the NSS task runner.
788 scoped_ptr<crypto::ECPrivateKey> channel_id_key_;
790 DISALLOW_COPY_AND_ASSIGN(Core);
793 SSLClientSocketNSS::Core::Core(
794 base::SequencedTaskRunner* network_task_runner,
795 base::SequencedTaskRunner* nss_task_runner,
796 ClientSocketHandle* transport,
797 const HostPortPair& host_and_port,
798 const SSLConfig& ssl_config,
799 BoundNetLog* net_log,
800 ChannelIDService* channel_id_service)
801 : detached_(false),
802 transport_(transport),
803 weak_net_log_factory_(net_log),
804 channel_id_service_(channel_id_service),
805 unhandled_buffer_size_(0),
806 nss_waiting_read_(false),
807 nss_waiting_write_(false),
808 nss_is_closed_(false),
809 was_ever_used_(false),
810 host_and_port_(host_and_port),
811 ssl_config_(ssl_config),
812 nss_fd_(NULL),
813 nss_bufs_(NULL),
814 pending_read_result_(kNoPendingReadResult),
815 pending_read_nss_error_(0),
816 next_handshake_state_(STATE_NONE),
817 channel_id_xtn_negotiated_(false),
818 channel_id_needed_(false),
819 client_auth_cert_needed_(false),
820 false_started_(false),
821 handshake_callback_called_(false),
822 transport_recv_busy_(false),
823 transport_recv_eof_(false),
824 transport_send_busy_(false),
825 user_read_buf_len_(0),
826 user_write_buf_len_(0),
827 network_task_runner_(network_task_runner),
828 nss_task_runner_(nss_task_runner),
829 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
832 SSLClientSocketNSS::Core::~Core() {
833 // TODO(wtc): Send SSL close_notify alert.
834 if (nss_fd_ != NULL) {
835 PR_Close(nss_fd_);
836 nss_fd_ = NULL;
838 nss_bufs_ = NULL;
841 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
842 memio_Private* buffers) {
843 DCHECK(OnNetworkTaskRunner());
844 DCHECK(!nss_fd_);
845 DCHECK(!nss_bufs_);
847 nss_fd_ = socket;
848 nss_bufs_ = buffers;
850 SECStatus rv = SECSuccess;
852 if (!ssl_config_.next_protos.empty()) {
853 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
854 const bool adequate_encryption =
855 PK11_TokenExists(CKM_AES_GCM) ||
856 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305);
857 const bool adequate_key_agreement = PK11_TokenExists(CKM_DH_PKCS_DERIVE) ||
858 PK11_TokenExists(CKM_ECDH1_DERIVE);
859 std::vector<uint8_t> wire_protos =
860 SerializeNextProtos(ssl_config_.next_protos,
861 adequate_encryption && adequate_key_agreement &&
862 IsTLSVersionAdequateForHTTP2(ssl_config_));
863 rv = SSL_SetNextProtoNego(
864 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
865 wire_protos.size());
866 if (rv != SECSuccess)
867 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
868 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
869 if (rv != SECSuccess)
870 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
871 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
872 if (rv != SECSuccess)
873 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
876 rv = SSL_AuthCertificateHook(
877 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
878 if (rv != SECSuccess) {
879 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
880 return false;
883 rv = SSL_GetClientAuthDataHook(
884 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
885 if (rv != SECSuccess) {
886 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
887 return false;
890 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
891 rv = SSL_SetClientChannelIDCallback(
892 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
893 if (rv != SECSuccess) {
894 LogFailedNSSFunction(
895 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
899 rv = SSL_SetCanFalseStartCallback(
900 nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
901 if (rv != SECSuccess) {
902 LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
903 return false;
906 rv = SSL_HandshakeCallback(
907 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
908 if (rv != SECSuccess) {
909 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
910 return false;
913 return true;
916 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
917 if (!OnNSSTaskRunner()) {
918 DCHECK(!detached_);
919 bool posted = nss_task_runner_->PostTask(
920 FROM_HERE,
921 base::Bind(IgnoreResult(&Core::Connect), this, callback));
922 return posted ? ERR_IO_PENDING : ERR_ABORTED;
925 DCHECK(OnNSSTaskRunner());
926 DCHECK_EQ(STATE_NONE, next_handshake_state_);
927 DCHECK(user_read_callback_.is_null());
928 DCHECK(user_write_callback_.is_null());
929 DCHECK(user_connect_callback_.is_null());
930 DCHECK(!user_read_buf_.get());
931 DCHECK(!user_write_buf_.get());
933 next_handshake_state_ = STATE_HANDSHAKE;
934 int rv = DoHandshakeLoop(OK);
935 if (rv == ERR_IO_PENDING) {
936 user_connect_callback_ = callback;
937 } else if (rv > OK) {
938 rv = OK;
940 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
941 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
942 return ERR_IO_PENDING;
945 return rv;
948 void SSLClientSocketNSS::Core::Detach() {
949 DCHECK(OnNetworkTaskRunner());
951 detached_ = true;
952 transport_ = NULL;
953 weak_net_log_factory_.InvalidateWeakPtrs();
955 network_handshake_state_.Reset();
957 channel_id_request_.Cancel();
960 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
961 const CompletionCallback& callback) {
962 if (!OnNSSTaskRunner()) {
963 DCHECK(OnNetworkTaskRunner());
964 DCHECK(!detached_);
965 DCHECK(transport_);
966 DCHECK(!nss_waiting_read_);
968 nss_waiting_read_ = true;
969 bool posted = nss_task_runner_->PostTask(
970 FROM_HERE,
971 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
972 buf_len, callback));
973 if (!posted) {
974 nss_is_closed_ = true;
975 nss_waiting_read_ = false;
977 return posted ? ERR_IO_PENDING : ERR_ABORTED;
980 DCHECK(OnNSSTaskRunner());
981 DCHECK(false_started_ || handshake_callback_called_);
982 DCHECK_EQ(STATE_NONE, next_handshake_state_);
983 DCHECK(user_read_callback_.is_null());
984 DCHECK(user_connect_callback_.is_null());
985 DCHECK(!user_read_buf_.get());
986 DCHECK(nss_bufs_);
988 user_read_buf_ = buf;
989 user_read_buf_len_ = buf_len;
991 int rv = DoReadLoop(OK);
992 if (rv == ERR_IO_PENDING) {
993 if (OnNetworkTaskRunner())
994 nss_waiting_read_ = true;
995 user_read_callback_ = callback;
996 } else {
997 user_read_buf_ = NULL;
998 user_read_buf_len_ = 0;
1000 if (!OnNetworkTaskRunner()) {
1001 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1002 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1003 return ERR_IO_PENDING;
1004 } else {
1005 DCHECK(!nss_waiting_read_);
1006 if (rv <= 0) {
1007 nss_is_closed_ = true;
1008 } else {
1009 was_ever_used_ = true;
1014 return rv;
1017 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1018 const CompletionCallback& callback) {
1019 if (!OnNSSTaskRunner()) {
1020 DCHECK(OnNetworkTaskRunner());
1021 DCHECK(!detached_);
1022 DCHECK(transport_);
1023 DCHECK(!nss_waiting_write_);
1025 nss_waiting_write_ = true;
1026 bool posted = nss_task_runner_->PostTask(
1027 FROM_HERE,
1028 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1029 buf_len, callback));
1030 if (!posted) {
1031 nss_is_closed_ = true;
1032 nss_waiting_write_ = false;
1034 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1037 DCHECK(OnNSSTaskRunner());
1038 DCHECK(false_started_ || handshake_callback_called_);
1039 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1040 DCHECK(user_write_callback_.is_null());
1041 DCHECK(user_connect_callback_.is_null());
1042 DCHECK(!user_write_buf_.get());
1043 DCHECK(nss_bufs_);
1045 user_write_buf_ = buf;
1046 user_write_buf_len_ = buf_len;
1048 int rv = DoWriteLoop(OK);
1049 if (rv == ERR_IO_PENDING) {
1050 if (OnNetworkTaskRunner())
1051 nss_waiting_write_ = true;
1052 user_write_callback_ = callback;
1053 } else {
1054 user_write_buf_ = NULL;
1055 user_write_buf_len_ = 0;
1057 if (!OnNetworkTaskRunner()) {
1058 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1059 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1060 return ERR_IO_PENDING;
1061 } else {
1062 DCHECK(!nss_waiting_write_);
1063 if (rv < 0) {
1064 nss_is_closed_ = true;
1065 } else if (rv > 0) {
1066 was_ever_used_ = true;
1071 return rv;
1074 bool SSLClientSocketNSS::Core::IsConnected() const {
1075 DCHECK(OnNetworkTaskRunner());
1076 return !nss_is_closed_;
1079 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1080 DCHECK(OnNetworkTaskRunner());
1081 return nss_waiting_read_ || nss_waiting_write_;
1084 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1085 DCHECK(OnNetworkTaskRunner());
1086 return unhandled_buffer_size_ != 0;
1089 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1090 DCHECK(OnNetworkTaskRunner());
1091 return was_ever_used_;
1094 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1095 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1096 // nss_fd_. However, it happens on the network task runner in order to match
1097 // the buggy behavior of ExportKeyingMaterial.
1099 // Once http://crbug.com/330360 is fixed, this should be moved to an
1100 // implementation that exclusively does this work on the NSS TaskRunner. This
1101 // is "safe" because it is only called during the certificate verification
1102 // state machine of the main socket, which is safe because no underlying
1103 // transport IO will be occuring in that state, and NSS will not be blocking
1104 // on any PKCS#11 related locks that might block the Network TaskRunner.
1105 DCHECK(OnNetworkTaskRunner());
1107 // Only cache the session if the connection was not False Started, because
1108 // sessions should only be cached *after* the peer's Finished message is
1109 // processed.
1110 // In the case of False Start, the session will be cached once the
1111 // HandshakeCallback is called, which signals the receipt and processing of
1112 // the Finished message, and which will happen during a call to
1113 // PR_Read/PR_Write.
1114 if (!false_started_)
1115 SSL_CacheSession(nss_fd_);
1118 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1119 return nss_task_runner_->RunsTasksOnCurrentThread();
1122 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1123 return network_task_runner_->RunsTasksOnCurrentThread();
1126 // static
1127 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1128 void* arg,
1129 PRFileDesc* socket,
1130 PRBool checksig,
1131 PRBool is_server) {
1132 Core* core = reinterpret_cast<Core*>(arg);
1133 if (core->handshake_callback_called_) {
1134 // Disallow the server certificate to change in a renegotiation.
1135 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1136 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1137 if (new_cert->derCert.len != old_cert->derCert.len ||
1138 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1139 new_cert->derCert.len) != 0) {
1140 // NSS doesn't have an error code that indicates the server certificate
1141 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1142 // for this purpose.
1143 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1144 return SECFailure;
1148 // Tell NSS to not verify the certificate.
1149 return SECSuccess;
1152 #if defined(OS_IOS)
1154 // static
1155 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1156 void* arg,
1157 PRFileDesc* socket,
1158 CERTDistNames* ca_names,
1159 CERTCertificate** result_certificate,
1160 SECKEYPrivateKey** result_private_key) {
1161 Core* core = reinterpret_cast<Core*>(arg);
1162 DCHECK(core->OnNSSTaskRunner());
1164 core->PostOrRunCallback(
1165 FROM_HERE,
1166 base::Bind(&AddLogEvent, core->weak_net_log_,
1167 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1169 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1170 LOG(WARNING) << "Client auth is not supported";
1172 // Never send a certificate.
1173 core->AddCertProvidedEvent(0);
1174 return SECFailure;
1177 #else // !OS_IOS
1179 // static
1180 // Based on Mozilla's NSS_GetClientAuthData.
1181 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1182 void* arg,
1183 PRFileDesc* socket,
1184 CERTDistNames* ca_names,
1185 CERTCertificate** result_certificate,
1186 SECKEYPrivateKey** result_private_key) {
1187 Core* core = reinterpret_cast<Core*>(arg);
1188 DCHECK(core->OnNSSTaskRunner());
1190 core->PostOrRunCallback(
1191 FROM_HERE,
1192 base::Bind(&AddLogEvent, core->weak_net_log_,
1193 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1195 // Regular client certificate requested.
1196 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1197 void* wincx = SSL_RevealPinArg(socket);
1199 if (core->ssl_config_.send_client_cert) {
1200 // Second pass: a client certificate should have been selected.
1201 if (core->ssl_config_.client_cert.get()) {
1202 CERTCertificate* cert =
1203 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1204 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1205 if (privkey) {
1206 // TODO(jsorianopastor): We should wait for server certificate
1207 // verification before sending our credentials. See
1208 // http://crbug.com/13934.
1209 *result_certificate = cert;
1210 *result_private_key = privkey;
1211 // A cert_count of -1 means the number of certificates is unknown.
1212 // NSS will construct the certificate chain.
1213 core->AddCertProvidedEvent(-1);
1215 return SECSuccess;
1217 LOG(WARNING) << "Client cert found without private key";
1219 // Send no client certificate.
1220 core->AddCertProvidedEvent(0);
1221 return SECFailure;
1224 // First pass: client certificate is needed.
1225 core->nss_handshake_state_.cert_authorities.clear();
1227 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1228 // the server and save them in |cert_authorities|.
1229 for (int i = 0; i < ca_names->nnames; i++) {
1230 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1231 reinterpret_cast<const char*>(ca_names->names[i].data),
1232 static_cast<size_t>(ca_names->names[i].len)));
1235 // Update the network task runner's view of the handshake state now that
1236 // server certificate request has been recorded.
1237 core->PostOrRunCallback(
1238 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1239 core->nss_handshake_state_));
1241 // Tell NSS to suspend the client authentication. We will then abort the
1242 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1243 return SECWouldBlock;
1245 #endif // OS_IOS
1247 // static
1248 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1249 PRFileDesc* socket,
1250 void* arg,
1251 PRBool* can_false_start) {
1252 // If the server doesn't support NPN or ALPN, then we don't do False
1253 // Start with it.
1254 PRBool negotiated_extension;
1255 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1256 ssl_app_layer_protocol_xtn,
1257 &negotiated_extension);
1258 if (rv != SECSuccess || !negotiated_extension) {
1259 rv = SSL_HandshakeNegotiatedExtension(socket,
1260 ssl_next_proto_nego_xtn,
1261 &negotiated_extension);
1263 if (rv != SECSuccess || !negotiated_extension) {
1264 *can_false_start = PR_FALSE;
1265 return SECSuccess;
1268 SSLChannelInfo channel_info;
1269 SECStatus ok =
1270 SSL_GetChannelInfo(socket, &channel_info, sizeof(channel_info));
1271 if (ok != SECSuccess || channel_info.length != sizeof(channel_info) ||
1272 channel_info.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_2 ||
1273 !IsFalseStartableTLSCipherSuite(channel_info.cipherSuite)) {
1274 *can_false_start = PR_FALSE;
1275 return SECSuccess;
1278 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1281 // static
1282 void SSLClientSocketNSS::Core::HandshakeCallback(
1283 PRFileDesc* socket,
1284 void* arg) {
1285 Core* core = reinterpret_cast<Core*>(arg);
1286 DCHECK(core->OnNSSTaskRunner());
1288 bool is_initial = !core->handshake_callback_called_;
1289 core->handshake_callback_called_ = true;
1290 if (core->false_started_) {
1291 core->false_started_ = false;
1292 // If the connection was False Started, then at the time of this callback,
1293 // the peer's certificate will have been verified or the caller will have
1294 // accepted the error.
1295 // This is guaranteed when using False Start because this callback will
1296 // not be invoked until processing the peer's Finished message, which
1297 // will only happen in a PR_Read/PR_Write call, which can only happen
1298 // after the peer's certificate is verified.
1299 SSL_CacheSessionUnlocked(socket);
1301 // Additionally, when False Starting, DoHandshake() will have already
1302 // called HandshakeSucceeded(), so return now.
1303 return;
1305 core->HandshakeSucceeded(is_initial);
1308 void SSLClientSocketNSS::Core::HandshakeSucceeded(bool is_initial) {
1309 DCHECK(OnNSSTaskRunner());
1311 PRBool last_handshake_resumed;
1312 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1313 if (rv == SECSuccess && last_handshake_resumed) {
1314 nss_handshake_state_.resumed_handshake = true;
1315 } else {
1316 nss_handshake_state_.resumed_handshake = false;
1319 RecordChannelIDSupportOnNSSTaskRunner();
1320 UpdateServerCert();
1321 UpdateSignedCertTimestamps();
1322 UpdateStapledOCSPResponse();
1323 UpdateConnectionStatus();
1324 UpdateNextProto();
1325 UpdateExtensionUsed();
1327 if (is_initial && IsRenegotiationAllowed()) {
1328 // For compatibility, do not enforce RFC 5746 support. Per section 4.1,
1329 // enforcement falls largely on the server.
1331 // This is done in a callback rather than after SSL_ForceHandshake returns
1332 // because SSL_ForceHandshake will otherwise greedly consume renegotiations
1333 // before returning if Finished and HelloRequest are in the same
1334 // record.
1336 // Note that SSL_OptionSet should only be called for an initial
1337 // handshake. See https://crbug.com/125299.
1338 SECStatus rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
1339 SSL_RENEGOTIATE_TRANSITIONAL);
1340 DCHECK_EQ(SECSuccess, rv);
1343 // Update the network task runners view of the handshake state whenever
1344 // a handshake has completed.
1345 PostOrRunCallback(
1346 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1347 nss_handshake_state_));
1350 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1351 DCHECK(OnNSSTaskRunner());
1353 return MapNSSClientError(nss_error);
1356 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1357 DCHECK(OnNSSTaskRunner());
1359 int rv = last_io_result;
1360 do {
1361 // Default to STATE_NONE for next state.
1362 State state = next_handshake_state_;
1363 GotoState(STATE_NONE);
1365 switch (state) {
1366 case STATE_HANDSHAKE:
1367 rv = DoHandshake();
1368 break;
1369 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1370 rv = DoGetDBCertComplete(rv);
1371 break;
1372 case STATE_NONE:
1373 default:
1374 rv = ERR_UNEXPECTED;
1375 LOG(DFATAL) << "unexpected state " << state;
1376 break;
1379 // Do the actual network I/O
1380 bool network_moved = DoTransportIO();
1381 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1382 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1383 // special case we keep looping even if rv is ERR_IO_PENDING because
1384 // the transport IO may allow DoHandshake to make progress.
1385 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1386 rv = OK; // This causes us to stay in the loop.
1388 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1389 return rv;
1392 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1393 DCHECK(OnNSSTaskRunner());
1394 DCHECK(false_started_ || handshake_callback_called_);
1395 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1397 if (result < 0)
1398 return result;
1400 if (!nss_bufs_) {
1401 LOG(DFATAL) << "!nss_bufs_";
1402 int rv = ERR_UNEXPECTED;
1403 PostOrRunCallback(
1404 FROM_HERE,
1405 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1406 NetLog::TYPE_SSL_READ_ERROR,
1407 CreateNetLogSSLErrorCallback(rv, 0)));
1408 return rv;
1411 bool network_moved;
1412 int rv;
1413 do {
1414 rv = DoPayloadRead();
1415 network_moved = DoTransportIO();
1416 } while (rv == ERR_IO_PENDING && network_moved);
1418 return rv;
1421 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1422 DCHECK(OnNSSTaskRunner());
1423 DCHECK(false_started_ || handshake_callback_called_);
1424 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1426 if (result < 0)
1427 return result;
1429 if (!nss_bufs_) {
1430 LOG(DFATAL) << "!nss_bufs_";
1431 int rv = ERR_UNEXPECTED;
1432 PostOrRunCallback(
1433 FROM_HERE,
1434 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1435 NetLog::TYPE_SSL_READ_ERROR,
1436 CreateNetLogSSLErrorCallback(rv, 0)));
1437 return rv;
1440 bool network_moved;
1441 int rv;
1442 do {
1443 rv = DoPayloadWrite();
1444 network_moved = DoTransportIO();
1445 } while (rv == ERR_IO_PENDING && network_moved);
1447 LeaveFunction(rv);
1448 return rv;
1451 int SSLClientSocketNSS::Core::DoHandshake() {
1452 DCHECK(OnNSSTaskRunner());
1454 int net_error = OK;
1455 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1457 // Note: this function may be called multiple times during the handshake, so
1458 // even though channel id and client auth are separate else cases, they can
1459 // both be used during a single SSL handshake.
1460 if (channel_id_needed_) {
1461 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1462 net_error = ERR_IO_PENDING;
1463 } else if (client_auth_cert_needed_) {
1464 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1465 PostOrRunCallback(
1466 FROM_HERE,
1467 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1468 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1469 CreateNetLogSSLErrorCallback(net_error, 0)));
1470 } else if (rv == SECSuccess) {
1471 if (!handshake_callback_called_) {
1472 false_started_ = true;
1473 HandshakeSucceeded(true);
1475 } else {
1476 PRErrorCode prerr = PR_GetError();
1477 net_error = HandleNSSError(prerr);
1479 // If not done, stay in this state
1480 if (net_error == ERR_IO_PENDING) {
1481 GotoState(STATE_HANDSHAKE);
1482 } else {
1483 PostOrRunCallback(
1484 FROM_HERE,
1485 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1486 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1487 CreateNetLogSSLErrorCallback(net_error, prerr)));
1491 return net_error;
1494 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1495 SECStatus rv;
1496 PostOrRunCallback(
1497 FROM_HERE,
1498 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1499 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1501 channel_id_needed_ = false;
1503 if (result != OK)
1504 return result;
1506 SECKEYPublicKey* public_key;
1507 SECKEYPrivateKey* private_key;
1508 int error = ImportChannelIDKeys(&public_key, &private_key);
1509 if (error != OK)
1510 return error;
1512 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1513 if (rv != SECSuccess)
1514 return MapNSSError(PORT_GetError());
1516 SetChannelIDProvided();
1517 GotoState(STATE_HANDSHAKE);
1518 return OK;
1521 int SSLClientSocketNSS::Core::DoPayloadRead() {
1522 DCHECK(OnNSSTaskRunner());
1523 DCHECK(user_read_buf_.get());
1524 DCHECK_GT(user_read_buf_len_, 0);
1526 int rv;
1527 // If a previous greedy read resulted in an error that was not consumed (eg:
1528 // due to the caller having read some data successfully), then return that
1529 // pending error now.
1530 if (pending_read_result_ != kNoPendingReadResult) {
1531 rv = pending_read_result_;
1532 PRErrorCode prerr = pending_read_nss_error_;
1533 pending_read_result_ = kNoPendingReadResult;
1534 pending_read_nss_error_ = 0;
1536 if (rv == 0) {
1537 PostOrRunCallback(
1538 FROM_HERE,
1539 base::Bind(&LogByteTransferEvent, weak_net_log_,
1540 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1541 scoped_refptr<IOBuffer>(user_read_buf_)));
1542 } else {
1543 PostOrRunCallback(
1544 FROM_HERE,
1545 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1546 NetLog::TYPE_SSL_READ_ERROR,
1547 CreateNetLogSSLErrorCallback(rv, prerr)));
1549 return rv;
1552 // Perform a greedy read, attempting to read as much as the caller has
1553 // requested. In the current NSS implementation, PR_Read will return
1554 // exactly one SSL application data record's worth of data per invocation.
1555 // The record size is dictated by the server, and may be noticeably smaller
1556 // than the caller's buffer. This may be as little as a single byte, if the
1557 // server is performing 1/n-1 record splitting.
1559 // However, this greedy read may result in renegotiations/re-handshakes
1560 // happening or may lead to some data being read, followed by an EOF (such as
1561 // a TLS close-notify). If at least some data was read, then that result
1562 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1563 // data was read, it's safe to return the error or EOF immediately.
1564 int total_bytes_read = 0;
1565 do {
1566 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1567 user_read_buf_len_ - total_bytes_read);
1568 if (rv > 0)
1569 total_bytes_read += rv;
1570 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1571 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1572 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1573 amount_in_read_buffer));
1575 if (total_bytes_read == user_read_buf_len_) {
1576 // The caller's entire request was satisfied without error. No further
1577 // processing needed.
1578 rv = total_bytes_read;
1579 } else {
1580 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1581 // immediately, while the NSPR/NSS errors are still available in
1582 // thread-local storage. However, the handled/remapped error code should
1583 // only be returned if no application data was already read; if it was, the
1584 // error code should be deferred until the next call of DoPayloadRead.
1586 // If no data was read, |*next_result| will point to the return value of
1587 // this function. If at least some data was read, |*next_result| will point
1588 // to |pending_read_error_|, to be returned in a future call to
1589 // DoPayloadRead() (e.g.: after the current data is handled).
1590 int* next_result = &rv;
1591 if (total_bytes_read > 0) {
1592 pending_read_result_ = rv;
1593 rv = total_bytes_read;
1594 next_result = &pending_read_result_;
1597 if (client_auth_cert_needed_) {
1598 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1599 pending_read_nss_error_ = 0;
1600 } else if (*next_result < 0) {
1601 // If *next_result == 0, then that indicates EOF, and no special error
1602 // handling is needed.
1603 pending_read_nss_error_ = PR_GetError();
1604 *next_result = HandleNSSError(pending_read_nss_error_);
1605 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1606 // If at least some data was read from PR_Read(), do not treat
1607 // insufficient data as an error to return in the next call to
1608 // DoPayloadRead() - instead, let the call fall through to check
1609 // PR_Read() again. This is because DoTransportIO() may complete
1610 // in between the next call to DoPayloadRead(), and thus it is
1611 // important to check PR_Read() on subsequent invocations to see
1612 // if a complete record may now be read.
1613 pending_read_nss_error_ = 0;
1614 pending_read_result_ = kNoPendingReadResult;
1619 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
1621 if (rv >= 0) {
1622 PostOrRunCallback(
1623 FROM_HERE,
1624 base::Bind(&LogByteTransferEvent, weak_net_log_,
1625 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1626 scoped_refptr<IOBuffer>(user_read_buf_)));
1627 } else if (rv != ERR_IO_PENDING) {
1628 PostOrRunCallback(
1629 FROM_HERE,
1630 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1631 NetLog::TYPE_SSL_READ_ERROR,
1632 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
1633 pending_read_nss_error_ = 0;
1635 return rv;
1638 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1639 DCHECK(OnNSSTaskRunner());
1641 DCHECK(user_write_buf_.get());
1643 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1644 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
1645 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1646 // PR_Write could potentially consume the unhandled data in the memio read
1647 // buffer if a renegotiation is in progress. If the buffer is consumed,
1648 // notify the latest buffer size to NetworkRunner.
1649 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
1650 PostOrRunCallback(
1651 FROM_HERE,
1652 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
1654 if (rv >= 0) {
1655 PostOrRunCallback(
1656 FROM_HERE,
1657 base::Bind(&LogByteTransferEvent, weak_net_log_,
1658 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1659 scoped_refptr<IOBuffer>(user_write_buf_)));
1660 return rv;
1662 PRErrorCode prerr = PR_GetError();
1663 if (prerr == PR_WOULD_BLOCK_ERROR)
1664 return ERR_IO_PENDING;
1666 rv = HandleNSSError(prerr);
1667 PostOrRunCallback(
1668 FROM_HERE,
1669 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1670 NetLog::TYPE_SSL_WRITE_ERROR,
1671 CreateNetLogSSLErrorCallback(rv, prerr)));
1672 return rv;
1675 // Do as much network I/O as possible between the buffer and the
1676 // transport socket. Return true if some I/O performed, false
1677 // otherwise (error or ERR_IO_PENDING).
1678 bool SSLClientSocketNSS::Core::DoTransportIO() {
1679 DCHECK(OnNSSTaskRunner());
1681 bool network_moved = false;
1682 if (nss_bufs_ != NULL) {
1683 int rv;
1684 // Read and write as much data as we can. The loop is neccessary
1685 // because Write() may return synchronously.
1686 do {
1687 rv = BufferSend();
1688 if (rv != ERR_IO_PENDING && rv != 0)
1689 network_moved = true;
1690 } while (rv > 0);
1691 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
1692 network_moved = true;
1694 return network_moved;
1697 int SSLClientSocketNSS::Core::BufferRecv() {
1698 DCHECK(OnNSSTaskRunner());
1700 if (transport_recv_busy_)
1701 return ERR_IO_PENDING;
1703 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
1704 // determine how much data NSS wants to read. If NSS was not blocked,
1705 // this will return 0.
1706 int requested = memio_GetReadRequest(nss_bufs_);
1707 if (requested == 0) {
1708 // This is not a perfect match of error codes, as no operation is
1709 // actually pending. However, returning 0 would be interpreted as a
1710 // possible sign of EOF, which is also an inappropriate match.
1711 return ERR_IO_PENDING;
1714 char* buf;
1715 int nb = memio_GetReadParams(nss_bufs_, &buf);
1716 int rv;
1717 if (!nb) {
1718 // buffer too full to read into, so no I/O possible at moment
1719 rv = ERR_IO_PENDING;
1720 } else {
1721 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
1722 if (OnNetworkTaskRunner()) {
1723 rv = DoBufferRecv(read_buffer.get(), nb);
1724 } else {
1725 bool posted = network_task_runner_->PostTask(
1726 FROM_HERE,
1727 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
1728 nb));
1729 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1732 if (rv == ERR_IO_PENDING) {
1733 transport_recv_busy_ = true;
1734 } else {
1735 if (rv > 0) {
1736 memcpy(buf, read_buffer->data(), rv);
1737 } else if (rv == 0) {
1738 transport_recv_eof_ = true;
1740 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
1743 return rv;
1746 // Return 0 if nss_bufs_ was empty,
1747 // > 0 for bytes transferred immediately,
1748 // < 0 for error (or the non-error ERR_IO_PENDING).
1749 int SSLClientSocketNSS::Core::BufferSend() {
1750 DCHECK(OnNSSTaskRunner());
1752 if (transport_send_busy_)
1753 return ERR_IO_PENDING;
1755 const char* buf1;
1756 const char* buf2;
1757 unsigned int len1, len2;
1758 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
1759 // It is important this return synchronously to prevent spinning infinitely
1760 // in the off-thread NSS case. The error code itself is ignored, so just
1761 // return ERR_ABORTED. See https://crbug.com/381160.
1762 return ERR_ABORTED;
1764 const size_t len = len1 + len2;
1766 int rv = 0;
1767 if (len) {
1768 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
1769 memcpy(send_buffer->data(), buf1, len1);
1770 memcpy(send_buffer->data() + len1, buf2, len2);
1772 if (OnNetworkTaskRunner()) {
1773 rv = DoBufferSend(send_buffer.get(), len);
1774 } else {
1775 bool posted = network_task_runner_->PostTask(
1776 FROM_HERE,
1777 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
1778 len));
1779 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1782 if (rv == ERR_IO_PENDING) {
1783 transport_send_busy_ = true;
1784 } else {
1785 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
1789 return rv;
1792 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
1793 DCHECK(OnNSSTaskRunner());
1795 if (next_handshake_state_ == STATE_HANDSHAKE) {
1796 OnHandshakeIOComplete(result);
1797 return;
1800 // Network layer received some data, check if client requested to read
1801 // decrypted data.
1802 if (!user_read_buf_.get())
1803 return;
1805 int rv = DoReadLoop(result);
1806 if (rv != ERR_IO_PENDING)
1807 DoReadCallback(rv);
1810 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
1811 DCHECK(OnNSSTaskRunner());
1813 if (next_handshake_state_ == STATE_HANDSHAKE) {
1814 OnHandshakeIOComplete(result);
1815 return;
1818 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1819 // handshake is in progress.
1820 int rv_read = ERR_IO_PENDING;
1821 int rv_write = ERR_IO_PENDING;
1822 bool network_moved;
1823 do {
1824 if (user_read_buf_.get())
1825 rv_read = DoPayloadRead();
1826 if (user_write_buf_.get())
1827 rv_write = DoPayloadWrite();
1828 network_moved = DoTransportIO();
1829 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1830 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1832 // If the parent SSLClientSocketNSS is deleted during the processing of the
1833 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
1834 // will be detached (and possibly deleted). Guard against deletion by taking
1835 // an extra reference, then check if the Core was detached before invoking the
1836 // next callback.
1837 scoped_refptr<Core> guard(this);
1838 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1839 DoReadCallback(rv_read);
1841 if (OnNetworkTaskRunner() && detached_)
1842 return;
1844 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1845 DoWriteCallback(rv_write);
1848 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
1849 // handshake. This requires network IO, which in turn calls
1850 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
1851 // winds its way through the state machine and ends up being passed to the
1852 // callback. For Read() and Write(), that's what we want. But for Connect(),
1853 // the caller expects OK (i.e. 0) for success.
1854 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
1855 DCHECK(OnNSSTaskRunner());
1856 DCHECK_NE(rv, ERR_IO_PENDING);
1857 DCHECK(!user_connect_callback_.is_null());
1859 base::Closure c = base::Bind(
1860 base::ResetAndReturn(&user_connect_callback_),
1861 rv > OK ? OK : rv);
1862 PostOrRunCallback(FROM_HERE, c);
1865 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
1866 DCHECK(OnNSSTaskRunner());
1867 DCHECK_NE(ERR_IO_PENDING, rv);
1868 DCHECK(!user_read_callback_.is_null());
1870 user_read_buf_ = NULL;
1871 user_read_buf_len_ = 0;
1872 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1873 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1874 // the network task runner.
1875 PostOrRunCallback(
1876 FROM_HERE,
1877 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1878 PostOrRunCallback(
1879 FROM_HERE,
1880 base::Bind(&Core::DidNSSRead, this, rv));
1881 PostOrRunCallback(
1882 FROM_HERE,
1883 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
1886 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
1887 DCHECK(OnNSSTaskRunner());
1888 DCHECK_NE(ERR_IO_PENDING, rv);
1889 DCHECK(!user_write_callback_.is_null());
1891 // Since Run may result in Write being called, clear |user_write_callback_|
1892 // up front.
1893 user_write_buf_ = NULL;
1894 user_write_buf_len_ = 0;
1895 // Update buffer status because DoWriteLoop called DoTransportIO which may
1896 // perform read operations.
1897 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1898 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1899 // the network task runner.
1900 PostOrRunCallback(
1901 FROM_HERE,
1902 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1903 PostOrRunCallback(
1904 FROM_HERE,
1905 base::Bind(&Core::DidNSSWrite, this, rv));
1906 PostOrRunCallback(
1907 FROM_HERE,
1908 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
1911 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
1912 void* arg,
1913 PRFileDesc* socket,
1914 SECKEYPublicKey **out_public_key,
1915 SECKEYPrivateKey **out_private_key) {
1916 Core* core = reinterpret_cast<Core*>(arg);
1917 DCHECK(core->OnNSSTaskRunner());
1919 core->PostOrRunCallback(
1920 FROM_HERE,
1921 base::Bind(&AddLogEvent, core->weak_net_log_,
1922 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
1924 // We have negotiated the TLS channel ID extension.
1925 core->channel_id_xtn_negotiated_ = true;
1926 std::string host = core->host_and_port_.host();
1927 int error = ERR_UNEXPECTED;
1928 if (core->OnNetworkTaskRunner()) {
1929 error = core->DoGetChannelID(host);
1930 } else {
1931 bool posted = core->network_task_runner_->PostTask(
1932 FROM_HERE,
1933 base::Bind(
1934 IgnoreResult(&Core::DoGetChannelID),
1935 core, host));
1936 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
1939 if (error == ERR_IO_PENDING) {
1940 // Asynchronous case.
1941 core->channel_id_needed_ = true;
1942 return SECWouldBlock;
1945 core->PostOrRunCallback(
1946 FROM_HERE,
1947 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
1948 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
1949 SECStatus rv = SECSuccess;
1950 if (error == OK) {
1951 // Synchronous success.
1952 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
1953 if (result == OK)
1954 core->SetChannelIDProvided();
1955 else
1956 rv = SECFailure;
1957 } else {
1958 rv = SECFailure;
1961 return rv;
1964 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
1965 SECKEYPrivateKey** key) {
1966 if (!channel_id_key_)
1967 return SECFailure;
1969 *public_key = SECKEY_CopyPublicKey(channel_id_key_->public_key());
1970 *key = SECKEY_CopyPrivateKey(channel_id_key_->key());
1972 return OK;
1975 void SSLClientSocketNSS::Core::UpdateServerCert() {
1976 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
1977 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
1978 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
1979 if (nss_handshake_state_.server_cert.get()) {
1980 // Since this will be called asynchronously on another thread, it needs to
1981 // own a reference to the certificate.
1982 NetLog::ParametersCallback net_log_callback =
1983 base::Bind(&NetLogX509CertificateCallback,
1984 nss_handshake_state_.server_cert);
1985 PostOrRunCallback(
1986 FROM_HERE,
1987 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1988 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1989 net_log_callback));
1993 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
1994 const SECItem* signed_cert_timestamps =
1995 SSL_PeerSignedCertTimestamps(nss_fd_);
1997 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
1998 return;
2000 nss_handshake_state_.sct_list_from_tls_extension = std::string(
2001 reinterpret_cast<char*>(signed_cert_timestamps->data),
2002 signed_cert_timestamps->len);
2005 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2006 PRBool ocsp_requested = PR_FALSE;
2007 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2008 const SECItemArray* ocsp_responses =
2009 SSL_PeerStapledOCSPResponses(nss_fd_);
2010 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2011 if (ocsp_requested)
2012 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2013 if (!ocsp_responses_present)
2014 return;
2016 nss_handshake_state_.stapled_ocsp_response = std::string(
2017 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2018 ocsp_responses->items[0].len);
2021 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2022 // Note: This function may be called multiple times for a single connection
2023 // if renegotiations occur.
2024 nss_handshake_state_.ssl_connection_status = 0;
2026 SSLChannelInfo channel_info;
2027 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2028 &channel_info, sizeof(channel_info));
2029 if (ok == SECSuccess &&
2030 channel_info.length == sizeof(channel_info) &&
2031 channel_info.cipherSuite) {
2032 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2034 nss_handshake_state_.ssl_connection_status |=
2035 (static_cast<int>(channel_info.compressionMethod) &
2036 SSL_CONNECTION_COMPRESSION_MASK) <<
2037 SSL_CONNECTION_COMPRESSION_SHIFT;
2039 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2040 if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2041 version = SSL_CONNECTION_VERSION_TLS1;
2042 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2043 version = SSL_CONNECTION_VERSION_TLS1_1;
2044 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2045 version = SSL_CONNECTION_VERSION_TLS1_2;
2047 DCHECK_NE(SSL_CONNECTION_VERSION_UNKNOWN, version);
2048 nss_handshake_state_.ssl_connection_status |=
2049 (version & SSL_CONNECTION_VERSION_MASK) <<
2050 SSL_CONNECTION_VERSION_SHIFT;
2053 PRBool peer_supports_renego_ext;
2054 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2055 &peer_supports_renego_ext);
2056 if (ok == SECSuccess) {
2057 if (!peer_supports_renego_ext) {
2058 nss_handshake_state_.ssl_connection_status |=
2059 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2060 // Log an informational message if the server does not support secure
2061 // renegotiation (RFC 5746).
2062 VLOG(1) << "The server " << host_and_port_.ToString()
2063 << " does not support the TLS renegotiation_info extension.";
2067 if (ssl_config_.version_fallback) {
2068 nss_handshake_state_.ssl_connection_status |=
2069 SSL_CONNECTION_VERSION_FALLBACK;
2073 void SSLClientSocketNSS::Core::UpdateNextProto() {
2074 uint8 buf[256];
2075 SSLNextProtoState state;
2076 unsigned buf_len;
2078 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2079 if (rv != SECSuccess)
2080 return;
2082 nss_handshake_state_.next_proto =
2083 std::string(reinterpret_cast<char*>(buf), buf_len);
2084 switch (state) {
2085 case SSL_NEXT_PROTO_NEGOTIATED:
2086 case SSL_NEXT_PROTO_SELECTED:
2087 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2088 break;
2089 case SSL_NEXT_PROTO_NO_OVERLAP:
2090 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2091 break;
2092 case SSL_NEXT_PROTO_NO_SUPPORT:
2093 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2094 break;
2095 default:
2096 NOTREACHED();
2097 break;
2101 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2102 PRBool negotiated_extension;
2103 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2104 ssl_app_layer_protocol_xtn,
2105 &negotiated_extension);
2106 if (rv == SECSuccess && negotiated_extension) {
2107 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2108 } else {
2109 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2110 ssl_next_proto_nego_xtn,
2111 &negotiated_extension);
2112 if (rv == SECSuccess && negotiated_extension) {
2113 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2118 bool SSLClientSocketNSS::Core::IsRenegotiationAllowed() const {
2119 DCHECK(OnNSSTaskRunner());
2121 if (nss_handshake_state_.next_proto_status == kNextProtoUnsupported)
2122 return ssl_config_.renego_allowed_default;
2124 NextProto next_proto = NextProtoFromString(nss_handshake_state_.next_proto);
2125 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
2126 if (next_proto == allowed)
2127 return true;
2129 return false;
2132 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2133 DCHECK(OnNSSTaskRunner());
2134 if (nss_handshake_state_.resumed_handshake)
2135 return;
2137 // Copy the NSS task runner-only state to the network task runner and
2138 // log histograms from there, since the histograms also need access to the
2139 // network task runner state.
2140 PostOrRunCallback(
2141 FROM_HERE,
2142 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2143 this,
2144 channel_id_xtn_negotiated_,
2145 ssl_config_.channel_id_enabled,
2146 crypto::ECPrivateKey::IsSupported()));
2149 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2150 bool negotiated_channel_id,
2151 bool channel_id_enabled,
2152 bool supports_ecc) const {
2153 DCHECK(OnNetworkTaskRunner());
2155 RecordChannelIDSupport(channel_id_service_,
2156 negotiated_channel_id,
2157 channel_id_enabled,
2158 supports_ecc);
2161 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2162 DCHECK(OnNetworkTaskRunner());
2163 DCHECK_GT(len, 0);
2165 if (detached_)
2166 return ERR_ABORTED;
2168 int rv = transport_->socket()->Read(
2169 read_buffer, len,
2170 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2171 scoped_refptr<IOBuffer>(read_buffer)));
2173 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2174 nss_task_runner_->PostTask(
2175 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2176 scoped_refptr<IOBuffer>(read_buffer), rv));
2177 return rv;
2180 return rv;
2183 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2184 DCHECK(OnNetworkTaskRunner());
2185 DCHECK_GT(len, 0);
2187 if (detached_)
2188 return ERR_ABORTED;
2190 int rv = transport_->socket()->Write(
2191 send_buffer, len,
2192 base::Bind(&Core::BufferSendComplete,
2193 base::Unretained(this)));
2195 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2196 nss_task_runner_->PostTask(
2197 FROM_HERE,
2198 base::Bind(&Core::BufferSendComplete, this, rv));
2199 return rv;
2202 return rv;
2205 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2206 DCHECK(OnNetworkTaskRunner());
2208 if (detached_)
2209 return ERR_ABORTED;
2211 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2213 int rv = channel_id_service_->GetOrCreateChannelID(
2214 host, &channel_id_key_,
2215 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2216 &channel_id_request_);
2218 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2219 nss_task_runner_->PostTask(
2220 FROM_HERE,
2221 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2222 return ERR_IO_PENDING;
2225 return rv;
2228 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2229 const HandshakeState& state) {
2230 DCHECK(OnNetworkTaskRunner());
2231 network_handshake_state_ = state;
2234 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2235 DCHECK(OnNetworkTaskRunner());
2236 unhandled_buffer_size_ = amount_in_read_buffer;
2239 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2240 DCHECK(OnNetworkTaskRunner());
2241 DCHECK(nss_waiting_read_);
2242 nss_waiting_read_ = false;
2243 if (result <= 0) {
2244 nss_is_closed_ = true;
2245 } else {
2246 was_ever_used_ = true;
2250 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2251 DCHECK(OnNetworkTaskRunner());
2252 DCHECK(nss_waiting_write_);
2253 nss_waiting_write_ = false;
2254 if (result < 0) {
2255 nss_is_closed_ = true;
2256 } else if (result > 0) {
2257 was_ever_used_ = true;
2261 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2262 if (!OnNSSTaskRunner()) {
2263 if (detached_)
2264 return;
2266 nss_task_runner_->PostTask(
2267 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2268 return;
2271 DCHECK(OnNSSTaskRunner());
2273 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2274 transport_send_busy_ = false;
2275 OnSendComplete(result);
2278 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2279 if (!OnNSSTaskRunner()) {
2280 if (detached_)
2281 return;
2283 nss_task_runner_->PostTask(
2284 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2285 return;
2288 DCHECK(OnNSSTaskRunner());
2290 int rv = DoHandshakeLoop(result);
2291 if (rv != ERR_IO_PENDING)
2292 DoConnectCallback(rv);
2295 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2296 DVLOG(1) << __FUNCTION__ << " " << result;
2297 DCHECK(OnNetworkTaskRunner());
2299 OnHandshakeIOComplete(result);
2302 void SSLClientSocketNSS::Core::BufferRecvComplete(
2303 IOBuffer* read_buffer,
2304 int result) {
2305 DCHECK(read_buffer);
2307 if (!OnNSSTaskRunner()) {
2308 if (detached_)
2309 return;
2311 nss_task_runner_->PostTask(
2312 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2313 scoped_refptr<IOBuffer>(read_buffer), result));
2314 return;
2317 DCHECK(OnNSSTaskRunner());
2319 if (result > 0) {
2320 char* buf;
2321 int nb = memio_GetReadParams(nss_bufs_, &buf);
2322 CHECK_GE(nb, result);
2323 memcpy(buf, read_buffer->data(), result);
2324 } else if (result == 0) {
2325 transport_recv_eof_ = true;
2328 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2329 transport_recv_busy_ = false;
2330 OnRecvComplete(result);
2333 void SSLClientSocketNSS::Core::PostOrRunCallback(
2334 const tracked_objects::Location& location,
2335 const base::Closure& task) {
2336 if (!OnNetworkTaskRunner()) {
2337 network_task_runner_->PostTask(
2338 FROM_HERE,
2339 base::Bind(&Core::PostOrRunCallback, this, location, task));
2340 return;
2343 if (detached_ || task.is_null())
2344 return;
2345 task.Run();
2348 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2349 PostOrRunCallback(
2350 FROM_HERE,
2351 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2352 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2353 NetLog::IntegerCallback("cert_count", cert_count)));
2356 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2357 PostOrRunCallback(
2358 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2359 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2360 nss_handshake_state_.channel_id_sent = true;
2361 // Update the network task runner's view of the handshake state now that
2362 // channel id has been sent.
2363 PostOrRunCallback(
2364 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2365 nss_handshake_state_));
2368 SSLClientSocketNSS::SSLClientSocketNSS(
2369 base::SequencedTaskRunner* nss_task_runner,
2370 scoped_ptr<ClientSocketHandle> transport_socket,
2371 const HostPortPair& host_and_port,
2372 const SSLConfig& ssl_config,
2373 const SSLClientSocketContext& context)
2374 : nss_task_runner_(nss_task_runner),
2375 transport_(transport_socket.Pass()),
2376 host_and_port_(host_and_port),
2377 ssl_config_(ssl_config),
2378 cert_verifier_(context.cert_verifier),
2379 cert_transparency_verifier_(context.cert_transparency_verifier),
2380 channel_id_service_(context.channel_id_service),
2381 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2382 completed_handshake_(false),
2383 next_handshake_state_(STATE_NONE),
2384 nss_fd_(NULL),
2385 net_log_(transport_->socket()->NetLog()),
2386 transport_security_state_(context.transport_security_state),
2387 policy_enforcer_(context.cert_policy_enforcer),
2388 valid_thread_id_(base::kInvalidThreadId) {
2389 DCHECK(cert_verifier_);
2391 EnterFunction("");
2392 InitCore();
2393 LeaveFunction("");
2396 SSLClientSocketNSS::~SSLClientSocketNSS() {
2397 EnterFunction("");
2398 Disconnect();
2399 LeaveFunction("");
2402 // static
2403 void SSLClientSocket::ClearSessionCache() {
2404 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2405 // bother initializing NSS just to clear an empty SSL session cache.
2406 if (!NSS_IsInitialized())
2407 return;
2409 SSL_ClearSessionCache();
2412 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2413 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2414 #endif
2416 // static
2417 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
2418 crypto::EnsureNSSInit();
2419 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) {
2420 return SSL_PROTOCOL_VERSION_TLS1_2;
2421 } else {
2422 return SSL_PROTOCOL_VERSION_TLS1_1;
2426 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2427 EnterFunction("");
2428 ssl_info->Reset();
2429 if (core_->state().server_cert_chain.empty() ||
2430 !core_->state().server_cert_chain[0]) {
2431 return false;
2434 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2435 ssl_info->cert = server_cert_verify_result_.verified_cert;
2436 ssl_info->unverified_cert = core_->state().server_cert;
2438 AddSCTInfoToSSLInfo(ssl_info);
2440 ssl_info->connection_status =
2441 core_->state().ssl_connection_status;
2442 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2443 ssl_info->is_issued_by_known_root =
2444 server_cert_verify_result_.is_issued_by_known_root;
2445 ssl_info->client_cert_sent =
2446 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2447 ssl_info->channel_id_sent = core_->state().channel_id_sent;
2448 ssl_info->pinning_failure_log = pinning_failure_log_;
2450 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2451 core_->state().ssl_connection_status);
2452 SSLCipherSuiteInfo cipher_info;
2453 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2454 &cipher_info, sizeof(cipher_info));
2455 if (ok == SECSuccess) {
2456 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2457 } else {
2458 ssl_info->security_bits = -1;
2459 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2460 << " for cipherSuite " << cipher_suite;
2463 ssl_info->handshake_type = core_->state().resumed_handshake ?
2464 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2466 LeaveFunction("");
2467 return true;
2470 void SSLClientSocketNSS::GetConnectionAttempts(ConnectionAttempts* out) const {
2471 out->clear();
2474 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2475 SSLCertRequestInfo* cert_request_info) {
2476 EnterFunction("");
2477 cert_request_info->host_and_port = host_and_port_;
2478 cert_request_info->cert_authorities = core_->state().cert_authorities;
2479 LeaveFunction("");
2482 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2483 bool has_context,
2484 const base::StringPiece& context,
2485 unsigned char* out,
2486 unsigned int outlen) {
2487 if (!IsConnected())
2488 return ERR_SOCKET_NOT_CONNECTED;
2490 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2491 // the midst of a handshake.
2492 SECStatus result = SSL_ExportKeyingMaterial(
2493 nss_fd_, label.data(), label.size(), has_context,
2494 reinterpret_cast<const unsigned char*>(context.data()),
2495 context.length(), out, outlen);
2496 if (result != SECSuccess) {
2497 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2498 return MapNSSError(PORT_GetError());
2500 return OK;
2503 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2504 if (!IsConnected())
2505 return ERR_SOCKET_NOT_CONNECTED;
2506 unsigned char buf[64];
2507 unsigned int len;
2508 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2509 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2510 buf, &len, arraysize(buf));
2511 if (result != SECSuccess) {
2512 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2513 return MapNSSError(PORT_GetError());
2515 out->assign(reinterpret_cast<char*>(buf), len);
2516 return OK;
2519 SSLClientSocket::NextProtoStatus SSLClientSocketNSS::GetNextProto(
2520 std::string* proto) const {
2521 *proto = core_->state().next_proto;
2522 return core_->state().next_proto_status;
2525 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2526 EnterFunction("");
2527 DCHECK(transport_.get());
2528 // It is an error to create an SSLClientSocket whose context has no
2529 // TransportSecurityState.
2530 DCHECK(transport_security_state_);
2531 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2532 DCHECK(user_connect_callback_.is_null());
2533 DCHECK(!callback.is_null());
2535 EnsureThreadIdAssigned();
2537 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2539 int rv = Init();
2540 if (rv != OK) {
2541 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2542 return rv;
2545 rv = InitializeSSLOptions();
2546 if (rv != OK) {
2547 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2548 return rv;
2551 rv = InitializeSSLPeerName();
2552 if (rv != OK) {
2553 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2554 return rv;
2557 GotoState(STATE_HANDSHAKE);
2559 rv = DoHandshakeLoop(OK);
2560 if (rv == ERR_IO_PENDING) {
2561 user_connect_callback_ = callback;
2562 } else {
2563 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2566 LeaveFunction("");
2567 return rv > OK ? OK : rv;
2570 void SSLClientSocketNSS::Disconnect() {
2571 EnterFunction("");
2573 CHECK(CalledOnValidThread());
2575 // Shut down anything that may call us back.
2576 core_->Detach();
2577 cert_verifier_request_.reset();
2578 transport_->socket()->Disconnect();
2580 // Reset object state.
2581 user_connect_callback_.Reset();
2582 server_cert_verify_result_.Reset();
2583 completed_handshake_ = false;
2584 start_cert_verification_time_ = base::TimeTicks();
2585 InitCore();
2587 LeaveFunction("");
2590 bool SSLClientSocketNSS::IsConnected() const {
2591 EnterFunction("");
2592 bool ret = completed_handshake_ &&
2593 (core_->HasPendingAsyncOperation() ||
2594 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2595 transport_->socket()->IsConnected());
2596 LeaveFunction("");
2597 return ret;
2600 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2601 EnterFunction("");
2602 bool ret = completed_handshake_ &&
2603 !core_->HasPendingAsyncOperation() &&
2604 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
2605 transport_->socket()->IsConnectedAndIdle();
2606 LeaveFunction("");
2607 return ret;
2610 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
2611 return transport_->socket()->GetPeerAddress(address);
2614 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
2615 return transport_->socket()->GetLocalAddress(address);
2618 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
2619 return net_log_;
2622 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2623 if (transport_.get() && transport_->socket()) {
2624 transport_->socket()->SetSubresourceSpeculation();
2625 } else {
2626 NOTREACHED();
2630 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2631 if (transport_.get() && transport_->socket()) {
2632 transport_->socket()->SetOmniboxSpeculation();
2633 } else {
2634 NOTREACHED();
2638 bool SSLClientSocketNSS::WasEverUsed() const {
2639 DCHECK(core_.get());
2641 return core_->WasEverUsed();
2644 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2645 if (transport_.get() && transport_->socket()) {
2646 return transport_->socket()->UsingTCPFastOpen();
2648 NOTREACHED();
2649 return false;
2652 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
2653 const CompletionCallback& callback) {
2654 DCHECK(core_.get());
2655 DCHECK(!callback.is_null());
2657 EnterFunction(buf_len);
2658 int rv = core_->Read(buf, buf_len, callback);
2659 LeaveFunction(rv);
2661 return rv;
2664 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
2665 const CompletionCallback& callback) {
2666 DCHECK(core_.get());
2667 DCHECK(!callback.is_null());
2669 EnterFunction(buf_len);
2670 int rv = core_->Write(buf, buf_len, callback);
2671 LeaveFunction(rv);
2673 return rv;
2676 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
2677 return transport_->socket()->SetReceiveBufferSize(size);
2680 int SSLClientSocketNSS::SetSendBufferSize(int32 size) {
2681 return transport_->socket()->SetSendBufferSize(size);
2684 int SSLClientSocketNSS::Init() {
2685 EnterFunction("");
2686 // Initialize the NSS SSL library in a threadsafe way. This also
2687 // initializes the NSS base library.
2688 EnsureNSSSSLInit();
2689 if (!NSS_IsInitialized())
2690 return ERR_UNEXPECTED;
2691 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
2692 if (ssl_config_.cert_io_enabled) {
2693 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
2694 // loop by MessageLoopForIO::current().
2695 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
2696 EnsureNSSHttpIOInit();
2698 #endif
2700 LeaveFunction("");
2701 return OK;
2704 void SSLClientSocketNSS::InitCore() {
2705 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
2706 nss_task_runner_.get(),
2707 transport_.get(),
2708 host_and_port_,
2709 ssl_config_,
2710 &net_log_,
2711 channel_id_service_);
2714 int SSLClientSocketNSS::InitializeSSLOptions() {
2715 // Transport connected, now hook it up to nss
2716 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
2717 if (nss_fd_ == NULL) {
2718 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
2721 // Grab pointer to buffers
2722 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
2724 /* Create SSL state machine */
2725 /* Push SSL onto our fake I/O socket */
2726 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
2727 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
2728 PR_Close(nss_fd_);
2729 nss_fd_ = NULL;
2730 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
2732 // TODO(port): set more ssl options! Check errors!
2734 int rv;
2736 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
2737 if (rv != SECSuccess) {
2738 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
2739 return ERR_UNEXPECTED;
2742 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
2743 if (rv != SECSuccess) {
2744 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
2745 return ERR_UNEXPECTED;
2748 // Don't do V2 compatible hellos because they don't support TLS extensions.
2749 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
2750 if (rv != SECSuccess) {
2751 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
2752 return ERR_UNEXPECTED;
2755 SSLVersionRange version_range;
2756 version_range.min = ssl_config_.version_min;
2757 version_range.max = ssl_config_.version_max;
2758 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
2759 if (rv != SECSuccess) {
2760 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
2761 return ERR_NO_SSL_VERSIONS_ENABLED;
2764 if (ssl_config_.require_ecdhe) {
2765 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2766 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2768 // Iterate over the cipher suites and disable those that don't use ECDHE.
2769 for (unsigned i = 0; i < num_ciphers; i++) {
2770 SSLCipherSuiteInfo info;
2771 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) ==
2772 SECSuccess) {
2773 if (strcmp(info.keaTypeName, "ECDHE") != 0) {
2774 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2780 if (ssl_config_.version_fallback) {
2781 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
2782 if (rv != SECSuccess) {
2783 LogFailedNSSFunction(
2784 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
2788 for (std::vector<uint16>::const_iterator it =
2789 ssl_config_.disabled_cipher_suites.begin();
2790 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
2791 // This will fail if the specified cipher is not implemented by NSS, but
2792 // the failure is harmless.
2793 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
2796 if (!ssl_config_.enable_deprecated_cipher_suites) {
2797 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2798 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2799 for (int i = 0; i < num_ciphers; i++) {
2800 SSLCipherSuiteInfo info;
2801 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) !=
2802 SECSuccess) {
2803 continue;
2805 if (info.symCipher == ssl_calg_rc4)
2806 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2810 // Support RFC 5077
2811 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
2812 if (rv != SECSuccess) {
2813 LogFailedNSSFunction(
2814 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
2817 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
2818 ssl_config_.false_start_enabled);
2819 if (rv != SECSuccess)
2820 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
2822 // By default, renegotiations are rejected. After the initial handshake
2823 // completes, some application protocols may re-enable it.
2824 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION, SSL_RENEGOTIATE_NEVER);
2825 if (rv != SECSuccess) {
2826 LogFailedNSSFunction(
2827 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
2830 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
2831 if (rv != SECSuccess)
2832 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
2834 // Added in NSS 3.15
2835 #ifdef SSL_ENABLE_OCSP_STAPLING
2836 // Request OCSP stapling even on platforms that don't support it, in
2837 // order to extract Certificate Transparency information.
2838 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
2839 cert_verifier_->SupportsOCSPStapling() ||
2840 ssl_config_.signed_cert_timestamps_enabled);
2841 if (rv != SECSuccess) {
2842 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2843 "SSL_ENABLE_OCSP_STAPLING");
2845 #endif
2847 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
2848 ssl_config_.signed_cert_timestamps_enabled);
2849 if (rv != SECSuccess) {
2850 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2851 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
2854 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
2855 if (rv != SECSuccess) {
2856 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
2857 return ERR_UNEXPECTED;
2860 if (!core_->Init(nss_fd_, nss_bufs))
2861 return ERR_UNEXPECTED;
2863 // Tell SSL the hostname we're trying to connect to.
2864 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
2866 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
2867 SSL_ResetHandshake(nss_fd_, PR_FALSE);
2869 return OK;
2872 int SSLClientSocketNSS::InitializeSSLPeerName() {
2873 // Tell NSS who we're connected to
2874 IPEndPoint peer_address;
2875 int err = transport_->socket()->GetPeerAddress(&peer_address);
2876 if (err != OK)
2877 return err;
2879 SockaddrStorage storage;
2880 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
2881 return ERR_ADDRESS_INVALID;
2883 PRNetAddr peername;
2884 memset(&peername, 0, sizeof(peername));
2885 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
2886 size_t len = std::min(static_cast<size_t>(storage.addr_len),
2887 sizeof(peername));
2888 memcpy(&peername, storage.addr, len);
2890 // Adjust the address family field for BSD, whose sockaddr
2891 // structure has a one-byte length and one-byte address family
2892 // field at the beginning. PRNetAddr has a two-byte address
2893 // family field at the beginning.
2894 peername.raw.family = storage.addr->sa_family;
2896 memio_SetPeerName(nss_fd_, &peername);
2898 // Set the peer ID for session reuse. This is necessary when we create an
2899 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
2900 // rather than the destination server's address in that case.
2901 std::string peer_id = host_and_port_.ToString();
2902 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
2903 // the session cache for incognito mode.
2904 peer_id += "/" + ssl_session_cache_shard_;
2905 peer_id += "/";
2906 // Shard the session cache based on maximum protocol version. This causes
2907 // fallback connections to use a separate session cache.
2908 switch (ssl_config_.version_max) {
2909 case SSL_PROTOCOL_VERSION_TLS1:
2910 peer_id += "tls1";
2911 break;
2912 case SSL_PROTOCOL_VERSION_TLS1_1:
2913 peer_id += "tls1.1";
2914 break;
2915 case SSL_PROTOCOL_VERSION_TLS1_2:
2916 peer_id += "tls1.2";
2917 break;
2918 default:
2919 NOTREACHED();
2921 peer_id += "/";
2922 if (ssl_config_.enable_deprecated_cipher_suites)
2923 peer_id += "deprecated";
2925 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
2926 if (rv != SECSuccess)
2927 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
2929 return OK;
2932 void SSLClientSocketNSS::DoConnectCallback(int rv) {
2933 EnterFunction(rv);
2934 DCHECK_NE(ERR_IO_PENDING, rv);
2935 DCHECK(!user_connect_callback_.is_null());
2937 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
2938 LeaveFunction("");
2941 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
2942 EnterFunction(result);
2943 int rv = DoHandshakeLoop(result);
2944 if (rv != ERR_IO_PENDING) {
2945 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2946 DoConnectCallback(rv);
2948 LeaveFunction("");
2951 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
2952 EnterFunction(last_io_result);
2953 int rv = last_io_result;
2954 do {
2955 // Default to STATE_NONE for next state.
2956 // (This is a quirk carried over from the windows
2957 // implementation. It makes reading the logs a bit harder.)
2958 // State handlers can and often do call GotoState just
2959 // to stay in the current state.
2960 State state = next_handshake_state_;
2961 GotoState(STATE_NONE);
2962 switch (state) {
2963 case STATE_HANDSHAKE:
2964 rv = DoHandshake();
2965 break;
2966 case STATE_HANDSHAKE_COMPLETE:
2967 rv = DoHandshakeComplete(rv);
2968 break;
2969 case STATE_VERIFY_CERT:
2970 DCHECK(rv == OK);
2971 rv = DoVerifyCert(rv);
2972 break;
2973 case STATE_VERIFY_CERT_COMPLETE:
2974 rv = DoVerifyCertComplete(rv);
2975 break;
2976 case STATE_NONE:
2977 default:
2978 rv = ERR_UNEXPECTED;
2979 LOG(DFATAL) << "unexpected state " << state;
2980 break;
2982 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
2983 LeaveFunction("");
2984 return rv;
2987 int SSLClientSocketNSS::DoHandshake() {
2988 EnterFunction("");
2989 int rv = core_->Connect(
2990 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
2991 base::Unretained(this)));
2992 GotoState(STATE_HANDSHAKE_COMPLETE);
2994 LeaveFunction(rv);
2995 return rv;
2998 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
2999 EnterFunction(result);
3001 if (result == OK) {
3002 if (ssl_config_.version_fallback &&
3003 ssl_config_.version_max < ssl_config_.version_fallback_min) {
3004 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
3007 RecordNegotiationExtension();
3009 // SSL handshake is completed. Let's verify the certificate.
3010 GotoState(STATE_VERIFY_CERT);
3011 // Done!
3013 set_signed_cert_timestamps_received(
3014 !core_->state().sct_list_from_tls_extension.empty());
3015 set_stapled_ocsp_response_received(
3016 !core_->state().stapled_ocsp_response.empty());
3017 set_negotiation_extension(core_->state().negotiation_extension_);
3019 LeaveFunction(result);
3020 return result;
3023 int SSLClientSocketNSS::DoVerifyCert(int result) {
3024 DCHECK(!core_->state().server_cert_chain.empty());
3025 DCHECK(core_->state().server_cert_chain[0]);
3027 GotoState(STATE_VERIFY_CERT_COMPLETE);
3029 // If the certificate is expected to be bad we can use the expectation as
3030 // the cert status.
3031 base::StringPiece der_cert(
3032 reinterpret_cast<char*>(
3033 core_->state().server_cert_chain[0]->derCert.data),
3034 core_->state().server_cert_chain[0]->derCert.len);
3035 CertStatus cert_status;
3036 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3037 DCHECK(start_cert_verification_time_.is_null());
3038 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3039 server_cert_verify_result_.Reset();
3040 server_cert_verify_result_.cert_status = cert_status;
3041 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3042 return OK;
3045 // We may have failed to create X509Certificate object if we are
3046 // running inside sandbox.
3047 if (!core_->state().server_cert.get()) {
3048 server_cert_verify_result_.Reset();
3049 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3050 return ERR_CERT_INVALID;
3053 start_cert_verification_time_ = base::TimeTicks::Now();
3055 return cert_verifier_->Verify(
3056 core_->state().server_cert.get(), host_and_port_.host(),
3057 core_->state().stapled_ocsp_response, ssl_config_.GetCertVerifyFlags(),
3058 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
3059 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3060 base::Unretained(this)),
3061 &cert_verifier_request_, net_log_);
3064 // Derived from AuthCertificateCallback() in
3065 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3066 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3067 cert_verifier_request_.reset();
3069 if (!start_cert_verification_time_.is_null()) {
3070 base::TimeDelta verify_time =
3071 base::TimeTicks::Now() - start_cert_verification_time_;
3072 if (result == OK)
3073 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3074 else
3075 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3078 // We used to remember the intermediate CA certs in the NSS database
3079 // persistently. However, NSS opens a connection to the SQLite database
3080 // during NSS initialization and doesn't close the connection until NSS
3081 // shuts down. If the file system where the database resides is gone,
3082 // the database connection goes bad. What's worse, the connection won't
3083 // recover when the file system comes back. Until this NSS or SQLite bug
3084 // is fixed, we need to avoid using the NSS database for non-essential
3085 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3086 // http://crbug.com/15630 for more info.
3088 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3089 if (transport_security_state_ &&
3090 (result == OK ||
3091 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3092 !transport_security_state_->CheckPublicKeyPins(
3093 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
3094 server_cert_verify_result_.public_key_hashes,
3095 core_->state().server_cert.get(),
3096 server_cert_verify_result_.verified_cert.get(),
3097 TransportSecurityState::ENABLE_PIN_REPORTS, &pinning_failure_log_)) {
3098 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3101 if (result == OK) {
3102 // Only check Certificate Transparency if there were no other errors with
3103 // the connection.
3104 VerifyCT();
3106 // Only cache the session if the certificate verified successfully.
3107 core_->CacheSessionIfNecessary();
3110 completed_handshake_ = true;
3112 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3113 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3114 return result;
3117 void SSLClientSocketNSS::VerifyCT() {
3118 if (!cert_transparency_verifier_)
3119 return;
3121 // Note that this is a completely synchronous operation: The CT Log Verifier
3122 // gets all the data it needs for SCT verification and does not do any
3123 // external communication.
3124 cert_transparency_verifier_->Verify(
3125 server_cert_verify_result_.verified_cert.get(),
3126 core_->state().stapled_ocsp_response,
3127 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3128 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3129 // from the state after verification is complete, to conserve memory.
3131 if (policy_enforcer_ &&
3132 (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV)) {
3133 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3134 SSLConfigService::GetEVCertsWhitelist();
3135 if (!policy_enforcer_->DoesConformToCTEVPolicy(
3136 server_cert_verify_result_.verified_cert.get(), ev_whitelist.get(),
3137 ct_verify_result_, net_log_)) {
3138 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3139 VLOG(1) << "EV certificate for "
3140 << server_cert_verify_result_.verified_cert->subject()
3141 .GetDisplayName()
3142 << " does not conform to CT policy, removing EV status.";
3143 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3148 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3149 base::AutoLock auto_lock(lock_);
3150 if (valid_thread_id_ != base::kInvalidThreadId)
3151 return;
3152 valid_thread_id_ = base::PlatformThread::CurrentId();
3155 bool SSLClientSocketNSS::CalledOnValidThread() const {
3156 EnsureThreadIdAssigned();
3157 base::AutoLock auto_lock(lock_);
3158 return valid_thread_id_ == base::PlatformThread::CurrentId();
3161 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3162 for (ct::SCTList::const_iterator iter =
3163 ct_verify_result_.verified_scts.begin();
3164 iter != ct_verify_result_.verified_scts.end(); ++iter) {
3165 ssl_info->signed_certificate_timestamps.push_back(
3166 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
3168 for (ct::SCTList::const_iterator iter =
3169 ct_verify_result_.invalid_scts.begin();
3170 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
3171 ssl_info->signed_certificate_timestamps.push_back(
3172 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
3174 for (ct::SCTList::const_iterator iter =
3175 ct_verify_result_.unknown_logs_scts.begin();
3176 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
3177 ssl_info->signed_certificate_timestamps.push_back(
3178 SignedCertificateTimestampAndStatus(*iter,
3179 ct::SCT_STATUS_LOG_UNKNOWN));
3183 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3184 return channel_id_service_;
3187 SSLFailureState SSLClientSocketNSS::GetSSLFailureState() const {
3188 if (completed_handshake_)
3189 return SSL_FAILURE_NONE;
3190 return SSL_FAILURE_UNKNOWN;
3193 } // namespace net