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/profiler/scoped_tracker.h"
75 #include "base/single_thread_task_runner.h"
76 #include "base/stl_util.h"
77 #include "base/strings/string_number_conversions.h"
78 #include "base/strings/string_util.h"
79 #include "base/strings/stringprintf.h"
80 #include "base/thread_task_runner_handle.h"
81 #include "base/threading/thread_restrictions.h"
82 #include "base/values.h"
83 #include "crypto/ec_private_key.h"
84 #include "crypto/nss_util.h"
85 #include "crypto/nss_util_internal.h"
86 #include "crypto/rsa_private_key.h"
87 #include "crypto/scoped_nss_types.h"
88 #include "net/base/address_list.h"
89 #include "net/base/dns_util.h"
90 #include "net/base/io_buffer.h"
91 #include "net/base/net_errors.h"
92 #include "net/cert/asn1_util.h"
93 #include "net/cert/cert_policy_enforcer.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/ct_ev_whitelist.h"
97 #include "net/cert/ct_verifier.h"
98 #include "net/cert/ct_verify_result.h"
99 #include "net/cert/scoped_nss_types.h"
100 #include "net/cert/sct_status_flags.h"
101 #include "net/cert/single_request_cert_verifier.h"
102 #include "net/cert/x509_certificate_net_log_param.h"
103 #include "net/cert/x509_util.h"
104 #include "net/http/transport_security_state.h"
105 #include "net/log/net_log.h"
106 #include "net/ocsp/nss_ocsp.h"
107 #include "net/socket/client_socket_handle.h"
108 #include "net/socket/nss_ssl_util.h"
109 #include "net/ssl/ssl_cert_request_info.h"
110 #include "net/ssl/ssl_cipher_suite_names.h"
111 #include "net/ssl/ssl_connection_status_flags.h"
112 #include "net/ssl/ssl_info.h"
116 #include <wincrypt.h>
118 #include "base/win/windows_version.h"
119 #elif defined(OS_MACOSX)
120 #include <Security/SecBase.h>
121 #include <Security/SecCertificate.h>
122 #include <Security/SecIdentity.h>
124 #include "base/mac/mac_logging.h"
125 #include "base/synchronization/lock.h"
126 #include "crypto/mac_security_services_lock.h"
127 #elif defined(USE_NSS)
133 // State machines are easier to debug if you log state transitions.
134 // Enable these if you want to see what's going on.
136 #define EnterFunction(x)
137 #define LeaveFunction(x)
138 #define GotoState(s) next_handshake_state_ = s
140 #define EnterFunction(x)\
141 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
142 << "; next_handshake_state " << next_handshake_state_
143 #define LeaveFunction(x)\
144 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
145 << "; next_handshake_state " << next_handshake_state_
146 #define GotoState(s)\
148 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
149 next_handshake_state_ = s;\
153 #if !defined(CKM_AES_GCM)
154 #define CKM_AES_GCM 0x00001087
157 #if !defined(CKM_NSS_CHACHA20_POLY1305)
158 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
163 // SSL plaintext fragments are shorter than 16KB. Although the record layer
164 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
165 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
166 // entire SSL record.
167 const int kRecvBufferSize
= 17 * 1024;
168 const int kSendBufferSize
= 17 * 1024;
170 // Used by SSLClientSocketNSS::Core to indicate there is no read result
171 // obtained by a previous operation waiting to be returned to the caller.
172 // This constant can be any non-negative/non-zero value (eg: it does not
173 // overlap with any value of the net::Error range, including net::OK).
174 const int kNoPendingReadResult
= 1;
177 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
178 // set on Windows XP without error. There is some overhead from the server
179 // sending the OCSP response if it supports the extension, for the subset of
180 // XP clients who will request it but be unable to use it, but this is an
181 // acceptable trade-off for simplicity of implementation.
182 bool IsOCSPStaplingSupported() {
185 #elif defined(USE_NSS)
187 (*CacheOCSPResponseFromSideChannelFunction
)(
188 CERTCertDBHandle
*handle
, CERTCertificate
*cert
, PRTime time
,
189 SECItem
*encodedResponse
, void *pwArg
);
191 // On Linux, we dynamically link against the system version of libnss3.so. In
192 // order to continue working on systems without up-to-date versions of NSS we
193 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
195 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
196 // runtime symbol resolution that we need.
197 class RuntimeLibNSSFunctionPointers
{
199 CacheOCSPResponseFromSideChannelFunction
200 GetCacheOCSPResponseFromSideChannelFunction() {
201 return cache_ocsp_response_from_side_channel_
;
204 static RuntimeLibNSSFunctionPointers
* GetInstance() {
205 return Singleton
<RuntimeLibNSSFunctionPointers
>::get();
209 friend struct DefaultSingletonTraits
<RuntimeLibNSSFunctionPointers
>;
211 RuntimeLibNSSFunctionPointers() {
212 cache_ocsp_response_from_side_channel_
=
213 (CacheOCSPResponseFromSideChannelFunction
)
214 dlsym(RTLD_DEFAULT
, "CERT_CacheOCSPResponseFromSideChannel");
217 CacheOCSPResponseFromSideChannelFunction
218 cache_ocsp_response_from_side_channel_
;
221 CacheOCSPResponseFromSideChannelFunction
222 GetCacheOCSPResponseFromSideChannelFunction() {
223 return RuntimeLibNSSFunctionPointers::GetInstance()
224 ->GetCacheOCSPResponseFromSideChannelFunction();
227 bool IsOCSPStaplingSupported() {
228 return GetCacheOCSPResponseFromSideChannelFunction() != NULL
;
231 bool IsOCSPStaplingSupported() {
238 // This callback is intended to be used with CertFindChainInStore. In addition
239 // to filtering by extended/enhanced key usage, we do not show expired
240 // certificates and require digital signature usage in the key usage
243 // This matches our behavior on Mac OS X and that of NSS. It also matches the
244 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
245 // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certificates-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
246 BOOL WINAPI
ClientCertFindCallback(PCCERT_CONTEXT cert_context
,
248 VLOG(1) << "Calling ClientCertFindCallback from _nss";
249 // Verify the certificate's KU is good.
251 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING
, cert_context
->pCertInfo
,
253 if (!(key_usage
& CERT_DIGITAL_SIGNATURE_KEY_USAGE
))
256 DWORD err
= GetLastError();
257 // If |err| is non-zero, it's an actual error. Otherwise the extension
258 // just isn't present, and we treat it as if everything was allowed.
260 DLOG(ERROR
) << "CertGetIntendedKeyUsage failed: " << err
;
265 // Verify the current time is within the certificate's validity period.
266 if (CertVerifyTimeValidity(NULL
, cert_context
->pCertInfo
) != 0)
269 // Verify private key metadata is associated with this certificate.
271 if (!CertGetCertificateContextProperty(
272 cert_context
, CERT_KEY_PROV_INFO_PROP_ID
, NULL
, &size
)) {
281 // Helper functions to make it possible to log events from within the
282 // SSLClientSocketNSS::Core.
283 void AddLogEvent(const base::WeakPtr
<BoundNetLog
>& net_log
,
284 NetLog::EventType event_type
) {
287 net_log
->AddEvent(event_type
);
290 // Helper function to make it possible to log events from within the
291 // SSLClientSocketNSS::Core.
292 void AddLogEventWithCallback(const base::WeakPtr
<BoundNetLog
>& net_log
,
293 NetLog::EventType event_type
,
294 const NetLog::ParametersCallback
& callback
) {
297 net_log
->AddEvent(event_type
, callback
);
300 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
301 // from within the SSLClientSocketNSS::Core.
302 // AddByteTransferEvent expects to receive a const char*, which within the
303 // Core is backed by an IOBuffer. If the "const char*" is bound via
304 // base::Bind and posted to another thread, and the IOBuffer that backs that
305 // pointer then goes out of scope on the origin thread, this would result in
306 // an invalid read of a stale pointer.
307 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
308 // to the owning IOBuffer can be bound to the Callback. This ensures that the
309 // IOBuffer will stay alive long enough to cross threads if needed.
310 void LogByteTransferEvent(
311 const base::WeakPtr
<BoundNetLog
>& net_log
, NetLog::EventType event_type
,
312 int len
, IOBuffer
* buffer
) {
315 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
318 // PeerCertificateChain is a helper object which extracts the certificate
319 // chain, as given by the server, from an NSS socket and performs the needed
320 // resource management. The first element of the chain is the leaf certificate
321 // and the other elements are in the order given by the server.
322 class PeerCertificateChain
{
324 PeerCertificateChain() {}
325 PeerCertificateChain(const PeerCertificateChain
& other
);
326 ~PeerCertificateChain();
327 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
329 // Resets the current chain, freeing any resources, and updates the current
330 // chain to be a copy of the chain stored in |nss_fd|.
331 // If |nss_fd| is NULL, then the current certificate chain will be freed.
332 void Reset(PRFileDesc
* nss_fd
);
334 // Returns the current certificate chain as a vector of DER-encoded
335 // base::StringPieces. The returned vector remains valid until Reset is
337 std::vector
<base::StringPiece
> AsStringPieceVector() const;
339 bool empty() const { return certs_
.empty(); }
341 CERTCertificate
* operator[](size_t index
) const {
342 DCHECK_LT(index
, certs_
.size());
343 return certs_
[index
];
347 std::vector
<CERTCertificate
*> certs_
;
350 PeerCertificateChain::PeerCertificateChain(
351 const PeerCertificateChain
& other
) {
355 PeerCertificateChain::~PeerCertificateChain() {
359 PeerCertificateChain
& PeerCertificateChain::operator=(
360 const PeerCertificateChain
& other
) {
365 certs_
.reserve(other
.certs_
.size());
366 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
367 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
372 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
373 for (size_t i
= 0; i
< certs_
.size(); ++i
)
374 CERT_DestroyCertificate(certs_
[i
]);
380 CERTCertList
* list
= SSL_PeerCertificateChain(nss_fd
);
381 // The handshake on |nss_fd| may not have completed.
385 for (CERTCertListNode
* node
= CERT_LIST_HEAD(list
);
386 !CERT_LIST_END(node
, list
); node
= CERT_LIST_NEXT(node
)) {
387 certs_
.push_back(CERT_DupCertificate(node
->cert
));
389 CERT_DestroyCertList(list
);
392 std::vector
<base::StringPiece
>
393 PeerCertificateChain::AsStringPieceVector() const {
394 std::vector
<base::StringPiece
> v(certs_
.size());
395 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
396 v
[i
] = base::StringPiece(
397 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
398 certs_
[i
]->derCert
.len
);
404 // HandshakeState is a helper struct used to pass handshake state between
405 // the NSS task runner and the network task runner.
407 // It contains members that may be read or written on the NSS task runner,
408 // but which also need to be read from the network task runner. The NSS task
409 // runner will notify the network task runner whenever this state changes, so
410 // that the network task runner can safely make a copy, which avoids the need
412 struct HandshakeState
{
413 HandshakeState() { Reset(); }
416 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
418 negotiation_extension_
= SSLClientSocket::kExtensionUnknown
;
419 channel_id_sent
= false;
420 server_cert_chain
.Reset(NULL
);
422 sct_list_from_tls_extension
.clear();
423 stapled_ocsp_response
.clear();
424 resumed_handshake
= false;
425 ssl_connection_status
= 0;
428 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
429 // negotiated protocol stored in |next_proto|.
430 SSLClientSocket::NextProtoStatus next_proto_status
;
431 std::string next_proto
;
433 // TLS extension used for protocol negotiation.
434 SSLClientSocket::SSLNegotiationExtension negotiation_extension_
;
436 // True if a channel ID was sent.
437 bool channel_id_sent
;
439 // List of DER-encoded X.509 DistinguishedName of certificate authorities
440 // allowed by the server.
441 std::vector
<std::string
> cert_authorities
;
443 // Set when the handshake fully completes.
445 // The server certificate is first received from NSS as an NSS certificate
446 // chain (|server_cert_chain|) and then converted into a platform-specific
447 // X509Certificate object (|server_cert|). It's possible for some
448 // certificates to be successfully parsed by NSS, and not by the platform
449 // libraries (i.e.: when running within a sandbox, different parsing
450 // algorithms, etc), so it's not safe to assume that |server_cert| will
451 // always be non-NULL.
452 PeerCertificateChain server_cert_chain
;
453 scoped_refptr
<X509Certificate
> server_cert
;
454 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
455 std::string sct_list_from_tls_extension
;
456 // Stapled OCSP response received.
457 std::string stapled_ocsp_response
;
459 // True if the current handshake was the result of TLS session resumption.
460 bool resumed_handshake
;
462 // The negotiated security parameters (TLS version, cipher, extensions) of
463 // the SSL connection.
464 int ssl_connection_status
;
467 // Client-side error mapping functions.
469 // Map NSS error code to network error code.
470 int MapNSSClientError(PRErrorCode err
) {
472 case SSL_ERROR_BAD_CERT_ALERT
:
473 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
474 case SSL_ERROR_REVOKED_CERT_ALERT
:
475 case SSL_ERROR_EXPIRED_CERT_ALERT
:
476 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
477 case SSL_ERROR_UNKNOWN_CA_ALERT
:
478 case SSL_ERROR_ACCESS_DENIED_ALERT
:
479 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
481 return MapNSSError(err
);
487 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
488 // able to marshal data between NSS functions and an underlying transport
491 // All public functions are meant to be called from the network task runner,
492 // and any callbacks supplied will be invoked there as well, provided that
493 // Detach() has not been called yet.
495 /////////////////////////////////////////////////////////////////////////////
497 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
499 // Because NSS may block on either hardware or user input during operations
500 // such as signing, creating certificates, or locating private keys, the Core
501 // handles all of the interactions with the underlying NSS SSL socket, so
502 // that these blocking calls can be executed on a dedicated task runner.
504 // Note that the network task runner and the NSS task runner may be executing
505 // on the same thread. If that happens, then it's more performant to try to
506 // complete as much work as possible synchronously, even if it might block,
507 // rather than continually PostTask-ing to the same thread.
509 // Because NSS functions should only be called on the NSS task runner, while
510 // I/O resources should only be accessed on the network task runner, most
511 // public functions are implemented via three methods, each with different
512 // task runner affinities.
514 // In the single-threaded mode (where the network and NSS task runners run on
515 // the same thread), these are all attempted synchronously, while in the
516 // multi-threaded mode, message passing is used.
518 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
520 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
521 // (BufferRecv, BufferSend)
522 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
523 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
524 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
525 // data from the network task runner back to NSS (BufferRecvComplete,
526 // BufferSendComplete, OnHandshakeIOComplete)
528 /////////////////////////////////////////////////////////////////////////////
529 // Single-threaded example
531 // |--------------------------Network Task Runner--------------------------|
532 // SSLClientSocketNSS Core (Transport Socket)
534 // |-------------------------V
542 // |-------------------------V
544 // V-------------------------|
545 // BufferRecvComplete()
547 // PostOrRunCallback()
548 // V-------------------------|
551 /////////////////////////////////////////////////////////////////////////////
552 // Multi-threaded example:
554 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
555 // SSLClientSocketNSS Core Socket Core
557 // |---------------------V
559 // |-------------------------------V
565 // V-------------------------------|
567 // |----------------V
569 // V----------------|
570 // BufferRecvComplete()
571 // |-------------------------------V
572 // BufferRecvComplete()
574 // PostOrRunCallback()
575 // V-------------------------------|
576 // PostOrRunCallback()
577 // V---------------------|
580 /////////////////////////////////////////////////////////////////////////////
581 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
583 // Creates a new Core.
585 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
586 // that need to operate on the underlying transport, net log, or server
587 // bound certificate fetching will happen on the |network_task_runner|, so
588 // that their lifetimes match that of the owning SSLClientSocketNSS.
590 // The caller retains ownership of |transport|, |net_log|, and
591 // |channel_id_service|, and they will not be accessed once Detach()
593 Core(base::SequencedTaskRunner
* network_task_runner
,
594 base::SequencedTaskRunner
* nss_task_runner
,
595 ClientSocketHandle
* transport
,
596 const HostPortPair
& host_and_port
,
597 const SSLConfig
& ssl_config
,
598 BoundNetLog
* net_log
,
599 ChannelIDService
* channel_id_service
);
601 // Called on the network task runner.
602 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
603 // underlying memio implementation, to the Core. Returns true if the Core
604 // was successfully registered with the socket.
605 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
607 // Called on the network task runner.
609 // Attempts to perform an SSL handshake. If the handshake cannot be
610 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
611 // the network task runner once the handshake has completed. Otherwise,
612 // returns OK on success or a network error code on failure.
613 int Connect(const CompletionCallback
& callback
);
615 // Called on the network task runner.
616 // Signals that the resources owned by the network task runner are going
617 // away. No further callbacks will be invoked on the network task runner.
618 // May be called at any time.
621 // Called on the network task runner.
622 // Returns the current state of the underlying SSL socket. May be called at
624 const HandshakeState
& state() const { return network_handshake_state_
; }
626 // Called on the network task runner.
627 // Read() and Write() mirror the net::Socket functions of the same name.
628 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
629 // task runner at a later point, unless the caller calls Detach().
630 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
631 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
633 // Called on the network task runner.
634 bool IsConnected() const;
635 bool HasPendingAsyncOperation() const;
636 bool HasUnhandledReceivedData() const;
637 bool WasEverUsed() const;
639 // Called on the network task runner.
640 // Causes the associated SSL/TLS session ID to be added to NSS's session
641 // cache, but only if the connection has not been False Started.
643 // This should only be called after the server's certificate has been
644 // verified, and may not be called within an NSS callback.
645 void CacheSessionIfNecessary();
648 friend class base::RefCountedThreadSafe
<Core
>;
654 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
657 bool OnNSSTaskRunner() const;
658 bool OnNetworkTaskRunner() const;
660 ////////////////////////////////////////////////////////////////////////////
661 // Methods that are ONLY called on the NSS task runner:
662 ////////////////////////////////////////////////////////////////////////////
664 // Called by NSS during full handshakes to allow the application to
665 // verify the certificate. Instead of verifying the certificate in the midst
666 // of the handshake, SECSuccess is always returned and the peer's certificate
667 // is verified afterwards.
668 // This behaviour is an artifact of the original SSLClientSocketWin
669 // implementation, which could not verify the peer's certificate until after
670 // the handshake had completed, as well as bugs in NSS that prevent
671 // SSL_RestartHandshakeAfterCertReq from working.
672 static SECStatus
OwnAuthCertHandler(void* arg
,
677 // Callbacks called by NSS when the peer requests client certificate
679 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
681 #if defined(NSS_PLATFORM_CLIENT_AUTH)
682 // When NSS has been integrated with awareness of the underlying system
683 // cryptographic libraries, this callback allows the caller to supply a
684 // native platform certificate and key for use by NSS. At most, one of
685 // either (result_certs, result_private_key) or (result_nss_certificate,
686 // result_nss_private_key) should be set.
687 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
688 static SECStatus
PlatformClientAuthHandler(
691 CERTDistNames
* ca_names
,
692 CERTCertList
** result_certs
,
693 void** result_private_key
,
694 CERTCertificate
** result_nss_certificate
,
695 SECKEYPrivateKey
** result_nss_private_key
);
697 static SECStatus
ClientAuthHandler(void* arg
,
699 CERTDistNames
* ca_names
,
700 CERTCertificate
** result_certificate
,
701 SECKEYPrivateKey
** result_private_key
);
704 // Called by NSS to determine if we can False Start.
705 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
706 static SECStatus
CanFalseStartCallback(PRFileDesc
* socket
,
708 PRBool
* can_false_start
);
710 // Called by NSS once the handshake has completed.
711 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
712 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
714 // Called once the handshake has succeeded.
715 void HandshakeSucceeded();
717 // Handles an NSS error generated while handshaking or performing IO.
718 // Returns a network error code mapped from the original NSS error.
719 int HandleNSSError(PRErrorCode error
);
721 int DoHandshakeLoop(int last_io_result
);
722 int DoReadLoop(int result
);
723 int DoWriteLoop(int result
);
726 int DoGetDBCertComplete(int result
);
729 int DoPayloadWrite();
731 bool DoTransportIO();
735 void OnRecvComplete(int result
);
736 void OnSendComplete(int result
);
738 void DoConnectCallback(int result
);
739 void DoReadCallback(int result
);
740 void DoWriteCallback(int result
);
742 // Client channel ID handler.
743 static SECStatus
ClientChannelIDHandler(
746 SECKEYPublicKey
**out_public_key
,
747 SECKEYPrivateKey
**out_private_key
);
749 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
750 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
751 // and an error code otherwise.
752 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
753 // set by a call to ChannelIDService->GetChannelID. The caller
754 // takes ownership of the |*cert| and |*key|.
755 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
757 // Updates the NSS and platform specific certificates.
758 void UpdateServerCert();
759 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
760 // received in the handshake via a TLS extension.
761 void UpdateSignedCertTimestamps();
762 // Update the OCSP response cache with the stapled response received in the
763 // handshake, and update nss_handshake_state_ with
764 // the SignedCertificateTimestampList received in the stapled OCSP response.
765 void UpdateStapledOCSPResponse();
766 // Updates the nss_handshake_state_ with the negotiated security parameters.
767 void UpdateConnectionStatus();
768 // Record histograms for channel id support during full handshakes - resumed
769 // handshakes are ignored.
770 void RecordChannelIDSupportOnNSSTaskRunner();
771 // UpdateNextProto gets any application-layer protocol that may have been
772 // negotiated by the TLS connection.
773 void UpdateNextProto();
774 // Record TLS extension used for protocol negotiation (NPN or ALPN).
775 void UpdateExtensionUsed();
777 ////////////////////////////////////////////////////////////////////////////
778 // Methods that are ONLY called on the network task runner:
779 ////////////////////////////////////////////////////////////////////////////
780 int DoBufferRecv(IOBuffer
* buffer
, int len
);
781 int DoBufferSend(IOBuffer
* buffer
, int len
);
782 int DoGetChannelID(const std::string
& host
);
784 void OnGetChannelIDComplete(int result
);
785 void OnHandshakeStateUpdated(const HandshakeState
& state
);
786 void OnNSSBufferUpdated(int amount_in_read_buffer
);
787 void DidNSSRead(int result
);
788 void DidNSSWrite(int result
);
789 void RecordChannelIDSupportOnNetworkTaskRunner(
790 bool negotiated_channel_id
,
791 bool channel_id_enabled
,
792 bool supports_ecc
) const;
794 ////////////////////////////////////////////////////////////////////////////
795 // Methods that are called on both the network task runner and the NSS
797 ////////////////////////////////////////////////////////////////////////////
798 void OnHandshakeIOComplete(int result
);
799 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
800 void BufferSendComplete(int result
);
802 // PostOrRunCallback is a helper function to ensure that |callback| is
803 // invoked on the network task runner, but only if Detach() has not yet
805 void PostOrRunCallback(const tracked_objects::Location
& location
,
806 const base::Closure
& callback
);
808 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
809 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
810 void AddCertProvidedEvent(int cert_count
);
812 // Sets the handshake state |channel_id_sent| flag and logs the
813 // SSL_CHANNEL_ID_PROVIDED event.
814 void SetChannelIDProvided();
816 ////////////////////////////////////////////////////////////////////////////
817 // Members that are ONLY accessed on the network task runner:
818 ////////////////////////////////////////////////////////////////////////////
820 // True if the owning SSLClientSocketNSS has called Detach(). No further
821 // callbacks will be invoked nor access to members owned by the network
825 // The underlying transport to use for network IO.
826 ClientSocketHandle
* transport_
;
827 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
829 // The current handshake state. Mirrors |nss_handshake_state_|.
830 HandshakeState network_handshake_state_
;
832 // The service for retrieving Channel ID keys. May be NULL.
833 ChannelIDService
* channel_id_service_
;
834 ChannelIDService::RequestHandle domain_bound_cert_request_handle_
;
836 // The information about NSS task runner.
837 int unhandled_buffer_size_
;
838 bool nss_waiting_read_
;
839 bool nss_waiting_write_
;
842 // Set when Read() or Write() successfully reads or writes data to or from the
846 ////////////////////////////////////////////////////////////////////////////
847 // Members that are ONLY accessed on the NSS task runner:
848 ////////////////////////////////////////////////////////////////////////////
849 HostPortPair host_and_port_
;
850 SSLConfig ssl_config_
;
855 // Buffers for the network end of the SSL state machine
856 memio_Private
* nss_bufs_
;
858 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
859 // as much data as possible, without blocking.
860 // If DoPayloadRead() encounters an error after having read some data, stores
861 // the results to return on the *next* call to DoPayloadRead(). A value of
862 // kNoPendingReadResult indicates there is no pending result, otherwise 0
863 // indicates EOF and < 0 indicates an error.
864 int pending_read_result_
;
865 // Contains the previously observed NSS error. Only valid when
866 // pending_read_result_ != kNoPendingReadResult.
867 PRErrorCode pending_read_nss_error_
;
869 // The certificate chain, in DER form, that is expected to be received from
871 std::vector
<std::string
> predicted_certs_
;
873 State next_handshake_state_
;
875 // True if channel ID extension was negotiated.
876 bool channel_id_xtn_negotiated_
;
877 // True if the handshake state machine was interrupted for channel ID.
878 bool channel_id_needed_
;
879 // True if the handshake state machine was interrupted for client auth.
880 bool client_auth_cert_needed_
;
881 // True if NSS has False Started.
883 // True if NSS has called HandshakeCallback.
884 bool handshake_callback_called_
;
886 HandshakeState nss_handshake_state_
;
888 bool transport_recv_busy_
;
889 bool transport_recv_eof_
;
890 bool transport_send_busy_
;
892 // Used by Read function.
893 scoped_refptr
<IOBuffer
> user_read_buf_
;
894 int user_read_buf_len_
;
896 // Used by Write function.
897 scoped_refptr
<IOBuffer
> user_write_buf_
;
898 int user_write_buf_len_
;
900 CompletionCallback user_connect_callback_
;
901 CompletionCallback user_read_callback_
;
902 CompletionCallback user_write_callback_
;
904 ////////////////////////////////////////////////////////////////////////////
905 // Members that are accessed on both the network task runner and the NSS
907 ////////////////////////////////////////////////////////////////////////////
908 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
909 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
911 // Dereferenced only on the network task runner, but bound to tasks destined
912 // for the network task runner from the NSS task runner.
913 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
915 // Written on the network task runner by the |channel_id_service_|,
916 // prior to invoking OnHandshakeIOComplete.
917 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
918 // on the NSS task runner.
919 std::string domain_bound_private_key_
;
920 std::string domain_bound_cert_
;
922 DISALLOW_COPY_AND_ASSIGN(Core
);
925 SSLClientSocketNSS::Core::Core(
926 base::SequencedTaskRunner
* network_task_runner
,
927 base::SequencedTaskRunner
* nss_task_runner
,
928 ClientSocketHandle
* transport
,
929 const HostPortPair
& host_and_port
,
930 const SSLConfig
& ssl_config
,
931 BoundNetLog
* net_log
,
932 ChannelIDService
* channel_id_service
)
934 transport_(transport
),
935 weak_net_log_factory_(net_log
),
936 channel_id_service_(channel_id_service
),
937 unhandled_buffer_size_(0),
938 nss_waiting_read_(false),
939 nss_waiting_write_(false),
940 nss_is_closed_(false),
941 was_ever_used_(false),
942 host_and_port_(host_and_port
),
943 ssl_config_(ssl_config
),
946 pending_read_result_(kNoPendingReadResult
),
947 pending_read_nss_error_(0),
948 next_handshake_state_(STATE_NONE
),
949 channel_id_xtn_negotiated_(false),
950 channel_id_needed_(false),
951 client_auth_cert_needed_(false),
952 false_started_(false),
953 handshake_callback_called_(false),
954 transport_recv_busy_(false),
955 transport_recv_eof_(false),
956 transport_send_busy_(false),
957 user_read_buf_len_(0),
958 user_write_buf_len_(0),
959 network_task_runner_(network_task_runner
),
960 nss_task_runner_(nss_task_runner
),
961 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
964 SSLClientSocketNSS::Core::~Core() {
965 // TODO(wtc): Send SSL close_notify alert.
966 if (nss_fd_
!= NULL
) {
973 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
974 memio_Private
* buffers
) {
975 DCHECK(OnNetworkTaskRunner());
982 SECStatus rv
= SECSuccess
;
984 if (!ssl_config_
.next_protos
.empty()) {
985 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
986 const bool adequate_encryption
=
987 PK11_TokenExists(CKM_AES_GCM
) ||
988 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305
);
989 const bool adequate_key_agreement
= PK11_TokenExists(CKM_DH_PKCS_DERIVE
) ||
990 PK11_TokenExists(CKM_ECDH1_DERIVE
);
991 std::vector
<uint8_t> wire_protos
=
992 SerializeNextProtos(ssl_config_
.next_protos
,
993 adequate_encryption
&& adequate_key_agreement
&&
994 IsTLSVersionAdequateForHTTP2(ssl_config_
));
995 rv
= SSL_SetNextProtoNego(
996 nss_fd_
, wire_protos
.empty() ? NULL
: &wire_protos
[0],
998 if (rv
!= SECSuccess
)
999 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoNego", "");
1000 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_ALPN
, PR_TRUE
);
1001 if (rv
!= SECSuccess
)
1002 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_ALPN");
1003 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_NPN
, PR_TRUE
);
1004 if (rv
!= SECSuccess
)
1005 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_NPN");
1008 rv
= SSL_AuthCertificateHook(
1009 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
1010 if (rv
!= SECSuccess
) {
1011 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
1015 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1016 rv
= SSL_GetPlatformClientAuthDataHook(
1017 nss_fd_
, SSLClientSocketNSS::Core::PlatformClientAuthHandler
,
1020 rv
= SSL_GetClientAuthDataHook(
1021 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
1023 if (rv
!= SECSuccess
) {
1024 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
1028 if (IsChannelIDEnabled(ssl_config_
, channel_id_service_
)) {
1029 rv
= SSL_SetClientChannelIDCallback(
1030 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
1031 if (rv
!= SECSuccess
) {
1032 LogFailedNSSFunction(
1033 *weak_net_log_
, "SSL_SetClientChannelIDCallback", "");
1037 rv
= SSL_SetCanFalseStartCallback(
1038 nss_fd_
, SSLClientSocketNSS::Core::CanFalseStartCallback
, this);
1039 if (rv
!= SECSuccess
) {
1040 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetCanFalseStartCallback", "");
1044 rv
= SSL_HandshakeCallback(
1045 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
1046 if (rv
!= SECSuccess
) {
1047 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
1054 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
1055 if (!OnNSSTaskRunner()) {
1057 bool posted
= nss_task_runner_
->PostTask(
1059 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
1060 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1063 DCHECK(OnNSSTaskRunner());
1064 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1065 DCHECK(user_read_callback_
.is_null());
1066 DCHECK(user_write_callback_
.is_null());
1067 DCHECK(user_connect_callback_
.is_null());
1068 DCHECK(!user_read_buf_
.get());
1069 DCHECK(!user_write_buf_
.get());
1071 next_handshake_state_
= STATE_HANDSHAKE
;
1072 int rv
= DoHandshakeLoop(OK
);
1073 if (rv
== ERR_IO_PENDING
) {
1074 user_connect_callback_
= callback
;
1075 } else if (rv
> OK
) {
1078 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
1079 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1080 return ERR_IO_PENDING
;
1086 void SSLClientSocketNSS::Core::Detach() {
1087 DCHECK(OnNetworkTaskRunner());
1091 weak_net_log_factory_
.InvalidateWeakPtrs();
1093 network_handshake_state_
.Reset();
1095 domain_bound_cert_request_handle_
.Cancel();
1098 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1099 const CompletionCallback
& callback
) {
1100 if (!OnNSSTaskRunner()) {
1101 DCHECK(OnNetworkTaskRunner());
1104 DCHECK(!nss_waiting_read_
);
1106 nss_waiting_read_
= true;
1107 bool posted
= nss_task_runner_
->PostTask(
1109 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1110 buf_len
, callback
));
1112 nss_is_closed_
= true;
1113 nss_waiting_read_
= false;
1115 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1118 DCHECK(OnNSSTaskRunner());
1119 DCHECK(false_started_
|| handshake_callback_called_
);
1120 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1121 DCHECK(user_read_callback_
.is_null());
1122 DCHECK(user_connect_callback_
.is_null());
1123 DCHECK(!user_read_buf_
.get());
1126 user_read_buf_
= buf
;
1127 user_read_buf_len_
= buf_len
;
1129 int rv
= DoReadLoop(OK
);
1130 if (rv
== ERR_IO_PENDING
) {
1131 if (OnNetworkTaskRunner())
1132 nss_waiting_read_
= true;
1133 user_read_callback_
= callback
;
1135 user_read_buf_
= NULL
;
1136 user_read_buf_len_
= 0;
1138 if (!OnNetworkTaskRunner()) {
1139 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1140 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1141 return ERR_IO_PENDING
;
1143 DCHECK(!nss_waiting_read_
);
1145 nss_is_closed_
= true;
1147 was_ever_used_
= true;
1155 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1156 const CompletionCallback
& callback
) {
1157 if (!OnNSSTaskRunner()) {
1158 DCHECK(OnNetworkTaskRunner());
1161 DCHECK(!nss_waiting_write_
);
1163 nss_waiting_write_
= true;
1164 bool posted
= nss_task_runner_
->PostTask(
1166 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1167 buf_len
, callback
));
1169 nss_is_closed_
= true;
1170 nss_waiting_write_
= false;
1172 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1175 DCHECK(OnNSSTaskRunner());
1176 DCHECK(false_started_
|| handshake_callback_called_
);
1177 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1178 DCHECK(user_write_callback_
.is_null());
1179 DCHECK(user_connect_callback_
.is_null());
1180 DCHECK(!user_write_buf_
.get());
1183 user_write_buf_
= buf
;
1184 user_write_buf_len_
= buf_len
;
1186 int rv
= DoWriteLoop(OK
);
1187 if (rv
== ERR_IO_PENDING
) {
1188 if (OnNetworkTaskRunner())
1189 nss_waiting_write_
= true;
1190 user_write_callback_
= callback
;
1192 user_write_buf_
= NULL
;
1193 user_write_buf_len_
= 0;
1195 if (!OnNetworkTaskRunner()) {
1196 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1197 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1198 return ERR_IO_PENDING
;
1200 DCHECK(!nss_waiting_write_
);
1202 nss_is_closed_
= true;
1203 } else if (rv
> 0) {
1204 was_ever_used_
= true;
1212 bool SSLClientSocketNSS::Core::IsConnected() const {
1213 DCHECK(OnNetworkTaskRunner());
1214 return !nss_is_closed_
;
1217 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1218 DCHECK(OnNetworkTaskRunner());
1219 return nss_waiting_read_
|| nss_waiting_write_
;
1222 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1223 DCHECK(OnNetworkTaskRunner());
1224 return unhandled_buffer_size_
!= 0;
1227 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1228 DCHECK(OnNetworkTaskRunner());
1229 return was_ever_used_
;
1232 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1233 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1234 // nss_fd_. However, it happens on the network task runner in order to match
1235 // the buggy behavior of ExportKeyingMaterial.
1237 // Once http://crbug.com/330360 is fixed, this should be moved to an
1238 // implementation that exclusively does this work on the NSS TaskRunner. This
1239 // is "safe" because it is only called during the certificate verification
1240 // state machine of the main socket, which is safe because no underlying
1241 // transport IO will be occuring in that state, and NSS will not be blocking
1242 // on any PKCS#11 related locks that might block the Network TaskRunner.
1243 DCHECK(OnNetworkTaskRunner());
1245 // Only cache the session if the connection was not False Started, because
1246 // sessions should only be cached *after* the peer's Finished message is
1248 // In the case of False Start, the session will be cached once the
1249 // HandshakeCallback is called, which signals the receipt and processing of
1250 // the Finished message, and which will happen during a call to
1251 // PR_Read/PR_Write.
1252 if (!false_started_
)
1253 SSL_CacheSession(nss_fd_
);
1256 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1257 return nss_task_runner_
->RunsTasksOnCurrentThread();
1260 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1261 return network_task_runner_
->RunsTasksOnCurrentThread();
1265 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1270 Core
* core
= reinterpret_cast<Core
*>(arg
);
1271 if (core
->handshake_callback_called_
) {
1272 // Disallow the server certificate to change in a renegotiation.
1273 CERTCertificate
* old_cert
= core
->nss_handshake_state_
.server_cert_chain
[0];
1274 ScopedCERTCertificate
new_cert(SSL_PeerCertificate(socket
));
1275 if (new_cert
->derCert
.len
!= old_cert
->derCert
.len
||
1276 memcmp(new_cert
->derCert
.data
, old_cert
->derCert
.data
,
1277 new_cert
->derCert
.len
) != 0) {
1278 // NSS doesn't have an error code that indicates the server certificate
1279 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1280 // for this purpose.
1281 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE
);
1286 // Tell NSS to not verify the certificate.
1290 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1292 SECStatus
SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1295 CERTDistNames
* ca_names
,
1296 CERTCertList
** result_certs
,
1297 void** result_private_key
,
1298 CERTCertificate
** result_nss_certificate
,
1299 SECKEYPrivateKey
** result_nss_private_key
) {
1300 Core
* core
= reinterpret_cast<Core
*>(arg
);
1301 DCHECK(core
->OnNSSTaskRunner());
1303 core
->PostOrRunCallback(
1305 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1306 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1308 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1310 if (core
->ssl_config_
.send_client_cert
) {
1311 if (core
->ssl_config_
.client_cert
.get()) {
1312 PCCERT_CONTEXT cert_context
=
1313 core
->ssl_config_
.client_cert
->os_cert_handle();
1315 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
1317 BOOL must_free
= FALSE
;
1319 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
1320 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
1322 BOOL acquired_key
= CryptAcquireCertificatePrivateKey(
1323 cert_context
, flags
, NULL
, &crypt_prov
, &key_spec
, &must_free
);
1326 // Should never get a cached handle back - ownership must always be
1328 CHECK_EQ(must_free
, TRUE
);
1331 der_cert
.type
= siDERCertBuffer
;
1332 der_cert
.data
= cert_context
->pbCertEncoded
;
1333 der_cert
.len
= cert_context
->cbCertEncoded
;
1335 // TODO(rsleevi): Error checking for NSS allocation errors.
1336 CERTCertDBHandle
* db_handle
= CERT_GetDefaultCertDB();
1337 CERTCertificate
* user_cert
= CERT_NewTempCertificate(
1338 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1340 // Importing the certificate can fail for reasons including a serial
1341 // number collision. See crbug.com/97355.
1342 core
->AddCertProvidedEvent(0);
1345 CERTCertList
* cert_chain
= CERT_NewCertList();
1346 CERT_AddCertToListTail(cert_chain
, user_cert
);
1348 // Add the intermediates.
1349 X509Certificate::OSCertHandles intermediates
=
1350 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1351 for (X509Certificate::OSCertHandles::const_iterator it
=
1352 intermediates
.begin(); it
!= intermediates
.end(); ++it
) {
1353 der_cert
.data
= (*it
)->pbCertEncoded
;
1354 der_cert
.len
= (*it
)->cbCertEncoded
;
1356 CERTCertificate
* intermediate
= CERT_NewTempCertificate(
1357 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1358 if (!intermediate
) {
1359 CERT_DestroyCertList(cert_chain
);
1360 core
->AddCertProvidedEvent(0);
1363 CERT_AddCertToListTail(cert_chain
, intermediate
);
1365 PCERT_KEY_CONTEXT key_context
= reinterpret_cast<PCERT_KEY_CONTEXT
>(
1366 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT
)));
1367 key_context
->cbSize
= sizeof(*key_context
);
1368 // NSS will free this context when no longer in use.
1369 key_context
->hCryptProv
= crypt_prov
;
1370 key_context
->dwKeySpec
= key_spec
;
1371 *result_private_key
= key_context
;
1372 *result_certs
= cert_chain
;
1374 int cert_count
= 1 + intermediates
.size();
1375 core
->AddCertProvidedEvent(cert_count
);
1378 LOG(WARNING
) << "Client cert found without private key";
1381 // Send no client certificate.
1382 core
->AddCertProvidedEvent(0);
1386 core
->nss_handshake_state_
.cert_authorities
.clear();
1388 std::vector
<CERT_NAME_BLOB
> issuer_list(ca_names
->nnames
);
1389 for (int i
= 0; i
< ca_names
->nnames
; ++i
) {
1390 issuer_list
[i
].cbData
= ca_names
->names
[i
].len
;
1391 issuer_list
[i
].pbData
= ca_names
->names
[i
].data
;
1392 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1393 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1394 static_cast<size_t>(ca_names
->names
[i
].len
)));
1397 // Update the network task runner's view of the handshake state now that
1398 // server certificate request has been recorded.
1399 core
->PostOrRunCallback(
1400 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1401 core
->nss_handshake_state_
));
1403 // Tell NSS to suspend the client authentication. We will then abort the
1404 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1405 return SECWouldBlock
;
1406 #elif defined(OS_MACOSX)
1407 if (core
->ssl_config_
.send_client_cert
) {
1408 if (core
->ssl_config_
.client_cert
.get()) {
1409 OSStatus os_error
= noErr
;
1410 SecIdentityRef identity
= NULL
;
1411 SecKeyRef private_key
= NULL
;
1412 X509Certificate::OSCertHandles chain
;
1414 base::AutoLock
lock(crypto::GetMacSecurityServicesLock());
1415 os_error
= SecIdentityCreateWithCertificate(
1416 NULL
, core
->ssl_config_
.client_cert
->os_cert_handle(), &identity
);
1418 if (os_error
== noErr
) {
1419 os_error
= SecIdentityCopyPrivateKey(identity
, &private_key
);
1420 CFRelease(identity
);
1423 if (os_error
== noErr
) {
1424 // TODO(rsleevi): Error checking for NSS allocation errors.
1425 *result_certs
= CERT_NewCertList();
1426 *result_private_key
= private_key
;
1428 chain
.push_back(core
->ssl_config_
.client_cert
->os_cert_handle());
1429 const X509Certificate::OSCertHandles
& intermediates
=
1430 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1431 if (!intermediates
.empty())
1432 chain
.insert(chain
.end(), intermediates
.begin(), intermediates
.end());
1434 for (size_t i
= 0, chain_count
= chain
.size(); i
< chain_count
; ++i
) {
1435 CSSM_DATA cert_data
;
1436 SecCertificateRef cert_ref
= chain
[i
];
1437 os_error
= SecCertificateGetData(cert_ref
, &cert_data
);
1438 if (os_error
!= noErr
)
1442 der_cert
.type
= siDERCertBuffer
;
1443 der_cert
.data
= cert_data
.Data
;
1444 der_cert
.len
= cert_data
.Length
;
1445 CERTCertificate
* nss_cert
= CERT_NewTempCertificate(
1446 CERT_GetDefaultCertDB(), &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1448 // In the event of an NSS error, make up an OS error and reuse
1449 // the error handling below.
1450 os_error
= errSecCreateChainFailed
;
1453 CERT_AddCertToListTail(*result_certs
, nss_cert
);
1457 if (os_error
== noErr
) {
1458 core
->AddCertProvidedEvent(chain
.size());
1462 OSSTATUS_LOG(WARNING
, os_error
)
1463 << "Client cert found, but could not be used";
1464 if (*result_certs
) {
1465 CERT_DestroyCertList(*result_certs
);
1466 *result_certs
= NULL
;
1468 if (*result_private_key
)
1469 *result_private_key
= NULL
;
1471 CFRelease(private_key
);
1474 // Send no client certificate.
1475 core
->AddCertProvidedEvent(0);
1479 core
->nss_handshake_state_
.cert_authorities
.clear();
1481 // Retrieve the cert issuers accepted by the server.
1482 std::vector
<CertPrincipal
> valid_issuers
;
1483 int n
= ca_names
->nnames
;
1484 for (int i
= 0; i
< n
; i
++) {
1485 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1486 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1487 static_cast<size_t>(ca_names
->names
[i
].len
)));
1490 // Update the network task runner's view of the handshake state now that
1491 // server certificate request has been recorded.
1492 core
->PostOrRunCallback(
1493 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1494 core
->nss_handshake_state_
));
1496 // Tell NSS to suspend the client authentication. We will then abort the
1497 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1498 return SECWouldBlock
;
1504 #elif defined(OS_IOS)
1506 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1509 CERTDistNames
* ca_names
,
1510 CERTCertificate
** result_certificate
,
1511 SECKEYPrivateKey
** result_private_key
) {
1512 Core
* core
= reinterpret_cast<Core
*>(arg
);
1513 DCHECK(core
->OnNSSTaskRunner());
1515 core
->PostOrRunCallback(
1517 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1518 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1520 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1521 LOG(WARNING
) << "Client auth is not supported";
1523 // Never send a certificate.
1524 core
->AddCertProvidedEvent(0);
1528 #else // NSS_PLATFORM_CLIENT_AUTH
1531 // Based on Mozilla's NSS_GetClientAuthData.
1532 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1535 CERTDistNames
* ca_names
,
1536 CERTCertificate
** result_certificate
,
1537 SECKEYPrivateKey
** result_private_key
) {
1538 Core
* core
= reinterpret_cast<Core
*>(arg
);
1539 DCHECK(core
->OnNSSTaskRunner());
1541 core
->PostOrRunCallback(
1543 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1544 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1546 // Regular client certificate requested.
1547 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1548 void* wincx
= SSL_RevealPinArg(socket
);
1550 if (core
->ssl_config_
.send_client_cert
) {
1551 // Second pass: a client certificate should have been selected.
1552 if (core
->ssl_config_
.client_cert
.get()) {
1553 CERTCertificate
* cert
=
1554 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1555 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1557 // TODO(jsorianopastor): We should wait for server certificate
1558 // verification before sending our credentials. See
1559 // http://crbug.com/13934.
1560 *result_certificate
= cert
;
1561 *result_private_key
= privkey
;
1562 // A cert_count of -1 means the number of certificates is unknown.
1563 // NSS will construct the certificate chain.
1564 core
->AddCertProvidedEvent(-1);
1568 LOG(WARNING
) << "Client cert found without private key";
1570 // Send no client certificate.
1571 core
->AddCertProvidedEvent(0);
1575 // First pass: client certificate is needed.
1576 core
->nss_handshake_state_
.cert_authorities
.clear();
1578 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1579 // the server and save them in |cert_authorities|.
1580 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1581 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1582 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1583 static_cast<size_t>(ca_names
->names
[i
].len
)));
1586 // Update the network task runner's view of the handshake state now that
1587 // server certificate request has been recorded.
1588 core
->PostOrRunCallback(
1589 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1590 core
->nss_handshake_state_
));
1592 // Tell NSS to suspend the client authentication. We will then abort the
1593 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1594 return SECWouldBlock
;
1596 #endif // NSS_PLATFORM_CLIENT_AUTH
1599 SECStatus
SSLClientSocketNSS::Core::CanFalseStartCallback(
1602 PRBool
* can_false_start
) {
1603 // If the server doesn't support NPN or ALPN, then we don't do False
1605 PRBool negotiated_extension
;
1606 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1607 ssl_app_layer_protocol_xtn
,
1608 &negotiated_extension
);
1609 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1610 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1611 ssl_next_proto_nego_xtn
,
1612 &negotiated_extension
);
1614 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1615 *can_false_start
= PR_FALSE
;
1619 SSLChannelInfo channel_info
;
1621 SSL_GetChannelInfo(socket
, &channel_info
, sizeof(channel_info
));
1622 if (ok
!= SECSuccess
|| channel_info
.length
!= sizeof(channel_info
) ||
1623 channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_TLS_1_2
||
1624 !IsFalseStartableTLSCipherSuite(channel_info
.cipherSuite
)) {
1625 *can_false_start
= PR_FALSE
;
1629 return SSL_RecommendedCanFalseStart(socket
, can_false_start
);
1633 void SSLClientSocketNSS::Core::HandshakeCallback(
1636 Core
* core
= reinterpret_cast<Core
*>(arg
);
1637 DCHECK(core
->OnNSSTaskRunner());
1639 core
->handshake_callback_called_
= true;
1640 if (core
->false_started_
) {
1641 core
->false_started_
= false;
1642 // If the connection was False Started, then at the time of this callback,
1643 // the peer's certificate will have been verified or the caller will have
1644 // accepted the error.
1645 // This is guaranteed when using False Start because this callback will
1646 // not be invoked until processing the peer's Finished message, which
1647 // will only happen in a PR_Read/PR_Write call, which can only happen
1648 // after the peer's certificate is verified.
1649 SSL_CacheSessionUnlocked(socket
);
1651 // Additionally, when False Starting, DoHandshake() will have already
1652 // called HandshakeSucceeded(), so return now.
1655 core
->HandshakeSucceeded();
1658 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1659 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1660 tracked_objects::ScopedTracker
tracking_profile(
1661 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1662 "424386 SSLClientSocketNSS::Core::HandshakeSucceeded"));
1664 DCHECK(OnNSSTaskRunner());
1666 PRBool last_handshake_resumed
;
1667 SECStatus rv
= SSL_HandshakeResumedSession(nss_fd_
, &last_handshake_resumed
);
1668 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1669 nss_handshake_state_
.resumed_handshake
= true;
1671 nss_handshake_state_
.resumed_handshake
= false;
1674 RecordChannelIDSupportOnNSSTaskRunner();
1676 UpdateSignedCertTimestamps();
1677 UpdateStapledOCSPResponse();
1678 UpdateConnectionStatus();
1680 UpdateExtensionUsed();
1682 // Update the network task runners view of the handshake state whenever
1683 // a handshake has completed.
1685 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
1686 nss_handshake_state_
));
1689 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
) {
1690 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1691 tracked_objects::ScopedTracker
tracking_profile(
1692 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1693 "424386 SSLClientSocketNSS::Core::HandleNSSError"));
1695 DCHECK(OnNSSTaskRunner());
1697 int net_error
= MapNSSClientError(nss_error
);
1700 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1701 // os_cert_handle() as an optimization. However, if the certificate
1702 // private key is stored on a smart card, and the smart card is removed,
1703 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1704 // preventing client certificate authentication. Because the
1705 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1706 // caching in X509Certificate, this failure ends up preventing client
1707 // certificate authentication with the same certificate for all future
1708 // attempts, even after the smart card has been re-inserted. By setting
1709 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1710 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1711 // the certificate on the next attempt, which should succeed if the smart
1712 // card has been re-inserted, or will typically prompt the user to
1713 // re-insert the smart card if not.
1714 if ((net_error
== ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
||
1715 net_error
== ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
) &&
1716 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get()) {
1717 CertSetCertificateContextProperty(
1718 ssl_config_
.client_cert
->os_cert_handle(),
1719 CERT_KEY_PROV_HANDLE_PROP_ID
, 0, NULL
);
1726 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1727 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1728 tracked_objects::ScopedTracker
tracking_profile(
1729 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1730 "424386 SSLClientSocketNSS::Core::DoHandshakeLoop"));
1732 DCHECK(OnNSSTaskRunner());
1734 int rv
= last_io_result
;
1736 // Default to STATE_NONE for next state.
1737 State state
= next_handshake_state_
;
1738 GotoState(STATE_NONE
);
1741 case STATE_HANDSHAKE
:
1744 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1745 rv
= DoGetDBCertComplete(rv
);
1749 rv
= ERR_UNEXPECTED
;
1750 LOG(DFATAL
) << "unexpected state " << state
;
1754 // Do the actual network I/O
1755 bool network_moved
= DoTransportIO();
1756 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1757 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1758 // special case we keep looping even if rv is ERR_IO_PENDING because
1759 // the transport IO may allow DoHandshake to make progress.
1760 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1761 rv
= OK
; // This causes us to stay in the loop.
1763 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1767 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1768 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1769 tracked_objects::ScopedTracker
tracking_profile(
1770 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1771 "424386 SSLClientSocketNSS::Core::DoReadLoop"));
1773 DCHECK(OnNSSTaskRunner());
1774 DCHECK(false_started_
|| handshake_callback_called_
);
1775 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1781 LOG(DFATAL
) << "!nss_bufs_";
1782 int rv
= ERR_UNEXPECTED
;
1785 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1786 NetLog::TYPE_SSL_READ_ERROR
,
1787 CreateNetLogSSLErrorCallback(rv
, 0)));
1794 rv
= DoPayloadRead();
1795 network_moved
= DoTransportIO();
1796 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1801 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1802 DCHECK(OnNSSTaskRunner());
1803 DCHECK(false_started_
|| handshake_callback_called_
);
1804 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1810 LOG(DFATAL
) << "!nss_bufs_";
1811 int rv
= ERR_UNEXPECTED
;
1814 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1815 NetLog::TYPE_SSL_READ_ERROR
,
1816 CreateNetLogSSLErrorCallback(rv
, 0)));
1823 rv
= DoPayloadWrite();
1824 network_moved
= DoTransportIO();
1825 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1831 int SSLClientSocketNSS::Core::DoHandshake() {
1832 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1833 tracked_objects::ScopedTracker
tracking_profile(
1834 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1835 "424386 SSLClientSocketNSS::Core::DoHandshake"));
1837 DCHECK(OnNSSTaskRunner());
1840 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1842 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1843 tracked_objects::ScopedTracker
tracking_profile1(
1844 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1845 "424386 SSLClientSocketNSS::Core::DoHandshake 1"));
1847 // Note: this function may be called multiple times during the handshake, so
1848 // even though channel id and client auth are separate else cases, they can
1849 // both be used during a single SSL handshake.
1850 if (channel_id_needed_
) {
1851 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1852 net_error
= ERR_IO_PENDING
;
1853 } else if (client_auth_cert_needed_
) {
1854 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1857 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1858 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1859 CreateNetLogSSLErrorCallback(net_error
, 0)));
1860 } else if (rv
== SECSuccess
) {
1861 if (!handshake_callback_called_
) {
1862 false_started_
= true;
1863 HandshakeSucceeded();
1866 PRErrorCode prerr
= PR_GetError();
1867 net_error
= HandleNSSError(prerr
);
1869 // If not done, stay in this state
1870 if (net_error
== ERR_IO_PENDING
) {
1871 GotoState(STATE_HANDSHAKE
);
1875 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1876 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1877 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1884 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1885 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
1886 tracked_objects::ScopedTracker
tracking_profile(
1887 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1888 "424386 SSLClientSocketNSS::Core::DoGetDBCertComplete"));
1893 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1894 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1896 channel_id_needed_
= false;
1901 SECKEYPublicKey
* public_key
;
1902 SECKEYPrivateKey
* private_key
;
1903 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1907 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1908 if (rv
!= SECSuccess
)
1909 return MapNSSError(PORT_GetError());
1911 SetChannelIDProvided();
1912 GotoState(STATE_HANDSHAKE
);
1916 int SSLClientSocketNSS::Core::DoPayloadRead() {
1917 DCHECK(OnNSSTaskRunner());
1918 DCHECK(user_read_buf_
.get());
1919 DCHECK_GT(user_read_buf_len_
, 0);
1922 // If a previous greedy read resulted in an error that was not consumed (eg:
1923 // due to the caller having read some data successfully), then return that
1924 // pending error now.
1925 if (pending_read_result_
!= kNoPendingReadResult
) {
1926 rv
= pending_read_result_
;
1927 PRErrorCode prerr
= pending_read_nss_error_
;
1928 pending_read_result_
= kNoPendingReadResult
;
1929 pending_read_nss_error_
= 0;
1934 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1935 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1936 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1940 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1941 NetLog::TYPE_SSL_READ_ERROR
,
1942 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1947 // Perform a greedy read, attempting to read as much as the caller has
1948 // requested. In the current NSS implementation, PR_Read will return
1949 // exactly one SSL application data record's worth of data per invocation.
1950 // The record size is dictated by the server, and may be noticeably smaller
1951 // than the caller's buffer. This may be as little as a single byte, if the
1952 // server is performing 1/n-1 record splitting.
1954 // However, this greedy read may result in renegotiations/re-handshakes
1955 // happening or may lead to some data being read, followed by an EOF (such as
1956 // a TLS close-notify). If at least some data was read, then that result
1957 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1958 // data was read, it's safe to return the error or EOF immediately.
1959 int total_bytes_read
= 0;
1961 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1962 user_read_buf_len_
- total_bytes_read
);
1964 total_bytes_read
+= rv
;
1965 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1966 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1967 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1968 amount_in_read_buffer
));
1970 if (total_bytes_read
== user_read_buf_len_
) {
1971 // The caller's entire request was satisfied without error. No further
1972 // processing needed.
1973 rv
= total_bytes_read
;
1975 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1976 // immediately, while the NSPR/NSS errors are still available in
1977 // thread-local storage. However, the handled/remapped error code should
1978 // only be returned if no application data was already read; if it was, the
1979 // error code should be deferred until the next call of DoPayloadRead.
1981 // If no data was read, |*next_result| will point to the return value of
1982 // this function. If at least some data was read, |*next_result| will point
1983 // to |pending_read_error_|, to be returned in a future call to
1984 // DoPayloadRead() (e.g.: after the current data is handled).
1985 int* next_result
= &rv
;
1986 if (total_bytes_read
> 0) {
1987 pending_read_result_
= rv
;
1988 rv
= total_bytes_read
;
1989 next_result
= &pending_read_result_
;
1992 if (client_auth_cert_needed_
) {
1993 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1994 pending_read_nss_error_
= 0;
1995 } else if (*next_result
< 0) {
1996 // If *next_result == 0, then that indicates EOF, and no special error
1997 // handling is needed.
1998 pending_read_nss_error_
= PR_GetError();
1999 *next_result
= HandleNSSError(pending_read_nss_error_
);
2000 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
2001 // If at least some data was read from PR_Read(), do not treat
2002 // insufficient data as an error to return in the next call to
2003 // DoPayloadRead() - instead, let the call fall through to check
2004 // PR_Read() again. This is because DoTransportIO() may complete
2005 // in between the next call to DoPayloadRead(), and thus it is
2006 // important to check PR_Read() on subsequent invocations to see
2007 // if a complete record may now be read.
2008 pending_read_nss_error_
= 0;
2009 pending_read_result_
= kNoPendingReadResult
;
2014 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
2019 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2020 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
2021 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
2022 } else if (rv
!= ERR_IO_PENDING
) {
2025 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2026 NetLog::TYPE_SSL_READ_ERROR
,
2027 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
2028 pending_read_nss_error_
= 0;
2033 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2034 DCHECK(OnNSSTaskRunner());
2036 DCHECK(user_write_buf_
.get());
2038 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2039 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
2040 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2041 // PR_Write could potentially consume the unhandled data in the memio read
2042 // buffer if a renegotiation is in progress. If the buffer is consumed,
2043 // notify the latest buffer size to NetworkRunner.
2044 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
2047 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
2052 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2053 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
2054 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
2057 PRErrorCode prerr
= PR_GetError();
2058 if (prerr
== PR_WOULD_BLOCK_ERROR
)
2059 return ERR_IO_PENDING
;
2061 rv
= HandleNSSError(prerr
);
2064 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2065 NetLog::TYPE_SSL_WRITE_ERROR
,
2066 CreateNetLogSSLErrorCallback(rv
, prerr
)));
2070 // Do as much network I/O as possible between the buffer and the
2071 // transport socket. Return true if some I/O performed, false
2072 // otherwise (error or ERR_IO_PENDING).
2073 bool SSLClientSocketNSS::Core::DoTransportIO() {
2074 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2075 tracked_objects::ScopedTracker
tracking_profile(
2076 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2077 "424386 SSLClientSocketNSS::Core::DoTransportIO"));
2079 DCHECK(OnNSSTaskRunner());
2081 bool network_moved
= false;
2082 if (nss_bufs_
!= NULL
) {
2084 // Read and write as much data as we can. The loop is neccessary
2085 // because Write() may return synchronously.
2088 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
2089 network_moved
= true;
2091 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
2092 network_moved
= true;
2094 return network_moved
;
2097 int SSLClientSocketNSS::Core::BufferRecv() {
2098 DCHECK(OnNSSTaskRunner());
2100 if (transport_recv_busy_
)
2101 return ERR_IO_PENDING
;
2103 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2104 // determine how much data NSS wants to read. If NSS was not blocked,
2105 // this will return 0.
2106 int requested
= memio_GetReadRequest(nss_bufs_
);
2107 if (requested
== 0) {
2108 // This is not a perfect match of error codes, as no operation is
2109 // actually pending. However, returning 0 would be interpreted as a
2110 // possible sign of EOF, which is also an inappropriate match.
2111 return ERR_IO_PENDING
;
2115 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2118 // buffer too full to read into, so no I/O possible at moment
2119 rv
= ERR_IO_PENDING
;
2121 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
2122 if (OnNetworkTaskRunner()) {
2123 rv
= DoBufferRecv(read_buffer
.get(), nb
);
2125 bool posted
= network_task_runner_
->PostTask(
2127 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
2129 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2132 if (rv
== ERR_IO_PENDING
) {
2133 transport_recv_busy_
= true;
2136 memcpy(buf
, read_buffer
->data(), rv
);
2137 } else if (rv
== 0) {
2138 transport_recv_eof_
= true;
2140 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
2146 // Return 0 if nss_bufs_ was empty,
2147 // > 0 for bytes transferred immediately,
2148 // < 0 for error (or the non-error ERR_IO_PENDING).
2149 int SSLClientSocketNSS::Core::BufferSend() {
2150 DCHECK(OnNSSTaskRunner());
2152 if (transport_send_busy_
)
2153 return ERR_IO_PENDING
;
2157 unsigned int len1
, len2
;
2158 if (memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
)) {
2159 // It is important this return synchronously to prevent spinning infinitely
2160 // in the off-thread NSS case. The error code itself is ignored, so just
2161 // return ERR_ABORTED. See https://crbug.com/381160.
2164 const unsigned int len
= len1
+ len2
;
2168 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
2169 memcpy(send_buffer
->data(), buf1
, len1
);
2170 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
2172 if (OnNetworkTaskRunner()) {
2173 rv
= DoBufferSend(send_buffer
.get(), len
);
2175 bool posted
= network_task_runner_
->PostTask(
2177 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
2179 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2182 if (rv
== ERR_IO_PENDING
) {
2183 transport_send_busy_
= true;
2185 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
2192 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
2193 DCHECK(OnNSSTaskRunner());
2195 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2196 OnHandshakeIOComplete(result
);
2200 // Network layer received some data, check if client requested to read
2202 if (!user_read_buf_
.get())
2205 int rv
= DoReadLoop(result
);
2206 if (rv
!= ERR_IO_PENDING
)
2210 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
2211 DCHECK(OnNSSTaskRunner());
2213 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2214 OnHandshakeIOComplete(result
);
2218 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2219 // handshake is in progress.
2220 int rv_read
= ERR_IO_PENDING
;
2221 int rv_write
= ERR_IO_PENDING
;
2224 if (user_read_buf_
.get())
2225 rv_read
= DoPayloadRead();
2226 if (user_write_buf_
.get())
2227 rv_write
= DoPayloadWrite();
2228 network_moved
= DoTransportIO();
2229 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
2230 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
2232 // If the parent SSLClientSocketNSS is deleted during the processing of the
2233 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2234 // will be detached (and possibly deleted). Guard against deletion by taking
2235 // an extra reference, then check if the Core was detached before invoking the
2237 scoped_refptr
<Core
> guard(this);
2238 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
2239 DoReadCallback(rv_read
);
2241 if (OnNetworkTaskRunner() && detached_
)
2244 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
2245 DoWriteCallback(rv_write
);
2248 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2249 // handshake. This requires network IO, which in turn calls
2250 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2251 // winds its way through the state machine and ends up being passed to the
2252 // callback. For Read() and Write(), that's what we want. But for Connect(),
2253 // the caller expects OK (i.e. 0) for success.
2254 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
2255 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2256 tracked_objects::ScopedTracker
tracking_profile(
2257 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2258 "424386 SSLClientSocketNSS::Core::DoConnectCallback"));
2260 DCHECK(OnNSSTaskRunner());
2261 DCHECK_NE(rv
, ERR_IO_PENDING
);
2262 DCHECK(!user_connect_callback_
.is_null());
2264 base::Closure c
= base::Bind(
2265 base::ResetAndReturn(&user_connect_callback_
),
2267 PostOrRunCallback(FROM_HERE
, c
);
2270 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
2271 // TODO(vadimt): Remove ScopedTracker below once crbug.com/424386 is fixed.
2272 tracked_objects::ScopedTracker
tracking_profile(
2273 FROM_HERE_WITH_EXPLICIT_FUNCTION(
2274 "424386 SSLClientSocketNSS::Core::DoReadCallback"));
2276 DCHECK(OnNSSTaskRunner());
2277 DCHECK_NE(ERR_IO_PENDING
, rv
);
2278 DCHECK(!user_read_callback_
.is_null());
2280 user_read_buf_
= NULL
;
2281 user_read_buf_len_
= 0;
2282 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2283 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2284 // the network task runner.
2287 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2290 base::Bind(&Core::DidNSSRead
, this, rv
));
2293 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
2296 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
2297 DCHECK(OnNSSTaskRunner());
2298 DCHECK_NE(ERR_IO_PENDING
, rv
);
2299 DCHECK(!user_write_callback_
.is_null());
2301 // Since Run may result in Write being called, clear |user_write_callback_|
2303 user_write_buf_
= NULL
;
2304 user_write_buf_len_
= 0;
2305 // Update buffer status because DoWriteLoop called DoTransportIO which may
2306 // perform read operations.
2307 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2308 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2309 // the network task runner.
2312 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2315 base::Bind(&Core::DidNSSWrite
, this, rv
));
2318 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
2321 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
2324 SECKEYPublicKey
**out_public_key
,
2325 SECKEYPrivateKey
**out_private_key
) {
2326 Core
* core
= reinterpret_cast<Core
*>(arg
);
2327 DCHECK(core
->OnNSSTaskRunner());
2329 core
->PostOrRunCallback(
2331 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
2332 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
2334 // We have negotiated the TLS channel ID extension.
2335 core
->channel_id_xtn_negotiated_
= true;
2336 std::string host
= core
->host_and_port_
.host();
2337 int error
= ERR_UNEXPECTED
;
2338 if (core
->OnNetworkTaskRunner()) {
2339 error
= core
->DoGetChannelID(host
);
2341 bool posted
= core
->network_task_runner_
->PostTask(
2344 IgnoreResult(&Core::DoGetChannelID
),
2346 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2349 if (error
== ERR_IO_PENDING
) {
2350 // Asynchronous case.
2351 core
->channel_id_needed_
= true;
2352 return SECWouldBlock
;
2355 core
->PostOrRunCallback(
2357 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
2358 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
2359 SECStatus rv
= SECSuccess
;
2361 // Synchronous success.
2362 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
2364 core
->SetChannelIDProvided();
2374 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
2375 SECKEYPrivateKey
** key
) {
2376 // Set the certificate.
2378 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
2379 cert_item
.len
= domain_bound_cert_
.size();
2380 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2386 return MapNSSError(PORT_GetError());
2388 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
2389 // Set the private key.
2390 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2392 ChannelIDService::kEPKIPassword
,
2393 reinterpret_cast<const unsigned char*>(
2394 domain_bound_private_key_
.data()),
2395 domain_bound_private_key_
.size(),
2396 &cert
->subjectPublicKeyInfo
,
2401 int error
= MapNSSError(PORT_GetError());
2408 void SSLClientSocketNSS::Core::UpdateServerCert() {
2409 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2410 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2411 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2412 if (nss_handshake_state_
.server_cert
.get()) {
2413 // Since this will be called asynchronously on another thread, it needs to
2414 // own a reference to the certificate.
2415 NetLog::ParametersCallback net_log_callback
=
2416 base::Bind(&NetLogX509CertificateCallback
,
2417 nss_handshake_state_
.server_cert
);
2420 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2421 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2426 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2427 const SECItem
* signed_cert_timestamps
=
2428 SSL_PeerSignedCertTimestamps(nss_fd_
);
2430 if (!signed_cert_timestamps
|| !signed_cert_timestamps
->len
)
2433 nss_handshake_state_
.sct_list_from_tls_extension
= std::string(
2434 reinterpret_cast<char*>(signed_cert_timestamps
->data
),
2435 signed_cert_timestamps
->len
);
2438 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2439 PRBool ocsp_requested
= PR_FALSE
;
2440 SSL_OptionGet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, &ocsp_requested
);
2441 const SECItemArray
* ocsp_responses
=
2442 SSL_PeerStapledOCSPResponses(nss_fd_
);
2443 bool ocsp_responses_present
= ocsp_responses
&& ocsp_responses
->len
;
2445 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present
);
2446 if (!ocsp_responses_present
)
2449 nss_handshake_state_
.stapled_ocsp_response
= std::string(
2450 reinterpret_cast<char*>(ocsp_responses
->items
[0].data
),
2451 ocsp_responses
->items
[0].len
);
2453 if (IsOCSPStaplingSupported()) {
2455 if (nss_handshake_state_
.server_cert
.get()) {
2456 CRYPT_DATA_BLOB ocsp_response_blob
;
2457 ocsp_response_blob
.cbData
= ocsp_responses
->items
[0].len
;
2458 ocsp_response_blob
.pbData
= ocsp_responses
->items
[0].data
;
2459 BOOL ok
= CertSetCertificateContextProperty(
2460 nss_handshake_state_
.server_cert
->os_cert_handle(),
2461 CERT_OCSP_RESPONSE_PROP_ID
,
2462 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
2463 &ocsp_response_blob
);
2465 VLOG(1) << "Failed to set OCSP response property: "
2469 #elif defined(USE_NSS)
2470 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
2471 GetCacheOCSPResponseFromSideChannelFunction();
2473 cache_ocsp_response(
2474 CERT_GetDefaultCertDB(),
2475 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
2476 &ocsp_responses
->items
[0], NULL
);
2478 } // IsOCSPStaplingSupported()
2481 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2482 // Note: This function may be called multiple times for a single connection
2483 // if renegotiations occur.
2484 nss_handshake_state_
.ssl_connection_status
= 0;
2486 SSLChannelInfo channel_info
;
2487 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2488 &channel_info
, sizeof(channel_info
));
2489 if (ok
== SECSuccess
&&
2490 channel_info
.length
== sizeof(channel_info
) &&
2491 channel_info
.cipherSuite
) {
2492 nss_handshake_state_
.ssl_connection_status
|= channel_info
.cipherSuite
;
2494 nss_handshake_state_
.ssl_connection_status
|=
2495 (static_cast<int>(channel_info
.compressionMethod
) &
2496 SSL_CONNECTION_COMPRESSION_MASK
) <<
2497 SSL_CONNECTION_COMPRESSION_SHIFT
;
2499 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2500 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2501 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2503 version
= SSL_CONNECTION_VERSION_SSL2
;
2504 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2505 version
= SSL_CONNECTION_VERSION_SSL3
;
2506 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_0
) {
2507 version
= SSL_CONNECTION_VERSION_TLS1
;
2508 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2509 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2510 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_2
) {
2511 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2513 nss_handshake_state_
.ssl_connection_status
|=
2514 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2515 SSL_CONNECTION_VERSION_SHIFT
;
2518 PRBool peer_supports_renego_ext
;
2519 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2520 &peer_supports_renego_ext
);
2521 if (ok
== SECSuccess
) {
2522 if (!peer_supports_renego_ext
) {
2523 nss_handshake_state_
.ssl_connection_status
|=
2524 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2525 // Log an informational message if the server does not support secure
2526 // renegotiation (RFC 5746).
2527 VLOG(1) << "The server " << host_and_port_
.ToString()
2528 << " does not support the TLS renegotiation_info extension.";
2532 if (ssl_config_
.version_fallback
) {
2533 nss_handshake_state_
.ssl_connection_status
|=
2534 SSL_CONNECTION_VERSION_FALLBACK
;
2538 void SSLClientSocketNSS::Core::UpdateNextProto() {
2540 SSLNextProtoState state
;
2543 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2544 if (rv
!= SECSuccess
)
2547 nss_handshake_state_
.next_proto
=
2548 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2550 case SSL_NEXT_PROTO_NEGOTIATED
:
2551 case SSL_NEXT_PROTO_SELECTED
:
2552 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2554 case SSL_NEXT_PROTO_NO_OVERLAP
:
2555 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2557 case SSL_NEXT_PROTO_NO_SUPPORT
:
2558 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2566 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2567 PRBool negotiated_extension
;
2568 SECStatus rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2569 ssl_app_layer_protocol_xtn
,
2570 &negotiated_extension
);
2571 if (rv
== SECSuccess
&& negotiated_extension
) {
2572 nss_handshake_state_
.negotiation_extension_
= kExtensionALPN
;
2574 rv
= SSL_HandshakeNegotiatedExtension(nss_fd_
,
2575 ssl_next_proto_nego_xtn
,
2576 &negotiated_extension
);
2577 if (rv
== SECSuccess
&& negotiated_extension
) {
2578 nss_handshake_state_
.negotiation_extension_
= kExtensionNPN
;
2583 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2584 DCHECK(OnNSSTaskRunner());
2585 if (nss_handshake_state_
.resumed_handshake
)
2588 // Copy the NSS task runner-only state to the network task runner and
2589 // log histograms from there, since the histograms also need access to the
2590 // network task runner state.
2593 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2595 channel_id_xtn_negotiated_
,
2596 ssl_config_
.channel_id_enabled
,
2597 crypto::ECPrivateKey::IsSupported()));
2600 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2601 bool negotiated_channel_id
,
2602 bool channel_id_enabled
,
2603 bool supports_ecc
) const {
2604 DCHECK(OnNetworkTaskRunner());
2606 RecordChannelIDSupport(channel_id_service_
,
2607 negotiated_channel_id
,
2612 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2613 DCHECK(OnNetworkTaskRunner());
2619 int rv
= transport_
->socket()->Read(
2621 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2622 scoped_refptr
<IOBuffer
>(read_buffer
)));
2624 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2625 nss_task_runner_
->PostTask(
2626 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2627 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2634 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2635 DCHECK(OnNetworkTaskRunner());
2641 int rv
= transport_
->socket()->Write(
2643 base::Bind(&Core::BufferSendComplete
,
2644 base::Unretained(this)));
2646 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2647 nss_task_runner_
->PostTask(
2649 base::Bind(&Core::BufferSendComplete
, this, rv
));
2656 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string
& host
) {
2657 DCHECK(OnNetworkTaskRunner());
2662 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2664 int rv
= channel_id_service_
->GetOrCreateChannelID(
2666 &domain_bound_private_key_
,
2667 &domain_bound_cert_
,
2668 base::Bind(&Core::OnGetChannelIDComplete
, base::Unretained(this)),
2669 &domain_bound_cert_request_handle_
);
2671 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2672 nss_task_runner_
->PostTask(
2674 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2675 return ERR_IO_PENDING
;
2681 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2682 const HandshakeState
& state
) {
2683 DCHECK(OnNetworkTaskRunner());
2684 network_handshake_state_
= state
;
2687 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2688 DCHECK(OnNetworkTaskRunner());
2689 unhandled_buffer_size_
= amount_in_read_buffer
;
2692 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2693 DCHECK(OnNetworkTaskRunner());
2694 DCHECK(nss_waiting_read_
);
2695 nss_waiting_read_
= false;
2697 nss_is_closed_
= true;
2699 was_ever_used_
= true;
2703 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2704 DCHECK(OnNetworkTaskRunner());
2705 DCHECK(nss_waiting_write_
);
2706 nss_waiting_write_
= false;
2708 nss_is_closed_
= true;
2709 } else if (result
> 0) {
2710 was_ever_used_
= true;
2714 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2715 if (!OnNSSTaskRunner()) {
2719 nss_task_runner_
->PostTask(
2720 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2724 DCHECK(OnNSSTaskRunner());
2726 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2727 transport_send_busy_
= false;
2728 OnSendComplete(result
);
2731 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2732 if (!OnNSSTaskRunner()) {
2736 nss_task_runner_
->PostTask(
2737 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2741 DCHECK(OnNSSTaskRunner());
2743 int rv
= DoHandshakeLoop(result
);
2744 if (rv
!= ERR_IO_PENDING
)
2745 DoConnectCallback(rv
);
2748 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result
) {
2749 DVLOG(1) << __FUNCTION__
<< " " << result
;
2750 DCHECK(OnNetworkTaskRunner());
2752 OnHandshakeIOComplete(result
);
2755 void SSLClientSocketNSS::Core::BufferRecvComplete(
2756 IOBuffer
* read_buffer
,
2758 DCHECK(read_buffer
);
2760 if (!OnNSSTaskRunner()) {
2764 nss_task_runner_
->PostTask(
2765 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2766 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2770 DCHECK(OnNSSTaskRunner());
2774 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2775 CHECK_GE(nb
, result
);
2776 memcpy(buf
, read_buffer
->data(), result
);
2777 } else if (result
== 0) {
2778 transport_recv_eof_
= true;
2781 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2782 transport_recv_busy_
= false;
2783 OnRecvComplete(result
);
2786 void SSLClientSocketNSS::Core::PostOrRunCallback(
2787 const tracked_objects::Location
& location
,
2788 const base::Closure
& task
) {
2789 if (!OnNetworkTaskRunner()) {
2790 network_task_runner_
->PostTask(
2792 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2796 if (detached_
|| task
.is_null())
2801 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2804 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2805 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2806 NetLog::IntegerCallback("cert_count", cert_count
)));
2809 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2811 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2812 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2813 nss_handshake_state_
.channel_id_sent
= true;
2814 // Update the network task runner's view of the handshake state now that
2815 // channel id has been sent.
2817 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2818 nss_handshake_state_
));
2821 SSLClientSocketNSS::SSLClientSocketNSS(
2822 base::SequencedTaskRunner
* nss_task_runner
,
2823 scoped_ptr
<ClientSocketHandle
> transport_socket
,
2824 const HostPortPair
& host_and_port
,
2825 const SSLConfig
& ssl_config
,
2826 const SSLClientSocketContext
& context
)
2827 : nss_task_runner_(nss_task_runner
),
2828 transport_(transport_socket
.Pass()),
2829 host_and_port_(host_and_port
),
2830 ssl_config_(ssl_config
),
2831 cert_verifier_(context
.cert_verifier
),
2832 cert_transparency_verifier_(context
.cert_transparency_verifier
),
2833 channel_id_service_(context
.channel_id_service
),
2834 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2835 completed_handshake_(false),
2836 next_handshake_state_(STATE_NONE
),
2838 net_log_(transport_
->socket()->NetLog()),
2839 transport_security_state_(context
.transport_security_state
),
2840 policy_enforcer_(context
.cert_policy_enforcer
),
2841 valid_thread_id_(base::kInvalidThreadId
) {
2847 SSLClientSocketNSS::~SSLClientSocketNSS() {
2854 void SSLClientSocket::ClearSessionCache() {
2855 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2856 // bother initializing NSS just to clear an empty SSL session cache.
2857 if (!NSS_IsInitialized())
2860 SSL_ClearSessionCache();
2863 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2864 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2868 uint16
SSLClientSocket::GetMaxSupportedSSLVersion() {
2869 crypto::EnsureNSSInit();
2870 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
)) {
2871 return SSL_PROTOCOL_VERSION_TLS1_2
;
2873 return SSL_PROTOCOL_VERSION_TLS1_1
;
2877 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2880 if (core_
->state().server_cert_chain
.empty() ||
2881 !core_
->state().server_cert_chain
[0]) {
2885 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2886 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2888 AddSCTInfoToSSLInfo(ssl_info
);
2890 ssl_info
->connection_status
=
2891 core_
->state().ssl_connection_status
;
2892 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2893 ssl_info
->is_issued_by_known_root
=
2894 server_cert_verify_result_
.is_issued_by_known_root
;
2895 ssl_info
->client_cert_sent
=
2896 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2897 ssl_info
->channel_id_sent
= WasChannelIDSent();
2898 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
2900 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2901 core_
->state().ssl_connection_status
);
2902 SSLCipherSuiteInfo cipher_info
;
2903 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2904 &cipher_info
, sizeof(cipher_info
));
2905 if (ok
== SECSuccess
) {
2906 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2908 ssl_info
->security_bits
= -1;
2909 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2910 << " for cipherSuite " << cipher_suite
;
2913 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2914 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2920 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2921 SSLCertRequestInfo
* cert_request_info
) {
2923 cert_request_info
->host_and_port
= host_and_port_
;
2924 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2928 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2930 const base::StringPiece
& context
,
2932 unsigned int outlen
) {
2934 return ERR_SOCKET_NOT_CONNECTED
;
2936 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2937 // the midst of a handshake.
2938 SECStatus result
= SSL_ExportKeyingMaterial(
2939 nss_fd_
, label
.data(), label
.size(), has_context
,
2940 reinterpret_cast<const unsigned char*>(context
.data()),
2941 context
.length(), out
, outlen
);
2942 if (result
!= SECSuccess
) {
2943 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2944 return MapNSSError(PORT_GetError());
2949 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2951 return ERR_SOCKET_NOT_CONNECTED
;
2952 unsigned char buf
[64];
2954 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2955 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2956 buf
, &len
, arraysize(buf
));
2957 if (result
!= SECSuccess
) {
2958 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2959 return MapNSSError(PORT_GetError());
2961 out
->assign(reinterpret_cast<char*>(buf
), len
);
2965 SSLClientSocket::NextProtoStatus
2966 SSLClientSocketNSS::GetNextProto(std::string
* proto
) {
2967 *proto
= core_
->state().next_proto
;
2968 return core_
->state().next_proto_status
;
2971 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2973 DCHECK(transport_
.get());
2974 // It is an error to create an SSLClientSocket whose context has no
2975 // TransportSecurityState.
2976 DCHECK(transport_security_state_
);
2977 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2978 DCHECK(user_connect_callback_
.is_null());
2979 DCHECK(!callback
.is_null());
2981 EnsureThreadIdAssigned();
2983 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2987 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2991 rv
= InitializeSSLOptions();
2993 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2997 rv
= InitializeSSLPeerName();
2999 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3003 GotoState(STATE_HANDSHAKE
);
3005 rv
= DoHandshakeLoop(OK
);
3006 if (rv
== ERR_IO_PENDING
) {
3007 user_connect_callback_
= callback
;
3009 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3013 return rv
> OK
? OK
: rv
;
3016 void SSLClientSocketNSS::Disconnect() {
3019 CHECK(CalledOnValidThread());
3021 // Shut down anything that may call us back.
3024 transport_
->socket()->Disconnect();
3026 // Reset object state.
3027 user_connect_callback_
.Reset();
3028 server_cert_verify_result_
.Reset();
3029 completed_handshake_
= false;
3030 start_cert_verification_time_
= base::TimeTicks();
3036 bool SSLClientSocketNSS::IsConnected() const {
3038 bool ret
= completed_handshake_
&&
3039 (core_
->HasPendingAsyncOperation() ||
3040 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
3041 transport_
->socket()->IsConnected());
3046 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
3048 bool ret
= completed_handshake_
&&
3049 !core_
->HasPendingAsyncOperation() &&
3050 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
3051 transport_
->socket()->IsConnectedAndIdle();
3056 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
3057 return transport_
->socket()->GetPeerAddress(address
);
3060 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
3061 return transport_
->socket()->GetLocalAddress(address
);
3064 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
3068 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3069 if (transport_
.get() && transport_
->socket()) {
3070 transport_
->socket()->SetSubresourceSpeculation();
3076 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3077 if (transport_
.get() && transport_
->socket()) {
3078 transport_
->socket()->SetOmniboxSpeculation();
3084 bool SSLClientSocketNSS::WasEverUsed() const {
3085 DCHECK(core_
.get());
3087 return core_
->WasEverUsed();
3090 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3091 if (transport_
.get() && transport_
->socket()) {
3092 return transport_
->socket()->UsingTCPFastOpen();
3098 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
3099 const CompletionCallback
& callback
) {
3100 DCHECK(core_
.get());
3101 DCHECK(!callback
.is_null());
3103 EnterFunction(buf_len
);
3104 int rv
= core_
->Read(buf
, buf_len
, callback
);
3110 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
3111 const CompletionCallback
& callback
) {
3112 DCHECK(core_
.get());
3113 DCHECK(!callback
.is_null());
3115 EnterFunction(buf_len
);
3116 int rv
= core_
->Write(buf
, buf_len
, callback
);
3122 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
3123 return transport_
->socket()->SetReceiveBufferSize(size
);
3126 int SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
3127 return transport_
->socket()->SetSendBufferSize(size
);
3130 int SSLClientSocketNSS::Init() {
3132 // Initialize the NSS SSL library in a threadsafe way. This also
3133 // initializes the NSS base library.
3135 if (!NSS_IsInitialized())
3136 return ERR_UNEXPECTED
;
3137 #if defined(USE_NSS) || defined(OS_IOS)
3138 if (ssl_config_
.cert_io_enabled
) {
3139 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3140 // loop by MessageLoopForIO::current().
3141 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3142 EnsureNSSHttpIOInit();
3150 void SSLClientSocketNSS::InitCore() {
3151 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
3152 nss_task_runner_
.get(),
3157 channel_id_service_
);
3160 int SSLClientSocketNSS::InitializeSSLOptions() {
3161 // Transport connected, now hook it up to nss
3162 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
3163 if (nss_fd_
== NULL
) {
3164 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
3167 // Grab pointer to buffers
3168 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
3170 /* Create SSL state machine */
3171 /* Push SSL onto our fake I/O socket */
3172 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_
) == NULL
) {
3173 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
3176 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
3178 // TODO(port): set more ssl options! Check errors!
3182 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
3183 if (rv
!= SECSuccess
) {
3184 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
3185 return ERR_UNEXPECTED
;
3188 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
3189 if (rv
!= SECSuccess
) {
3190 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3191 return ERR_UNEXPECTED
;
3194 // Don't do V2 compatible hellos because they don't support TLS extensions.
3195 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
3196 if (rv
!= SECSuccess
) {
3197 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3198 return ERR_UNEXPECTED
;
3201 SSLVersionRange version_range
;
3202 version_range
.min
= ssl_config_
.version_min
;
3203 version_range
.max
= ssl_config_
.version_max
;
3204 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
3205 if (rv
!= SECSuccess
) {
3206 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
3207 return ERR_NO_SSL_VERSIONS_ENABLED
;
3210 if (ssl_config_
.version_fallback
) {
3211 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALLBACK_SCSV
, PR_TRUE
);
3212 if (rv
!= SECSuccess
) {
3213 LogFailedNSSFunction(
3214 net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
3218 for (std::vector
<uint16
>::const_iterator it
=
3219 ssl_config_
.disabled_cipher_suites
.begin();
3220 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
3221 // This will fail if the specified cipher is not implemented by NSS, but
3222 // the failure is harmless.
3223 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
3226 if (!ssl_config_
.enable_deprecated_cipher_suites
) {
3227 const PRUint16
* const ssl_ciphers
= SSL_GetImplementedCiphers();
3228 const PRUint16 num_ciphers
= SSL_GetNumImplementedCiphers();
3229 for (int i
= 0; i
< num_ciphers
; i
++) {
3230 SSLCipherSuiteInfo info
;
3231 if (SSL_GetCipherSuiteInfo(ssl_ciphers
[i
], &info
, sizeof(info
)) !=
3235 if (info
.symCipher
== ssl_calg_rc4
)
3236 SSL_CipherPrefSet(nss_fd_
, ssl_ciphers
[i
], PR_FALSE
);
3241 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
3242 if (rv
!= SECSuccess
) {
3243 LogFailedNSSFunction(
3244 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3247 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
3248 ssl_config_
.false_start_enabled
);
3249 if (rv
!= SECSuccess
)
3250 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3252 // We allow servers to request renegotiation. Since we're a client,
3253 // prohibiting this is rather a waste of time. Only servers are in a
3254 // position to prevent renegotiation attacks.
3255 // http://extendedsubset.com/?p=8
3257 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
3258 SSL_RENEGOTIATE_TRANSITIONAL
);
3259 if (rv
!= SECSuccess
) {
3260 LogFailedNSSFunction(
3261 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3264 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
3265 if (rv
!= SECSuccess
)
3266 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3268 // Added in NSS 3.15
3269 #ifdef SSL_ENABLE_OCSP_STAPLING
3270 // Request OCSP stapling even on platforms that don't support it, in
3271 // order to extract Certificate Transparency information.
3272 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
,
3273 (IsOCSPStaplingSupported() ||
3274 ssl_config_
.signed_cert_timestamps_enabled
));
3275 if (rv
!= SECSuccess
) {
3276 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3277 "SSL_ENABLE_OCSP_STAPLING");
3281 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS
,
3282 ssl_config_
.signed_cert_timestamps_enabled
);
3283 if (rv
!= SECSuccess
) {
3284 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3285 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
3288 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
3289 if (rv
!= SECSuccess
) {
3290 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3291 return ERR_UNEXPECTED
;
3294 if (!core_
->Init(nss_fd_
, nss_bufs
))
3295 return ERR_UNEXPECTED
;
3297 // Tell SSL the hostname we're trying to connect to.
3298 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
3300 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3301 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
3306 int SSLClientSocketNSS::InitializeSSLPeerName() {
3307 // Tell NSS who we're connected to
3308 IPEndPoint peer_address
;
3309 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
3313 SockaddrStorage storage
;
3314 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
3315 return ERR_ADDRESS_INVALID
;
3318 memset(&peername
, 0, sizeof(peername
));
3319 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
3320 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
3322 memcpy(&peername
, storage
.addr
, len
);
3324 // Adjust the address family field for BSD, whose sockaddr
3325 // structure has a one-byte length and one-byte address family
3326 // field at the beginning. PRNetAddr has a two-byte address
3327 // family field at the beginning.
3328 peername
.raw
.family
= storage
.addr
->sa_family
;
3330 memio_SetPeerName(nss_fd_
, &peername
);
3332 // Set the peer ID for session reuse. This is necessary when we create an
3333 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3334 // rather than the destination server's address in that case.
3335 std::string peer_id
= host_and_port_
.ToString();
3336 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
3337 // the session cache for incognito mode.
3338 peer_id
+= "/" + ssl_session_cache_shard_
;
3340 // Shard the session cache based on maximum protocol version. This causes
3341 // fallback connections to use a separate session cache.
3342 switch (ssl_config_
.version_max
) {
3343 case SSL_PROTOCOL_VERSION_SSL3
:
3346 case SSL_PROTOCOL_VERSION_TLS1
:
3349 case SSL_PROTOCOL_VERSION_TLS1_1
:
3350 peer_id
+= "tls1.1";
3352 case SSL_PROTOCOL_VERSION_TLS1_2
:
3353 peer_id
+= "tls1.2";
3359 if (ssl_config_
.enable_deprecated_cipher_suites
)
3360 peer_id
+= "deprecated";
3362 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
3363 if (rv
!= SECSuccess
)
3364 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
3369 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
3371 DCHECK_NE(ERR_IO_PENDING
, rv
);
3372 DCHECK(!user_connect_callback_
.is_null());
3374 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
3378 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
3379 EnterFunction(result
);
3380 int rv
= DoHandshakeLoop(result
);
3381 if (rv
!= ERR_IO_PENDING
) {
3382 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3383 DoConnectCallback(rv
);
3388 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
3389 EnterFunction(last_io_result
);
3390 int rv
= last_io_result
;
3392 // Default to STATE_NONE for next state.
3393 // (This is a quirk carried over from the windows
3394 // implementation. It makes reading the logs a bit harder.)
3395 // State handlers can and often do call GotoState just
3396 // to stay in the current state.
3397 State state
= next_handshake_state_
;
3398 GotoState(STATE_NONE
);
3400 case STATE_HANDSHAKE
:
3403 case STATE_HANDSHAKE_COMPLETE
:
3404 rv
= DoHandshakeComplete(rv
);
3406 case STATE_VERIFY_CERT
:
3408 rv
= DoVerifyCert(rv
);
3410 case STATE_VERIFY_CERT_COMPLETE
:
3411 rv
= DoVerifyCertComplete(rv
);
3415 rv
= ERR_UNEXPECTED
;
3416 LOG(DFATAL
) << "unexpected state " << state
;
3419 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3424 int SSLClientSocketNSS::DoHandshake() {
3426 int rv
= core_
->Connect(
3427 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3428 base::Unretained(this)));
3429 GotoState(STATE_HANDSHAKE_COMPLETE
);
3435 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3436 EnterFunction(result
);
3439 if (ssl_config_
.version_fallback
&&
3440 ssl_config_
.version_max
< ssl_config_
.version_fallback_min
) {
3441 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
;
3444 // SSL handshake is completed. Let's verify the certificate.
3445 GotoState(STATE_VERIFY_CERT
);
3448 set_channel_id_sent(core_
->state().channel_id_sent
);
3449 set_signed_cert_timestamps_received(
3450 !core_
->state().sct_list_from_tls_extension
.empty());
3451 set_stapled_ocsp_response_received(
3452 !core_
->state().stapled_ocsp_response
.empty());
3453 set_negotiation_extension(core_
->state().negotiation_extension_
);
3455 LeaveFunction(result
);
3459 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3460 DCHECK(!core_
->state().server_cert_chain
.empty());
3461 DCHECK(core_
->state().server_cert_chain
[0]);
3463 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3465 // If the certificate is expected to be bad we can use the expectation as
3467 base::StringPiece
der_cert(
3468 reinterpret_cast<char*>(
3469 core_
->state().server_cert_chain
[0]->derCert
.data
),
3470 core_
->state().server_cert_chain
[0]->derCert
.len
);
3471 CertStatus cert_status
;
3472 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3473 DCHECK(start_cert_verification_time_
.is_null());
3474 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3475 server_cert_verify_result_
.Reset();
3476 server_cert_verify_result_
.cert_status
= cert_status
;
3477 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3481 // We may have failed to create X509Certificate object if we are
3482 // running inside sandbox.
3483 if (!core_
->state().server_cert
.get()) {
3484 server_cert_verify_result_
.Reset();
3485 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3486 return ERR_CERT_INVALID
;
3489 start_cert_verification_time_
= base::TimeTicks::Now();
3492 if (ssl_config_
.rev_checking_enabled
)
3493 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3494 if (ssl_config_
.verify_ev_cert
)
3495 flags
|= CertVerifier::VERIFY_EV_CERT
;
3496 if (ssl_config_
.cert_io_enabled
)
3497 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3498 if (ssl_config_
.rev_checking_required_local_anchors
)
3499 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3500 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3501 return verifier_
->Verify(
3502 core_
->state().server_cert
.get(),
3503 host_and_port_
.host(),
3505 SSLConfigService::GetCRLSet().get(),
3506 &server_cert_verify_result_
,
3507 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3508 base::Unretained(this)),
3512 // Derived from AuthCertificateCallback() in
3513 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3514 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3517 if (!start_cert_verification_time_
.is_null()) {
3518 base::TimeDelta verify_time
=
3519 base::TimeTicks::Now() - start_cert_verification_time_
;
3521 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3523 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3526 // We used to remember the intermediate CA certs in the NSS database
3527 // persistently. However, NSS opens a connection to the SQLite database
3528 // during NSS initialization and doesn't close the connection until NSS
3529 // shuts down. If the file system where the database resides is gone,
3530 // the database connection goes bad. What's worse, the connection won't
3531 // recover when the file system comes back. Until this NSS or SQLite bug
3532 // is fixed, we need to avoid using the NSS database for non-essential
3533 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3534 // http://crbug.com/15630 for more info.
3536 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3537 if (transport_security_state_
&&
3539 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3540 !transport_security_state_
->CheckPublicKeyPins(
3541 host_and_port_
.host(),
3542 server_cert_verify_result_
.is_issued_by_known_root
,
3543 server_cert_verify_result_
.public_key_hashes
,
3544 &pinning_failure_log_
)) {
3545 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3549 // Only check Certificate Transparency if there were no other errors with
3553 // Only cache the session if the certificate verified successfully.
3554 core_
->CacheSessionIfNecessary();
3557 completed_handshake_
= true;
3559 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3560 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3564 void SSLClientSocketNSS::VerifyCT() {
3565 if (!cert_transparency_verifier_
)
3568 // Note that this is a completely synchronous operation: The CT Log Verifier
3569 // gets all the data it needs for SCT verification and does not do any
3570 // external communication.
3571 cert_transparency_verifier_
->Verify(
3572 server_cert_verify_result_
.verified_cert
.get(),
3573 core_
->state().stapled_ocsp_response
,
3574 core_
->state().sct_list_from_tls_extension
, &ct_verify_result_
, net_log_
);
3575 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3576 // from the state after verification is complete, to conserve memory.
3578 if (!policy_enforcer_
) {
3579 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3581 if (server_cert_verify_result_
.cert_status
& CERT_STATUS_IS_EV
) {
3582 scoped_refptr
<ct::EVCertsWhitelist
> ev_whitelist
=
3583 SSLConfigService::GetEVCertsWhitelist();
3584 if (!policy_enforcer_
->DoesConformToCTEVPolicy(
3585 server_cert_verify_result_
.verified_cert
.get(),
3586 ev_whitelist
.get(), ct_verify_result_
, net_log_
)) {
3587 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3588 VLOG(1) << "EV certificate for "
3589 << server_cert_verify_result_
.verified_cert
->subject()
3591 << " does not conform to CT policy, removing EV status.";
3592 server_cert_verify_result_
.cert_status
&= ~CERT_STATUS_IS_EV
;
3598 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3599 base::AutoLock
auto_lock(lock_
);
3600 if (valid_thread_id_
!= base::kInvalidThreadId
)
3602 valid_thread_id_
= base::PlatformThread::CurrentId();
3605 bool SSLClientSocketNSS::CalledOnValidThread() const {
3606 EnsureThreadIdAssigned();
3607 base::AutoLock
auto_lock(lock_
);
3608 return valid_thread_id_
== base::PlatformThread::CurrentId();
3611 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
3612 for (ct::SCTList::const_iterator iter
=
3613 ct_verify_result_
.verified_scts
.begin();
3614 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
3615 ssl_info
->signed_certificate_timestamps
.push_back(
3616 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
3618 for (ct::SCTList::const_iterator iter
=
3619 ct_verify_result_
.invalid_scts
.begin();
3620 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
3621 ssl_info
->signed_certificate_timestamps
.push_back(
3622 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
3624 for (ct::SCTList::const_iterator iter
=
3625 ct_verify_result_
.unknown_logs_scts
.begin();
3626 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
3627 ssl_info
->signed_certificate_timestamps
.push_back(
3628 SignedCertificateTimestampAndStatus(*iter
,
3629 ct::SCT_STATUS_LOG_UNKNOWN
));
3633 scoped_refptr
<X509Certificate
>
3634 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3635 return core_
->state().server_cert
.get();
3638 ChannelIDService
* SSLClientSocketNSS::GetChannelIDService() const {
3639 return channel_id_service_
;