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/memory/singleton.h"
73 #include "base/metrics/histogram.h"
74 #include "base/single_thread_task_runner.h"
75 #include "base/stl_util.h"
76 #include "base/strings/string_number_conversions.h"
77 #include "base/strings/string_util.h"
78 #include "base/strings/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/dns_util.h"
89 #include "net/base/io_buffer.h"
90 #include "net/base/net_errors.h"
91 #include "net/cert/asn1_util.h"
92 #include "net/cert/cert_policy_enforcer.h"
93 #include "net/cert/cert_status_flags.h"
94 #include "net/cert/cert_verifier.h"
95 #include "net/cert/ct_ev_whitelist.h"
96 #include "net/cert/ct_verifier.h"
97 #include "net/cert/ct_verify_result.h"
98 #include "net/cert/scoped_nss_types.h"
99 #include "net/cert/sct_status_flags.h"
100 #include "net/cert/single_request_cert_verifier.h"
101 #include "net/cert/x509_certificate_net_log_param.h"
102 #include "net/cert/x509_util.h"
103 #include "net/cert_net/nss_ocsp.h"
104 #include "net/http/transport_security_state.h"
105 #include "net/log/net_log.h"
106 #include "net/socket/client_socket_handle.h"
107 #include "net/socket/nss_ssl_util.h"
108 #include "net/ssl/ssl_cert_request_info.h"
109 #include "net/ssl/ssl_cipher_suite_names.h"
110 #include "net/ssl/ssl_connection_status_flags.h"
111 #include "net/ssl/ssl_info.h"
113 #if defined(USE_NSS_CERTS)
119 // State machines are easier to debug if you log state transitions.
120 // Enable these if you want to see what's going on.
122 #define EnterFunction(x)
123 #define LeaveFunction(x)
124 #define GotoState(s) next_handshake_state_ = s
126 #define EnterFunction(x)\
127 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
128 << "; next_handshake_state " << next_handshake_state_
129 #define LeaveFunction(x)\
130 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
131 << "; next_handshake_state " << next_handshake_state_
132 #define GotoState(s)\
134 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
135 next_handshake_state_ = s;\
139 #if !defined(CKM_AES_GCM)
140 #define CKM_AES_GCM 0x00001087
143 #if !defined(CKM_NSS_CHACHA20_POLY1305)
144 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
149 // SSL plaintext fragments are shorter than 16KB. Although the record layer
150 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
151 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
152 // entire SSL record.
153 const int kRecvBufferSize
= 17 * 1024;
154 const int kSendBufferSize
= 17 * 1024;
156 // Used by SSLClientSocketNSS::Core to indicate there is no read result
157 // obtained by a previous operation waiting to be returned to the caller.
158 // This constant can be any non-negative/non-zero value (eg: it does not
159 // overlap with any value of the net::Error range, including net::OK).
160 const int kNoPendingReadResult
= 1;
162 #if defined(USE_NSS_CERTS)
164 (*CacheOCSPResponseFromSideChannelFunction
)(
165 CERTCertDBHandle
*handle
, CERTCertificate
*cert
, PRTime time
,
166 SECItem
*encodedResponse
, void *pwArg
);
168 // On Linux, we dynamically link against the system version of libnss3.so. In
169 // order to continue working on systems without up-to-date versions of NSS we
170 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
172 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
173 // runtime symbol resolution that we need.
174 class RuntimeLibNSSFunctionPointers
{
176 CacheOCSPResponseFromSideChannelFunction
177 GetCacheOCSPResponseFromSideChannelFunction() {
178 return cache_ocsp_response_from_side_channel_
;
181 static RuntimeLibNSSFunctionPointers
* GetInstance() {
182 return Singleton
<RuntimeLibNSSFunctionPointers
>::get();
186 friend struct DefaultSingletonTraits
<RuntimeLibNSSFunctionPointers
>;
188 RuntimeLibNSSFunctionPointers() {
189 cache_ocsp_response_from_side_channel_
=
190 (CacheOCSPResponseFromSideChannelFunction
)
191 dlsym(RTLD_DEFAULT
, "CERT_CacheOCSPResponseFromSideChannel");
194 CacheOCSPResponseFromSideChannelFunction
195 cache_ocsp_response_from_side_channel_
;
198 CacheOCSPResponseFromSideChannelFunction
199 GetCacheOCSPResponseFromSideChannelFunction() {
200 return RuntimeLibNSSFunctionPointers::GetInstance()
201 ->GetCacheOCSPResponseFromSideChannelFunction();
204 bool IsOCSPStaplingSupported() {
205 return GetCacheOCSPResponseFromSideChannelFunction() != NULL
;
208 bool IsOCSPStaplingSupported() {
213 // Helper functions to make it possible to log events from within the
214 // SSLClientSocketNSS::Core.
215 void AddLogEvent(const base::WeakPtr
<BoundNetLog
>& net_log
,
216 NetLog::EventType event_type
) {
219 net_log
->AddEvent(event_type
);
222 // Helper function to make it possible to log events from within the
223 // SSLClientSocketNSS::Core.
224 void AddLogEventWithCallback(const base::WeakPtr
<BoundNetLog
>& net_log
,
225 NetLog::EventType event_type
,
226 const NetLog::ParametersCallback
& callback
) {
229 net_log
->AddEvent(event_type
, callback
);
232 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
233 // from within the SSLClientSocketNSS::Core.
234 // AddByteTransferEvent expects to receive a const char*, which within the
235 // Core is backed by an IOBuffer. If the "const char*" is bound via
236 // base::Bind and posted to another thread, and the IOBuffer that backs that
237 // pointer then goes out of scope on the origin thread, this would result in
238 // an invalid read of a stale pointer.
239 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
240 // to the owning IOBuffer can be bound to the Callback. This ensures that the
241 // IOBuffer will stay alive long enough to cross threads if needed.
242 void LogByteTransferEvent(
243 const base::WeakPtr
<BoundNetLog
>& net_log
, NetLog::EventType event_type
,
244 int len
, IOBuffer
* buffer
) {
247 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
250 // PeerCertificateChain is a helper object which extracts the certificate
251 // chain, as given by the server, from an NSS socket and performs the needed
252 // resource management. The first element of the chain is the leaf certificate
253 // and the other elements are in the order given by the server.
254 class PeerCertificateChain
{
256 PeerCertificateChain() {}
257 PeerCertificateChain(const PeerCertificateChain
& other
);
258 ~PeerCertificateChain();
259 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
261 // Resets the current chain, freeing any resources, and updates the current
262 // chain to be a copy of the chain stored in |nss_fd|.
263 // If |nss_fd| is NULL, then the current certificate chain will be freed.
264 void Reset(PRFileDesc
* nss_fd
);
266 // Returns the current certificate chain as a vector of DER-encoded
267 // base::StringPieces. The returned vector remains valid until Reset is
269 std::vector
<base::StringPiece
> AsStringPieceVector() const;
271 bool empty() const { return certs_
.empty(); }
273 CERTCertificate
* operator[](size_t index
) const {
274 DCHECK_LT(index
, certs_
.size());
275 return certs_
[index
];
279 std::vector
<CERTCertificate
*> certs_
;
282 PeerCertificateChain::PeerCertificateChain(
283 const PeerCertificateChain
& other
) {
287 PeerCertificateChain::~PeerCertificateChain() {
291 PeerCertificateChain
& PeerCertificateChain::operator=(
292 const PeerCertificateChain
& other
) {
297 certs_
.reserve(other
.certs_
.size());
298 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
299 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
304 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
305 for (size_t i
= 0; i
< certs_
.size(); ++i
)
306 CERT_DestroyCertificate(certs_
[i
]);
312 CERTCertList
* list
= SSL_PeerCertificateChain(nss_fd
);
313 // The handshake on |nss_fd| may not have completed.
317 for (CERTCertListNode
* node
= CERT_LIST_HEAD(list
);
318 !CERT_LIST_END(node
, list
); node
= CERT_LIST_NEXT(node
)) {
319 certs_
.push_back(CERT_DupCertificate(node
->cert
));
321 CERT_DestroyCertList(list
);
324 std::vector
<base::StringPiece
>
325 PeerCertificateChain::AsStringPieceVector() const {
326 std::vector
<base::StringPiece
> v(certs_
.size());
327 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
328 v
[i
] = base::StringPiece(
329 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
330 certs_
[i
]->derCert
.len
);
336 // HandshakeState is a helper struct used to pass handshake state between
337 // the NSS task runner and the network task runner.
339 // It contains members that may be read or written on the NSS task runner,
340 // but which also need to be read from the network task runner. The NSS task
341 // runner will notify the network task runner whenever this state changes, so
342 // that the network task runner can safely make a copy, which avoids the need
344 struct HandshakeState
{
345 HandshakeState() { Reset(); }
348 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
350 negotiation_extension_
= SSLClientSocket::kExtensionUnknown
;
351 channel_id_sent
= false;
352 server_cert_chain
.Reset(NULL
);
354 sct_list_from_tls_extension
.clear();
355 stapled_ocsp_response
.clear();
356 resumed_handshake
= false;
357 ssl_connection_status
= 0;
360 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
361 // negotiated protocol stored in |next_proto|.
362 SSLClientSocket::NextProtoStatus next_proto_status
;
363 std::string next_proto
;
365 // TLS extension used for protocol negotiation.
366 SSLClientSocket::SSLNegotiationExtension negotiation_extension_
;
368 // True if a channel ID was sent.
369 bool channel_id_sent
;
371 // List of DER-encoded X.509 DistinguishedName of certificate authorities
372 // allowed by the server.
373 std::vector
<std::string
> cert_authorities
;
375 // Set when the handshake fully completes.
377 // The server certificate is first received from NSS as an NSS certificate
378 // chain (|server_cert_chain|) and then converted into a platform-specific
379 // X509Certificate object (|server_cert|). It's possible for some
380 // certificates to be successfully parsed by NSS, and not by the platform
381 // libraries (i.e.: when running within a sandbox, different parsing
382 // algorithms, etc), so it's not safe to assume that |server_cert| will
383 // always be non-NULL.
384 PeerCertificateChain server_cert_chain
;
385 scoped_refptr
<X509Certificate
> server_cert
;
386 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
387 std::string sct_list_from_tls_extension
;
388 // Stapled OCSP response received.
389 std::string stapled_ocsp_response
;
391 // True if the current handshake was the result of TLS session resumption.
392 bool resumed_handshake
;
394 // The negotiated security parameters (TLS version, cipher, extensions) of
395 // the SSL connection.
396 int ssl_connection_status
;
399 // Client-side error mapping functions.
401 // Map NSS error code to network error code.
402 int MapNSSClientError(PRErrorCode err
) {
404 case SSL_ERROR_BAD_CERT_ALERT
:
405 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
406 case SSL_ERROR_REVOKED_CERT_ALERT
:
407 case SSL_ERROR_EXPIRED_CERT_ALERT
:
408 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
409 case SSL_ERROR_UNKNOWN_CA_ALERT
:
410 case SSL_ERROR_ACCESS_DENIED_ALERT
:
411 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
413 return MapNSSError(err
);
419 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
420 // able to marshal data between NSS functions and an underlying transport
423 // All public functions are meant to be called from the network task runner,
424 // and any callbacks supplied will be invoked there as well, provided that
425 // Detach() has not been called yet.
427 /////////////////////////////////////////////////////////////////////////////
429 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
431 // Because NSS may block on either hardware or user input during operations
432 // such as signing, creating certificates, or locating private keys, the Core
433 // handles all of the interactions with the underlying NSS SSL socket, so
434 // that these blocking calls can be executed on a dedicated task runner.
436 // Note that the network task runner and the NSS task runner may be executing
437 // on the same thread. If that happens, then it's more performant to try to
438 // complete as much work as possible synchronously, even if it might block,
439 // rather than continually PostTask-ing to the same thread.
441 // Because NSS functions should only be called on the NSS task runner, while
442 // I/O resources should only be accessed on the network task runner, most
443 // public functions are implemented via three methods, each with different
444 // task runner affinities.
446 // In the single-threaded mode (where the network and NSS task runners run on
447 // the same thread), these are all attempted synchronously, while in the
448 // multi-threaded mode, message passing is used.
450 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
452 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
453 // (BufferRecv, BufferSend)
454 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
455 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
456 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
457 // data from the network task runner back to NSS (BufferRecvComplete,
458 // BufferSendComplete, OnHandshakeIOComplete)
460 /////////////////////////////////////////////////////////////////////////////
461 // Single-threaded example
463 // |--------------------------Network Task Runner--------------------------|
464 // SSLClientSocketNSS Core (Transport Socket)
466 // |-------------------------V
474 // |-------------------------V
476 // V-------------------------|
477 // BufferRecvComplete()
479 // PostOrRunCallback()
480 // V-------------------------|
483 /////////////////////////////////////////////////////////////////////////////
484 // Multi-threaded example:
486 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
487 // SSLClientSocketNSS Core Socket Core
489 // |---------------------V
491 // |-------------------------------V
497 // V-------------------------------|
499 // |----------------V
501 // V----------------|
502 // BufferRecvComplete()
503 // |-------------------------------V
504 // BufferRecvComplete()
506 // PostOrRunCallback()
507 // V-------------------------------|
508 // PostOrRunCallback()
509 // V---------------------|
512 /////////////////////////////////////////////////////////////////////////////
513 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
515 // Creates a new Core.
517 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
518 // that need to operate on the underlying transport, net log, or server
519 // bound certificate fetching will happen on the |network_task_runner|, so
520 // that their lifetimes match that of the owning SSLClientSocketNSS.
522 // The caller retains ownership of |transport|, |net_log|, and
523 // |channel_id_service|, and they will not be accessed once Detach()
525 Core(base::SequencedTaskRunner
* network_task_runner
,
526 base::SequencedTaskRunner
* nss_task_runner
,
527 ClientSocketHandle
* transport
,
528 const HostPortPair
& host_and_port
,
529 const SSLConfig
& ssl_config
,
530 BoundNetLog
* net_log
,
531 ChannelIDService
* channel_id_service
);
533 // Called on the network task runner.
534 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
535 // underlying memio implementation, to the Core. Returns true if the Core
536 // was successfully registered with the socket.
537 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
539 // Called on the network task runner.
541 // Attempts to perform an SSL handshake. If the handshake cannot be
542 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
543 // the network task runner once the handshake has completed. Otherwise,
544 // returns OK on success or a network error code on failure.
545 int Connect(const CompletionCallback
& callback
);
547 // Called on the network task runner.
548 // Signals that the resources owned by the network task runner are going
549 // away. No further callbacks will be invoked on the network task runner.
550 // May be called at any time.
553 // Called on the network task runner.
554 // Returns the current state of the underlying SSL socket. May be called at
556 const HandshakeState
& state() const { return network_handshake_state_
; }
558 // Called on the network task runner.
559 // Read() and Write() mirror the net::Socket functions of the same name.
560 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
561 // task runner at a later point, unless the caller calls Detach().
562 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
563 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
565 // Called on the network task runner.
566 bool IsConnected() const;
567 bool HasPendingAsyncOperation() const;
568 bool HasUnhandledReceivedData() const;
569 bool WasEverUsed() const;
571 // Called on the network task runner.
572 // Causes the associated SSL/TLS session ID to be added to NSS's session
573 // cache, but only if the connection has not been False Started.
575 // This should only be called after the server's certificate has been
576 // verified, and may not be called within an NSS callback.
577 void CacheSessionIfNecessary();
580 friend class base::RefCountedThreadSafe
<Core
>;
586 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
589 bool OnNSSTaskRunner() const;
590 bool OnNetworkTaskRunner() const;
592 ////////////////////////////////////////////////////////////////////////////
593 // Methods that are ONLY called on the NSS task runner:
594 ////////////////////////////////////////////////////////////////////////////
596 // Called by NSS during full handshakes to allow the application to
597 // verify the certificate. Instead of verifying the certificate in the midst
598 // of the handshake, SECSuccess is always returned and the peer's certificate
599 // is verified afterwards.
600 // This behaviour is an artifact of the original SSLClientSocketWin
601 // implementation, which could not verify the peer's certificate until after
602 // the handshake had completed, as well as bugs in NSS that prevent
603 // SSL_RestartHandshakeAfterCertReq from working.
604 static SECStatus
OwnAuthCertHandler(void* arg
,
609 // Callbacks called by NSS when the peer requests client certificate
611 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
613 static SECStatus
ClientAuthHandler(void* arg
,
615 CERTDistNames
* ca_names
,
616 CERTCertificate
** result_certificate
,
617 SECKEYPrivateKey
** result_private_key
);
619 // Called by NSS to determine if we can False Start.
620 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
621 static SECStatus
CanFalseStartCallback(PRFileDesc
* socket
,
623 PRBool
* can_false_start
);
625 // Called by NSS once the handshake has completed.
626 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
627 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
629 // Called once the handshake has succeeded.
630 void HandshakeSucceeded();
632 // Handles an NSS error generated while handshaking or performing IO.
633 // Returns a network error code mapped from the original NSS error.
634 int HandleNSSError(PRErrorCode error
);
636 int DoHandshakeLoop(int last_io_result
);
637 int DoReadLoop(int result
);
638 int DoWriteLoop(int result
);
641 int DoGetDBCertComplete(int result
);
644 int DoPayloadWrite();
646 bool DoTransportIO();
650 void OnRecvComplete(int result
);
651 void OnSendComplete(int result
);
653 void DoConnectCallback(int result
);
654 void DoReadCallback(int result
);
655 void DoWriteCallback(int result
);
657 // Client channel ID handler.
658 static SECStatus
ClientChannelIDHandler(
661 SECKEYPublicKey
**out_public_key
,
662 SECKEYPrivateKey
**out_private_key
);
664 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
665 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
666 // and an error code otherwise.
667 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
668 // set by a call to ChannelIDService->GetChannelID. The caller
669 // takes ownership of the |*cert| and |*key|.
670 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
672 // Updates the NSS and platform specific certificates.
673 void UpdateServerCert();
674 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
675 // received in the handshake via a TLS extension.
676 void UpdateSignedCertTimestamps();
677 // Update the OCSP response cache with the stapled response received in the
678 // handshake, and update nss_handshake_state_ with
679 // the SignedCertificateTimestampList received in the stapled OCSP response.
680 void UpdateStapledOCSPResponse();
681 // Updates the nss_handshake_state_ with the negotiated security parameters.
682 void UpdateConnectionStatus();
683 // Record histograms for channel id support during full handshakes - resumed
684 // handshakes are ignored.
685 void RecordChannelIDSupportOnNSSTaskRunner();
686 // UpdateNextProto gets any application-layer protocol that may have been
687 // negotiated by the TLS connection.
688 void UpdateNextProto();
689 // Record TLS extension used for protocol negotiation (NPN or ALPN).
690 void UpdateExtensionUsed();
692 ////////////////////////////////////////////////////////////////////////////
693 // Methods that are ONLY called on the network task runner:
694 ////////////////////////////////////////////////////////////////////////////
695 int DoBufferRecv(IOBuffer
* buffer
, int len
);
696 int DoBufferSend(IOBuffer
* buffer
, int len
);
697 int DoGetChannelID(const std::string
& host
);
699 void OnGetChannelIDComplete(int result
);
700 void OnHandshakeStateUpdated(const HandshakeState
& state
);
701 void OnNSSBufferUpdated(int amount_in_read_buffer
);
702 void DidNSSRead(int result
);
703 void DidNSSWrite(int result
);
704 void RecordChannelIDSupportOnNetworkTaskRunner(
705 bool negotiated_channel_id
,
706 bool channel_id_enabled
,
707 bool supports_ecc
) const;
709 ////////////////////////////////////////////////////////////////////////////
710 // Methods that are called on both the network task runner and the NSS
712 ////////////////////////////////////////////////////////////////////////////
713 void OnHandshakeIOComplete(int result
);
714 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
715 void BufferSendComplete(int result
);
717 // PostOrRunCallback is a helper function to ensure that |callback| is
718 // invoked on the network task runner, but only if Detach() has not yet
720 void PostOrRunCallback(const tracked_objects::Location
& location
,
721 const base::Closure
& callback
);
723 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
724 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
725 void AddCertProvidedEvent(int cert_count
);
727 // Sets the handshake state |channel_id_sent| flag and logs the
728 // SSL_CHANNEL_ID_PROVIDED event.
729 void SetChannelIDProvided();
731 ////////////////////////////////////////////////////////////////////////////
732 // Members that are ONLY accessed on the network task runner:
733 ////////////////////////////////////////////////////////////////////////////
735 // True if the owning SSLClientSocketNSS has called Detach(). No further
736 // callbacks will be invoked nor access to members owned by the network
740 // The underlying transport to use for network IO.
741 ClientSocketHandle
* transport_
;
742 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
744 // The current handshake state. Mirrors |nss_handshake_state_|.
745 HandshakeState network_handshake_state_
;
747 // The service for retrieving Channel ID keys. May be NULL.
748 ChannelIDService
* channel_id_service_
;
749 ChannelIDService::RequestHandle domain_bound_cert_request_handle_
;
751 // The information about NSS task runner.
752 int unhandled_buffer_size_
;
753 bool nss_waiting_read_
;
754 bool nss_waiting_write_
;
757 // Set when Read() or Write() successfully reads or writes data to or from the
761 ////////////////////////////////////////////////////////////////////////////
762 // Members that are ONLY accessed on the NSS task runner:
763 ////////////////////////////////////////////////////////////////////////////
764 HostPortPair host_and_port_
;
765 SSLConfig ssl_config_
;
770 // Buffers for the network end of the SSL state machine
771 memio_Private
* nss_bufs_
;
773 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
774 // as much data as possible, without blocking.
775 // If DoPayloadRead() encounters an error after having read some data, stores
776 // the results to return on the *next* call to DoPayloadRead(). A value of
777 // kNoPendingReadResult indicates there is no pending result, otherwise 0
778 // indicates EOF and < 0 indicates an error.
779 int pending_read_result_
;
780 // Contains the previously observed NSS error. Only valid when
781 // pending_read_result_ != kNoPendingReadResult.
782 PRErrorCode pending_read_nss_error_
;
784 // The certificate chain, in DER form, that is expected to be received from
786 std::vector
<std::string
> predicted_certs_
;
788 State next_handshake_state_
;
790 // True if channel ID extension was negotiated.
791 bool channel_id_xtn_negotiated_
;
792 // True if the handshake state machine was interrupted for channel ID.
793 bool channel_id_needed_
;
794 // True if the handshake state machine was interrupted for client auth.
795 bool client_auth_cert_needed_
;
796 // True if NSS has False Started.
798 // True if NSS has called HandshakeCallback.
799 bool handshake_callback_called_
;
801 HandshakeState nss_handshake_state_
;
803 bool transport_recv_busy_
;
804 bool transport_recv_eof_
;
805 bool transport_send_busy_
;
807 // Used by Read function.
808 scoped_refptr
<IOBuffer
> user_read_buf_
;
809 int user_read_buf_len_
;
811 // Used by Write function.
812 scoped_refptr
<IOBuffer
> user_write_buf_
;
813 int user_write_buf_len_
;
815 CompletionCallback user_connect_callback_
;
816 CompletionCallback user_read_callback_
;
817 CompletionCallback user_write_callback_
;
819 ////////////////////////////////////////////////////////////////////////////
820 // Members that are accessed on both the network task runner and the NSS
822 ////////////////////////////////////////////////////////////////////////////
823 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
824 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
826 // Dereferenced only on the network task runner, but bound to tasks destined
827 // for the network task runner from the NSS task runner.
828 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
830 // Written on the network task runner by the |channel_id_service_|,
831 // prior to invoking OnHandshakeIOComplete.
832 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
833 // on the NSS task runner.
834 std::string domain_bound_private_key_
;
835 std::string domain_bound_cert_
;
837 DISALLOW_COPY_AND_ASSIGN(Core
);
840 SSLClientSocketNSS::Core::Core(
841 base::SequencedTaskRunner
* network_task_runner
,
842 base::SequencedTaskRunner
* nss_task_runner
,
843 ClientSocketHandle
* transport
,
844 const HostPortPair
& host_and_port
,
845 const SSLConfig
& ssl_config
,
846 BoundNetLog
* net_log
,
847 ChannelIDService
* channel_id_service
)
849 transport_(transport
),
850 weak_net_log_factory_(net_log
),
851 channel_id_service_(channel_id_service
),
852 unhandled_buffer_size_(0),
853 nss_waiting_read_(false),
854 nss_waiting_write_(false),
855 nss_is_closed_(false),
856 was_ever_used_(false),
857 host_and_port_(host_and_port
),
858 ssl_config_(ssl_config
),
861 pending_read_result_(kNoPendingReadResult
),
862 pending_read_nss_error_(0),
863 next_handshake_state_(STATE_NONE
),
864 channel_id_xtn_negotiated_(false),
865 channel_id_needed_(false),
866 client_auth_cert_needed_(false),
867 false_started_(false),
868 handshake_callback_called_(false),
869 transport_recv_busy_(false),
870 transport_recv_eof_(false),
871 transport_send_busy_(false),
872 user_read_buf_len_(0),
873 user_write_buf_len_(0),
874 network_task_runner_(network_task_runner
),
875 nss_task_runner_(nss_task_runner
),
876 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
879 SSLClientSocketNSS::Core::~Core() {
880 // TODO(wtc): Send SSL close_notify alert.
881 if (nss_fd_
!= NULL
) {
888 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
889 memio_Private
* buffers
) {
890 DCHECK(OnNetworkTaskRunner());
897 SECStatus rv
= SECSuccess
;
899 if (!ssl_config_
.next_protos
.empty()) {
900 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
901 const bool adequate_encryption
=
902 PK11_TokenExists(CKM_AES_GCM
) ||
903 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305
);
904 const bool adequate_key_agreement
= PK11_TokenExists(CKM_DH_PKCS_DERIVE
) ||
905 PK11_TokenExists(CKM_ECDH1_DERIVE
);
906 std::vector
<uint8_t> wire_protos
=
907 SerializeNextProtos(ssl_config_
.next_protos
,
908 adequate_encryption
&& adequate_key_agreement
&&
909 IsTLSVersionAdequateForHTTP2(ssl_config_
));
910 rv
= SSL_SetNextProtoNego(
911 nss_fd_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
913 if (rv
!= SECSuccess
)
914 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoNego", "");
915 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_ALPN
, PR_TRUE
);
916 if (rv
!= SECSuccess
)
917 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_ALPN");
918 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_NPN
, PR_TRUE
);
919 if (rv
!= SECSuccess
)
920 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_NPN");
923 rv
= SSL_AuthCertificateHook(
924 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
925 if (rv
!= SECSuccess
) {
926 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
930 rv
= SSL_GetClientAuthDataHook(
931 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
932 if (rv
!= SECSuccess
) {
933 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
937 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
938 rv
= SSL_SetClientChannelIDCallback(
939 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
940 if (rv
!= SECSuccess
) {
941 LogFailedNSSFunction(
942 *weak_net_log_
, "SSL_SetClientChannelIDCallback", "");
946 rv
= SSL_SetCanFalseStartCallback(
947 nss_fd_
, SSLClientSocketNSS::Core::CanFalseStartCallback
, this);
948 if (rv
!= SECSuccess
) {
949 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetCanFalseStartCallback", "");
953 rv
= SSL_HandshakeCallback(
954 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
955 if (rv
!= SECSuccess
) {
956 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
963 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
964 if (!OnNSSTaskRunner()) {
966 bool posted
= nss_task_runner_
->PostTask(
968 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
969 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
972 DCHECK(OnNSSTaskRunner());
973 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
974 DCHECK(user_read_callback_
.is_null());
975 DCHECK(user_write_callback_
.is_null());
976 DCHECK(user_connect_callback_
.is_null());
977 DCHECK(!user_read_buf_
.get());
978 DCHECK(!user_write_buf_
.get());
980 next_handshake_state_
= STATE_HANDSHAKE
;
981 int rv
= DoHandshakeLoop(OK
);
982 if (rv
== ERR_IO_PENDING
) {
983 user_connect_callback_
= callback
;
984 } else if (rv
> OK
) {
987 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
988 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
989 return ERR_IO_PENDING
;
995 void SSLClientSocketNSS::Core::Detach() {
996 DCHECK(OnNetworkTaskRunner());
1000 weak_net_log_factory_
.InvalidateWeakPtrs();
1002 network_handshake_state_
.Reset();
1004 domain_bound_cert_request_handle_
.Cancel();
1007 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1008 const CompletionCallback
& callback
) {
1009 if (!OnNSSTaskRunner()) {
1010 DCHECK(OnNetworkTaskRunner());
1013 DCHECK(!nss_waiting_read_
);
1015 nss_waiting_read_
= true;
1016 bool posted
= nss_task_runner_
->PostTask(
1018 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1019 buf_len
, callback
));
1021 nss_is_closed_
= true;
1022 nss_waiting_read_
= false;
1024 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1027 DCHECK(OnNSSTaskRunner());
1028 DCHECK(false_started_
|| handshake_callback_called_
);
1029 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1030 DCHECK(user_read_callback_
.is_null());
1031 DCHECK(user_connect_callback_
.is_null());
1032 DCHECK(!user_read_buf_
.get());
1035 user_read_buf_
= buf
;
1036 user_read_buf_len_
= buf_len
;
1038 int rv
= DoReadLoop(OK
);
1039 if (rv
== ERR_IO_PENDING
) {
1040 if (OnNetworkTaskRunner())
1041 nss_waiting_read_
= true;
1042 user_read_callback_
= callback
;
1044 user_read_buf_
= NULL
;
1045 user_read_buf_len_
= 0;
1047 if (!OnNetworkTaskRunner()) {
1048 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1049 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1050 return ERR_IO_PENDING
;
1052 DCHECK(!nss_waiting_read_
);
1054 nss_is_closed_
= true;
1056 was_ever_used_
= true;
1064 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1065 const CompletionCallback
& callback
) {
1066 if (!OnNSSTaskRunner()) {
1067 DCHECK(OnNetworkTaskRunner());
1070 DCHECK(!nss_waiting_write_
);
1072 nss_waiting_write_
= true;
1073 bool posted
= nss_task_runner_
->PostTask(
1075 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1076 buf_len
, callback
));
1078 nss_is_closed_
= true;
1079 nss_waiting_write_
= false;
1081 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1084 DCHECK(OnNSSTaskRunner());
1085 DCHECK(false_started_
|| handshake_callback_called_
);
1086 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1087 DCHECK(user_write_callback_
.is_null());
1088 DCHECK(user_connect_callback_
.is_null());
1089 DCHECK(!user_write_buf_
.get());
1092 user_write_buf_
= buf
;
1093 user_write_buf_len_
= buf_len
;
1095 int rv
= DoWriteLoop(OK
);
1096 if (rv
== ERR_IO_PENDING
) {
1097 if (OnNetworkTaskRunner())
1098 nss_waiting_write_
= true;
1099 user_write_callback_
= callback
;
1101 user_write_buf_
= NULL
;
1102 user_write_buf_len_
= 0;
1104 if (!OnNetworkTaskRunner()) {
1105 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1106 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1107 return ERR_IO_PENDING
;
1109 DCHECK(!nss_waiting_write_
);
1111 nss_is_closed_
= true;
1112 } else if (rv
> 0) {
1113 was_ever_used_
= true;
1121 bool SSLClientSocketNSS::Core::IsConnected() const {
1122 DCHECK(OnNetworkTaskRunner());
1123 return !nss_is_closed_
;
1126 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1127 DCHECK(OnNetworkTaskRunner());
1128 return nss_waiting_read_
|| nss_waiting_write_
;
1131 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1132 DCHECK(OnNetworkTaskRunner());
1133 return unhandled_buffer_size_
!= 0;
1136 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1137 DCHECK(OnNetworkTaskRunner());
1138 return was_ever_used_
;
1141 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1142 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1143 // nss_fd_. However, it happens on the network task runner in order to match
1144 // the buggy behavior of ExportKeyingMaterial.
1146 // Once http://crbug.com/330360 is fixed, this should be moved to an
1147 // implementation that exclusively does this work on the NSS TaskRunner. This
1148 // is "safe" because it is only called during the certificate verification
1149 // state machine of the main socket, which is safe because no underlying
1150 // transport IO will be occuring in that state, and NSS will not be blocking
1151 // on any PKCS#11 related locks that might block the Network TaskRunner.
1152 DCHECK(OnNetworkTaskRunner());
1154 // Only cache the session if the connection was not False Started, because
1155 // sessions should only be cached *after* the peer's Finished message is
1157 // In the case of False Start, the session will be cached once the
1158 // HandshakeCallback is called, which signals the receipt and processing of
1159 // the Finished message, and which will happen during a call to
1160 // PR_Read/PR_Write.
1161 if (!false_started_
)
1162 SSL_CacheSession(nss_fd_
);
1165 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1166 return nss_task_runner_
->RunsTasksOnCurrentThread();
1169 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1170 return network_task_runner_
->RunsTasksOnCurrentThread();
1174 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1179 Core
* core
= reinterpret_cast<Core
*>(arg
);
1180 if (core
->handshake_callback_called_
) {
1181 // Disallow the server certificate to change in a renegotiation.
1182 CERTCertificate
* old_cert
= core
->nss_handshake_state_
.server_cert_chain
[0];
1183 ScopedCERTCertificate
new_cert(SSL_PeerCertificate(socket
));
1184 if (new_cert
->derCert
.len
!= old_cert
->derCert
.len
||
1185 memcmp(new_cert
->derCert
.data
, old_cert
->derCert
.data
,
1186 new_cert
->derCert
.len
) != 0) {
1187 // NSS doesn't have an error code that indicates the server certificate
1188 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1189 // for this purpose.
1190 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE
);
1195 // Tell NSS to not verify the certificate.
1202 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1205 CERTDistNames
* ca_names
,
1206 CERTCertificate
** result_certificate
,
1207 SECKEYPrivateKey
** result_private_key
) {
1208 Core
* core
= reinterpret_cast<Core
*>(arg
);
1209 DCHECK(core
->OnNSSTaskRunner());
1211 core
->PostOrRunCallback(
1213 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1214 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1216 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1217 LOG(WARNING
) << "Client auth is not supported";
1219 // Never send a certificate.
1220 core
->AddCertProvidedEvent(0);
1227 // Based on Mozilla's NSS_GetClientAuthData.
1228 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1231 CERTDistNames
* ca_names
,
1232 CERTCertificate
** result_certificate
,
1233 SECKEYPrivateKey
** result_private_key
) {
1234 Core
* core
= reinterpret_cast<Core
*>(arg
);
1235 DCHECK(core
->OnNSSTaskRunner());
1237 core
->PostOrRunCallback(
1239 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1240 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1242 // Regular client certificate requested.
1243 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1244 void* wincx
= SSL_RevealPinArg(socket
);
1246 if (core
->ssl_config_
.send_client_cert
) {
1247 // Second pass: a client certificate should have been selected.
1248 if (core
->ssl_config_
.client_cert
.get()) {
1249 CERTCertificate
* cert
=
1250 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1251 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1253 // TODO(jsorianopastor): We should wait for server certificate
1254 // verification before sending our credentials. See
1255 // http://crbug.com/13934.
1256 *result_certificate
= cert
;
1257 *result_private_key
= privkey
;
1258 // A cert_count of -1 means the number of certificates is unknown.
1259 // NSS will construct the certificate chain.
1260 core
->AddCertProvidedEvent(-1);
1264 LOG(WARNING
) << "Client cert found without private key";
1266 // Send no client certificate.
1267 core
->AddCertProvidedEvent(0);
1271 // First pass: client certificate is needed.
1272 core
->nss_handshake_state_
.cert_authorities
.clear();
1274 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1275 // the server and save them in |cert_authorities|.
1276 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1277 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1278 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1279 static_cast<size_t>(ca_names
->names
[i
].len
)));
1282 // Update the network task runner's view of the handshake state now that
1283 // server certificate request has been recorded.
1284 core
->PostOrRunCallback(
1285 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1286 core
->nss_handshake_state_
));
1288 // Tell NSS to suspend the client authentication. We will then abort the
1289 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1290 return SECWouldBlock
;
1295 SECStatus
SSLClientSocketNSS::Core::CanFalseStartCallback(
1298 PRBool
* can_false_start
) {
1299 // If the server doesn't support NPN or ALPN, then we don't do False
1301 PRBool negotiated_extension
;
1302 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1303 ssl_app_layer_protocol_xtn
,
1304 &negotiated_extension
);
1305 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1306 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1307 ssl_next_proto_nego_xtn
,
1308 &negotiated_extension
);
1310 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1311 *can_false_start
= PR_FALSE
;
1315 SSLChannelInfo channel_info
;
1317 SSL_GetChannelInfo(socket
, &channel_info
, sizeof(channel_info
));
1318 if (ok
!= SECSuccess
|| channel_info
.length
!= sizeof(channel_info
) ||
1319 channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_TLS_1_2
||
1320 !IsFalseStartableTLSCipherSuite(channel_info
.cipherSuite
)) {
1321 *can_false_start
= PR_FALSE
;
1325 return SSL_RecommendedCanFalseStart(socket
, can_false_start
);
1329 void SSLClientSocketNSS::Core::HandshakeCallback(
1332 Core
* core
= reinterpret_cast<Core
*>(arg
);
1333 DCHECK(core
->OnNSSTaskRunner());
1335 core
->handshake_callback_called_
= true;
1336 if (core
->false_started_
) {
1337 core
->false_started_
= false;
1338 // If the connection was False Started, then at the time of this callback,
1339 // the peer's certificate will have been verified or the caller will have
1340 // accepted the error.
1341 // This is guaranteed when using False Start because this callback will
1342 // not be invoked until processing the peer's Finished message, which
1343 // will only happen in a PR_Read/PR_Write call, which can only happen
1344 // after the peer's certificate is verified.
1345 SSL_CacheSessionUnlocked(socket
);
1347 // Additionally, when False Starting, DoHandshake() will have already
1348 // called HandshakeSucceeded(), so return now.
1351 core
->HandshakeSucceeded();
1354 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1355 DCHECK(OnNSSTaskRunner());
1357 PRBool last_handshake_resumed
;
1358 SECStatus rv
= SSL_HandshakeResumedSession(nss_fd_
, &last_handshake_resumed
);
1359 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1360 nss_handshake_state_
.resumed_handshake
= true;
1362 nss_handshake_state_
.resumed_handshake
= false;
1365 RecordChannelIDSupportOnNSSTaskRunner();
1367 UpdateSignedCertTimestamps();
1368 UpdateStapledOCSPResponse();
1369 UpdateConnectionStatus();
1371 UpdateExtensionUsed();
1373 // Update the network task runners view of the handshake state whenever
1374 // a handshake has completed.
1376 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
1377 nss_handshake_state_
));
1380 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
) {
1381 DCHECK(OnNSSTaskRunner());
1383 return MapNSSClientError(nss_error
);
1386 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1387 DCHECK(OnNSSTaskRunner());
1389 int rv
= last_io_result
;
1391 // Default to STATE_NONE for next state.
1392 State state
= next_handshake_state_
;
1393 GotoState(STATE_NONE
);
1396 case STATE_HANDSHAKE
:
1399 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1400 rv
= DoGetDBCertComplete(rv
);
1404 rv
= ERR_UNEXPECTED
;
1405 LOG(DFATAL
) << "unexpected state " << state
;
1409 // Do the actual network I/O
1410 bool network_moved
= DoTransportIO();
1411 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1412 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1413 // special case we keep looping even if rv is ERR_IO_PENDING because
1414 // the transport IO may allow DoHandshake to make progress.
1415 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1416 rv
= OK
; // This causes us to stay in the loop.
1418 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1422 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1423 DCHECK(OnNSSTaskRunner());
1424 DCHECK(false_started_
|| handshake_callback_called_
);
1425 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1431 LOG(DFATAL
) << "!nss_bufs_";
1432 int rv
= ERR_UNEXPECTED
;
1435 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1436 NetLog::TYPE_SSL_READ_ERROR
,
1437 CreateNetLogSSLErrorCallback(rv
, 0)));
1444 rv
= DoPayloadRead();
1445 network_moved
= DoTransportIO();
1446 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1451 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1452 DCHECK(OnNSSTaskRunner());
1453 DCHECK(false_started_
|| handshake_callback_called_
);
1454 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1460 LOG(DFATAL
) << "!nss_bufs_";
1461 int rv
= ERR_UNEXPECTED
;
1464 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1465 NetLog::TYPE_SSL_READ_ERROR
,
1466 CreateNetLogSSLErrorCallback(rv
, 0)));
1473 rv
= DoPayloadWrite();
1474 network_moved
= DoTransportIO();
1475 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1481 int SSLClientSocketNSS::Core::DoHandshake() {
1482 DCHECK(OnNSSTaskRunner());
1485 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1487 // Note: this function may be called multiple times during the handshake, so
1488 // even though channel id and client auth are separate else cases, they can
1489 // both be used during a single SSL handshake.
1490 if (channel_id_needed_
) {
1491 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1492 net_error
= ERR_IO_PENDING
;
1493 } else if (client_auth_cert_needed_
) {
1494 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1497 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1498 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1499 CreateNetLogSSLErrorCallback(net_error
, 0)));
1500 } else if (rv
== SECSuccess
) {
1501 if (!handshake_callback_called_
) {
1502 false_started_
= true;
1503 HandshakeSucceeded();
1506 PRErrorCode prerr
= PR_GetError();
1507 net_error
= HandleNSSError(prerr
);
1509 // If not done, stay in this state
1510 if (net_error
== ERR_IO_PENDING
) {
1511 GotoState(STATE_HANDSHAKE
);
1515 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1516 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1517 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1524 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1528 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1529 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1531 channel_id_needed_
= false;
1536 SECKEYPublicKey
* public_key
;
1537 SECKEYPrivateKey
* private_key
;
1538 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1542 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1543 if (rv
!= SECSuccess
)
1544 return MapNSSError(PORT_GetError());
1546 SetChannelIDProvided();
1547 GotoState(STATE_HANDSHAKE
);
1551 int SSLClientSocketNSS::Core::DoPayloadRead() {
1552 DCHECK(OnNSSTaskRunner());
1553 DCHECK(user_read_buf_
.get());
1554 DCHECK_GT(user_read_buf_len_
, 0);
1557 // If a previous greedy read resulted in an error that was not consumed (eg:
1558 // due to the caller having read some data successfully), then return that
1559 // pending error now.
1560 if (pending_read_result_
!= kNoPendingReadResult
) {
1561 rv
= pending_read_result_
;
1562 PRErrorCode prerr
= pending_read_nss_error_
;
1563 pending_read_result_
= kNoPendingReadResult
;
1564 pending_read_nss_error_
= 0;
1569 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1570 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1571 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1575 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1576 NetLog::TYPE_SSL_READ_ERROR
,
1577 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1582 // Perform a greedy read, attempting to read as much as the caller has
1583 // requested. In the current NSS implementation, PR_Read will return
1584 // exactly one SSL application data record's worth of data per invocation.
1585 // The record size is dictated by the server, and may be noticeably smaller
1586 // than the caller's buffer. This may be as little as a single byte, if the
1587 // server is performing 1/n-1 record splitting.
1589 // However, this greedy read may result in renegotiations/re-handshakes
1590 // happening or may lead to some data being read, followed by an EOF (such as
1591 // a TLS close-notify). If at least some data was read, then that result
1592 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1593 // data was read, it's safe to return the error or EOF immediately.
1594 int total_bytes_read
= 0;
1596 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1597 user_read_buf_len_
- total_bytes_read
);
1599 total_bytes_read
+= rv
;
1600 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1601 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1602 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1603 amount_in_read_buffer
));
1605 if (total_bytes_read
== user_read_buf_len_
) {
1606 // The caller's entire request was satisfied without error. No further
1607 // processing needed.
1608 rv
= total_bytes_read
;
1610 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1611 // immediately, while the NSPR/NSS errors are still available in
1612 // thread-local storage. However, the handled/remapped error code should
1613 // only be returned if no application data was already read; if it was, the
1614 // error code should be deferred until the next call of DoPayloadRead.
1616 // If no data was read, |*next_result| will point to the return value of
1617 // this function. If at least some data was read, |*next_result| will point
1618 // to |pending_read_error_|, to be returned in a future call to
1619 // DoPayloadRead() (e.g.: after the current data is handled).
1620 int* next_result
= &rv
;
1621 if (total_bytes_read
> 0) {
1622 pending_read_result_
= rv
;
1623 rv
= total_bytes_read
;
1624 next_result
= &pending_read_result_
;
1627 if (client_auth_cert_needed_
) {
1628 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1629 pending_read_nss_error_
= 0;
1630 } else if (*next_result
< 0) {
1631 // If *next_result == 0, then that indicates EOF, and no special error
1632 // handling is needed.
1633 pending_read_nss_error_
= PR_GetError();
1634 *next_result
= HandleNSSError(pending_read_nss_error_
);
1635 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1636 // If at least some data was read from PR_Read(), do not treat
1637 // insufficient data as an error to return in the next call to
1638 // DoPayloadRead() - instead, let the call fall through to check
1639 // PR_Read() again. This is because DoTransportIO() may complete
1640 // in between the next call to DoPayloadRead(), and thus it is
1641 // important to check PR_Read() on subsequent invocations to see
1642 // if a complete record may now be read.
1643 pending_read_nss_error_
= 0;
1644 pending_read_result_
= kNoPendingReadResult
;
1649 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
1654 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1655 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1656 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1657 } else if (rv
!= ERR_IO_PENDING
) {
1660 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1661 NetLog::TYPE_SSL_READ_ERROR
,
1662 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
1663 pending_read_nss_error_
= 0;
1668 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1669 DCHECK(OnNSSTaskRunner());
1671 DCHECK(user_write_buf_
.get());
1673 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1674 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
1675 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1676 // PR_Write could potentially consume the unhandled data in the memio read
1677 // buffer if a renegotiation is in progress. If the buffer is consumed,
1678 // notify the latest buffer size to NetworkRunner.
1679 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
1682 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
1687 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1688 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
1689 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
1692 PRErrorCode prerr
= PR_GetError();
1693 if (prerr
== PR_WOULD_BLOCK_ERROR
)
1694 return ERR_IO_PENDING
;
1696 rv
= HandleNSSError(prerr
);
1699 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1700 NetLog::TYPE_SSL_WRITE_ERROR
,
1701 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1705 // Do as much network I/O as possible between the buffer and the
1706 // transport socket. Return true if some I/O performed, false
1707 // otherwise (error or ERR_IO_PENDING).
1708 bool SSLClientSocketNSS::Core::DoTransportIO() {
1709 DCHECK(OnNSSTaskRunner());
1711 bool network_moved
= false;
1712 if (nss_bufs_
!= NULL
) {
1714 // Read and write as much data as we can. The loop is neccessary
1715 // because Write() may return synchronously.
1718 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
1719 network_moved
= true;
1721 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
1722 network_moved
= true;
1724 return network_moved
;
1727 int SSLClientSocketNSS::Core::BufferRecv() {
1728 DCHECK(OnNSSTaskRunner());
1730 if (transport_recv_busy_
)
1731 return ERR_IO_PENDING
;
1733 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
1734 // determine how much data NSS wants to read. If NSS was not blocked,
1735 // this will return 0.
1736 int requested
= memio_GetReadRequest(nss_bufs_
);
1737 if (requested
== 0) {
1738 // This is not a perfect match of error codes, as no operation is
1739 // actually pending. However, returning 0 would be interpreted as a
1740 // possible sign of EOF, which is also an inappropriate match.
1741 return ERR_IO_PENDING
;
1745 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
1748 // buffer too full to read into, so no I/O possible at moment
1749 rv
= ERR_IO_PENDING
;
1751 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
1752 if (OnNetworkTaskRunner()) {
1753 rv
= DoBufferRecv(read_buffer
.get(), nb
);
1755 bool posted
= network_task_runner_
->PostTask(
1757 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
1759 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1762 if (rv
== ERR_IO_PENDING
) {
1763 transport_recv_busy_
= true;
1766 memcpy(buf
, read_buffer
->data(), rv
);
1767 } else if (rv
== 0) {
1768 transport_recv_eof_
= true;
1770 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
1776 // Return 0 if nss_bufs_ was empty,
1777 // > 0 for bytes transferred immediately,
1778 // < 0 for error (or the non-error ERR_IO_PENDING).
1779 int SSLClientSocketNSS::Core::BufferSend() {
1780 DCHECK(OnNSSTaskRunner());
1782 if (transport_send_busy_
)
1783 return ERR_IO_PENDING
;
1787 unsigned int len1
, len2
;
1788 if (memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
)) {
1789 // It is important this return synchronously to prevent spinning infinitely
1790 // in the off-thread NSS case. The error code itself is ignored, so just
1791 // return ERR_ABORTED. See https://crbug.com/381160.
1794 const unsigned int len
= len1
+ len2
;
1798 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
1799 memcpy(send_buffer
->data(), buf1
, len1
);
1800 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
1802 if (OnNetworkTaskRunner()) {
1803 rv
= DoBufferSend(send_buffer
.get(), len
);
1805 bool posted
= network_task_runner_
->PostTask(
1807 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
1809 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1812 if (rv
== ERR_IO_PENDING
) {
1813 transport_send_busy_
= true;
1815 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
1822 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
1823 DCHECK(OnNSSTaskRunner());
1825 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1826 OnHandshakeIOComplete(result
);
1830 // Network layer received some data, check if client requested to read
1832 if (!user_read_buf_
.get())
1835 int rv
= DoReadLoop(result
);
1836 if (rv
!= ERR_IO_PENDING
)
1840 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
1841 DCHECK(OnNSSTaskRunner());
1843 if (next_handshake_state_
== STATE_HANDSHAKE
) {
1844 OnHandshakeIOComplete(result
);
1848 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1849 // handshake is in progress.
1850 int rv_read
= ERR_IO_PENDING
;
1851 int rv_write
= ERR_IO_PENDING
;
1854 if (user_read_buf_
.get())
1855 rv_read
= DoPayloadRead();
1856 if (user_write_buf_
.get())
1857 rv_write
= DoPayloadWrite();
1858 network_moved
= DoTransportIO();
1859 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
1860 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
1862 // If the parent SSLClientSocketNSS is deleted during the processing of the
1863 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
1864 // will be detached (and possibly deleted). Guard against deletion by taking
1865 // an extra reference, then check if the Core was detached before invoking the
1867 scoped_refptr
<Core
> guard(this);
1868 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
1869 DoReadCallback(rv_read
);
1871 if (OnNetworkTaskRunner() && detached_
)
1874 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
1875 DoWriteCallback(rv_write
);
1878 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
1879 // handshake. This requires network IO, which in turn calls
1880 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
1881 // winds its way through the state machine and ends up being passed to the
1882 // callback. For Read() and Write(), that's what we want. But for Connect(),
1883 // the caller expects OK (i.e. 0) for success.
1884 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
1885 DCHECK(OnNSSTaskRunner());
1886 DCHECK_NE(rv
, ERR_IO_PENDING
);
1887 DCHECK(!user_connect_callback_
.is_null());
1889 base::Closure c
= base::Bind(
1890 base::ResetAndReturn(&user_connect_callback_
),
1892 PostOrRunCallback(FROM_HERE
, c
);
1895 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
1896 DCHECK(OnNSSTaskRunner());
1897 DCHECK_NE(ERR_IO_PENDING
, rv
);
1898 DCHECK(!user_read_callback_
.is_null());
1900 user_read_buf_
= NULL
;
1901 user_read_buf_len_
= 0;
1902 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1903 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1904 // the network task runner.
1907 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
1910 base::Bind(&Core::DidNSSRead
, this, rv
));
1913 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
1916 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
1917 DCHECK(OnNSSTaskRunner());
1918 DCHECK_NE(ERR_IO_PENDING
, rv
);
1919 DCHECK(!user_write_callback_
.is_null());
1921 // Since Run may result in Write being called, clear |user_write_callback_|
1923 user_write_buf_
= NULL
;
1924 user_write_buf_len_
= 0;
1925 // Update buffer status because DoWriteLoop called DoTransportIO which may
1926 // perform read operations.
1927 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1928 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1929 // the network task runner.
1932 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
1935 base::Bind(&Core::DidNSSWrite
, this, rv
));
1938 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
1941 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
1944 SECKEYPublicKey
**out_public_key
,
1945 SECKEYPrivateKey
**out_private_key
) {
1946 Core
* core
= reinterpret_cast<Core
*>(arg
);
1947 DCHECK(core
->OnNSSTaskRunner());
1949 core
->PostOrRunCallback(
1951 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1952 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
1954 // We have negotiated the TLS channel ID extension.
1955 core
->channel_id_xtn_negotiated_
= true;
1956 std::string host
= core
->host_and_port_
.host();
1957 int error
= ERR_UNEXPECTED
;
1958 if (core
->OnNetworkTaskRunner()) {
1959 error
= core
->DoGetChannelID(host
);
1961 bool posted
= core
->network_task_runner_
->PostTask(
1964 IgnoreResult(&Core::DoGetChannelID
),
1966 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1969 if (error
== ERR_IO_PENDING
) {
1970 // Asynchronous case.
1971 core
->channel_id_needed_
= true;
1972 return SECWouldBlock
;
1975 core
->PostOrRunCallback(
1977 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
1978 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
1979 SECStatus rv
= SECSuccess
;
1981 // Synchronous success.
1982 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
1984 core
->SetChannelIDProvided();
1994 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
1995 SECKEYPrivateKey
** key
) {
1996 // Set the certificate.
1998 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
1999 cert_item
.len
= domain_bound_cert_
.size();
2000 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2006 return MapNSSError(PORT_GetError());
2008 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
2009 // Set the private key.
2010 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2012 ChannelIDService::kEPKIPassword
,
2013 reinterpret_cast<const unsigned char*>(
2014 domain_bound_private_key_
.data()),
2015 domain_bound_private_key_
.size(),
2016 &cert
->subjectPublicKeyInfo
,
2021 int error
= MapNSSError(PORT_GetError());
2028 void SSLClientSocketNSS::Core::UpdateServerCert() {
2029 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2030 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2031 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2032 if (nss_handshake_state_
.server_cert
.get()) {
2033 // Since this will be called asynchronously on another thread, it needs to
2034 // own a reference to the certificate.
2035 NetLog::ParametersCallback net_log_callback
=
2036 base::Bind(&NetLogX509CertificateCallback
,
2037 nss_handshake_state_
.server_cert
);
2040 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2041 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2046 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2047 const SECItem
* signed_cert_timestamps
=
2048 SSL_PeerSignedCertTimestamps(nss_fd_
);
2050 if (!signed_cert_timestamps
|| !signed_cert_timestamps
->len
)
2053 nss_handshake_state_
.sct_list_from_tls_extension
= std::string(
2054 reinterpret_cast<char*>(signed_cert_timestamps
->data
),
2055 signed_cert_timestamps
->len
);
2058 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2059 PRBool ocsp_requested
= PR_FALSE
;
2060 SSL_OptionGet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, &ocsp_requested
);
2061 const SECItemArray
* ocsp_responses
=
2062 SSL_PeerStapledOCSPResponses(nss_fd_
);
2063 bool ocsp_responses_present
= ocsp_responses
&& ocsp_responses
->len
;
2065 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present
);
2066 if (!ocsp_responses_present
)
2069 nss_handshake_state_
.stapled_ocsp_response
= std::string(
2070 reinterpret_cast<char*>(ocsp_responses
->items
[0].data
),
2071 ocsp_responses
->items
[0].len
);
2073 if (IsOCSPStaplingSupported()) {
2074 #if defined(USE_NSS_CERTS)
2075 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
2076 GetCacheOCSPResponseFromSideChannelFunction();
2078 cache_ocsp_response(
2079 CERT_GetDefaultCertDB(),
2080 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
2081 &ocsp_responses
->items
[0], NULL
);
2086 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2087 // Note: This function may be called multiple times for a single connection
2088 // if renegotiations occur.
2089 nss_handshake_state_
.ssl_connection_status
= 0;
2091 SSLChannelInfo channel_info
;
2092 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2093 &channel_info
, sizeof(channel_info
));
2094 if (ok
== SECSuccess
&&
2095 channel_info
.length
== sizeof(channel_info
) &&
2096 channel_info
.cipherSuite
) {
2097 nss_handshake_state_
.ssl_connection_status
|= channel_info
.cipherSuite
;
2099 nss_handshake_state_
.ssl_connection_status
|=
2100 (static_cast<int>(channel_info
.compressionMethod
) &
2101 SSL_CONNECTION_COMPRESSION_MASK
) <<
2102 SSL_CONNECTION_COMPRESSION_SHIFT
;
2104 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2105 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2106 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2108 version
= SSL_CONNECTION_VERSION_SSL2
;
2109 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2110 version
= SSL_CONNECTION_VERSION_SSL3
;
2111 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_0
) {
2112 version
= SSL_CONNECTION_VERSION_TLS1
;
2113 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2114 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2115 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_2
) {
2116 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2118 nss_handshake_state_
.ssl_connection_status
|=
2119 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2120 SSL_CONNECTION_VERSION_SHIFT
;
2123 PRBool peer_supports_renego_ext
;
2124 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2125 &peer_supports_renego_ext
);
2126 if (ok
== SECSuccess
) {
2127 if (!peer_supports_renego_ext
) {
2128 nss_handshake_state_
.ssl_connection_status
|=
2129 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2130 // Log an informational message if the server does not support secure
2131 // renegotiation (RFC 5746).
2132 VLOG(1) << "The server " << host_and_port_
.ToString()
2133 << " does not support the TLS renegotiation_info extension.";
2137 if (ssl_config_
.version_fallback
) {
2138 nss_handshake_state_
.ssl_connection_status
|=
2139 SSL_CONNECTION_VERSION_FALLBACK
;
2143 void SSLClientSocketNSS::Core::UpdateNextProto() {
2145 SSLNextProtoState state
;
2148 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2149 if (rv
!= SECSuccess
)
2152 nss_handshake_state_
.next_proto
=
2153 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2155 case SSL_NEXT_PROTO_NEGOTIATED
:
2156 case SSL_NEXT_PROTO_SELECTED
:
2157 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2159 case SSL_NEXT_PROTO_NO_OVERLAP
:
2160 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2162 case SSL_NEXT_PROTO_NO_SUPPORT
:
2163 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2171 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2172 PRBool negotiated_extension
;
2173 SECStatus rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2174 ssl_app_layer_protocol_xtn
,
2175 &negotiated_extension
);
2176 if (rv
== SECSuccess
&& negotiated_extension
) {
2177 nss_handshake_state_
.negotiation_extension_
= kExtensionALPN
;
2179 rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2180 ssl_next_proto_nego_xtn
,
2181 &negotiated_extension
);
2182 if (rv
== SECSuccess
&& negotiated_extension
) {
2183 nss_handshake_state_
.negotiation_extension_
= kExtensionNPN
;
2188 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2189 DCHECK(OnNSSTaskRunner());
2190 if (nss_handshake_state_
.resumed_handshake
)
2193 // Copy the NSS task runner-only state to the network task runner and
2194 // log histograms from there, since the histograms also need access to the
2195 // network task runner state.
2198 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2200 channel_id_xtn_negotiated_
,
2201 ssl_config_
.channel_id_enabled
,
2202 crypto::ECPrivateKey::IsSupported()));
2205 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2206 bool negotiated_channel_id
,
2207 bool channel_id_enabled
,
2208 bool supports_ecc
) const {
2209 DCHECK(OnNetworkTaskRunner());
2211 RecordChannelIDSupport(channel_id_service_
,
2212 negotiated_channel_id
,
2217 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2218 DCHECK(OnNetworkTaskRunner());
2224 int rv
= transport_
->socket()->Read(
2226 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2227 scoped_refptr
<IOBuffer
>(read_buffer
)));
2229 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2230 nss_task_runner_
->PostTask(
2231 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2232 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2239 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2240 DCHECK(OnNetworkTaskRunner());
2246 int rv
= transport_
->socket()->Write(
2248 base::Bind(&Core::BufferSendComplete
,
2249 base::Unretained(this)));
2251 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2252 nss_task_runner_
->PostTask(
2254 base::Bind(&Core::BufferSendComplete
, this, rv
));
2261 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string
& host
) {
2262 DCHECK(OnNetworkTaskRunner());
2267 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2269 int rv
= channel_id_service_
->GetOrCreateChannelID(
2271 &domain_bound_private_key_
,
2272 &domain_bound_cert_
,
2273 base::Bind(&Core::OnGetChannelIDComplete
, base::Unretained(this)),
2274 &domain_bound_cert_request_handle_
);
2276 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2277 nss_task_runner_
->PostTask(
2279 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2280 return ERR_IO_PENDING
;
2286 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2287 const HandshakeState
& state
) {
2288 DCHECK(OnNetworkTaskRunner());
2289 network_handshake_state_
= state
;
2292 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2293 DCHECK(OnNetworkTaskRunner());
2294 unhandled_buffer_size_
= amount_in_read_buffer
;
2297 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2298 DCHECK(OnNetworkTaskRunner());
2299 DCHECK(nss_waiting_read_
);
2300 nss_waiting_read_
= false;
2302 nss_is_closed_
= true;
2304 was_ever_used_
= true;
2308 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2309 DCHECK(OnNetworkTaskRunner());
2310 DCHECK(nss_waiting_write_
);
2311 nss_waiting_write_
= false;
2313 nss_is_closed_
= true;
2314 } else if (result
> 0) {
2315 was_ever_used_
= true;
2319 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2320 if (!OnNSSTaskRunner()) {
2324 nss_task_runner_
->PostTask(
2325 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2329 DCHECK(OnNSSTaskRunner());
2331 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2332 transport_send_busy_
= false;
2333 OnSendComplete(result
);
2336 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2337 if (!OnNSSTaskRunner()) {
2341 nss_task_runner_
->PostTask(
2342 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2346 DCHECK(OnNSSTaskRunner());
2348 int rv
= DoHandshakeLoop(result
);
2349 if (rv
!= ERR_IO_PENDING
)
2350 DoConnectCallback(rv
);
2353 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result
) {
2354 DVLOG(1) << __FUNCTION__
<< " " << result
;
2355 DCHECK(OnNetworkTaskRunner());
2357 OnHandshakeIOComplete(result
);
2360 void SSLClientSocketNSS::Core::BufferRecvComplete(
2361 IOBuffer
* read_buffer
,
2363 DCHECK(read_buffer
);
2365 if (!OnNSSTaskRunner()) {
2369 nss_task_runner_
->PostTask(
2370 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2371 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2375 DCHECK(OnNSSTaskRunner());
2379 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2380 CHECK_GE(nb
, result
);
2381 memcpy(buf
, read_buffer
->data(), result
);
2382 } else if (result
== 0) {
2383 transport_recv_eof_
= true;
2386 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2387 transport_recv_busy_
= false;
2388 OnRecvComplete(result
);
2391 void SSLClientSocketNSS::Core::PostOrRunCallback(
2392 const tracked_objects::Location
& location
,
2393 const base::Closure
& task
) {
2394 if (!OnNetworkTaskRunner()) {
2395 network_task_runner_
->PostTask(
2397 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2401 if (detached_
|| task
.is_null())
2406 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2409 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2410 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2411 NetLog::IntegerCallback("cert_count", cert_count
)));
2414 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2416 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2417 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2418 nss_handshake_state_
.channel_id_sent
= true;
2419 // Update the network task runner's view of the handshake state now that
2420 // channel id has been sent.
2422 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2423 nss_handshake_state_
));
2426 SSLClientSocketNSS::SSLClientSocketNSS(
2427 base::SequencedTaskRunner
* nss_task_runner
,
2428 scoped_ptr
<ClientSocketHandle
> transport_socket
,
2429 const HostPortPair
& host_and_port
,
2430 const SSLConfig
& ssl_config
,
2431 const SSLClientSocketContext
& context
)
2432 : nss_task_runner_(nss_task_runner
),
2433 transport_(transport_socket
.Pass()),
2434 host_and_port_(host_and_port
),
2435 ssl_config_(ssl_config
),
2436 cert_verifier_(context
.cert_verifier
),
2437 cert_transparency_verifier_(context
.cert_transparency_verifier
),
2438 channel_id_service_(context
.channel_id_service
),
2439 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2440 completed_handshake_(false),
2441 next_handshake_state_(STATE_NONE
),
2443 net_log_(transport_
->socket()->NetLog()),
2444 transport_security_state_(context
.transport_security_state
),
2445 policy_enforcer_(context
.cert_policy_enforcer
),
2446 valid_thread_id_(base::kInvalidThreadId
) {
2452 SSLClientSocketNSS::~SSLClientSocketNSS() {
2459 void SSLClientSocket::ClearSessionCache() {
2460 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2461 // bother initializing NSS just to clear an empty SSL session cache.
2462 if (!NSS_IsInitialized())
2465 SSL_ClearSessionCache();
2468 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2469 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2473 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
2474 crypto::EnsureNSSInit();
2475 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
)) {
2476 return SSL_PROTOCOL_VERSION_TLS1_2
;
2478 return SSL_PROTOCOL_VERSION_TLS1_1
;
2482 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2485 if (core_
->state().server_cert_chain
.empty() ||
2486 !core_
->state().server_cert_chain
[0]) {
2490 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2491 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2493 AddSCTInfoToSSLInfo(ssl_info
);
2495 ssl_info
->connection_status
=
2496 core_
->state().ssl_connection_status
;
2497 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2498 ssl_info
->is_issued_by_known_root
=
2499 server_cert_verify_result_
.is_issued_by_known_root
;
2500 ssl_info
->client_cert_sent
=
2501 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2502 ssl_info
->channel_id_sent
= WasChannelIDSent();
2503 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
2505 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2506 core_
->state().ssl_connection_status
);
2507 SSLCipherSuiteInfo cipher_info
;
2508 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2509 &cipher_info
, sizeof(cipher_info
));
2510 if (ok
== SECSuccess
) {
2511 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2513 ssl_info
->security_bits
= -1;
2514 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2515 << " for cipherSuite " << cipher_suite
;
2518 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2519 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2525 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2526 SSLCertRequestInfo
* cert_request_info
) {
2528 cert_request_info
->host_and_port
= host_and_port_
;
2529 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2533 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2535 const base::StringPiece
& context
,
2537 unsigned int outlen
) {
2539 return ERR_SOCKET_NOT_CONNECTED
;
2541 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2542 // the midst of a handshake.
2543 SECStatus result
= SSL_ExportKeyingMaterial(
2544 nss_fd_
, label
.data(), label
.size(), has_context
,
2545 reinterpret_cast<const unsigned char*>(context
.data()),
2546 context
.length(), out
, outlen
);
2547 if (result
!= SECSuccess
) {
2548 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2549 return MapNSSError(PORT_GetError());
2554 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2556 return ERR_SOCKET_NOT_CONNECTED
;
2557 unsigned char buf
[64];
2559 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2560 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2561 buf
, &len
, arraysize(buf
));
2562 if (result
!= SECSuccess
) {
2563 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2564 return MapNSSError(PORT_GetError());
2566 out
->assign(reinterpret_cast<char*>(buf
), len
);
2570 SSLClientSocket::NextProtoStatus
2571 SSLClientSocketNSS::GetNextProto(std::string
* proto
) {
2572 *proto
= core_
->state().next_proto
;
2573 return core_
->state().next_proto_status
;
2576 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2578 DCHECK(transport_
.get());
2579 // It is an error to create an SSLClientSocket whose context has no
2580 // TransportSecurityState.
2581 DCHECK(transport_security_state_
);
2582 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2583 DCHECK(user_connect_callback_
.is_null());
2584 DCHECK(!callback
.is_null());
2586 EnsureThreadIdAssigned();
2588 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2592 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2596 rv
= InitializeSSLOptions();
2598 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2602 rv
= InitializeSSLPeerName();
2604 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2608 GotoState(STATE_HANDSHAKE
);
2610 rv
= DoHandshakeLoop(OK
);
2611 if (rv
== ERR_IO_PENDING
) {
2612 user_connect_callback_
= callback
;
2614 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2618 return rv
> OK
? OK
: rv
;
2621 void SSLClientSocketNSS::Disconnect() {
2624 CHECK(CalledOnValidThread());
2626 // Shut down anything that may call us back.
2629 transport_
->socket()->Disconnect();
2631 // Reset object state.
2632 user_connect_callback_
.Reset();
2633 server_cert_verify_result_
.Reset();
2634 completed_handshake_
= false;
2635 start_cert_verification_time_
= base::TimeTicks();
2641 bool SSLClientSocketNSS::IsConnected() const {
2643 bool ret
= completed_handshake_
&&
2644 (core_
->HasPendingAsyncOperation() ||
2645 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2646 transport_
->socket()->IsConnected());
2651 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2653 bool ret
= completed_handshake_
&&
2654 !core_
->HasPendingAsyncOperation() &&
2655 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2656 transport_
->socket()->IsConnectedAndIdle();
2661 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2662 return transport_
->socket()->GetPeerAddress(address
);
2665 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
2666 return transport_
->socket()->GetLocalAddress(address
);
2669 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
2673 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2674 if (transport_
.get() && transport_
->socket()) {
2675 transport_
->socket()->SetSubresourceSpeculation();
2681 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2682 if (transport_
.get() && transport_
->socket()) {
2683 transport_
->socket()->SetOmniboxSpeculation();
2689 bool SSLClientSocketNSS::WasEverUsed() const {
2690 DCHECK(core_
.get());
2692 return core_
->WasEverUsed();
2695 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2696 if (transport_
.get() && transport_
->socket()) {
2697 return transport_
->socket()->UsingTCPFastOpen();
2703 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
2704 const CompletionCallback
& callback
) {
2705 DCHECK(core_
.get());
2706 DCHECK(!callback
.is_null());
2708 EnterFunction(buf_len
);
2709 int rv
= core_
->Read(buf
, buf_len
, callback
);
2715 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
2716 const CompletionCallback
& callback
) {
2717 DCHECK(core_
.get());
2718 DCHECK(!callback
.is_null());
2720 EnterFunction(buf_len
);
2721 int rv
= core_
->Write(buf
, buf_len
, callback
);
2727 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
2728 return transport_
->socket()->SetReceiveBufferSize(size
);
2731 int SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
2732 return transport_
->socket()->SetSendBufferSize(size
);
2735 int SSLClientSocketNSS::Init() {
2737 // Initialize the NSS SSL library in a threadsafe way. This also
2738 // initializes the NSS base library.
2740 if (!NSS_IsInitialized())
2741 return ERR_UNEXPECTED
;
2742 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
2743 if (ssl_config_
.cert_io_enabled
) {
2744 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
2745 // loop by MessageLoopForIO::current().
2746 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
2747 EnsureNSSHttpIOInit();
2755 void SSLClientSocketNSS::InitCore() {
2756 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
2757 nss_task_runner_
.get(),
2762 channel_id_service_
);
2765 int SSLClientSocketNSS::InitializeSSLOptions() {
2766 // Transport connected, now hook it up to nss
2767 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
2768 if (nss_fd_
== NULL
) {
2769 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
2772 // Grab pointer to buffers
2773 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
2775 /* Create SSL state machine */
2776 /* Push SSL onto our fake I/O socket */
2777 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_
) == NULL
) {
2778 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
2781 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
2783 // TODO(port): set more ssl options! Check errors!
2787 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
2788 if (rv
!= SECSuccess
) {
2789 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
2790 return ERR_UNEXPECTED
;
2793 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
2794 if (rv
!= SECSuccess
) {
2795 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
2796 return ERR_UNEXPECTED
;
2799 // Don't do V2 compatible hellos because they don't support TLS extensions.
2800 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
2801 if (rv
!= SECSuccess
) {
2802 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
2803 return ERR_UNEXPECTED
;
2806 SSLVersionRange version_range
;
2807 version_range
.min
= ssl_config_
.version_min
;
2808 version_range
.max
= ssl_config_
.version_max
;
2809 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
2810 if (rv
!= SECSuccess
) {
2811 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
2812 return ERR_NO_SSL_VERSIONS_ENABLED
;
2815 if (ssl_config_
.version_fallback
) {
2816 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALLBACK_SCSV
, PR_TRUE
);
2817 if (rv
!= SECSuccess
) {
2818 LogFailedNSSFunction(
2819 net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
2823 for (std::vector
<uint16
>::const_iterator it
=
2824 ssl_config_
.disabled_cipher_suites
.begin();
2825 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
2826 // This will fail if the specified cipher is not implemented by NSS, but
2827 // the failure is harmless.
2828 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
2831 if (!ssl_config_
.enable_deprecated_cipher_suites
) {
2832 const PRUint16
* const ssl_ciphers
= SSL_GetImplementedCiphers();
2833 const PRUint16 num_ciphers
= SSL_GetNumImplementedCiphers();
2834 for (int i
= 0; i
< num_ciphers
; i
++) {
2835 SSLCipherSuiteInfo info
;
2836 if (SSL_GetCipherSuiteInfo(ssl_ciphers
[i
], &info
, sizeof(info
)) !=
2840 if (info
.symCipher
== ssl_calg_rc4
)
2841 SSL_CipherPrefSet(nss_fd_
, ssl_ciphers
[i
], PR_FALSE
);
2846 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
2847 if (rv
!= SECSuccess
) {
2848 LogFailedNSSFunction(
2849 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
2852 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
2853 ssl_config_
.false_start_enabled
);
2854 if (rv
!= SECSuccess
)
2855 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
2857 // We allow servers to request renegotiation. Since we're a client,
2858 // prohibiting this is rather a waste of time. Only servers are in a
2859 // position to prevent renegotiation attacks.
2860 // http://extendedsubset.com/?p=8
2862 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
2863 SSL_RENEGOTIATE_TRANSITIONAL
);
2864 if (rv
!= SECSuccess
) {
2865 LogFailedNSSFunction(
2866 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
2869 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
2870 if (rv
!= SECSuccess
)
2871 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
2873 // Added in NSS 3.15
2874 #ifdef SSL_ENABLE_OCSP_STAPLING
2875 // Request OCSP stapling even on platforms that don't support it, in
2876 // order to extract Certificate Transparency information.
2877 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
,
2878 (IsOCSPStaplingSupported() ||
2879 ssl_config_
.signed_cert_timestamps_enabled
));
2880 if (rv
!= SECSuccess
) {
2881 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
2882 "SSL_ENABLE_OCSP_STAPLING");
2886 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS
,
2887 ssl_config_
.signed_cert_timestamps_enabled
);
2888 if (rv
!= SECSuccess
) {
2889 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
2890 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
2893 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
2894 if (rv
!= SECSuccess
) {
2895 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
2896 return ERR_UNEXPECTED
;
2899 if (!core_
->Init(nss_fd_
, nss_bufs
))
2900 return ERR_UNEXPECTED
;
2902 // Tell SSL the hostname we're trying to connect to.
2903 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
2905 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
2906 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
2911 int SSLClientSocketNSS::InitializeSSLPeerName() {
2912 // Tell NSS who we're connected to
2913 IPEndPoint peer_address
;
2914 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
2918 SockaddrStorage storage
;
2919 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
2920 return ERR_ADDRESS_INVALID
;
2923 memset(&peername
, 0, sizeof(peername
));
2924 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
2925 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
2927 memcpy(&peername
, storage
.addr
, len
);
2929 // Adjust the address family field for BSD, whose sockaddr
2930 // structure has a one-byte length and one-byte address family
2931 // field at the beginning. PRNetAddr has a two-byte address
2932 // family field at the beginning.
2933 peername
.raw
.family
= storage
.addr
->sa_family
;
2935 memio_SetPeerName(nss_fd_
, &peername
);
2937 // Set the peer ID for session reuse. This is necessary when we create an
2938 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
2939 // rather than the destination server's address in that case.
2940 std::string peer_id
= host_and_port_
.ToString();
2941 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
2942 // the session cache for incognito mode.
2943 peer_id
+= "/" + ssl_session_cache_shard_
;
2945 // Shard the session cache based on maximum protocol version. This causes
2946 // fallback connections to use a separate session cache.
2947 switch (ssl_config_
.version_max
) {
2948 case SSL_PROTOCOL_VERSION_SSL3
:
2951 case SSL_PROTOCOL_VERSION_TLS1
:
2954 case SSL_PROTOCOL_VERSION_TLS1_1
:
2955 peer_id
+= "tls1.1";
2957 case SSL_PROTOCOL_VERSION_TLS1_2
:
2958 peer_id
+= "tls1.2";
2964 if (ssl_config_
.enable_deprecated_cipher_suites
)
2965 peer_id
+= "deprecated";
2967 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
2968 if (rv
!= SECSuccess
)
2969 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
2974 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
2976 DCHECK_NE(ERR_IO_PENDING
, rv
);
2977 DCHECK(!user_connect_callback_
.is_null());
2979 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
2983 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
2984 EnterFunction(result
);
2985 int rv
= DoHandshakeLoop(result
);
2986 if (rv
!= ERR_IO_PENDING
) {
2987 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2988 DoConnectCallback(rv
);
2993 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
2994 EnterFunction(last_io_result
);
2995 int rv
= last_io_result
;
2997 // Default to STATE_NONE for next state.
2998 // (This is a quirk carried over from the windows
2999 // implementation. It makes reading the logs a bit harder.)
3000 // State handlers can and often do call GotoState just
3001 // to stay in the current state.
3002 State state
= next_handshake_state_
;
3003 GotoState(STATE_NONE
);
3005 case STATE_HANDSHAKE
:
3008 case STATE_HANDSHAKE_COMPLETE
:
3009 rv
= DoHandshakeComplete(rv
);
3011 case STATE_VERIFY_CERT
:
3013 rv
= DoVerifyCert(rv
);
3015 case STATE_VERIFY_CERT_COMPLETE
:
3016 rv
= DoVerifyCertComplete(rv
);
3020 rv
= ERR_UNEXPECTED
;
3021 LOG(DFATAL
) << "unexpected state " << state
;
3024 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3029 int SSLClientSocketNSS::DoHandshake() {
3031 int rv
= core_
->Connect(
3032 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3033 base::Unretained(this)));
3034 GotoState(STATE_HANDSHAKE_COMPLETE
);
3040 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3041 EnterFunction(result
);
3044 if (ssl_config_
.version_fallback
&&
3045 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
3046 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
3049 // SSL handshake is completed. Let's verify the certificate.
3050 GotoState(STATE_VERIFY_CERT
);
3053 set_channel_id_sent(core_
->state().channel_id_sent
);
3054 set_signed_cert_timestamps_received(
3055 !core_
->state().sct_list_from_tls_extension
.empty());
3056 set_stapled_ocsp_response_received(
3057 !core_
->state().stapled_ocsp_response
.empty());
3058 set_negotiation_extension(core_
->state().negotiation_extension_
);
3060 LeaveFunction(result
);
3064 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3065 DCHECK(!core_
->state().server_cert_chain
.empty());
3066 DCHECK(core_
->state().server_cert_chain
[0]);
3068 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3070 // If the certificate is expected to be bad we can use the expectation as
3072 base::StringPiece
der_cert(
3073 reinterpret_cast<char*>(
3074 core_
->state().server_cert_chain
[0]->derCert
.data
),
3075 core_
->state().server_cert_chain
[0]->derCert
.len
);
3076 CertStatus cert_status
;
3077 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3078 DCHECK(start_cert_verification_time_
.is_null());
3079 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3080 server_cert_verify_result_
.Reset();
3081 server_cert_verify_result_
.cert_status
= cert_status
;
3082 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3086 // We may have failed to create X509Certificate object if we are
3087 // running inside sandbox.
3088 if (!core_
->state().server_cert
.get()) {
3089 server_cert_verify_result_
.Reset();
3090 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3091 return ERR_CERT_INVALID
;
3094 start_cert_verification_time_
= base::TimeTicks::Now();
3097 if (ssl_config_
.rev_checking_enabled
)
3098 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3099 if (ssl_config_
.verify_ev_cert
)
3100 flags
|= CertVerifier::VERIFY_EV_CERT
;
3101 if (ssl_config_
.cert_io_enabled
)
3102 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3103 if (ssl_config_
.rev_checking_required_local_anchors
)
3104 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3105 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3106 return verifier_
->Verify(
3107 core_
->state().server_cert
.get(),
3108 host_and_port_
.host(),
3110 SSLConfigService::GetCRLSet().get(),
3111 &server_cert_verify_result_
,
3112 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3113 base::Unretained(this)),
3117 // Derived from AuthCertificateCallback() in
3118 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3119 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3122 if (!start_cert_verification_time_
.is_null()) {
3123 base::TimeDelta verify_time
=
3124 base::TimeTicks::Now() - start_cert_verification_time_
;
3126 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3128 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3131 // We used to remember the intermediate CA certs in the NSS database
3132 // persistently. However, NSS opens a connection to the SQLite database
3133 // during NSS initialization and doesn't close the connection until NSS
3134 // shuts down. If the file system where the database resides is gone,
3135 // the database connection goes bad. What's worse, the connection won't
3136 // recover when the file system comes back. Until this NSS or SQLite bug
3137 // is fixed, we need to avoid using the NSS database for non-essential
3138 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3139 // http://crbug.com/15630 for more info.
3141 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3142 if (transport_security_state_
&&
3144 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3145 !transport_security_state_
->CheckPublicKeyPins(
3146 host_and_port_
.host(),
3147 server_cert_verify_result_
.is_issued_by_known_root
,
3148 server_cert_verify_result_
.public_key_hashes
,
3149 &pinning_failure_log_
)) {
3150 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3154 // Only check Certificate Transparency if there were no other errors with
3158 // Only cache the session if the certificate verified successfully.
3159 core_
->CacheSessionIfNecessary();
3162 completed_handshake_
= true;
3164 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3165 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3169 void SSLClientSocketNSS::VerifyCT() {
3170 if (!cert_transparency_verifier_
)
3173 // Note that this is a completely synchronous operation: The CT Log Verifier
3174 // gets all the data it needs for SCT verification and does not do any
3175 // external communication.
3176 cert_transparency_verifier_
->Verify(
3177 server_cert_verify_result_
.verified_cert
.get(),
3178 core_
->state().stapled_ocsp_response
,
3179 core_
->state().sct_list_from_tls_extension
, &ct_verify_result_
, net_log_
);
3180 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3181 // from the state after verification is complete, to conserve memory.
3183 if (!policy_enforcer_
) {
3184 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3186 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
3187 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
3188 SSLConfigService::GetEVCertsWhitelist();
3189 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
3190 server_cert_verify_result_
.verified_cert
.get(),
3191 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
3192 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3193 VLOG(1) << "EV certificate for "
3194 << server_cert_verify_result_
.verified_cert
->subject()
3196 << " does not conform to CT policy, removing EV status.";
3197 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3203 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3204 base::AutoLock
auto_lock(lock_
);
3205 if (valid_thread_id_
!= base::kInvalidThreadId
)
3207 valid_thread_id_
= base::PlatformThread::CurrentId();
3210 bool SSLClientSocketNSS::CalledOnValidThread() const {
3211 EnsureThreadIdAssigned();
3212 base::AutoLock
auto_lock(lock_
);
3213 return valid_thread_id_
== base::PlatformThread::CurrentId();
3216 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
3217 for (ct::SCTList::const_iterator iter
=
3218 ct_verify_result_
.verified_scts
.begin();
3219 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
3220 ssl_info
->signed_certificate_timestamps
.push_back(
3221 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
3223 for (ct::SCTList::const_iterator iter
=
3224 ct_verify_result_
.invalid_scts
.begin();
3225 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
3226 ssl_info
->signed_certificate_timestamps
.push_back(
3227 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
3229 for (ct::SCTList::const_iterator iter
=
3230 ct_verify_result_
.unknown_logs_scts
.begin();
3231 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
3232 ssl_info
->signed_certificate_timestamps
.push_back(
3233 SignedCertificateTimestampAndStatus(*iter
,
3234 ct::SCT_STATUS_LOG_UNKNOWN
));
3238 scoped_refptr
<X509Certificate
>
3239 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3240 return core_
->state().server_cert
.get();
3243 ChannelIDService
* SSLClientSocketNSS::GetChannelIDService() const {
3244 return channel_id_service_
;