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
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.
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"
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.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_info.h"
111 #if defined(USE_NSS_CERTS)
117 // State machines are easier to debug if you log state transitions.
118 // Enable these if you want to see what's going on.
120 #define EnterFunction(x)
121 #define LeaveFunction(x)
122 #define GotoState(s) next_handshake_state_ = s
124 #define EnterFunction(x)\
125 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
126 << "; next_handshake_state " << next_handshake_state_
127 #define LeaveFunction(x)\
128 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
129 << "; next_handshake_state " << next_handshake_state_
130 #define GotoState(s)\
132 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
133 next_handshake_state_ = s;\
137 #if !defined(CKM_AES_GCM)
138 #define CKM_AES_GCM 0x00001087
141 #if !defined(CKM_NSS_CHACHA20_POLY1305)
142 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
147 // SSL plaintext fragments are shorter than 16KB. Although the record layer
148 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
149 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
150 // entire SSL record.
151 const int kRecvBufferSize
= 17 * 1024;
152 const int kSendBufferSize
= 17 * 1024;
154 // Used by SSLClientSocketNSS::Core to indicate there is no read result
155 // obtained by a previous operation waiting to be returned to the caller.
156 // This constant can be any non-negative/non-zero value (eg: it does not
157 // overlap with any value of the net::Error range, including net::OK).
158 const int kNoPendingReadResult
= 1;
160 // Helper functions to make it possible to log events from within the
161 // SSLClientSocketNSS::Core.
162 void AddLogEvent(const base::WeakPtr
<BoundNetLog
>& net_log
,
163 NetLog::EventType event_type
) {
166 net_log
->AddEvent(event_type
);
169 // Helper function to make it possible to log events from within the
170 // SSLClientSocketNSS::Core.
171 void AddLogEventWithCallback(const base::WeakPtr
<BoundNetLog
>& net_log
,
172 NetLog::EventType event_type
,
173 const NetLog::ParametersCallback
& callback
) {
176 net_log
->AddEvent(event_type
, callback
);
179 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
180 // from within the SSLClientSocketNSS::Core.
181 // AddByteTransferEvent expects to receive a const char*, which within the
182 // Core is backed by an IOBuffer. If the "const char*" is bound via
183 // base::Bind and posted to another thread, and the IOBuffer that backs that
184 // pointer then goes out of scope on the origin thread, this would result in
185 // an invalid read of a stale pointer.
186 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
187 // to the owning IOBuffer can be bound to the Callback. This ensures that the
188 // IOBuffer will stay alive long enough to cross threads if needed.
189 void LogByteTransferEvent(
190 const base::WeakPtr
<BoundNetLog
>& net_log
, NetLog::EventType event_type
,
191 int len
, IOBuffer
* buffer
) {
194 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
197 // PeerCertificateChain is a helper object which extracts the certificate
198 // chain, as given by the server, from an NSS socket and performs the needed
199 // resource management. The first element of the chain is the leaf certificate
200 // and the other elements are in the order given by the server.
201 class PeerCertificateChain
{
203 PeerCertificateChain() {}
204 PeerCertificateChain(const PeerCertificateChain
& other
);
205 ~PeerCertificateChain();
206 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
208 // Resets the current chain, freeing any resources, and updates the current
209 // chain to be a copy of the chain stored in |nss_fd|.
210 // If |nss_fd| is NULL, then the current certificate chain will be freed.
211 void Reset(PRFileDesc
* nss_fd
);
213 // Returns the current certificate chain as a vector of DER-encoded
214 // base::StringPieces. The returned vector remains valid until Reset is
216 std::vector
<base::StringPiece
> AsStringPieceVector() const;
218 bool empty() const { return certs_
.empty(); }
220 CERTCertificate
* operator[](size_t index
) const {
221 DCHECK_LT(index
, certs_
.size());
222 return certs_
[index
];
226 std::vector
<CERTCertificate
*> certs_
;
229 PeerCertificateChain::PeerCertificateChain(
230 const PeerCertificateChain
& other
) {
234 PeerCertificateChain::~PeerCertificateChain() {
238 PeerCertificateChain
& PeerCertificateChain::operator=(
239 const PeerCertificateChain
& other
) {
244 certs_
.reserve(other
.certs_
.size());
245 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
246 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
251 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
252 for (size_t i
= 0; i
< certs_
.size(); ++i
)
253 CERT_DestroyCertificate(certs_
[i
]);
259 CERTCertList
* list
= SSL_PeerCertificateChain(nss_fd
);
260 // The handshake on |nss_fd| may not have completed.
264 for (CERTCertListNode
* node
= CERT_LIST_HEAD(list
);
265 !CERT_LIST_END(node
, list
); node
= CERT_LIST_NEXT(node
)) {
266 certs_
.push_back(CERT_DupCertificate(node
->cert
));
268 CERT_DestroyCertList(list
);
271 std::vector
<base::StringPiece
>
272 PeerCertificateChain::AsStringPieceVector() const {
273 std::vector
<base::StringPiece
> v(certs_
.size());
274 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
275 v
[i
] = base::StringPiece(
276 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
277 certs_
[i
]->derCert
.len
);
283 // HandshakeState is a helper struct used to pass handshake state between
284 // the NSS task runner and the network task runner.
286 // It contains members that may be read or written on the NSS task runner,
287 // but which also need to be read from the network task runner. The NSS task
288 // runner will notify the network task runner whenever this state changes, so
289 // that the network task runner can safely make a copy, which avoids the need
291 struct HandshakeState
{
292 HandshakeState() { Reset(); }
295 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
297 negotiation_extension_
= SSLClientSocket::kExtensionUnknown
;
298 channel_id_sent
= false;
299 server_cert_chain
.Reset(NULL
);
301 sct_list_from_tls_extension
.clear();
302 stapled_ocsp_response
.clear();
303 resumed_handshake
= false;
304 ssl_connection_status
= 0;
307 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
308 // negotiated protocol stored in |next_proto|.
309 SSLClientSocket::NextProtoStatus next_proto_status
;
310 std::string next_proto
;
312 // TLS extension used for protocol negotiation.
313 SSLClientSocket::SSLNegotiationExtension negotiation_extension_
;
315 // True if a channel ID was sent.
316 bool channel_id_sent
;
318 // List of DER-encoded X.509 DistinguishedName of certificate authorities
319 // allowed by the server.
320 std::vector
<std::string
> cert_authorities
;
322 // Set when the handshake fully completes.
324 // The server certificate is first received from NSS as an NSS certificate
325 // chain (|server_cert_chain|) and then converted into a platform-specific
326 // X509Certificate object (|server_cert|). It's possible for some
327 // certificates to be successfully parsed by NSS, and not by the platform
328 // libraries (i.e.: when running within a sandbox, different parsing
329 // algorithms, etc), so it's not safe to assume that |server_cert| will
330 // always be non-NULL.
331 PeerCertificateChain server_cert_chain
;
332 scoped_refptr
<X509Certificate
> server_cert
;
333 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
334 std::string sct_list_from_tls_extension
;
335 // Stapled OCSP response received.
336 std::string stapled_ocsp_response
;
338 // True if the current handshake was the result of TLS session resumption.
339 bool resumed_handshake
;
341 // The negotiated security parameters (TLS version, cipher, extensions) of
342 // the SSL connection.
343 int ssl_connection_status
;
346 // Client-side error mapping functions.
348 // Map NSS error code to network error code.
349 int MapNSSClientError(PRErrorCode err
) {
351 case SSL_ERROR_BAD_CERT_ALERT
:
352 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
353 case SSL_ERROR_REVOKED_CERT_ALERT
:
354 case SSL_ERROR_EXPIRED_CERT_ALERT
:
355 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
356 case SSL_ERROR_UNKNOWN_CA_ALERT
:
357 case SSL_ERROR_ACCESS_DENIED_ALERT
:
358 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
360 return MapNSSError(err
);
366 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
367 // able to marshal data between NSS functions and an underlying transport
370 // All public functions are meant to be called from the network task runner,
371 // and any callbacks supplied will be invoked there as well, provided that
372 // Detach() has not been called yet.
374 /////////////////////////////////////////////////////////////////////////////
376 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
378 // Because NSS may block on either hardware or user input during operations
379 // such as signing, creating certificates, or locating private keys, the Core
380 // handles all of the interactions with the underlying NSS SSL socket, so
381 // that these blocking calls can be executed on a dedicated task runner.
383 // Note that the network task runner and the NSS task runner may be executing
384 // on the same thread. If that happens, then it's more performant to try to
385 // complete as much work as possible synchronously, even if it might block,
386 // rather than continually PostTask-ing to the same thread.
388 // Because NSS functions should only be called on the NSS task runner, while
389 // I/O resources should only be accessed on the network task runner, most
390 // public functions are implemented via three methods, each with different
391 // task runner affinities.
393 // In the single-threaded mode (where the network and NSS task runners run on
394 // the same thread), these are all attempted synchronously, while in the
395 // multi-threaded mode, message passing is used.
397 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
399 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
400 // (BufferRecv, BufferSend)
401 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
402 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
403 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
404 // data from the network task runner back to NSS (BufferRecvComplete,
405 // BufferSendComplete, OnHandshakeIOComplete)
407 /////////////////////////////////////////////////////////////////////////////
408 // Single-threaded example
410 // |--------------------------Network Task Runner--------------------------|
411 // SSLClientSocketNSS Core (Transport Socket)
413 // |-------------------------V
421 // |-------------------------V
423 // V-------------------------|
424 // BufferRecvComplete()
426 // PostOrRunCallback()
427 // V-------------------------|
430 /////////////////////////////////////////////////////////////////////////////
431 // Multi-threaded example:
433 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
434 // SSLClientSocketNSS Core Socket Core
436 // |---------------------V
438 // |-------------------------------V
444 // V-------------------------------|
446 // |----------------V
448 // V----------------|
449 // BufferRecvComplete()
450 // |-------------------------------V
451 // BufferRecvComplete()
453 // PostOrRunCallback()
454 // V-------------------------------|
455 // PostOrRunCallback()
456 // V---------------------|
459 /////////////////////////////////////////////////////////////////////////////
460 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
462 // Creates a new Core.
464 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
465 // that need to operate on the underlying transport, net log, or server
466 // bound certificate fetching will happen on the |network_task_runner|, so
467 // that their lifetimes match that of the owning SSLClientSocketNSS.
469 // The caller retains ownership of |transport|, |net_log|, and
470 // |channel_id_service|, and they will not be accessed once Detach()
472 Core(base::SequencedTaskRunner
* network_task_runner
,
473 base::SequencedTaskRunner
* nss_task_runner
,
474 ClientSocketHandle
* transport
,
475 const HostPortPair
& host_and_port
,
476 const SSLConfig
& ssl_config
,
477 BoundNetLog
* net_log
,
478 ChannelIDService
* channel_id_service
);
480 // Called on the network task runner.
481 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
482 // underlying memio implementation, to the Core. Returns true if the Core
483 // was successfully registered with the socket.
484 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
486 // Called on the network task runner.
488 // Attempts to perform an SSL handshake. If the handshake cannot be
489 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
490 // the network task runner once the handshake has completed. Otherwise,
491 // returns OK on success or a network error code on failure.
492 int Connect(const CompletionCallback
& callback
);
494 // Called on the network task runner.
495 // Signals that the resources owned by the network task runner are going
496 // away. No further callbacks will be invoked on the network task runner.
497 // May be called at any time.
500 // Called on the network task runner.
501 // Returns the current state of the underlying SSL socket. May be called at
503 const HandshakeState
& state() const { return network_handshake_state_
; }
505 // Called on the network task runner.
506 // Read() and Write() mirror the net::Socket functions of the same name.
507 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
508 // task runner at a later point, unless the caller calls Detach().
509 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
510 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
512 // Called on the network task runner.
513 bool IsConnected() const;
514 bool HasPendingAsyncOperation() const;
515 bool HasUnhandledReceivedData() const;
516 bool WasEverUsed() const;
518 // Called on the network task runner.
519 // Causes the associated SSL/TLS session ID to be added to NSS's session
520 // cache, but only if the connection has not been False Started.
522 // This should only be called after the server's certificate has been
523 // verified, and may not be called within an NSS callback.
524 void CacheSessionIfNecessary();
527 friend class base::RefCountedThreadSafe
<Core
>;
533 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
536 bool OnNSSTaskRunner() const;
537 bool OnNetworkTaskRunner() const;
539 ////////////////////////////////////////////////////////////////////////////
540 // Methods that are ONLY called on the NSS task runner:
541 ////////////////////////////////////////////////////////////////////////////
543 // Called by NSS during full handshakes to allow the application to
544 // verify the certificate. Instead of verifying the certificate in the midst
545 // of the handshake, SECSuccess is always returned and the peer's certificate
546 // is verified afterwards.
547 // This behaviour is an artifact of the original SSLClientSocketWin
548 // implementation, which could not verify the peer's certificate until after
549 // the handshake had completed, as well as bugs in NSS that prevent
550 // SSL_RestartHandshakeAfterCertReq from working.
551 static SECStatus
OwnAuthCertHandler(void* arg
,
556 // Callbacks called by NSS when the peer requests client certificate
558 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
560 static SECStatus
ClientAuthHandler(void* arg
,
562 CERTDistNames
* ca_names
,
563 CERTCertificate
** result_certificate
,
564 SECKEYPrivateKey
** result_private_key
);
566 // Called by NSS to determine if we can False Start.
567 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
568 static SECStatus
CanFalseStartCallback(PRFileDesc
* socket
,
570 PRBool
* can_false_start
);
572 // Called by NSS once the handshake has completed.
573 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
574 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
576 // Called once the handshake has succeeded.
577 void HandshakeSucceeded();
579 // Handles an NSS error generated while handshaking or performing IO.
580 // Returns a network error code mapped from the original NSS error.
581 int HandleNSSError(PRErrorCode error
);
583 int DoHandshakeLoop(int last_io_result
);
584 int DoReadLoop(int result
);
585 int DoWriteLoop(int result
);
588 int DoGetDBCertComplete(int result
);
591 int DoPayloadWrite();
593 bool DoTransportIO();
597 void OnRecvComplete(int result
);
598 void OnSendComplete(int result
);
600 void DoConnectCallback(int result
);
601 void DoReadCallback(int result
);
602 void DoWriteCallback(int result
);
604 // Client channel ID handler.
605 static SECStatus
ClientChannelIDHandler(
608 SECKEYPublicKey
**out_public_key
,
609 SECKEYPrivateKey
**out_private_key
);
611 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
612 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
613 // and an error code otherwise.
614 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
615 // set by a call to ChannelIDService->GetChannelID. The caller
616 // takes ownership of the |*cert| and |*key|.
617 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
619 // Updates the NSS and platform specific certificates.
620 void UpdateServerCert();
621 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
622 // received in the handshake via a TLS extension.
623 void UpdateSignedCertTimestamps();
624 // Update the OCSP response cache with the stapled response received in the
625 // handshake, and update nss_handshake_state_ with
626 // the SignedCertificateTimestampList received in the stapled OCSP response.
627 void UpdateStapledOCSPResponse();
628 // Updates the nss_handshake_state_ with the negotiated security parameters.
629 void UpdateConnectionStatus();
630 // Record histograms for channel id support during full handshakes - resumed
631 // handshakes are ignored.
632 void RecordChannelIDSupportOnNSSTaskRunner();
633 // UpdateNextProto gets any application-layer protocol that may have been
634 // negotiated by the TLS connection.
635 void UpdateNextProto();
636 // Record TLS extension used for protocol negotiation (NPN or ALPN).
637 void UpdateExtensionUsed();
639 ////////////////////////////////////////////////////////////////////////////
640 // Methods that are ONLY called on the network task runner:
641 ////////////////////////////////////////////////////////////////////////////
642 int DoBufferRecv(IOBuffer
* buffer
, int len
);
643 int DoBufferSend(IOBuffer
* buffer
, int len
);
644 int DoGetChannelID(const std::string
& host
);
646 void OnGetChannelIDComplete(int result
);
647 void OnHandshakeStateUpdated(const HandshakeState
& state
);
648 void OnNSSBufferUpdated(int amount_in_read_buffer
);
649 void DidNSSRead(int result
);
650 void DidNSSWrite(int result
);
651 void RecordChannelIDSupportOnNetworkTaskRunner(
652 bool negotiated_channel_id
,
653 bool channel_id_enabled
,
654 bool supports_ecc
) const;
656 ////////////////////////////////////////////////////////////////////////////
657 // Methods that are called on both the network task runner and the NSS
659 ////////////////////////////////////////////////////////////////////////////
660 void OnHandshakeIOComplete(int result
);
661 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
662 void BufferSendComplete(int result
);
664 // PostOrRunCallback is a helper function to ensure that |callback| is
665 // invoked on the network task runner, but only if Detach() has not yet
667 void PostOrRunCallback(const tracked_objects::Location
& location
,
668 const base::Closure
& callback
);
670 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
671 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
672 void AddCertProvidedEvent(int cert_count
);
674 // Sets the handshake state |channel_id_sent| flag and logs the
675 // SSL_CHANNEL_ID_PROVIDED event.
676 void SetChannelIDProvided();
678 ////////////////////////////////////////////////////////////////////////////
679 // Members that are ONLY accessed on the network task runner:
680 ////////////////////////////////////////////////////////////////////////////
682 // True if the owning SSLClientSocketNSS has called Detach(). No further
683 // callbacks will be invoked nor access to members owned by the network
687 // The underlying transport to use for network IO.
688 ClientSocketHandle
* transport_
;
689 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
691 // The current handshake state. Mirrors |nss_handshake_state_|.
692 HandshakeState network_handshake_state_
;
694 // The service for retrieving Channel ID keys. May be NULL.
695 ChannelIDService
* channel_id_service_
;
696 ChannelIDService::RequestHandle domain_bound_cert_request_handle_
;
698 // The information about NSS task runner.
699 int unhandled_buffer_size_
;
700 bool nss_waiting_read_
;
701 bool nss_waiting_write_
;
704 // Set when Read() or Write() successfully reads or writes data to or from the
708 ////////////////////////////////////////////////////////////////////////////
709 // Members that are ONLY accessed on the NSS task runner:
710 ////////////////////////////////////////////////////////////////////////////
711 HostPortPair host_and_port_
;
712 SSLConfig ssl_config_
;
717 // Buffers for the network end of the SSL state machine
718 memio_Private
* nss_bufs_
;
720 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
721 // as much data as possible, without blocking.
722 // If DoPayloadRead() encounters an error after having read some data, stores
723 // the results to return on the *next* call to DoPayloadRead(). A value of
724 // kNoPendingReadResult indicates there is no pending result, otherwise 0
725 // indicates EOF and < 0 indicates an error.
726 int pending_read_result_
;
727 // Contains the previously observed NSS error. Only valid when
728 // pending_read_result_ != kNoPendingReadResult.
729 PRErrorCode pending_read_nss_error_
;
731 // The certificate chain, in DER form, that is expected to be received from
733 std::vector
<std::string
> predicted_certs_
;
735 State next_handshake_state_
;
737 // True if channel ID extension was negotiated.
738 bool channel_id_xtn_negotiated_
;
739 // True if the handshake state machine was interrupted for channel ID.
740 bool channel_id_needed_
;
741 // True if the handshake state machine was interrupted for client auth.
742 bool client_auth_cert_needed_
;
743 // True if NSS has False Started.
745 // True if NSS has called HandshakeCallback.
746 bool handshake_callback_called_
;
748 HandshakeState nss_handshake_state_
;
750 bool transport_recv_busy_
;
751 bool transport_recv_eof_
;
752 bool transport_send_busy_
;
754 // Used by Read function.
755 scoped_refptr
<IOBuffer
> user_read_buf_
;
756 int user_read_buf_len_
;
758 // Used by Write function.
759 scoped_refptr
<IOBuffer
> user_write_buf_
;
760 int user_write_buf_len_
;
762 CompletionCallback user_connect_callback_
;
763 CompletionCallback user_read_callback_
;
764 CompletionCallback user_write_callback_
;
766 ////////////////////////////////////////////////////////////////////////////
767 // Members that are accessed on both the network task runner and the NSS
769 ////////////////////////////////////////////////////////////////////////////
770 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
771 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
773 // Dereferenced only on the network task runner, but bound to tasks destined
774 // for the network task runner from the NSS task runner.
775 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
777 // Written on the network task runner by the |channel_id_service_|,
778 // prior to invoking OnHandshakeIOComplete.
779 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
780 // on the NSS task runner.
781 std::string domain_bound_private_key_
;
782 std::string domain_bound_cert_
;
784 DISALLOW_COPY_AND_ASSIGN(Core
);
787 SSLClientSocketNSS::Core::Core(
788 base::SequencedTaskRunner
* network_task_runner
,
789 base::SequencedTaskRunner
* nss_task_runner
,
790 ClientSocketHandle
* transport
,
791 const HostPortPair
& host_and_port
,
792 const SSLConfig
& ssl_config
,
793 BoundNetLog
* net_log
,
794 ChannelIDService
* channel_id_service
)
796 transport_(transport
),
797 weak_net_log_factory_(net_log
),
798 channel_id_service_(channel_id_service
),
799 unhandled_buffer_size_(0),
800 nss_waiting_read_(false),
801 nss_waiting_write_(false),
802 nss_is_closed_(false),
803 was_ever_used_(false),
804 host_and_port_(host_and_port
),
805 ssl_config_(ssl_config
),
808 pending_read_result_(kNoPendingReadResult
),
809 pending_read_nss_error_(0),
810 next_handshake_state_(STATE_NONE
),
811 channel_id_xtn_negotiated_(false),
812 channel_id_needed_(false),
813 client_auth_cert_needed_(false),
814 false_started_(false),
815 handshake_callback_called_(false),
816 transport_recv_busy_(false),
817 transport_recv_eof_(false),
818 transport_send_busy_(false),
819 user_read_buf_len_(0),
820 user_write_buf_len_(0),
821 network_task_runner_(network_task_runner
),
822 nss_task_runner_(nss_task_runner
),
823 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
826 SSLClientSocketNSS::Core::~Core() {
827 // TODO(wtc): Send SSL close_notify alert.
828 if (nss_fd_
!= NULL
) {
835 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
836 memio_Private
* buffers
) {
837 DCHECK(OnNetworkTaskRunner());
844 SECStatus rv
= SECSuccess
;
846 if (!ssl_config_
.next_protos
.empty()) {
847 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
848 const bool adequate_encryption
=
849 PK11_TokenExists(CKM_AES_GCM
) ||
850 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305
);
851 const bool adequate_key_agreement
= PK11_TokenExists(CKM_DH_PKCS_DERIVE
) ||
852 PK11_TokenExists(CKM_ECDH1_DERIVE
);
853 std::vector
<uint8_t> wire_protos
=
854 SerializeNextProtos(ssl_config_
.next_protos
,
855 adequate_encryption
&& adequate_key_agreement
&&
856 IsTLSVersionAdequateForHTTP2(ssl_config_
));
857 rv
= SSL_SetNextProtoNego(
858 nss_fd_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
860 if (rv
!= SECSuccess
)
861 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoNego", "");
862 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_ALPN
, PR_TRUE
);
863 if (rv
!= SECSuccess
)
864 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_ALPN");
865 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_NPN
, PR_TRUE
);
866 if (rv
!= SECSuccess
)
867 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_NPN");
870 rv
= SSL_AuthCertificateHook(
871 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
872 if (rv
!= SECSuccess
) {
873 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
877 rv
= SSL_GetClientAuthDataHook(
878 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
879 if (rv
!= SECSuccess
) {
880 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
884 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
885 rv
= SSL_SetClientChannelIDCallback(
886 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
887 if (rv
!= SECSuccess
) {
888 LogFailedNSSFunction(
889 *weak_net_log_
, "SSL_SetClientChannelIDCallback", "");
893 rv
= SSL_SetCanFalseStartCallback(
894 nss_fd_
, SSLClientSocketNSS::Core::CanFalseStartCallback
, this);
895 if (rv
!= SECSuccess
) {
896 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetCanFalseStartCallback", "");
900 rv
= SSL_HandshakeCallback(
901 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
902 if (rv
!= SECSuccess
) {
903 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
910 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
911 if (!OnNSSTaskRunner()) {
913 bool posted
= nss_task_runner_
->PostTask(
915 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
916 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
919 DCHECK(OnNSSTaskRunner());
920 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
921 DCHECK(user_read_callback_
.is_null());
922 DCHECK(user_write_callback_
.is_null());
923 DCHECK(user_connect_callback_
.is_null());
924 DCHECK(!user_read_buf_
.get());
925 DCHECK(!user_write_buf_
.get());
927 next_handshake_state_
= STATE_HANDSHAKE
;
928 int rv
= DoHandshakeLoop(OK
);
929 if (rv
== ERR_IO_PENDING
) {
930 user_connect_callback_
= callback
;
931 } else if (rv
> OK
) {
934 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
935 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
936 return ERR_IO_PENDING
;
942 void SSLClientSocketNSS::Core::Detach() {
943 DCHECK(OnNetworkTaskRunner());
947 weak_net_log_factory_
.InvalidateWeakPtrs();
949 network_handshake_state_
.Reset();
951 domain_bound_cert_request_handle_
.Cancel();
954 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
955 const CompletionCallback
& callback
) {
956 if (!OnNSSTaskRunner()) {
957 DCHECK(OnNetworkTaskRunner());
960 DCHECK(!nss_waiting_read_
);
962 nss_waiting_read_
= true;
963 bool posted
= nss_task_runner_
->PostTask(
965 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
968 nss_is_closed_
= true;
969 nss_waiting_read_
= false;
971 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
974 DCHECK(OnNSSTaskRunner());
975 DCHECK(false_started_
|| handshake_callback_called_
);
976 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
977 DCHECK(user_read_callback_
.is_null());
978 DCHECK(user_connect_callback_
.is_null());
979 DCHECK(!user_read_buf_
.get());
982 user_read_buf_
= buf
;
983 user_read_buf_len_
= buf_len
;
985 int rv
= DoReadLoop(OK
);
986 if (rv
== ERR_IO_PENDING
) {
987 if (OnNetworkTaskRunner())
988 nss_waiting_read_
= true;
989 user_read_callback_
= callback
;
991 user_read_buf_
= NULL
;
992 user_read_buf_len_
= 0;
994 if (!OnNetworkTaskRunner()) {
995 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
996 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
997 return ERR_IO_PENDING
;
999 DCHECK(!nss_waiting_read_
);
1001 nss_is_closed_
= true;
1003 was_ever_used_
= true;
1011 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1012 const CompletionCallback
& callback
) {
1013 if (!OnNSSTaskRunner()) {
1014 DCHECK(OnNetworkTaskRunner());
1017 DCHECK(!nss_waiting_write_
);
1019 nss_waiting_write_
= true;
1020 bool posted
= nss_task_runner_
->PostTask(
1022 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1023 buf_len
, callback
));
1025 nss_is_closed_
= true;
1026 nss_waiting_write_
= false;
1028 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1031 DCHECK(OnNSSTaskRunner());
1032 DCHECK(false_started_
|| handshake_callback_called_
);
1033 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1034 DCHECK(user_write_callback_
.is_null());
1035 DCHECK(user_connect_callback_
.is_null());
1036 DCHECK(!user_write_buf_
.get());
1039 user_write_buf_
= buf
;
1040 user_write_buf_len_
= buf_len
;
1042 int rv
= DoWriteLoop(OK
);
1043 if (rv
== ERR_IO_PENDING
) {
1044 if (OnNetworkTaskRunner())
1045 nss_waiting_write_
= true;
1046 user_write_callback_
= callback
;
1048 user_write_buf_
= NULL
;
1049 user_write_buf_len_
= 0;
1051 if (!OnNetworkTaskRunner()) {
1052 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1053 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1054 return ERR_IO_PENDING
;
1056 DCHECK(!nss_waiting_write_
);
1058 nss_is_closed_
= true;
1059 } else if (rv
> 0) {
1060 was_ever_used_
= true;
1068 bool SSLClientSocketNSS::Core::IsConnected() const {
1069 DCHECK(OnNetworkTaskRunner());
1070 return !nss_is_closed_
;
1073 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1074 DCHECK(OnNetworkTaskRunner());
1075 return nss_waiting_read_
|| nss_waiting_write_
;
1078 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1079 DCHECK(OnNetworkTaskRunner());
1080 return unhandled_buffer_size_
!= 0;
1083 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1084 DCHECK(OnNetworkTaskRunner());
1085 return was_ever_used_
;
1088 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1089 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1090 // nss_fd_. However, it happens on the network task runner in order to match
1091 // the buggy behavior of ExportKeyingMaterial.
1093 // Once http://crbug.com/330360 is fixed, this should be moved to an
1094 // implementation that exclusively does this work on the NSS TaskRunner. This
1095 // is "safe" because it is only called during the certificate verification
1096 // state machine of the main socket, which is safe because no underlying
1097 // transport IO will be occuring in that state, and NSS will not be blocking
1098 // on any PKCS#11 related locks that might block the Network TaskRunner.
1099 DCHECK(OnNetworkTaskRunner());
1101 // Only cache the session if the connection was not False Started, because
1102 // sessions should only be cached *after* the peer's Finished message is
1104 // In the case of False Start, the session will be cached once the
1105 // HandshakeCallback is called, which signals the receipt and processing of
1106 // the Finished message, and which will happen during a call to
1107 // PR_Read/PR_Write.
1108 if (!false_started_
)
1109 SSL_CacheSession(nss_fd_
);
1112 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1113 return nss_task_runner_
->RunsTasksOnCurrentThread();
1116 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1117 return network_task_runner_
->RunsTasksOnCurrentThread();
1121 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1126 Core
* core
= reinterpret_cast<Core
*>(arg
);
1127 if (core
->handshake_callback_called_
) {
1128 // Disallow the server certificate to change in a renegotiation.
1129 CERTCertificate
* old_cert
= core
->nss_handshake_state_
.server_cert_chain
[0];
1130 ScopedCERTCertificate
new_cert(SSL_PeerCertificate(socket
));
1131 if (new_cert
->derCert
.len
!= old_cert
->derCert
.len
||
1132 memcmp(new_cert
->derCert
.data
, old_cert
->derCert
.data
,
1133 new_cert
->derCert
.len
) != 0) {
1134 // NSS doesn't have an error code that indicates the server certificate
1135 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1136 // for this purpose.
1137 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE
);
1142 // Tell NSS to not verify the certificate.
1149 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1152 CERTDistNames
* ca_names
,
1153 CERTCertificate
** result_certificate
,
1154 SECKEYPrivateKey
** result_private_key
) {
1155 Core
* core
= reinterpret_cast<Core
*>(arg
);
1156 DCHECK(core
->OnNSSTaskRunner());
1158 core
->PostOrRunCallback(
1160 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1161 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1163 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1164 LOG(WARNING
) << "Client auth is not supported";
1166 // Never send a certificate.
1167 core
->AddCertProvidedEvent(0);
1174 // Based on Mozilla's NSS_GetClientAuthData.
1175 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1178 CERTDistNames
* ca_names
,
1179 CERTCertificate
** result_certificate
,
1180 SECKEYPrivateKey
** result_private_key
) {
1181 Core
* core
= reinterpret_cast<Core
*>(arg
);
1182 DCHECK(core
->OnNSSTaskRunner());
1184 core
->PostOrRunCallback(
1186 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1187 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1189 // Regular client certificate requested.
1190 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1191 void* wincx
= SSL_RevealPinArg(socket
);
1193 if (core
->ssl_config_
.send_client_cert
) {
1194 // Second pass: a client certificate should have been selected.
1195 if (core
->ssl_config_
.client_cert
.get()) {
1196 CERTCertificate
* cert
=
1197 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1198 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1200 // TODO(jsorianopastor): We should wait for server certificate
1201 // verification before sending our credentials. See
1202 // http://crbug.com/13934.
1203 *result_certificate
= cert
;
1204 *result_private_key
= privkey
;
1205 // A cert_count of -1 means the number of certificates is unknown.
1206 // NSS will construct the certificate chain.
1207 core
->AddCertProvidedEvent(-1);
1211 LOG(WARNING
) << "Client cert found without private key";
1213 // Send no client certificate.
1214 core
->AddCertProvidedEvent(0);
1218 // First pass: client certificate is needed.
1219 core
->nss_handshake_state_
.cert_authorities
.clear();
1221 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1222 // the server and save them in |cert_authorities|.
1223 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1224 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1225 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1226 static_cast<size_t>(ca_names
->names
[i
].len
)));
1229 // Update the network task runner's view of the handshake state now that
1230 // server certificate request has been recorded.
1231 core
->PostOrRunCallback(
1232 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1233 core
->nss_handshake_state_
));
1235 // Tell NSS to suspend the client authentication. We will then abort the
1236 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1237 return SECWouldBlock
;
1242 SECStatus
SSLClientSocketNSS::Core::CanFalseStartCallback(
1245 PRBool
* can_false_start
) {
1246 // If the server doesn't support NPN or ALPN, then we don't do False
1248 PRBool negotiated_extension
;
1249 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1250 ssl_app_layer_protocol_xtn
,
1251 &negotiated_extension
);
1252 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1253 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1254 ssl_next_proto_nego_xtn
,
1255 &negotiated_extension
);
1257 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1258 *can_false_start
= PR_FALSE
;
1262 SSLChannelInfo channel_info
;
1264 SSL_GetChannelInfo(socket
, &channel_info
, sizeof(channel_info
));
1265 if (ok
!= SECSuccess
|| channel_info
.length
!= sizeof(channel_info
) ||
1266 channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_TLS_1_2
||
1267 !IsFalseStartableTLSCipherSuite(channel_info
.cipherSuite
)) {
1268 *can_false_start
= PR_FALSE
;
1272 return SSL_RecommendedCanFalseStart(socket
, can_false_start
);
1276 void SSLClientSocketNSS::Core::HandshakeCallback(
1279 Core
* core
= reinterpret_cast<Core
*>(arg
);
1280 DCHECK(core
->OnNSSTaskRunner());
1282 core
->handshake_callback_called_
= true;
1283 if (core
->false_started_
) {
1284 core
->false_started_
= false;
1285 // If the connection was False Started, then at the time of this callback,
1286 // the peer's certificate will have been verified or the caller will have
1287 // accepted the error.
1288 // This is guaranteed when using False Start because this callback will
1289 // not be invoked until processing the peer's Finished message, which
1290 // will only happen in a PR_Read/PR_Write call, which can only happen
1291 // after the peer's certificate is verified.
1292 SSL_CacheSessionUnlocked(socket
);
1294 // Additionally, when False Starting, DoHandshake() will have already
1295 // called HandshakeSucceeded(), so return now.
1298 core
->HandshakeSucceeded();
1301 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1302 DCHECK(OnNSSTaskRunner());
1304 PRBool last_handshake_resumed
;
1305 SECStatus rv
= SSL_HandshakeResumedSession(nss_fd_
, &last_handshake_resumed
);
1306 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1307 nss_handshake_state_
.resumed_handshake
= true;
1309 nss_handshake_state_
.resumed_handshake
= false;
1312 RecordChannelIDSupportOnNSSTaskRunner();
1314 UpdateSignedCertTimestamps();
1315 UpdateStapledOCSPResponse();
1316 UpdateConnectionStatus();
1318 UpdateExtensionUsed();
1320 // Update the network task runners view of the handshake state whenever
1321 // a handshake has completed.
1323 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
1324 nss_handshake_state_
));
1327 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
) {
1328 DCHECK(OnNSSTaskRunner());
1330 return MapNSSClientError(nss_error
);
1333 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1334 DCHECK(OnNSSTaskRunner());
1336 int rv
= last_io_result
;
1338 // Default to STATE_NONE for next state.
1339 State state
= next_handshake_state_
;
1340 GotoState(STATE_NONE
);
1343 case STATE_HANDSHAKE
:
1346 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1347 rv
= DoGetDBCertComplete(rv
);
1351 rv
= ERR_UNEXPECTED
;
1352 LOG(DFATAL
) << "unexpected state " << state
;
1356 // Do the actual network I/O
1357 bool network_moved
= DoTransportIO();
1358 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1359 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1360 // special case we keep looping even if rv is ERR_IO_PENDING because
1361 // the transport IO may allow DoHandshake to make progress.
1362 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1363 rv
= OK
; // This causes us to stay in the loop.
1365 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1369 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1370 DCHECK(OnNSSTaskRunner());
1371 DCHECK(false_started_
|| handshake_callback_called_
);
1372 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1378 LOG(DFATAL
) << "!nss_bufs_";
1379 int rv
= ERR_UNEXPECTED
;
1382 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1383 NetLog::TYPE_SSL_READ_ERROR
,
1384 CreateNetLogSSLErrorCallback(rv
, 0)));
1391 rv
= DoPayloadRead();
1392 network_moved
= DoTransportIO();
1393 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1398 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1399 DCHECK(OnNSSTaskRunner());
1400 DCHECK(false_started_
|| handshake_callback_called_
);
1401 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1407 LOG(DFATAL
) << "!nss_bufs_";
1408 int rv
= ERR_UNEXPECTED
;
1411 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1412 NetLog::TYPE_SSL_READ_ERROR
,
1413 CreateNetLogSSLErrorCallback(rv
, 0)));
1420 rv
= DoPayloadWrite();
1421 network_moved
= DoTransportIO();
1422 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1428 int SSLClientSocketNSS::Core::DoHandshake() {
1429 DCHECK(OnNSSTaskRunner());
1432 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1434 // Note: this function may be called multiple times during the handshake, so
1435 // even though channel id and client auth are separate else cases, they can
1436 // both be used during a single SSL handshake.
1437 if (channel_id_needed_
) {
1438 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1439 net_error
= ERR_IO_PENDING
;
1440 } else if (client_auth_cert_needed_
) {
1441 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1444 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1445 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1446 CreateNetLogSSLErrorCallback(net_error
, 0)));
1447 } else if (rv
== SECSuccess
) {
1448 if (!handshake_callback_called_
) {
1449 false_started_
= true;
1450 HandshakeSucceeded();
1453 PRErrorCode prerr
= PR_GetError();
1454 net_error
= HandleNSSError(prerr
);
1456 // If not done, stay in this state
1457 if (net_error
== ERR_IO_PENDING
) {
1458 GotoState(STATE_HANDSHAKE
);
1462 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1463 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1464 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1471 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1475 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1476 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1478 channel_id_needed_
= false;
1483 SECKEYPublicKey
* public_key
;
1484 SECKEYPrivateKey
* private_key
;
1485 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1489 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1490 if (rv
!= SECSuccess
)
1491 return MapNSSError(PORT_GetError());
1493 SetChannelIDProvided();
1494 GotoState(STATE_HANDSHAKE
);
1498 int SSLClientSocketNSS::Core::DoPayloadRead() {
1499 DCHECK(OnNSSTaskRunner());
1500 DCHECK(user_read_buf_
.get());
1501 DCHECK_GT(user_read_buf_len_
, 0);
1504 // If a previous greedy read resulted in an error that was not consumed (eg:
1505 // due to the caller having read some data successfully), then return that
1506 // pending error now.
1507 if (pending_read_result_
!= kNoPendingReadResult
) {
1508 rv
= pending_read_result_
;
1509 PRErrorCode prerr
= pending_read_nss_error_
;
1510 pending_read_result_
= kNoPendingReadResult
;
1511 pending_read_nss_error_
= 0;
1516 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1517 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1518 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1522 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1523 NetLog::TYPE_SSL_READ_ERROR
,
1524 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1529 // Perform a greedy read, attempting to read as much as the caller has
1530 // requested. In the current NSS implementation, PR_Read will return
1531 // exactly one SSL application data record's worth of data per invocation.
1532 // The record size is dictated by the server, and may be noticeably smaller
1533 // than the caller's buffer. This may be as little as a single byte, if the
1534 // server is performing 1/n-1 record splitting.
1536 // However, this greedy read may result in renegotiations/re-handshakes
1537 // happening or may lead to some data being read, followed by an EOF (such as
1538 // a TLS close-notify). If at least some data was read, then that result
1539 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1540 // data was read, it's safe to return the error or EOF immediately.
1541 int total_bytes_read
= 0;
1543 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1544 user_read_buf_len_
- total_bytes_read
);
1546 total_bytes_read
+= rv
;
1547 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1548 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1549 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1550 amount_in_read_buffer
));
1552 if (total_bytes_read
== user_read_buf_len_
) {
1553 // The caller's entire request was satisfied without error. No further
1554 // processing needed.
1555 rv
= total_bytes_read
;
1557 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1558 // immediately, while the NSPR/NSS errors are still available in
1559 // thread-local storage. However, the handled/remapped error code should
1560 // only be returned if no application data was already read; if it was, the
1561 // error code should be deferred until the next call of DoPayloadRead.
1563 // If no data was read, |*next_result| will point to the return value of
1564 // this function. If at least some data was read, |*next_result| will point
1565 // to |pending_read_error_|, to be returned in a future call to
1566 // DoPayloadRead() (e.g.: after the current data is handled).
1567 int* next_result
= &rv
;
1568 if (total_bytes_read
> 0) {
1569 pending_read_result_
= rv
;
1570 rv
= total_bytes_read
;
1571 next_result
= &pending_read_result_
;
1574 if (client_auth_cert_needed_
) {
1575 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1576 pending_read_nss_error_
= 0;
1577 } else if (*next_result
< 0) {
1578 // If *next_result == 0, then that indicates EOF, and no special error
1579 // handling is needed.
1580 pending_read_nss_error_
= PR_GetError();
1581 *next_result
= HandleNSSError(pending_read_nss_error_
);
1582 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1583 // If at least some data was read from PR_Read(), do not treat
1584 // insufficient data as an error to return in the next call to
1585 // DoPayloadRead() - instead, let the call fall through to check
1586 // PR_Read() again. This is because DoTransportIO() may complete
1587 // in between the next call to DoPayloadRead(), and thus it is
1588 // important to check PR_Read() on subsequent invocations to see
1589 // if a complete record may now be read.
1590 pending_read_nss_error_
= 0;
1591 pending_read_result_
= kNoPendingReadResult
;
1596 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
1601 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1602 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1603 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1604 } else if (rv
!= ERR_IO_PENDING
) {
1607 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1608 NetLog::TYPE_SSL_READ_ERROR
,
1609 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
1610 pending_read_nss_error_
= 0;
1615 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1616 DCHECK(OnNSSTaskRunner());
1618 DCHECK(user_write_buf_
.get());
1620 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1621 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
1622 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1623 // PR_Write could potentially consume the unhandled data in the memio read
1624 // buffer if a renegotiation is in progress. If the buffer is consumed,
1625 // notify the latest buffer size to NetworkRunner.
1626 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
1629 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
1634 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1635 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1636 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
1639 PRErrorCode prerr
= PR_GetError();
1640 if (prerr
== PR_WOULD_BLOCK_ERROR
)
1641 return ERR_IO_PENDING
;
1643 rv
= HandleNSSError(prerr
);
1646 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1647 NetLog::TYPE_SSL_WRITE_ERROR
,
1648 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1652 // Do as much network I/O as possible between the buffer and the
1653 // transport socket. Return true if some I/O performed, false
1654 // otherwise (error or ERR_IO_PENDING).
1655 bool SSLClientSocketNSS::Core::DoTransportIO() {
1656 DCHECK(OnNSSTaskRunner());
1658 bool network_moved
= false;
1659 if (nss_bufs_
!= NULL
) {
1661 // Read and write as much data as we can. The loop is neccessary
1662 // because Write() may return synchronously.
1665 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
1666 network_moved
= true;
1668 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
1669 network_moved
= true;
1671 return network_moved
;
1674 int SSLClientSocketNSS::Core::BufferRecv() {
1675 DCHECK(OnNSSTaskRunner());
1677 if (transport_recv_busy_
)
1678 return ERR_IO_PENDING
;
1680 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
1681 // determine how much data NSS wants to read. If NSS was not blocked,
1682 // this will return 0.
1683 int requested
= memio_GetReadRequest(nss_bufs_
);
1684 if (requested
== 0) {
1685 // This is not a perfect match of error codes, as no operation is
1686 // actually pending. However, returning 0 would be interpreted as a
1687 // possible sign of EOF, which is also an inappropriate match.
1688 return ERR_IO_PENDING
;
1692 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
1695 // buffer too full to read into, so no I/O possible at moment
1696 rv
= ERR_IO_PENDING
;
1698 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
1699 if (OnNetworkTaskRunner()) {
1700 rv
= DoBufferRecv(read_buffer
.get(), nb
);
1702 bool posted
= network_task_runner_
->PostTask(
1704 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
1706 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1709 if (rv
== ERR_IO_PENDING
) {
1710 transport_recv_busy_
= true;
1713 memcpy(buf
, read_buffer
->data(), rv
);
1714 } else if (rv
== 0) {
1715 transport_recv_eof_
= true;
1717 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
1723 // Return 0 if nss_bufs_ was empty,
1724 // > 0 for bytes transferred immediately,
1725 // < 0 for error (or the non-error ERR_IO_PENDING).
1726 int SSLClientSocketNSS::Core::BufferSend() {
1727 DCHECK(OnNSSTaskRunner());
1729 if (transport_send_busy_
)
1730 return ERR_IO_PENDING
;
1734 unsigned int len1
, len2
;
1735 if (memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
)) {
1736 // It is important this return synchronously to prevent spinning infinitely
1737 // in the off-thread NSS case. The error code itself is ignored, so just
1738 // return ERR_ABORTED. See https://crbug.com/381160.
1741 const unsigned int len
= len1
+ len2
;
1745 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
1746 memcpy(send_buffer
->data(), buf1
, len1
);
1747 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
1749 if (OnNetworkTaskRunner()) {
1750 rv
= DoBufferSend(send_buffer
.get(), len
);
1752 bool posted
= network_task_runner_
->PostTask(
1754 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
1756 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1759 if (rv
== ERR_IO_PENDING
) {
1760 transport_send_busy_
= true;
1762 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
1769 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
1770 DCHECK(OnNSSTaskRunner());
1772 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1773 OnHandshakeIOComplete(result
);
1777 // Network layer received some data, check if client requested to read
1779 if (!user_read_buf_
.get())
1782 int rv
= DoReadLoop(result
);
1783 if (rv
!= ERR_IO_PENDING
)
1787 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
1788 DCHECK(OnNSSTaskRunner());
1790 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1791 OnHandshakeIOComplete(result
);
1795 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1796 // handshake is in progress.
1797 int rv_read
= ERR_IO_PENDING
;
1798 int rv_write
= ERR_IO_PENDING
;
1801 if (user_read_buf_
.get())
1802 rv_read
= DoPayloadRead();
1803 if (user_write_buf_
.get())
1804 rv_write
= DoPayloadWrite();
1805 network_moved
= DoTransportIO();
1806 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1807 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1809 // If the parent SSLClientSocketNSS is deleted during the processing of the
1810 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
1811 // will be detached (and possibly deleted). Guard against deletion by taking
1812 // an extra reference, then check if the Core was detached before invoking the
1814 scoped_refptr
<Core
> guard(this);
1815 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1816 DoReadCallback(rv_read
);
1818 if (OnNetworkTaskRunner() && detached_
)
1821 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1822 DoWriteCallback(rv_write
);
1825 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
1826 // handshake. This requires network IO, which in turn calls
1827 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
1828 // winds its way through the state machine and ends up being passed to the
1829 // callback. For Read() and Write(), that's what we want. But for Connect(),
1830 // the caller expects OK (i.e. 0) for success.
1831 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
1832 DCHECK(OnNSSTaskRunner());
1833 DCHECK_NE(rv
, ERR_IO_PENDING
);
1834 DCHECK(!user_connect_callback_
.is_null());
1836 base::Closure c
= base::Bind(
1837 base::ResetAndReturn(&user_connect_callback_
),
1839 PostOrRunCallback(FROM_HERE
, c
);
1842 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
1843 DCHECK(OnNSSTaskRunner());
1844 DCHECK_NE(ERR_IO_PENDING
, rv
);
1845 DCHECK(!user_read_callback_
.is_null());
1847 user_read_buf_
= NULL
;
1848 user_read_buf_len_
= 0;
1849 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1850 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1851 // the network task runner.
1854 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
1857 base::Bind(&Core::DidNSSRead
, this, rv
));
1860 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
1863 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
1864 DCHECK(OnNSSTaskRunner());
1865 DCHECK_NE(ERR_IO_PENDING
, rv
);
1866 DCHECK(!user_write_callback_
.is_null());
1868 // Since Run may result in Write being called, clear |user_write_callback_|
1870 user_write_buf_
= NULL
;
1871 user_write_buf_len_
= 0;
1872 // Update buffer status because DoWriteLoop called DoTransportIO which may
1873 // perform read operations.
1874 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1875 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1876 // the network task runner.
1879 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
1882 base::Bind(&Core::DidNSSWrite
, this, rv
));
1885 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
1888 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
1891 SECKEYPublicKey
**out_public_key
,
1892 SECKEYPrivateKey
**out_private_key
) {
1893 Core
* core
= reinterpret_cast<Core
*>(arg
);
1894 DCHECK(core
->OnNSSTaskRunner());
1896 core
->PostOrRunCallback(
1898 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1899 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
1901 // We have negotiated the TLS channel ID extension.
1902 core
->channel_id_xtn_negotiated_
= true;
1903 std::string host
= core
->host_and_port_
.host();
1904 int error
= ERR_UNEXPECTED
;
1905 if (core
->OnNetworkTaskRunner()) {
1906 error
= core
->DoGetChannelID(host
);
1908 bool posted
= core
->network_task_runner_
->PostTask(
1911 IgnoreResult(&Core::DoGetChannelID
),
1913 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1916 if (error
== ERR_IO_PENDING
) {
1917 // Asynchronous case.
1918 core
->channel_id_needed_
= true;
1919 return SECWouldBlock
;
1922 core
->PostOrRunCallback(
1924 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
1925 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
1926 SECStatus rv
= SECSuccess
;
1928 // Synchronous success.
1929 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
1931 core
->SetChannelIDProvided();
1941 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
1942 SECKEYPrivateKey
** key
) {
1943 // Set the certificate.
1945 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
1946 cert_item
.len
= domain_bound_cert_
.size();
1947 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
1953 return MapNSSError(PORT_GetError());
1955 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
1956 // Set the private key.
1957 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
1959 ChannelIDService::kEPKIPassword
,
1960 reinterpret_cast<const unsigned char*>(
1961 domain_bound_private_key_
.data()),
1962 domain_bound_private_key_
.size(),
1963 &cert
->subjectPublicKeyInfo
,
1968 int error
= MapNSSError(PORT_GetError());
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
);
1987 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1988 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
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
)
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
;
2012 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present
);
2013 if (!ocsp_responses_present
)
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_3_0
) {
2041 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2043 version
= SSL_CONNECTION_VERSION_SSL2
;
2044 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2045 version
= SSL_CONNECTION_VERSION_SSL3
;
2046 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_0
) {
2047 version
= SSL_CONNECTION_VERSION_TLS1
;
2048 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2049 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2050 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_2
) {
2051 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2053 nss_handshake_state_
.ssl_connection_status
|=
2054 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2055 SSL_CONNECTION_VERSION_SHIFT
;
2058 PRBool peer_supports_renego_ext
;
2059 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2060 &peer_supports_renego_ext
);
2061 if (ok
== SECSuccess
) {
2062 if (!peer_supports_renego_ext
) {
2063 nss_handshake_state_
.ssl_connection_status
|=
2064 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2065 // Log an informational message if the server does not support secure
2066 // renegotiation (RFC 5746).
2067 VLOG(1) << "The server " << host_and_port_
.ToString()
2068 << " does not support the TLS renegotiation_info extension.";
2072 if (ssl_config_
.version_fallback
) {
2073 nss_handshake_state_
.ssl_connection_status
|=
2074 SSL_CONNECTION_VERSION_FALLBACK
;
2078 void SSLClientSocketNSS::Core::UpdateNextProto() {
2080 SSLNextProtoState state
;
2083 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2084 if (rv
!= SECSuccess
)
2087 nss_handshake_state_
.next_proto
=
2088 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2090 case SSL_NEXT_PROTO_NEGOTIATED
:
2091 case SSL_NEXT_PROTO_SELECTED
:
2092 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2094 case SSL_NEXT_PROTO_NO_OVERLAP
:
2095 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2097 case SSL_NEXT_PROTO_NO_SUPPORT
:
2098 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2106 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2107 PRBool negotiated_extension
;
2108 SECStatus rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2109 ssl_app_layer_protocol_xtn
,
2110 &negotiated_extension
);
2111 if (rv
== SECSuccess
&& negotiated_extension
) {
2112 nss_handshake_state_
.negotiation_extension_
= kExtensionALPN
;
2114 rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2115 ssl_next_proto_nego_xtn
,
2116 &negotiated_extension
);
2117 if (rv
== SECSuccess
&& negotiated_extension
) {
2118 nss_handshake_state_
.negotiation_extension_
= kExtensionNPN
;
2123 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2124 DCHECK(OnNSSTaskRunner());
2125 if (nss_handshake_state_
.resumed_handshake
)
2128 // Copy the NSS task runner-only state to the network task runner and
2129 // log histograms from there, since the histograms also need access to the
2130 // network task runner state.
2133 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2135 channel_id_xtn_negotiated_
,
2136 ssl_config_
.channel_id_enabled
,
2137 crypto::ECPrivateKey::IsSupported()));
2140 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2141 bool negotiated_channel_id
,
2142 bool channel_id_enabled
,
2143 bool supports_ecc
) const {
2144 DCHECK(OnNetworkTaskRunner());
2146 RecordChannelIDSupport(channel_id_service_
,
2147 negotiated_channel_id
,
2152 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2153 DCHECK(OnNetworkTaskRunner());
2159 int rv
= transport_
->socket()->Read(
2161 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2162 scoped_refptr
<IOBuffer
>(read_buffer
)));
2164 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2165 nss_task_runner_
->PostTask(
2166 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2167 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2174 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2175 DCHECK(OnNetworkTaskRunner());
2181 int rv
= transport_
->socket()->Write(
2183 base::Bind(&Core::BufferSendComplete
,
2184 base::Unretained(this)));
2186 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2187 nss_task_runner_
->PostTask(
2189 base::Bind(&Core::BufferSendComplete
, this, rv
));
2196 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string
& host
) {
2197 DCHECK(OnNetworkTaskRunner());
2202 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2204 int rv
= channel_id_service_
->GetOrCreateChannelID(
2206 &domain_bound_private_key_
,
2207 &domain_bound_cert_
,
2208 base::Bind(&Core::OnGetChannelIDComplete
, base::Unretained(this)),
2209 &domain_bound_cert_request_handle_
);
2211 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2212 nss_task_runner_
->PostTask(
2214 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2215 return ERR_IO_PENDING
;
2221 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2222 const HandshakeState
& state
) {
2223 DCHECK(OnNetworkTaskRunner());
2224 network_handshake_state_
= state
;
2227 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2228 DCHECK(OnNetworkTaskRunner());
2229 unhandled_buffer_size_
= amount_in_read_buffer
;
2232 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2233 DCHECK(OnNetworkTaskRunner());
2234 DCHECK(nss_waiting_read_
);
2235 nss_waiting_read_
= false;
2237 nss_is_closed_
= true;
2239 was_ever_used_
= true;
2243 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2244 DCHECK(OnNetworkTaskRunner());
2245 DCHECK(nss_waiting_write_
);
2246 nss_waiting_write_
= false;
2248 nss_is_closed_
= true;
2249 } else if (result
> 0) {
2250 was_ever_used_
= true;
2254 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2255 if (!OnNSSTaskRunner()) {
2259 nss_task_runner_
->PostTask(
2260 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2264 DCHECK(OnNSSTaskRunner());
2266 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2267 transport_send_busy_
= false;
2268 OnSendComplete(result
);
2271 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2272 if (!OnNSSTaskRunner()) {
2276 nss_task_runner_
->PostTask(
2277 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2281 DCHECK(OnNSSTaskRunner());
2283 int rv
= DoHandshakeLoop(result
);
2284 if (rv
!= ERR_IO_PENDING
)
2285 DoConnectCallback(rv
);
2288 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result
) {
2289 DVLOG(1) << __FUNCTION__
<< " " << result
;
2290 DCHECK(OnNetworkTaskRunner());
2292 OnHandshakeIOComplete(result
);
2295 void SSLClientSocketNSS::Core::BufferRecvComplete(
2296 IOBuffer
* read_buffer
,
2298 DCHECK(read_buffer
);
2300 if (!OnNSSTaskRunner()) {
2304 nss_task_runner_
->PostTask(
2305 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2306 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2310 DCHECK(OnNSSTaskRunner());
2314 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2315 CHECK_GE(nb
, result
);
2316 memcpy(buf
, read_buffer
->data(), result
);
2317 } else if (result
== 0) {
2318 transport_recv_eof_
= true;
2321 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2322 transport_recv_busy_
= false;
2323 OnRecvComplete(result
);
2326 void SSLClientSocketNSS::Core::PostOrRunCallback(
2327 const tracked_objects::Location
& location
,
2328 const base::Closure
& task
) {
2329 if (!OnNetworkTaskRunner()) {
2330 network_task_runner_
->PostTask(
2332 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2336 if (detached_
|| task
.is_null())
2341 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2344 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2345 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2346 NetLog::IntegerCallback("cert_count", cert_count
)));
2349 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2351 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2352 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2353 nss_handshake_state_
.channel_id_sent
= true;
2354 // Update the network task runner's view of the handshake state now that
2355 // channel id has been sent.
2357 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2358 nss_handshake_state_
));
2361 SSLClientSocketNSS::SSLClientSocketNSS(
2362 base::SequencedTaskRunner
* nss_task_runner
,
2363 scoped_ptr
<ClientSocketHandle
> transport_socket
,
2364 const HostPortPair
& host_and_port
,
2365 const SSLConfig
& ssl_config
,
2366 const SSLClientSocketContext
& context
)
2367 : nss_task_runner_(nss_task_runner
),
2368 transport_(transport_socket
.Pass()),
2369 host_and_port_(host_and_port
),
2370 ssl_config_(ssl_config
),
2371 cert_verifier_(context
.cert_verifier
),
2372 cert_transparency_verifier_(context
.cert_transparency_verifier
),
2373 channel_id_service_(context
.channel_id_service
),
2374 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2375 completed_handshake_(false),
2376 next_handshake_state_(STATE_NONE
),
2378 net_log_(transport_
->socket()->NetLog()),
2379 transport_security_state_(context
.transport_security_state
),
2380 policy_enforcer_(context
.cert_policy_enforcer
),
2381 valid_thread_id_(base::kInvalidThreadId
) {
2382 DCHECK(cert_verifier_
);
2389 SSLClientSocketNSS::~SSLClientSocketNSS() {
2396 void SSLClientSocket::ClearSessionCache() {
2397 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2398 // bother initializing NSS just to clear an empty SSL session cache.
2399 if (!NSS_IsInitialized())
2402 SSL_ClearSessionCache();
2405 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2406 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2410 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
2411 crypto::EnsureNSSInit();
2412 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
)) {
2413 return SSL_PROTOCOL_VERSION_TLS1_2
;
2415 return SSL_PROTOCOL_VERSION_TLS1_1
;
2419 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2422 if (core_
->state().server_cert_chain
.empty() ||
2423 !core_
->state().server_cert_chain
[0]) {
2427 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2428 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2430 AddSCTInfoToSSLInfo(ssl_info
);
2432 ssl_info
->connection_status
=
2433 core_
->state().ssl_connection_status
;
2434 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2435 ssl_info
->is_issued_by_known_root
=
2436 server_cert_verify_result_
.is_issued_by_known_root
;
2437 ssl_info
->client_cert_sent
=
2438 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2439 ssl_info
->channel_id_sent
= core_
->state().channel_id_sent
;
2440 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
2442 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2443 core_
->state().ssl_connection_status
);
2444 SSLCipherSuiteInfo cipher_info
;
2445 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2446 &cipher_info
, sizeof(cipher_info
));
2447 if (ok
== SECSuccess
) {
2448 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2450 ssl_info
->security_bits
= -1;
2451 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2452 << " for cipherSuite " << cipher_suite
;
2455 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2456 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2462 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2463 SSLCertRequestInfo
* cert_request_info
) {
2465 cert_request_info
->host_and_port
= host_and_port_
;
2466 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2470 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2472 const base::StringPiece
& context
,
2474 unsigned int outlen
) {
2476 return ERR_SOCKET_NOT_CONNECTED
;
2478 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2479 // the midst of a handshake.
2480 SECStatus result
= SSL_ExportKeyingMaterial(
2481 nss_fd_
, label
.data(), label
.size(), has_context
,
2482 reinterpret_cast<const unsigned char*>(context
.data()),
2483 context
.length(), out
, outlen
);
2484 if (result
!= SECSuccess
) {
2485 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2486 return MapNSSError(PORT_GetError());
2491 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2493 return ERR_SOCKET_NOT_CONNECTED
;
2494 unsigned char buf
[64];
2496 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2497 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2498 buf
, &len
, arraysize(buf
));
2499 if (result
!= SECSuccess
) {
2500 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2501 return MapNSSError(PORT_GetError());
2503 out
->assign(reinterpret_cast<char*>(buf
), len
);
2507 SSLClientSocket::NextProtoStatus
SSLClientSocketNSS::GetNextProto(
2508 std::string
* proto
) const {
2509 *proto
= core_
->state().next_proto
;
2510 return core_
->state().next_proto_status
;
2513 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2515 DCHECK(transport_
.get());
2516 // It is an error to create an SSLClientSocket whose context has no
2517 // TransportSecurityState.
2518 DCHECK(transport_security_state_
);
2519 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2520 DCHECK(user_connect_callback_
.is_null());
2521 DCHECK(!callback
.is_null());
2523 EnsureThreadIdAssigned();
2525 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2529 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2533 rv
= InitializeSSLOptions();
2535 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2539 rv
= InitializeSSLPeerName();
2541 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2545 GotoState(STATE_HANDSHAKE
);
2547 rv
= DoHandshakeLoop(OK
);
2548 if (rv
== ERR_IO_PENDING
) {
2549 user_connect_callback_
= callback
;
2551 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2555 return rv
> OK
? OK
: rv
;
2558 void SSLClientSocketNSS::Disconnect() {
2561 CHECK(CalledOnValidThread());
2563 // Shut down anything that may call us back.
2565 cert_verifier_request_
.reset();
2566 transport_
->socket()->Disconnect();
2568 // Reset object state.
2569 user_connect_callback_
.Reset();
2570 server_cert_verify_result_
.Reset();
2571 completed_handshake_
= false;
2572 start_cert_verification_time_
= base::TimeTicks();
2578 bool SSLClientSocketNSS::IsConnected() const {
2580 bool ret
= completed_handshake_
&&
2581 (core_
->HasPendingAsyncOperation() ||
2582 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2583 transport_
->socket()->IsConnected());
2588 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2590 bool ret
= completed_handshake_
&&
2591 !core_
->HasPendingAsyncOperation() &&
2592 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2593 transport_
->socket()->IsConnectedAndIdle();
2598 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2599 return transport_
->socket()->GetPeerAddress(address
);
2602 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
2603 return transport_
->socket()->GetLocalAddress(address
);
2606 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
2610 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2611 if (transport_
.get() && transport_
->socket()) {
2612 transport_
->socket()->SetSubresourceSpeculation();
2618 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2619 if (transport_
.get() && transport_
->socket()) {
2620 transport_
->socket()->SetOmniboxSpeculation();
2626 bool SSLClientSocketNSS::WasEverUsed() const {
2627 DCHECK(core_
.get());
2629 return core_
->WasEverUsed();
2632 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2633 if (transport_
.get() && transport_
->socket()) {
2634 return transport_
->socket()->UsingTCPFastOpen();
2640 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
2641 const CompletionCallback
& callback
) {
2642 DCHECK(core_
.get());
2643 DCHECK(!callback
.is_null());
2645 EnterFunction(buf_len
);
2646 int rv
= core_
->Read(buf
, buf_len
, callback
);
2652 int SSLClientSocketNSS::Write(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_
->Write(buf
, buf_len
, callback
);
2664 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
2665 return transport_
->socket()->SetReceiveBufferSize(size
);
2668 int SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
2669 return transport_
->socket()->SetSendBufferSize(size
);
2672 int SSLClientSocketNSS::Init() {
2674 // Initialize the NSS SSL library in a threadsafe way. This also
2675 // initializes the NSS base library.
2677 if (!NSS_IsInitialized())
2678 return ERR_UNEXPECTED
;
2679 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
2680 if (ssl_config_
.cert_io_enabled
) {
2681 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
2682 // loop by MessageLoopForIO::current().
2683 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
2684 EnsureNSSHttpIOInit();
2692 void SSLClientSocketNSS::InitCore() {
2693 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
2694 nss_task_runner_
.get(),
2699 channel_id_service_
);
2702 int SSLClientSocketNSS::InitializeSSLOptions() {
2703 // Transport connected, now hook it up to nss
2704 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
2705 if (nss_fd_
== NULL
) {
2706 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
2709 // Grab pointer to buffers
2710 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
2712 /* Create SSL state machine */
2713 /* Push SSL onto our fake I/O socket */
2714 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_
) == NULL
) {
2715 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
2718 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
2720 // TODO(port): set more ssl options! Check errors!
2724 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
2725 if (rv
!= SECSuccess
) {
2726 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
2727 return ERR_UNEXPECTED
;
2730 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
2731 if (rv
!= SECSuccess
) {
2732 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
2733 return ERR_UNEXPECTED
;
2736 // Don't do V2 compatible hellos because they don't support TLS extensions.
2737 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
2738 if (rv
!= SECSuccess
) {
2739 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
2740 return ERR_UNEXPECTED
;
2743 SSLVersionRange version_range
;
2744 version_range
.min
= ssl_config_
.version_min
;
2745 version_range
.max
= ssl_config_
.version_max
;
2746 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
2747 if (rv
!= SECSuccess
) {
2748 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
2749 return ERR_NO_SSL_VERSIONS_ENABLED
;
2752 if (ssl_config_
.version_fallback
) {
2753 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALLBACK_SCSV
, PR_TRUE
);
2754 if (rv
!= SECSuccess
) {
2755 LogFailedNSSFunction(
2756 net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
2760 for (std::vector
<uint16
>::const_iterator it
=
2761 ssl_config_
.disabled_cipher_suites
.begin();
2762 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
2763 // This will fail if the specified cipher is not implemented by NSS, but
2764 // the failure is harmless.
2765 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
2768 if (!ssl_config_
.enable_deprecated_cipher_suites
) {
2769 const PRUint16
* const ssl_ciphers
= SSL_GetImplementedCiphers();
2770 const PRUint16 num_ciphers
= SSL_GetNumImplementedCiphers();
2771 for (int i
= 0; i
< num_ciphers
; i
++) {
2772 SSLCipherSuiteInfo info
;
2773 if (SSL_GetCipherSuiteInfo(ssl_ciphers
[i
], &info
, sizeof(info
)) !=
2777 if (info
.symCipher
== ssl_calg_rc4
)
2778 SSL_CipherPrefSet(nss_fd_
, ssl_ciphers
[i
], PR_FALSE
);
2783 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
2784 if (rv
!= SECSuccess
) {
2785 LogFailedNSSFunction(
2786 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
2789 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
2790 ssl_config_
.false_start_enabled
);
2791 if (rv
!= SECSuccess
)
2792 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
2794 // We allow servers to request renegotiation. Since we're a client,
2795 // prohibiting this is rather a waste of time. Only servers are in a
2796 // position to prevent renegotiation attacks.
2797 // http://extendedsubset.com/?p=8
2799 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
2800 SSL_RENEGOTIATE_TRANSITIONAL
);
2801 if (rv
!= SECSuccess
) {
2802 LogFailedNSSFunction(
2803 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
2806 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
2807 if (rv
!= SECSuccess
)
2808 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
2810 // Added in NSS 3.15
2811 #ifdef SSL_ENABLE_OCSP_STAPLING
2812 // Request OCSP stapling even on platforms that don't support it, in
2813 // order to extract Certificate Transparency information.
2814 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
,
2815 cert_verifier_
->SupportsOCSPStapling() ||
2816 ssl_config_
.signed_cert_timestamps_enabled
);
2817 if (rv
!= SECSuccess
) {
2818 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
2819 "SSL_ENABLE_OCSP_STAPLING");
2823 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS
,
2824 ssl_config_
.signed_cert_timestamps_enabled
);
2825 if (rv
!= SECSuccess
) {
2826 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
2827 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
2830 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
2831 if (rv
!= SECSuccess
) {
2832 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
2833 return ERR_UNEXPECTED
;
2836 if (!core_
->Init(nss_fd_
, nss_bufs
))
2837 return ERR_UNEXPECTED
;
2839 // Tell SSL the hostname we're trying to connect to.
2840 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
2842 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
2843 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
2848 int SSLClientSocketNSS::InitializeSSLPeerName() {
2849 // Tell NSS who we're connected to
2850 IPEndPoint peer_address
;
2851 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
2855 SockaddrStorage storage
;
2856 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
2857 return ERR_ADDRESS_INVALID
;
2860 memset(&peername
, 0, sizeof(peername
));
2861 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
2862 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
2864 memcpy(&peername
, storage
.addr
, len
);
2866 // Adjust the address family field for BSD, whose sockaddr
2867 // structure has a one-byte length and one-byte address family
2868 // field at the beginning. PRNetAddr has a two-byte address
2869 // family field at the beginning.
2870 peername
.raw
.family
= storage
.addr
->sa_family
;
2872 memio_SetPeerName(nss_fd_
, &peername
);
2874 // Set the peer ID for session reuse. This is necessary when we create an
2875 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
2876 // rather than the destination server's address in that case.
2877 std::string peer_id
= host_and_port_
.ToString();
2878 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
2879 // the session cache for incognito mode.
2880 peer_id
+= "/" + ssl_session_cache_shard_
;
2882 // Shard the session cache based on maximum protocol version. This causes
2883 // fallback connections to use a separate session cache.
2884 switch (ssl_config_
.version_max
) {
2885 case SSL_PROTOCOL_VERSION_SSL3
:
2888 case SSL_PROTOCOL_VERSION_TLS1
:
2891 case SSL_PROTOCOL_VERSION_TLS1_1
:
2892 peer_id
+= "tls1.1";
2894 case SSL_PROTOCOL_VERSION_TLS1_2
:
2895 peer_id
+= "tls1.2";
2901 if (ssl_config_
.enable_deprecated_cipher_suites
)
2902 peer_id
+= "deprecated";
2904 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
2905 if (rv
!= SECSuccess
)
2906 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
2911 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
2913 DCHECK_NE(ERR_IO_PENDING
, rv
);
2914 DCHECK(!user_connect_callback_
.is_null());
2916 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
2920 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
2921 EnterFunction(result
);
2922 int rv
= DoHandshakeLoop(result
);
2923 if (rv
!= ERR_IO_PENDING
) {
2924 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2925 DoConnectCallback(rv
);
2930 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
2931 EnterFunction(last_io_result
);
2932 int rv
= last_io_result
;
2934 // Default to STATE_NONE for next state.
2935 // (This is a quirk carried over from the windows
2936 // implementation. It makes reading the logs a bit harder.)
2937 // State handlers can and often do call GotoState just
2938 // to stay in the current state.
2939 State state
= next_handshake_state_
;
2940 GotoState(STATE_NONE
);
2942 case STATE_HANDSHAKE
:
2945 case STATE_HANDSHAKE_COMPLETE
:
2946 rv
= DoHandshakeComplete(rv
);
2948 case STATE_VERIFY_CERT
:
2950 rv
= DoVerifyCert(rv
);
2952 case STATE_VERIFY_CERT_COMPLETE
:
2953 rv
= DoVerifyCertComplete(rv
);
2957 rv
= ERR_UNEXPECTED
;
2958 LOG(DFATAL
) << "unexpected state " << state
;
2961 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
2966 int SSLClientSocketNSS::DoHandshake() {
2968 int rv
= core_
->Connect(
2969 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
2970 base::Unretained(this)));
2971 GotoState(STATE_HANDSHAKE_COMPLETE
);
2977 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
2978 EnterFunction(result
);
2981 if (ssl_config_
.version_fallback
&&
2982 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
2983 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
2986 RecordNegotiationExtension();
2988 // SSL handshake is completed. Let's verify the certificate.
2989 GotoState(STATE_VERIFY_CERT
);
2992 set_signed_cert_timestamps_received(
2993 !core_
->state().sct_list_from_tls_extension
.empty());
2994 set_stapled_ocsp_response_received(
2995 !core_
->state().stapled_ocsp_response
.empty());
2996 set_negotiation_extension(core_
->state().negotiation_extension_
);
2998 LeaveFunction(result
);
3002 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3003 DCHECK(!core_
->state().server_cert_chain
.empty());
3004 DCHECK(core_
->state().server_cert_chain
[0]);
3006 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3008 // If the certificate is expected to be bad we can use the expectation as
3010 base::StringPiece
der_cert(
3011 reinterpret_cast<char*>(
3012 core_
->state().server_cert_chain
[0]->derCert
.data
),
3013 core_
->state().server_cert_chain
[0]->derCert
.len
);
3014 CertStatus cert_status
;
3015 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3016 DCHECK(start_cert_verification_time_
.is_null());
3017 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3018 server_cert_verify_result_
.Reset();
3019 server_cert_verify_result_
.cert_status
= cert_status
;
3020 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3024 // We may have failed to create X509Certificate object if we are
3025 // running inside sandbox.
3026 if (!core_
->state().server_cert
.get()) {
3027 server_cert_verify_result_
.Reset();
3028 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3029 return ERR_CERT_INVALID
;
3032 start_cert_verification_time_
= base::TimeTicks::Now();
3035 if (ssl_config_
.rev_checking_enabled
)
3036 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3037 if (ssl_config_
.verify_ev_cert
)
3038 flags
|= CertVerifier::VERIFY_EV_CERT
;
3039 if (ssl_config_
.cert_io_enabled
)
3040 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3041 if (ssl_config_
.rev_checking_required_local_anchors
)
3042 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3043 return cert_verifier_
->Verify(
3044 core_
->state().server_cert
.get(), host_and_port_
.host(),
3045 core_
->state().stapled_ocsp_response
, flags
,
3046 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_
,
3047 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3048 base::Unretained(this)),
3049 &cert_verifier_request_
, net_log_
);
3052 // Derived from AuthCertificateCallback() in
3053 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3054 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3055 cert_verifier_request_
.reset();
3057 if (!start_cert_verification_time_
.is_null()) {
3058 base::TimeDelta verify_time
=
3059 base::TimeTicks::Now() - start_cert_verification_time_
;
3061 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3063 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3066 // We used to remember the intermediate CA certs in the NSS database
3067 // persistently. However, NSS opens a connection to the SQLite database
3068 // during NSS initialization and doesn't close the connection until NSS
3069 // shuts down. If the file system where the database resides is gone,
3070 // the database connection goes bad. What's worse, the connection won't
3071 // recover when the file system comes back. Until this NSS or SQLite bug
3072 // is fixed, we need to avoid using the NSS database for non-essential
3073 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3074 // http://crbug.com/15630 for more info.
3076 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3077 if (transport_security_state_
&&
3079 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3080 !transport_security_state_
->CheckPublicKeyPins(
3081 host_and_port_
.host(),
3082 server_cert_verify_result_
.is_issued_by_known_root
,
3083 server_cert_verify_result_
.public_key_hashes
,
3084 &pinning_failure_log_
)) {
3085 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3089 // Only check Certificate Transparency if there were no other errors with
3093 // Only cache the session if the certificate verified successfully.
3094 core_
->CacheSessionIfNecessary();
3097 completed_handshake_
= true;
3099 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3100 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3104 void SSLClientSocketNSS::VerifyCT() {
3105 if (!cert_transparency_verifier_
)
3108 // Note that this is a completely synchronous operation: The CT Log Verifier
3109 // gets all the data it needs for SCT verification and does not do any
3110 // external communication.
3111 cert_transparency_verifier_
->Verify(
3112 server_cert_verify_result_
.verified_cert
.get(),
3113 core_
->state().stapled_ocsp_response
,
3114 core_
->state().sct_list_from_tls_extension
, &ct_verify_result_
, net_log_
);
3115 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3116 // from the state after verification is complete, to conserve memory.
3118 if (!policy_enforcer_
) {
3119 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3121 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
3122 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
3123 SSLConfigService::GetEVCertsWhitelist();
3124 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
3125 server_cert_verify_result_
.verified_cert
.get(),
3126 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
3127 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3128 VLOG(1) << "EV certificate for "
3129 << server_cert_verify_result_
.verified_cert
->subject()
3131 << " does not conform to CT policy, removing EV status.";
3132 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3138 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3139 base::AutoLock
auto_lock(lock_
);
3140 if (valid_thread_id_
!= base::kInvalidThreadId
)
3142 valid_thread_id_
= base::PlatformThread::CurrentId();
3145 bool SSLClientSocketNSS::CalledOnValidThread() const {
3146 EnsureThreadIdAssigned();
3147 base::AutoLock
auto_lock(lock_
);
3148 return valid_thread_id_
== base::PlatformThread::CurrentId();
3151 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
3152 for (ct::SCTList::const_iterator iter
=
3153 ct_verify_result_
.verified_scts
.begin();
3154 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
3155 ssl_info
->signed_certificate_timestamps
.push_back(
3156 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
3158 for (ct::SCTList::const_iterator iter
=
3159 ct_verify_result_
.invalid_scts
.begin();
3160 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
3161 ssl_info
->signed_certificate_timestamps
.push_back(
3162 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
3164 for (ct::SCTList::const_iterator iter
=
3165 ct_verify_result_
.unknown_logs_scts
.begin();
3166 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
3167 ssl_info
->signed_certificate_timestamps
.push_back(
3168 SignedCertificateTimestampAndStatus(*iter
,
3169 ct::SCT_STATUS_LOG_UNKNOWN
));
3173 scoped_refptr
<X509Certificate
>
3174 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3175 return core_
->state().server_cert
.get();
3178 ChannelIDService
* SSLClientSocketNSS::GetChannelIDService() const {
3179 return channel_id_service_
;