1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
6 // from AuthCertificateCallback() in
7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
9 /* ***** BEGIN LICENSE BLOCK *****
10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
12 * The contents of this file are subject to the Mozilla Public License Version
13 * 1.1 (the "License"); you may not use this file except in compliance with
14 * the License. You may obtain a copy of the License at
15 * http://www.mozilla.org/MPL/
17 * Software distributed under the License is distributed on an "AS IS" basis,
18 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
19 * for the specific language governing rights and limitations under the
22 * The Original Code is the Netscape security libraries.
24 * The Initial Developer of the Original Code is
25 * Netscape Communications Corporation.
26 * Portions created by the Initial Developer are Copyright (C) 2000
27 * the Initial Developer. All Rights Reserved.
30 * Ian McGreer <mcgreer@netscape.com>
31 * Javier Delgadillo <javi@netscape.com>
32 * Kai Engert <kengert@redhat.com>
34 * Alternatively, the contents of this file may be used under the terms of
35 * either the GNU General Public License Version 2 or later (the "GPL"), or
36 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
37 * in which case the provisions of the GPL or the LGPL are applicable instead
38 * of those above. If you wish to allow use of your version of this file only
39 * under the terms of either the GPL or the LGPL, and not to allow others to
40 * use your version of this file under the terms of the MPL, indicate your
41 * decision by deleting the provisions above and replace them with the notice
42 * and other provisions required by the GPL or the LGPL. If you do not delete
43 * the provisions above, a recipient may use your version of this file under
44 * the terms of any one of the MPL, the GPL or the LGPL.
46 * ***** END LICENSE BLOCK ***** */
48 #include "net/socket/ssl_client_socket_nss.h"
67 #include "base/bind.h"
68 #include "base/bind_helpers.h"
69 #include "base/callback_helpers.h"
70 #include "base/compiler_specific.h"
71 #include "base/logging.h"
72 #include "base/memory/singleton.h"
73 #include "base/metrics/histogram.h"
74 #include "base/single_thread_task_runner.h"
75 #include "base/stl_util.h"
76 #include "base/strings/string_number_conversions.h"
77 #include "base/strings/string_util.h"
78 #include "base/strings/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/connection_type_histograms.h"
89 #include "net/base/dns_util.h"
90 #include "net/base/io_buffer.h"
91 #include "net/base/net_errors.h"
92 #include "net/base/net_log.h"
93 #include "net/cert/asn1_util.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/single_request_cert_verifier.h"
97 #include "net/cert/x509_certificate_net_log_param.h"
98 #include "net/cert/x509_util.h"
99 #include "net/http/transport_security_state.h"
100 #include "net/ocsp/nss_ocsp.h"
101 #include "net/socket/client_socket_handle.h"
102 #include "net/socket/nss_ssl_util.h"
103 #include "net/socket/ssl_error_params.h"
104 #include "net/ssl/ssl_cert_request_info.h"
105 #include "net/ssl/ssl_connection_status_flags.h"
106 #include "net/ssl/ssl_info.h"
110 #include <wincrypt.h>
112 #include "base/win/windows_version.h"
113 #elif defined(OS_MACOSX)
114 #include <Security/SecBase.h>
115 #include <Security/SecCertificate.h>
116 #include <Security/SecIdentity.h>
118 #include "base/mac/mac_logging.h"
119 #include "base/synchronization/lock.h"
120 #include "crypto/mac_security_services_lock.h"
121 #elif defined(USE_NSS)
127 // State machines are easier to debug if you log state transitions.
128 // Enable these if you want to see what's going on.
130 #define EnterFunction(x)
131 #define LeaveFunction(x)
132 #define GotoState(s) next_handshake_state_ = s
134 #define EnterFunction(x)\
135 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
136 << "; next_handshake_state " << next_handshake_state_
137 #define LeaveFunction(x)\
138 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
139 << "; next_handshake_state " << next_handshake_state_
140 #define GotoState(s)\
142 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
143 next_handshake_state_ = s;\
149 // SSL plaintext fragments are shorter than 16KB. Although the record layer
150 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
151 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
152 // entire SSL record.
153 const int kRecvBufferSize
= 17 * 1024;
154 const int kSendBufferSize
= 17 * 1024;
156 // Used by SSLClientSocketNSS::Core to indicate there is no read result
157 // obtained by a previous operation waiting to be returned to the caller.
158 // This constant can be any non-negative/non-zero value (eg: it does not
159 // overlap with any value of the net::Error range, including net::OK).
160 const int kNoPendingReadResult
= 1;
163 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
164 // set on Windows XP without error. There is some overhead from the server
165 // sending the OCSP response if it supports the extension, for the subset of
166 // XP clients who will request it but be unable to use it, but this is an
167 // acceptable trade-off for simplicity of implementation.
168 bool IsOCSPStaplingSupported() {
171 #elif defined(USE_NSS)
173 (*CacheOCSPResponseFromSideChannelFunction
)(
174 CERTCertDBHandle
*handle
, CERTCertificate
*cert
, PRTime time
,
175 SECItem
*encodedResponse
, void *pwArg
);
177 // On Linux, we dynamically link against the system version of libnss3.so. In
178 // order to continue working on systems without up-to-date versions of NSS we
179 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
181 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
182 // runtime symbol resolution that we need.
183 class RuntimeLibNSSFunctionPointers
{
185 CacheOCSPResponseFromSideChannelFunction
186 GetCacheOCSPResponseFromSideChannelFunction() {
187 return cache_ocsp_response_from_side_channel_
;
190 static RuntimeLibNSSFunctionPointers
* GetInstance() {
191 return Singleton
<RuntimeLibNSSFunctionPointers
>::get();
195 friend struct DefaultSingletonTraits
<RuntimeLibNSSFunctionPointers
>;
197 RuntimeLibNSSFunctionPointers() {
198 cache_ocsp_response_from_side_channel_
=
199 (CacheOCSPResponseFromSideChannelFunction
)
200 dlsym(RTLD_DEFAULT
, "CERT_CacheOCSPResponseFromSideChannel");
203 CacheOCSPResponseFromSideChannelFunction
204 cache_ocsp_response_from_side_channel_
;
207 CacheOCSPResponseFromSideChannelFunction
208 GetCacheOCSPResponseFromSideChannelFunction() {
209 return RuntimeLibNSSFunctionPointers::GetInstance()
210 ->GetCacheOCSPResponseFromSideChannelFunction();
213 bool IsOCSPStaplingSupported() {
214 return GetCacheOCSPResponseFromSideChannelFunction() != NULL
;
217 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
218 // certificate validation functions.
219 bool IsOCSPStaplingSupported() {
224 class FreeCERTCertificate
{
226 inline void operator()(CERTCertificate
* x
) const {
227 CERT_DestroyCertificate(x
);
230 typedef scoped_ptr_malloc
<CERTCertificate
, FreeCERTCertificate
>
231 ScopedCERTCertificate
;
235 // This callback is intended to be used with CertFindChainInStore. In addition
236 // to filtering by extended/enhanced key usage, we do not show expired
237 // certificates and require digital signature usage in the key usage
240 // This matches our behavior on Mac OS X and that of NSS. It also matches the
241 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
242 // 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
243 BOOL WINAPI
ClientCertFindCallback(PCCERT_CONTEXT cert_context
,
245 VLOG(1) << "Calling ClientCertFindCallback from _nss";
246 // Verify the certificate's KU is good.
248 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING
, cert_context
->pCertInfo
,
250 if (!(key_usage
& CERT_DIGITAL_SIGNATURE_KEY_USAGE
))
253 DWORD err
= GetLastError();
254 // If |err| is non-zero, it's an actual error. Otherwise the extension
255 // just isn't present, and we treat it as if everything was allowed.
257 DLOG(ERROR
) << "CertGetIntendedKeyUsage failed: " << err
;
262 // Verify the current time is within the certificate's validity period.
263 if (CertVerifyTimeValidity(NULL
, cert_context
->pCertInfo
) != 0)
266 // Verify private key metadata is associated with this certificate.
268 if (!CertGetCertificateContextProperty(
269 cert_context
, CERT_KEY_PROV_INFO_PROP_ID
, NULL
, &size
)) {
278 void DestroyCertificates(CERTCertificate
** certs
, size_t len
) {
279 for (size_t i
= 0; i
< len
; i
++)
280 CERT_DestroyCertificate(certs
[i
]);
283 // Helper functions to make it possible to log events from within the
284 // SSLClientSocketNSS::Core.
285 void AddLogEvent(const base::WeakPtr
<BoundNetLog
>& net_log
,
286 NetLog::EventType event_type
) {
289 net_log
->AddEvent(event_type
);
292 // Helper function to make it possible to log events from within the
293 // SSLClientSocketNSS::Core.
294 void AddLogEventWithCallback(const base::WeakPtr
<BoundNetLog
>& net_log
,
295 NetLog::EventType event_type
,
296 const NetLog::ParametersCallback
& callback
) {
299 net_log
->AddEvent(event_type
, callback
);
302 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
303 // from within the SSLClientSocketNSS::Core.
304 // AddByteTransferEvent expects to receive a const char*, which within the
305 // Core is backed by an IOBuffer. If the "const char*" is bound via
306 // base::Bind and posted to another thread, and the IOBuffer that backs that
307 // pointer then goes out of scope on the origin thread, this would result in
308 // an invalid read of a stale pointer.
309 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
310 // to the owning IOBuffer can be bound to the Callback. This ensures that the
311 // IOBuffer will stay alive long enough to cross threads if needed.
312 void LogByteTransferEvent(
313 const base::WeakPtr
<BoundNetLog
>& net_log
, NetLog::EventType event_type
,
314 int len
, IOBuffer
* buffer
) {
317 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
320 // PeerCertificateChain is a helper object which extracts the certificate
321 // chain, as given by the server, from an NSS socket and performs the needed
322 // resource management. The first element of the chain is the leaf certificate
323 // and the other elements are in the order given by the server.
324 class PeerCertificateChain
{
326 PeerCertificateChain() {}
327 PeerCertificateChain(const PeerCertificateChain
& other
);
328 ~PeerCertificateChain();
329 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
331 // Resets the current chain, freeing any resources, and updates the current
332 // chain to be a copy of the chain stored in |nss_fd|.
333 // If |nss_fd| is NULL, then the current certificate chain will be freed.
334 void Reset(PRFileDesc
* nss_fd
);
336 // Returns the current certificate chain as a vector of DER-encoded
337 // base::StringPieces. The returned vector remains valid until Reset is
339 std::vector
<base::StringPiece
> AsStringPieceVector() const;
341 bool empty() const { return certs_
.empty(); }
342 size_t size() const { return certs_
.size(); }
344 CERTCertificate
* operator[](size_t index
) const {
345 DCHECK_LT(index
, certs_
.size());
346 return certs_
[index
];
350 std::vector
<CERTCertificate
*> certs_
;
353 PeerCertificateChain::PeerCertificateChain(
354 const PeerCertificateChain
& other
) {
358 PeerCertificateChain::~PeerCertificateChain() {
362 PeerCertificateChain
& PeerCertificateChain::operator=(
363 const PeerCertificateChain
& other
) {
368 certs_
.reserve(other
.certs_
.size());
369 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
370 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
375 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
376 for (size_t i
= 0; i
< certs_
.size(); ++i
)
377 CERT_DestroyCertificate(certs_
[i
]);
383 unsigned int num_certs
= 0;
384 SECStatus rv
= SSL_PeerCertificateChain(nss_fd
, NULL
, &num_certs
, 0);
385 DCHECK_EQ(SECSuccess
, rv
);
387 // The handshake on |nss_fd| may not have completed.
391 certs_
.resize(num_certs
);
392 const unsigned int expected_num_certs
= num_certs
;
393 rv
= SSL_PeerCertificateChain(nss_fd
, vector_as_array(&certs_
),
394 &num_certs
, expected_num_certs
);
395 DCHECK_EQ(SECSuccess
, rv
);
396 DCHECK_EQ(expected_num_certs
, num_certs
);
399 std::vector
<base::StringPiece
>
400 PeerCertificateChain::AsStringPieceVector() const {
401 std::vector
<base::StringPiece
> v(certs_
.size());
402 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
403 v
[i
] = base::StringPiece(
404 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
405 certs_
[i
]->derCert
.len
);
411 // HandshakeState is a helper struct used to pass handshake state between
412 // the NSS task runner and the network task runner.
414 // It contains members that may be read or written on the NSS task runner,
415 // but which also need to be read from the network task runner. The NSS task
416 // runner will notify the network task runner whenever this state changes, so
417 // that the network task runner can safely make a copy, which avoids the need
419 struct HandshakeState
{
420 HandshakeState() { Reset(); }
423 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
425 server_protos
.clear();
426 channel_id_sent
= false;
427 server_cert_chain
.Reset(NULL
);
429 resumed_handshake
= false;
430 ssl_connection_status
= 0;
433 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
434 // negotiated protocol stored in |next_proto|.
435 SSLClientSocket::NextProtoStatus next_proto_status
;
436 std::string next_proto
;
437 // If the server supports NPN, the protocols supported by the server.
438 std::string server_protos
;
440 // True if a channel ID was sent.
441 bool channel_id_sent
;
443 // List of DER-encoded X.509 DistinguishedName of certificate authorities
444 // allowed by the server.
445 std::vector
<std::string
> cert_authorities
;
447 // Set when the handshake fully completes.
449 // The server certificate is first received from NSS as an NSS certificate
450 // chain (|server_cert_chain|) and then converted into a platform-specific
451 // X509Certificate object (|server_cert|). It's possible for some
452 // certificates to be successfully parsed by NSS, and not by the platform
453 // libraries (i.e.: when running within a sandbox, different parsing
454 // algorithms, etc), so it's not safe to assume that |server_cert| will
455 // always be non-NULL.
456 PeerCertificateChain server_cert_chain
;
457 scoped_refptr
<X509Certificate
> server_cert
;
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
);
485 // Map NSS error code from the first SSL handshake to network error code.
486 int MapNSSClientHandshakeError(PRErrorCode err
) {
488 // If the server closed on us, it is a protocol error.
489 // Some TLS-intolerant servers do this when we request TLS.
490 case PR_END_OF_FILE_ERROR
:
491 return ERR_SSL_PROTOCOL_ERROR
;
493 return MapNSSClientError(err
);
499 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
500 // able to marshal data between NSS functions and an underlying transport
503 // All public functions are meant to be called from the network task runner,
504 // and any callbacks supplied will be invoked there as well, provided that
505 // Detach() has not been called yet.
507 /////////////////////////////////////////////////////////////////////////////
509 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
511 // Because NSS may block on either hardware or user input during operations
512 // such as signing, creating certificates, or locating private keys, the Core
513 // handles all of the interactions with the underlying NSS SSL socket, so
514 // that these blocking calls can be executed on a dedicated task runner.
516 // Note that the network task runner and the NSS task runner may be executing
517 // on the same thread. If that happens, then it's more performant to try to
518 // complete as much work as possible synchronously, even if it might block,
519 // rather than continually PostTask-ing to the same thread.
521 // Because NSS functions should only be called on the NSS task runner, while
522 // I/O resources should only be accessed on the network task runner, most
523 // public functions are implemented via three methods, each with different
524 // task runner affinities.
526 // In the single-threaded mode (where the network and NSS task runners run on
527 // the same thread), these are all attempted synchronously, while in the
528 // multi-threaded mode, message passing is used.
530 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
532 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
533 // (BufferRecv, BufferSend)
534 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
535 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
536 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
537 // data from the network task runner back to NSS (BufferRecvComplete,
538 // BufferSendComplete, OnHandshakeIOComplete)
540 /////////////////////////////////////////////////////////////////////////////
541 // Single-threaded example
543 // |--------------------------Network Task Runner--------------------------|
544 // SSLClientSocketNSS Core (Transport Socket)
546 // |-------------------------V
554 // |-------------------------V
556 // V-------------------------|
557 // BufferRecvComplete()
559 // PostOrRunCallback()
560 // V-------------------------|
563 /////////////////////////////////////////////////////////////////////////////
564 // Multi-threaded example:
566 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
567 // SSLClientSocketNSS Core Socket Core
569 // |---------------------V
571 // |-------------------------------V
577 // V-------------------------------|
579 // |----------------V
581 // V----------------|
582 // BufferRecvComplete()
583 // |-------------------------------V
584 // BufferRecvComplete()
586 // PostOrRunCallback()
587 // V-------------------------------|
588 // PostOrRunCallback()
589 // V---------------------|
592 /////////////////////////////////////////////////////////////////////////////
593 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
595 // Creates a new Core.
597 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
598 // that need to operate on the underlying transport, net log, or server
599 // bound certificate fetching will happen on the |network_task_runner|, so
600 // that their lifetimes match that of the owning SSLClientSocketNSS.
602 // The caller retains ownership of |transport|, |net_log|, and
603 // |server_bound_cert_service|, and they will not be accessed once Detach()
605 Core(base::SequencedTaskRunner
* network_task_runner
,
606 base::SequencedTaskRunner
* nss_task_runner
,
607 ClientSocketHandle
* transport
,
608 const HostPortPair
& host_and_port
,
609 const SSLConfig
& ssl_config
,
610 BoundNetLog
* net_log
,
611 ServerBoundCertService
* server_bound_cert_service
);
613 // Called on the network task runner.
614 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
615 // underlying memio implementation, to the Core. Returns true if the Core
616 // was successfully registered with the socket.
617 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
619 // Called on the network task runner.
620 // Sets the predicted certificate chain that the peer will send, for use
621 // with the TLS CachedInfo extension. If called, it must not be called
622 // before Init() or after Connect().
623 void SetPredictedCertificates(
624 const std::vector
<std::string
>& predicted_certificates
);
626 // Called on the network task runner.
628 // Attempts to perform an SSL handshake. If the handshake cannot be
629 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
630 // the network task runner once the handshake has completed. Otherwise,
631 // returns OK on success or a network error code on failure.
632 int Connect(const CompletionCallback
& callback
);
634 // Called on the network task runner.
635 // Signals that the resources owned by the network task runner are going
636 // away. No further callbacks will be invoked on the network task runner.
637 // May be called at any time.
640 // Called on the network task runner.
641 // Returns the current state of the underlying SSL socket. May be called at
643 const HandshakeState
& state() const { return network_handshake_state_
; }
645 // Called on the network task runner.
646 // Read() and Write() mirror the net::Socket functions of the same name.
647 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
648 // task runner at a later point, unless the caller calls Detach().
649 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
650 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
652 // Called on the network task runner.
654 bool HasPendingAsyncOperation();
655 bool HasUnhandledReceivedData();
658 friend class base::RefCountedThreadSafe
<Core
>;
664 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
667 bool OnNSSTaskRunner() const;
668 bool OnNetworkTaskRunner() const;
670 ////////////////////////////////////////////////////////////////////////////
671 // Methods that are ONLY called on the NSS task runner:
672 ////////////////////////////////////////////////////////////////////////////
674 // Called by NSS during full handshakes to allow the application to
675 // verify the certificate. Instead of verifying the certificate in the midst
676 // of the handshake, SECSuccess is always returned and the peer's certificate
677 // is verified afterwards.
678 // This behaviour is an artifact of the original SSLClientSocketWin
679 // implementation, which could not verify the peer's certificate until after
680 // the handshake had completed, as well as bugs in NSS that prevent
681 // SSL_RestartHandshakeAfterCertReq from working.
682 static SECStatus
OwnAuthCertHandler(void* arg
,
687 // Callbacks called by NSS when the peer requests client certificate
689 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
691 #if defined(NSS_PLATFORM_CLIENT_AUTH)
692 // When NSS has been integrated with awareness of the underlying system
693 // cryptographic libraries, this callback allows the caller to supply a
694 // native platform certificate and key for use by NSS. At most, one of
695 // either (result_certs, result_private_key) or (result_nss_certificate,
696 // result_nss_private_key) should be set.
697 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
698 static SECStatus
PlatformClientAuthHandler(
701 CERTDistNames
* ca_names
,
702 CERTCertList
** result_certs
,
703 void** result_private_key
,
704 CERTCertificate
** result_nss_certificate
,
705 SECKEYPrivateKey
** result_nss_private_key
);
707 static SECStatus
ClientAuthHandler(void* arg
,
709 CERTDistNames
* ca_names
,
710 CERTCertificate
** result_certificate
,
711 SECKEYPrivateKey
** result_private_key
);
714 // Called by NSS once the handshake has completed.
715 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
716 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
718 // Handles an NSS error generated while handshaking or performing IO.
719 // Returns a network error code mapped from the original NSS error.
720 int HandleNSSError(PRErrorCode error
, bool handshake_error
);
722 int DoHandshakeLoop(int last_io_result
);
723 int DoReadLoop(int result
);
724 int DoWriteLoop(int result
);
727 int DoGetDBCertComplete(int result
);
730 int DoPayloadWrite();
732 bool DoTransportIO();
736 void OnRecvComplete(int result
);
737 void OnSendComplete(int result
);
739 void DoConnectCallback(int result
);
740 void DoReadCallback(int result
);
741 void DoWriteCallback(int result
);
743 // Client channel ID handler.
744 static SECStatus
ClientChannelIDHandler(
747 SECKEYPublicKey
**out_public_key
,
748 SECKEYPrivateKey
**out_private_key
);
750 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
751 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
752 // and an error code otherwise.
753 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
754 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
755 // takes ownership of the |*cert| and |*key|.
756 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
758 // Updates the NSS and platform specific certificates.
759 void UpdateServerCert();
760 // Updates the nss_handshake_state_ with the negotiated security parameters.
761 void UpdateConnectionStatus();
762 // Record histograms for channel id support during full handshakes - resumed
763 // handshakes are ignored.
764 void RecordChannelIDSupport();
765 // UpdateNextProto gets any application-layer protocol that may have been
766 // negotiated by the TLS connection.
767 void UpdateNextProto();
769 ////////////////////////////////////////////////////////////////////////////
770 // Methods that are ONLY called on the network task runner:
771 ////////////////////////////////////////////////////////////////////////////
772 int DoBufferRecv(IOBuffer
* buffer
, int len
);
773 int DoBufferSend(IOBuffer
* buffer
, int len
);
774 int DoGetDomainBoundCert(const std::string
& host
);
776 void OnGetDomainBoundCertComplete(int result
);
777 void OnHandshakeStateUpdated(const HandshakeState
& state
);
778 void OnNSSBufferUpdated(int amount_in_read_buffer
);
779 void DidNSSRead(int result
);
780 void DidNSSWrite(int result
);
781 void RecordChannelIDSupportOnNetworkTaskRunner(
782 bool negotiated_channel_id
,
783 bool channel_id_enabled
,
784 bool supports_ecc
) const;
786 ////////////////////////////////////////////////////////////////////////////
787 // Methods that are called on both the network task runner and the NSS
789 ////////////////////////////////////////////////////////////////////////////
790 void OnHandshakeIOComplete(int result
);
791 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
792 void BufferSendComplete(int result
);
794 // PostOrRunCallback is a helper function to ensure that |callback| is
795 // invoked on the network task runner, but only if Detach() has not yet
797 void PostOrRunCallback(const tracked_objects::Location
& location
,
798 const base::Closure
& callback
);
800 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
801 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
802 void AddCertProvidedEvent(int cert_count
);
804 // Sets the handshake state |channel_id_sent| flag and logs the
805 // SSL_CHANNEL_ID_PROVIDED event.
806 void SetChannelIDProvided();
808 ////////////////////////////////////////////////////////////////////////////
809 // Members that are ONLY accessed on the network task runner:
810 ////////////////////////////////////////////////////////////////////////////
812 // True if the owning SSLClientSocketNSS has called Detach(). No further
813 // callbacks will be invoked nor access to members owned by the network
817 // The underlying transport to use for network IO.
818 ClientSocketHandle
* transport_
;
819 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
821 // The current handshake state. Mirrors |nss_handshake_state_|.
822 HandshakeState network_handshake_state_
;
824 // The service for retrieving Channel ID keys. May be NULL.
825 ServerBoundCertService
* server_bound_cert_service_
;
826 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_
;
828 // The information about NSS task runner.
829 int unhandled_buffer_size_
;
830 bool nss_waiting_read_
;
831 bool nss_waiting_write_
;
834 ////////////////////////////////////////////////////////////////////////////
835 // Members that are ONLY accessed on the NSS task runner:
836 ////////////////////////////////////////////////////////////////////////////
837 HostPortPair host_and_port_
;
838 SSLConfig ssl_config_
;
843 // Buffers for the network end of the SSL state machine
844 memio_Private
* nss_bufs_
;
846 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
847 // as much data as possible, without blocking.
848 // If DoPayloadRead() encounters an error after having read some data, stores
849 // the results to return on the *next* call to DoPayloadRead(). A value of
850 // kNoPendingReadResult indicates there is no pending result, otherwise 0
851 // indicates EOF and < 0 indicates an error.
852 int pending_read_result_
;
853 // Contains the previously observed NSS error. Only valid when
854 // pending_read_result_ != kNoPendingReadResult.
855 PRErrorCode pending_read_nss_error_
;
857 // The certificate chain, in DER form, that is expected to be received from
859 std::vector
<std::string
> predicted_certs_
;
861 State next_handshake_state_
;
863 // True if channel ID extension was negotiated.
864 bool channel_id_xtn_negotiated_
;
865 // True if the handshake state machine was interrupted for channel ID.
866 bool channel_id_needed_
;
867 // True if the handshake state machine was interrupted for client auth.
868 bool client_auth_cert_needed_
;
869 // True if NSS has called HandshakeCallback.
870 bool handshake_callback_called_
;
872 HandshakeState nss_handshake_state_
;
874 bool transport_recv_busy_
;
875 bool transport_recv_eof_
;
876 bool transport_send_busy_
;
878 // Used by Read function.
879 scoped_refptr
<IOBuffer
> user_read_buf_
;
880 int user_read_buf_len_
;
882 // Used by Write function.
883 scoped_refptr
<IOBuffer
> user_write_buf_
;
884 int user_write_buf_len_
;
886 CompletionCallback user_connect_callback_
;
887 CompletionCallback user_read_callback_
;
888 CompletionCallback user_write_callback_
;
890 ////////////////////////////////////////////////////////////////////////////
891 // Members that are accessed on both the network task runner and the NSS
893 ////////////////////////////////////////////////////////////////////////////
894 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
895 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
897 // Dereferenced only on the network task runner, but bound to tasks destined
898 // for the network task runner from the NSS task runner.
899 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
901 // Written on the network task runner by the |server_bound_cert_service_|,
902 // prior to invoking OnHandshakeIOComplete.
903 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
904 // on the NSS task runner.
905 std::string domain_bound_private_key_
;
906 std::string domain_bound_cert_
;
908 DISALLOW_COPY_AND_ASSIGN(Core
);
911 SSLClientSocketNSS::Core::Core(
912 base::SequencedTaskRunner
* network_task_runner
,
913 base::SequencedTaskRunner
* nss_task_runner
,
914 ClientSocketHandle
* transport
,
915 const HostPortPair
& host_and_port
,
916 const SSLConfig
& ssl_config
,
917 BoundNetLog
* net_log
,
918 ServerBoundCertService
* server_bound_cert_service
)
920 transport_(transport
),
921 weak_net_log_factory_(net_log
),
922 server_bound_cert_service_(server_bound_cert_service
),
923 unhandled_buffer_size_(0),
924 nss_waiting_read_(false),
925 nss_waiting_write_(false),
926 nss_is_closed_(false),
927 host_and_port_(host_and_port
),
928 ssl_config_(ssl_config
),
931 pending_read_result_(kNoPendingReadResult
),
932 pending_read_nss_error_(0),
933 next_handshake_state_(STATE_NONE
),
934 channel_id_xtn_negotiated_(false),
935 channel_id_needed_(false),
936 client_auth_cert_needed_(false),
937 handshake_callback_called_(false),
938 transport_recv_busy_(false),
939 transport_recv_eof_(false),
940 transport_send_busy_(false),
941 user_read_buf_len_(0),
942 user_write_buf_len_(0),
943 network_task_runner_(network_task_runner
),
944 nss_task_runner_(nss_task_runner
),
945 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
948 SSLClientSocketNSS::Core::~Core() {
949 // TODO(wtc): Send SSL close_notify alert.
950 if (nss_fd_
!= NULL
) {
956 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
957 memio_Private
* buffers
) {
958 DCHECK(OnNetworkTaskRunner());
965 SECStatus rv
= SECSuccess
;
967 if (!ssl_config_
.next_protos
.empty()) {
968 size_t wire_length
= 0;
969 for (std::vector
<std::string
>::const_iterator
970 i
= ssl_config_
.next_protos
.begin();
971 i
!= ssl_config_
.next_protos
.end(); ++i
) {
972 if (i
->size() > 255) {
973 LOG(WARNING
) << "Ignoring overlong NPN/ALPN protocol: " << *i
;
976 wire_length
+= i
->size();
979 scoped_ptr
<uint8
[]> wire_protos(new uint8
[wire_length
]);
980 uint8
* dst
= wire_protos
.get();
981 for (std::vector
<std::string
>::const_iterator
982 i
= ssl_config_
.next_protos
.begin();
983 i
!= ssl_config_
.next_protos
.end(); i
++) {
987 memcpy(dst
, i
->data(), i
->size());
990 DCHECK_EQ(dst
, wire_protos
.get() + wire_length
);
991 rv
= SSL_SetNextProtoNego(nss_fd_
, wire_protos
.get(), wire_length
);
992 if (rv
!= SECSuccess
)
993 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoCallback", "");
996 rv
= SSL_AuthCertificateHook(
997 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
998 if (rv
!= SECSuccess
) {
999 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
1003 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1004 rv
= SSL_GetPlatformClientAuthDataHook(
1005 nss_fd_
, SSLClientSocketNSS::Core::PlatformClientAuthHandler
,
1008 rv
= SSL_GetClientAuthDataHook(
1009 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
1011 if (rv
!= SECSuccess
) {
1012 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
1016 if (ssl_config_
.channel_id_enabled
) {
1017 if (!server_bound_cert_service_
) {
1018 DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
1019 } else if (!crypto::ECPrivateKey::IsSupported()) {
1020 DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
1021 } else if (!server_bound_cert_service_
->IsSystemTimeValid()) {
1022 DVLOG(1) << "System time is weird, not enabling channel ID.";
1024 rv
= SSL_SetClientChannelIDCallback(
1025 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
1026 if (rv
!= SECSuccess
)
1027 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetClientChannelIDCallback",
1032 rv
= SSL_HandshakeCallback(
1033 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
1034 if (rv
!= SECSuccess
) {
1035 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
1042 void SSLClientSocketNSS::Core::SetPredictedCertificates(
1043 const std::vector
<std::string
>& predicted_certs
) {
1044 if (predicted_certs
.empty())
1047 if (!OnNSSTaskRunner()) {
1049 nss_task_runner_
->PostTask(
1051 base::Bind(&Core::SetPredictedCertificates
, this, predicted_certs
));
1057 predicted_certs_
= predicted_certs
;
1059 scoped_ptr
<CERTCertificate
*[]> certs(
1060 new CERTCertificate
*[predicted_certs
.size()]);
1062 for (size_t i
= 0; i
< predicted_certs
.size(); i
++) {
1064 derCert
.data
= const_cast<uint8
*>(reinterpret_cast<const uint8
*>(
1065 predicted_certs
[i
].data()));
1066 derCert
.len
= predicted_certs
[i
].size();
1067 certs
[i
] = CERT_NewTempCertificate(
1068 CERT_GetDefaultCertDB(), &derCert
, NULL
/* no nickname given */,
1069 PR_FALSE
/* not permanent */, PR_TRUE
/* copy DER data */);
1071 DestroyCertificates(&certs
[0], i
);
1078 #ifdef SSL_ENABLE_CACHED_INFO
1079 rv
= SSL_SetPredictedPeerCertificates(nss_fd_
, certs
.get(),
1080 predicted_certs
.size());
1081 DCHECK_EQ(SECSuccess
, rv
);
1083 rv
= SECFailure
; // Not implemented.
1085 DestroyCertificates(&certs
[0], predicted_certs
.size());
1087 if (rv
!= SECSuccess
) {
1088 LOG(WARNING
) << "SetPredictedCertificates failed: "
1089 << host_and_port_
.ToString();
1093 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
1094 if (!OnNSSTaskRunner()) {
1096 bool posted
= nss_task_runner_
->PostTask(
1098 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
1099 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1102 DCHECK(OnNSSTaskRunner());
1103 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1104 DCHECK(user_read_callback_
.is_null());
1105 DCHECK(user_write_callback_
.is_null());
1106 DCHECK(user_connect_callback_
.is_null());
1107 DCHECK(!user_read_buf_
.get());
1108 DCHECK(!user_write_buf_
.get());
1110 next_handshake_state_
= STATE_HANDSHAKE
;
1111 int rv
= DoHandshakeLoop(OK
);
1112 if (rv
== ERR_IO_PENDING
) {
1113 user_connect_callback_
= callback
;
1114 } else if (rv
> OK
) {
1117 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
1118 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1119 return ERR_IO_PENDING
;
1125 void SSLClientSocketNSS::Core::Detach() {
1126 DCHECK(OnNetworkTaskRunner());
1130 weak_net_log_factory_
.InvalidateWeakPtrs();
1132 network_handshake_state_
.Reset();
1134 domain_bound_cert_request_handle_
.Cancel();
1137 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1138 const CompletionCallback
& callback
) {
1139 if (!OnNSSTaskRunner()) {
1140 DCHECK(OnNetworkTaskRunner());
1143 DCHECK(!nss_waiting_read_
);
1145 nss_waiting_read_
= true;
1146 bool posted
= nss_task_runner_
->PostTask(
1148 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1149 buf_len
, callback
));
1151 nss_is_closed_
= true;
1152 nss_waiting_read_
= false;
1154 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1157 DCHECK(OnNSSTaskRunner());
1158 DCHECK(handshake_callback_called_
);
1159 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1160 DCHECK(user_read_callback_
.is_null());
1161 DCHECK(user_connect_callback_
.is_null());
1162 DCHECK(!user_read_buf_
.get());
1165 user_read_buf_
= buf
;
1166 user_read_buf_len_
= buf_len
;
1168 int rv
= DoReadLoop(OK
);
1169 if (rv
== ERR_IO_PENDING
) {
1170 if (OnNetworkTaskRunner())
1171 nss_waiting_read_
= true;
1172 user_read_callback_
= callback
;
1174 user_read_buf_
= NULL
;
1175 user_read_buf_len_
= 0;
1177 if (!OnNetworkTaskRunner()) {
1178 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1179 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1180 return ERR_IO_PENDING
;
1182 DCHECK(!nss_waiting_read_
);
1184 nss_is_closed_
= true;
1191 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1192 const CompletionCallback
& callback
) {
1193 if (!OnNSSTaskRunner()) {
1194 DCHECK(OnNetworkTaskRunner());
1197 DCHECK(!nss_waiting_write_
);
1199 nss_waiting_write_
= true;
1200 bool posted
= nss_task_runner_
->PostTask(
1202 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1203 buf_len
, callback
));
1205 nss_is_closed_
= true;
1206 nss_waiting_write_
= false;
1208 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1211 DCHECK(OnNSSTaskRunner());
1212 DCHECK(handshake_callback_called_
);
1213 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1214 DCHECK(user_write_callback_
.is_null());
1215 DCHECK(user_connect_callback_
.is_null());
1216 DCHECK(!user_write_buf_
.get());
1219 user_write_buf_
= buf
;
1220 user_write_buf_len_
= buf_len
;
1222 int rv
= DoWriteLoop(OK
);
1223 if (rv
== ERR_IO_PENDING
) {
1224 if (OnNetworkTaskRunner())
1225 nss_waiting_write_
= true;
1226 user_write_callback_
= callback
;
1228 user_write_buf_
= NULL
;
1229 user_write_buf_len_
= 0;
1231 if (!OnNetworkTaskRunner()) {
1232 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1233 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1234 return ERR_IO_PENDING
;
1236 DCHECK(!nss_waiting_write_
);
1238 nss_is_closed_
= true;
1245 bool SSLClientSocketNSS::Core::IsConnected() {
1246 DCHECK(OnNetworkTaskRunner());
1247 return !nss_is_closed_
;
1250 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
1251 DCHECK(OnNetworkTaskRunner());
1252 return nss_waiting_read_
|| nss_waiting_write_
;
1255 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
1256 DCHECK(OnNetworkTaskRunner());
1257 return unhandled_buffer_size_
!= 0;
1260 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1261 return nss_task_runner_
->RunsTasksOnCurrentThread();
1264 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1265 return network_task_runner_
->RunsTasksOnCurrentThread();
1269 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1274 Core
* core
= reinterpret_cast<Core
*>(arg
);
1275 if (!core
->handshake_callback_called_
) {
1276 // Only need to turn off False Start in the initial handshake. Also, it is
1277 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1278 // handshake" lock isn't already held, which will result in an assertion
1279 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1280 PRBool negotiated_extension
;
1281 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1282 ssl_app_layer_protocol_xtn
,
1283 &negotiated_extension
);
1284 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1285 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1286 ssl_next_proto_nego_xtn
,
1287 &negotiated_extension
);
1289 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1290 // If the server doesn't support NPN or ALPN, then we don't do False
1292 SSL_OptionSet(socket
, SSL_ENABLE_FALSE_START
, PR_FALSE
);
1296 // Tell NSS to not verify the certificate.
1300 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1302 SECStatus
SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1305 CERTDistNames
* ca_names
,
1306 CERTCertList
** result_certs
,
1307 void** result_private_key
,
1308 CERTCertificate
** result_nss_certificate
,
1309 SECKEYPrivateKey
** result_nss_private_key
) {
1310 Core
* core
= reinterpret_cast<Core
*>(arg
);
1311 DCHECK(core
->OnNSSTaskRunner());
1313 core
->PostOrRunCallback(
1315 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1316 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1318 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1320 if (core
->ssl_config_
.send_client_cert
) {
1321 if (core
->ssl_config_
.client_cert
) {
1322 PCCERT_CONTEXT cert_context
=
1323 core
->ssl_config_
.client_cert
->os_cert_handle();
1325 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
1327 BOOL must_free
= FALSE
;
1329 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
1330 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
1332 BOOL acquired_key
= CryptAcquireCertificatePrivateKey(
1333 cert_context
, flags
, NULL
, &crypt_prov
, &key_spec
, &must_free
);
1336 // Should never get a cached handle back - ownership must always be
1338 CHECK_EQ(must_free
, TRUE
);
1341 der_cert
.type
= siDERCertBuffer
;
1342 der_cert
.data
= cert_context
->pbCertEncoded
;
1343 der_cert
.len
= cert_context
->cbCertEncoded
;
1345 // TODO(rsleevi): Error checking for NSS allocation errors.
1346 CERTCertDBHandle
* db_handle
= CERT_GetDefaultCertDB();
1347 CERTCertificate
* user_cert
= CERT_NewTempCertificate(
1348 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1350 // Importing the certificate can fail for reasons including a serial
1351 // number collision. See crbug.com/97355.
1352 core
->AddCertProvidedEvent(0);
1355 CERTCertList
* cert_chain
= CERT_NewCertList();
1356 CERT_AddCertToListTail(cert_chain
, user_cert
);
1358 // Add the intermediates.
1359 X509Certificate::OSCertHandles intermediates
=
1360 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1361 for (X509Certificate::OSCertHandles::const_iterator it
=
1362 intermediates
.begin(); it
!= intermediates
.end(); ++it
) {
1363 der_cert
.data
= (*it
)->pbCertEncoded
;
1364 der_cert
.len
= (*it
)->cbCertEncoded
;
1366 CERTCertificate
* intermediate
= CERT_NewTempCertificate(
1367 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1368 if (!intermediate
) {
1369 CERT_DestroyCertList(cert_chain
);
1370 core
->AddCertProvidedEvent(0);
1373 CERT_AddCertToListTail(cert_chain
, intermediate
);
1375 PCERT_KEY_CONTEXT key_context
= reinterpret_cast<PCERT_KEY_CONTEXT
>(
1376 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT
)));
1377 key_context
->cbSize
= sizeof(*key_context
);
1378 // NSS will free this context when no longer in use.
1379 key_context
->hCryptProv
= crypt_prov
;
1380 key_context
->dwKeySpec
= key_spec
;
1381 *result_private_key
= key_context
;
1382 *result_certs
= cert_chain
;
1384 int cert_count
= 1 + intermediates
.size();
1385 core
->AddCertProvidedEvent(cert_count
);
1388 LOG(WARNING
) << "Client cert found without private key";
1391 // Send no client certificate.
1392 core
->AddCertProvidedEvent(0);
1396 core
->nss_handshake_state_
.cert_authorities
.clear();
1398 std::vector
<CERT_NAME_BLOB
> issuer_list(ca_names
->nnames
);
1399 for (int i
= 0; i
< ca_names
->nnames
; ++i
) {
1400 issuer_list
[i
].cbData
= ca_names
->names
[i
].len
;
1401 issuer_list
[i
].pbData
= ca_names
->names
[i
].data
;
1402 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1403 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1404 static_cast<size_t>(ca_names
->names
[i
].len
)));
1407 // Update the network task runner's view of the handshake state now that
1408 // server certificate request has been recorded.
1409 core
->PostOrRunCallback(
1410 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1411 core
->nss_handshake_state_
));
1413 // Tell NSS to suspend the client authentication. We will then abort the
1414 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1415 return SECWouldBlock
;
1416 #elif defined(OS_MACOSX)
1417 if (core
->ssl_config_
.send_client_cert
) {
1418 if (core
->ssl_config_
.client_cert
.get()) {
1419 OSStatus os_error
= noErr
;
1420 SecIdentityRef identity
= NULL
;
1421 SecKeyRef private_key
= NULL
;
1422 X509Certificate::OSCertHandles chain
;
1424 base::AutoLock
lock(crypto::GetMacSecurityServicesLock());
1425 os_error
= SecIdentityCreateWithCertificate(
1426 NULL
, core
->ssl_config_
.client_cert
->os_cert_handle(), &identity
);
1428 if (os_error
== noErr
) {
1429 os_error
= SecIdentityCopyPrivateKey(identity
, &private_key
);
1430 CFRelease(identity
);
1433 if (os_error
== noErr
) {
1434 // TODO(rsleevi): Error checking for NSS allocation errors.
1435 *result_certs
= CERT_NewCertList();
1436 *result_private_key
= private_key
;
1438 chain
.push_back(core
->ssl_config_
.client_cert
->os_cert_handle());
1439 const X509Certificate::OSCertHandles
& intermediates
=
1440 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1441 if (!intermediates
.empty())
1442 chain
.insert(chain
.end(), intermediates
.begin(), intermediates
.end());
1444 for (size_t i
= 0, chain_count
= chain
.size(); i
< chain_count
; ++i
) {
1445 CSSM_DATA cert_data
;
1446 SecCertificateRef cert_ref
= chain
[i
];
1447 os_error
= SecCertificateGetData(cert_ref
, &cert_data
);
1448 if (os_error
!= noErr
)
1452 der_cert
.type
= siDERCertBuffer
;
1453 der_cert
.data
= cert_data
.Data
;
1454 der_cert
.len
= cert_data
.Length
;
1455 CERTCertificate
* nss_cert
= CERT_NewTempCertificate(
1456 CERT_GetDefaultCertDB(), &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1458 // In the event of an NSS error, make up an OS error and reuse
1459 // the error handling below.
1460 os_error
= errSecCreateChainFailed
;
1463 CERT_AddCertToListTail(*result_certs
, nss_cert
);
1467 if (os_error
== noErr
) {
1468 core
->AddCertProvidedEvent(chain
.size());
1472 OSSTATUS_LOG(WARNING
, os_error
)
1473 << "Client cert found, but could not be used";
1474 if (*result_certs
) {
1475 CERT_DestroyCertList(*result_certs
);
1476 *result_certs
= NULL
;
1478 if (*result_private_key
)
1479 *result_private_key
= NULL
;
1481 CFRelease(private_key
);
1484 // Send no client certificate.
1485 core
->AddCertProvidedEvent(0);
1489 core
->nss_handshake_state_
.cert_authorities
.clear();
1491 // Retrieve the cert issuers accepted by the server.
1492 std::vector
<CertPrincipal
> valid_issuers
;
1493 int n
= ca_names
->nnames
;
1494 for (int i
= 0; i
< n
; i
++) {
1495 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1496 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1497 static_cast<size_t>(ca_names
->names
[i
].len
)));
1500 // Update the network task runner's view of the handshake state now that
1501 // server certificate request has been recorded.
1502 core
->PostOrRunCallback(
1503 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1504 core
->nss_handshake_state_
));
1506 // Tell NSS to suspend the client authentication. We will then abort the
1507 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1508 return SECWouldBlock
;
1514 #elif defined(OS_IOS)
1516 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1519 CERTDistNames
* ca_names
,
1520 CERTCertificate
** result_certificate
,
1521 SECKEYPrivateKey
** result_private_key
) {
1522 Core
* core
= reinterpret_cast<Core
*>(arg
);
1523 DCHECK(core
->OnNSSTaskRunner());
1525 core
->PostOrRunCallback(
1527 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1528 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1530 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1531 LOG(WARNING
) << "Client auth is not supported";
1533 // Never send a certificate.
1534 core
->AddCertProvidedEvent(0);
1538 #else // NSS_PLATFORM_CLIENT_AUTH
1541 // Based on Mozilla's NSS_GetClientAuthData.
1542 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1545 CERTDistNames
* ca_names
,
1546 CERTCertificate
** result_certificate
,
1547 SECKEYPrivateKey
** result_private_key
) {
1548 Core
* core
= reinterpret_cast<Core
*>(arg
);
1549 DCHECK(core
->OnNSSTaskRunner());
1551 core
->PostOrRunCallback(
1553 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1554 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1556 // Regular client certificate requested.
1557 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1558 void* wincx
= SSL_RevealPinArg(socket
);
1560 if (core
->ssl_config_
.send_client_cert
) {
1561 // Second pass: a client certificate should have been selected.
1562 if (core
->ssl_config_
.client_cert
.get()) {
1563 CERTCertificate
* cert
=
1564 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1565 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1567 // TODO(jsorianopastor): We should wait for server certificate
1568 // verification before sending our credentials. See
1569 // http://crbug.com/13934.
1570 *result_certificate
= cert
;
1571 *result_private_key
= privkey
;
1572 // A cert_count of -1 means the number of certificates is unknown.
1573 // NSS will construct the certificate chain.
1574 core
->AddCertProvidedEvent(-1);
1578 LOG(WARNING
) << "Client cert found without private key";
1580 // Send no client certificate.
1581 core
->AddCertProvidedEvent(0);
1585 // First pass: client certificate is needed.
1586 core
->nss_handshake_state_
.cert_authorities
.clear();
1588 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1589 // the server and save them in |cert_authorities|.
1590 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1591 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1592 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1593 static_cast<size_t>(ca_names
->names
[i
].len
)));
1596 // Update the network task runner's view of the handshake state now that
1597 // server certificate request has been recorded.
1598 core
->PostOrRunCallback(
1599 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1600 core
->nss_handshake_state_
));
1602 // Tell NSS to suspend the client authentication. We will then abort the
1603 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1604 return SECWouldBlock
;
1606 #endif // NSS_PLATFORM_CLIENT_AUTH
1609 void SSLClientSocketNSS::Core::HandshakeCallback(
1612 Core
* core
= reinterpret_cast<Core
*>(arg
);
1613 DCHECK(core
->OnNSSTaskRunner());
1615 core
->handshake_callback_called_
= true;
1617 HandshakeState
* nss_state
= &core
->nss_handshake_state_
;
1619 PRBool last_handshake_resumed
;
1620 SECStatus rv
= SSL_HandshakeResumedSession(socket
, &last_handshake_resumed
);
1621 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1622 nss_state
->resumed_handshake
= true;
1624 nss_state
->resumed_handshake
= false;
1627 core
->RecordChannelIDSupport();
1628 core
->UpdateServerCert();
1629 core
->UpdateConnectionStatus();
1630 core
->UpdateNextProto();
1632 // Update the network task runners view of the handshake state whenever
1633 // a handshake has completed.
1634 core
->PostOrRunCallback(
1635 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1639 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
,
1640 bool handshake_error
) {
1641 DCHECK(OnNSSTaskRunner());
1643 int net_error
= handshake_error
? MapNSSClientHandshakeError(nss_error
) :
1644 MapNSSClientError(nss_error
);
1647 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1648 // os_cert_handle() as an optimization. However, if the certificate
1649 // private key is stored on a smart card, and the smart card is removed,
1650 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1651 // preventing client certificate authentication. Because the
1652 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1653 // caching in X509Certificate, this failure ends up preventing client
1654 // certificate authentication with the same certificate for all future
1655 // attempts, even after the smart card has been re-inserted. By setting
1656 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1657 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1658 // the certificate on the next attempt, which should succeed if the smart
1659 // card has been re-inserted, or will typically prompt the user to
1660 // re-insert the smart card if not.
1661 if ((net_error
== ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
||
1662 net_error
== ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
) &&
1663 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
) {
1664 CertSetCertificateContextProperty(
1665 ssl_config_
.client_cert
->os_cert_handle(),
1666 CERT_KEY_PROV_HANDLE_PROP_ID
, 0, NULL
);
1673 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1674 DCHECK(OnNSSTaskRunner());
1676 int rv
= last_io_result
;
1678 // Default to STATE_NONE for next state.
1679 State state
= next_handshake_state_
;
1680 GotoState(STATE_NONE
);
1683 case STATE_HANDSHAKE
:
1686 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1687 rv
= DoGetDBCertComplete(rv
);
1691 rv
= ERR_UNEXPECTED
;
1692 LOG(DFATAL
) << "unexpected state " << state
;
1696 // Do the actual network I/O
1697 bool network_moved
= DoTransportIO();
1698 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1699 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1700 // special case we keep looping even if rv is ERR_IO_PENDING because
1701 // the transport IO may allow DoHandshake to make progress.
1702 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1703 rv
= OK
; // This causes us to stay in the loop.
1705 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1709 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1710 DCHECK(OnNSSTaskRunner());
1711 DCHECK(handshake_callback_called_
);
1712 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1718 LOG(DFATAL
) << "!nss_bufs_";
1719 int rv
= ERR_UNEXPECTED
;
1722 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1723 NetLog::TYPE_SSL_READ_ERROR
,
1724 CreateNetLogSSLErrorCallback(rv
, 0)));
1731 rv
= DoPayloadRead();
1732 network_moved
= DoTransportIO();
1733 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1738 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1739 DCHECK(OnNSSTaskRunner());
1740 DCHECK(handshake_callback_called_
);
1741 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1747 LOG(DFATAL
) << "!nss_bufs_";
1748 int rv
= ERR_UNEXPECTED
;
1751 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1752 NetLog::TYPE_SSL_READ_ERROR
,
1753 CreateNetLogSSLErrorCallback(rv
, 0)));
1760 rv
= DoPayloadWrite();
1761 network_moved
= DoTransportIO();
1762 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1768 int SSLClientSocketNSS::Core::DoHandshake() {
1769 DCHECK(OnNSSTaskRunner());
1771 int net_error
= net::OK
;
1772 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1774 // Note: this function may be called multiple times during the handshake, so
1775 // even though channel id and client auth are separate else cases, they can
1776 // both be used during a single SSL handshake.
1777 if (channel_id_needed_
) {
1778 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1779 net_error
= ERR_IO_PENDING
;
1780 } else if (client_auth_cert_needed_
) {
1781 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1784 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1785 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1786 CreateNetLogSSLErrorCallback(net_error
, 0)));
1788 // If the handshake already succeeded (because the server requests but
1789 // doesn't require a client cert), we need to invalidate the SSL session
1790 // so that we won't try to resume the non-client-authenticated session in
1791 // the next handshake. This will cause the server to ask for a client
1793 if (rv
== SECSuccess
&& SSL_InvalidateSession(nss_fd_
) != SECSuccess
)
1794 LOG(WARNING
) << "Couldn't invalidate SSL session: " << PR_GetError();
1795 } else if (rv
== SECSuccess
) {
1796 if (!handshake_callback_called_
) {
1797 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1798 // SSL_ForceHandshake returned SECSuccess prematurely.
1800 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1803 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1804 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1805 CreateNetLogSSLErrorCallback(net_error
, 0)));
1807 #if defined(SSL_ENABLE_OCSP_STAPLING)
1808 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1809 // system library and update IsOCSPStaplingSupported for Mac.
1810 if (IsOCSPStaplingSupported()) {
1811 const SECItemArray
* ocsp_responses
=
1812 SSL_PeerStapledOCSPResponses(nss_fd_
);
1813 if (ocsp_responses
->len
) {
1815 if (nss_handshake_state_
.server_cert
) {
1816 CRYPT_DATA_BLOB ocsp_response_blob
;
1817 ocsp_response_blob
.cbData
= ocsp_responses
->items
[0].len
;
1818 ocsp_response_blob
.pbData
= ocsp_responses
->items
[0].data
;
1819 BOOL ok
= CertSetCertificateContextProperty(
1820 nss_handshake_state_
.server_cert
->os_cert_handle(),
1821 CERT_OCSP_RESPONSE_PROP_ID
,
1822 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1823 &ocsp_response_blob
);
1825 VLOG(1) << "Failed to set OCSP response property: "
1829 #elif defined(USE_NSS)
1830 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
1831 GetCacheOCSPResponseFromSideChannelFunction();
1833 cache_ocsp_response(
1834 CERT_GetDefaultCertDB(),
1835 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
1836 &ocsp_responses
->items
[0], NULL
);
1844 PRErrorCode prerr
= PR_GetError();
1845 net_error
= HandleNSSError(prerr
, true);
1847 // Some network devices that inspect application-layer packets seem to
1848 // inject TCP reset packets to break the connections when they see
1849 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1851 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1852 // 1.2. We don't lose much in this fallback because the explicit IV for CBC
1853 // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
1854 // fallback will be more painful for TLS 1.2 when we have GCM support.
1856 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1857 // to trigger a version fallback in general, especially the TLS 1.0 ->
1858 // SSL 3.0 fallback, which would drop TLS extensions.
1859 if (prerr
== PR_CONNECT_RESET_ERROR
&&
1860 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
) {
1861 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1864 // If not done, stay in this state
1865 if (net_error
== ERR_IO_PENDING
) {
1866 GotoState(STATE_HANDSHAKE
);
1870 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1871 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1872 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1879 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1883 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1884 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1886 channel_id_needed_
= false;
1891 SECKEYPublicKey
* public_key
;
1892 SECKEYPrivateKey
* private_key
;
1893 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1897 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1898 if (rv
!= SECSuccess
)
1899 return MapNSSError(PORT_GetError());
1901 SetChannelIDProvided();
1902 GotoState(STATE_HANDSHAKE
);
1906 int SSLClientSocketNSS::Core::DoPayloadRead() {
1907 DCHECK(OnNSSTaskRunner());
1908 DCHECK(user_read_buf_
.get());
1909 DCHECK_GT(user_read_buf_len_
, 0);
1912 // If a previous greedy read resulted in an error that was not consumed (eg:
1913 // due to the caller having read some data successfully), then return that
1914 // pending error now.
1915 if (pending_read_result_
!= kNoPendingReadResult
) {
1916 rv
= pending_read_result_
;
1917 PRErrorCode prerr
= pending_read_nss_error_
;
1918 pending_read_result_
= kNoPendingReadResult
;
1919 pending_read_nss_error_
= 0;
1924 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1925 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1926 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1930 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1931 NetLog::TYPE_SSL_READ_ERROR
,
1932 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1937 // Perform a greedy read, attempting to read as much as the caller has
1938 // requested. In the current NSS implementation, PR_Read will return
1939 // exactly one SSL application data record's worth of data per invocation.
1940 // The record size is dictated by the server, and may be noticeably smaller
1941 // than the caller's buffer. This may be as little as a single byte, if the
1942 // server is performing 1/n-1 record splitting.
1944 // However, this greedy read may result in renegotiations/re-handshakes
1945 // happening or may lead to some data being read, followed by an EOF (such as
1946 // a TLS close-notify). If at least some data was read, then that result
1947 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1948 // data was read, it's safe to return the error or EOF immediately.
1949 int total_bytes_read
= 0;
1951 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1952 user_read_buf_len_
- total_bytes_read
);
1954 total_bytes_read
+= rv
;
1955 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1956 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1957 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1958 amount_in_read_buffer
));
1960 if (total_bytes_read
== user_read_buf_len_
) {
1961 // The caller's entire request was satisfied without error. No further
1962 // processing needed.
1963 rv
= total_bytes_read
;
1965 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1966 // immediately, while the NSPR/NSS errors are still available in
1967 // thread-local storage. However, the handled/remapped error code should
1968 // only be returned if no application data was already read; if it was, the
1969 // error code should be deferred until the next call of DoPayloadRead.
1971 // If no data was read, |*next_result| will point to the return value of
1972 // this function. If at least some data was read, |*next_result| will point
1973 // to |pending_read_error_|, to be returned in a future call to
1974 // DoPayloadRead() (e.g.: after the current data is handled).
1975 int* next_result
= &rv
;
1976 if (total_bytes_read
> 0) {
1977 pending_read_result_
= rv
;
1978 rv
= total_bytes_read
;
1979 next_result
= &pending_read_result_
;
1982 if (client_auth_cert_needed_
) {
1983 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1984 pending_read_nss_error_
= 0;
1985 } else if (*next_result
< 0) {
1986 // If *next_result == 0, then that indicates EOF, and no special error
1987 // handling is needed.
1988 pending_read_nss_error_
= PR_GetError();
1989 *next_result
= HandleNSSError(pending_read_nss_error_
, false);
1990 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1991 // If at least some data was read from PR_Read(), do not treat
1992 // insufficient data as an error to return in the next call to
1993 // DoPayloadRead() - instead, let the call fall through to check
1994 // PR_Read() again. This is because DoTransportIO() may complete
1995 // in between the next call to DoPayloadRead(), and thus it is
1996 // important to check PR_Read() on subsequent invocations to see
1997 // if a complete record may now be read.
1998 pending_read_nss_error_
= 0;
1999 pending_read_result_
= kNoPendingReadResult
;
2004 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
2009 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2010 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
2011 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
2012 } else if (rv
!= ERR_IO_PENDING
) {
2015 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2016 NetLog::TYPE_SSL_READ_ERROR
,
2017 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
2018 pending_read_nss_error_
= 0;
2023 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2024 DCHECK(OnNSSTaskRunner());
2026 DCHECK(user_write_buf_
.get());
2028 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2029 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
2030 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2031 // PR_Write could potentially consume the unhandled data in the memio read
2032 // buffer if a renegotiation is in progress. If the buffer is consumed,
2033 // notify the latest buffer size to NetworkRunner.
2034 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
2037 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
2042 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2043 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
2044 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
2047 PRErrorCode prerr
= PR_GetError();
2048 if (prerr
== PR_WOULD_BLOCK_ERROR
)
2049 return ERR_IO_PENDING
;
2051 rv
= HandleNSSError(prerr
, false);
2054 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2055 NetLog::TYPE_SSL_WRITE_ERROR
,
2056 CreateNetLogSSLErrorCallback(rv
, prerr
)));
2060 // Do as much network I/O as possible between the buffer and the
2061 // transport socket. Return true if some I/O performed, false
2062 // otherwise (error or ERR_IO_PENDING).
2063 bool SSLClientSocketNSS::Core::DoTransportIO() {
2064 DCHECK(OnNSSTaskRunner());
2066 bool network_moved
= false;
2067 if (nss_bufs_
!= NULL
) {
2069 // Read and write as much data as we can. The loop is neccessary
2070 // because Write() may return synchronously.
2073 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
2074 network_moved
= true;
2076 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
2077 network_moved
= true;
2079 return network_moved
;
2082 int SSLClientSocketNSS::Core::BufferRecv() {
2083 DCHECK(OnNSSTaskRunner());
2085 if (transport_recv_busy_
)
2086 return ERR_IO_PENDING
;
2088 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2089 // determine how much data NSS wants to read. If NSS was not blocked,
2090 // this will return 0.
2091 int requested
= memio_GetReadRequest(nss_bufs_
);
2092 if (requested
== 0) {
2093 // This is not a perfect match of error codes, as no operation is
2094 // actually pending. However, returning 0 would be interpreted as a
2095 // possible sign of EOF, which is also an inappropriate match.
2096 return ERR_IO_PENDING
;
2100 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2103 // buffer too full to read into, so no I/O possible at moment
2104 rv
= ERR_IO_PENDING
;
2106 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
2107 if (OnNetworkTaskRunner()) {
2108 rv
= DoBufferRecv(read_buffer
.get(), nb
);
2110 bool posted
= network_task_runner_
->PostTask(
2112 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
2114 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2117 if (rv
== ERR_IO_PENDING
) {
2118 transport_recv_busy_
= true;
2121 memcpy(buf
, read_buffer
->data(), rv
);
2122 } else if (rv
== 0) {
2123 transport_recv_eof_
= true;
2125 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
2131 // Return 0 if nss_bufs_ was empty,
2132 // > 0 for bytes transferred immediately,
2133 // < 0 for error (or the non-error ERR_IO_PENDING).
2134 int SSLClientSocketNSS::Core::BufferSend() {
2135 DCHECK(OnNSSTaskRunner());
2137 if (transport_send_busy_
)
2138 return ERR_IO_PENDING
;
2142 unsigned int len1
, len2
;
2143 memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
);
2144 const unsigned int len
= len1
+ len2
;
2148 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
2149 memcpy(send_buffer
->data(), buf1
, len1
);
2150 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
2152 if (OnNetworkTaskRunner()) {
2153 rv
= DoBufferSend(send_buffer
.get(), len
);
2155 bool posted
= network_task_runner_
->PostTask(
2157 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
2159 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2162 if (rv
== ERR_IO_PENDING
) {
2163 transport_send_busy_
= true;
2165 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
2172 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
2173 DCHECK(OnNSSTaskRunner());
2175 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2176 OnHandshakeIOComplete(result
);
2180 // Network layer received some data, check if client requested to read
2182 if (!user_read_buf_
.get())
2185 int rv
= DoReadLoop(result
);
2186 if (rv
!= ERR_IO_PENDING
)
2190 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
2191 DCHECK(OnNSSTaskRunner());
2193 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2194 OnHandshakeIOComplete(result
);
2198 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2199 // handshake is in progress.
2200 int rv_read
= ERR_IO_PENDING
;
2201 int rv_write
= ERR_IO_PENDING
;
2204 if (user_read_buf_
.get())
2205 rv_read
= DoPayloadRead();
2206 if (user_write_buf_
.get())
2207 rv_write
= DoPayloadWrite();
2208 network_moved
= DoTransportIO();
2209 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
2210 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
2212 // If the parent SSLClientSocketNSS is deleted during the processing of the
2213 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2214 // will be detached (and possibly deleted). Guard against deletion by taking
2215 // an extra reference, then check if the Core was detached before invoking the
2217 scoped_refptr
<Core
> guard(this);
2218 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
2219 DoReadCallback(rv_read
);
2221 if (OnNetworkTaskRunner() && detached_
)
2224 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
2225 DoWriteCallback(rv_write
);
2228 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2229 // handshake. This requires network IO, which in turn calls
2230 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2231 // winds its way through the state machine and ends up being passed to the
2232 // callback. For Read() and Write(), that's what we want. But for Connect(),
2233 // the caller expects OK (i.e. 0) for success.
2234 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
2235 DCHECK(OnNSSTaskRunner());
2236 DCHECK_NE(rv
, ERR_IO_PENDING
);
2237 DCHECK(!user_connect_callback_
.is_null());
2239 base::Closure c
= base::Bind(
2240 base::ResetAndReturn(&user_connect_callback_
),
2242 PostOrRunCallback(FROM_HERE
, c
);
2245 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
2246 DCHECK(OnNSSTaskRunner());
2247 DCHECK_NE(ERR_IO_PENDING
, rv
);
2248 DCHECK(!user_read_callback_
.is_null());
2250 user_read_buf_
= NULL
;
2251 user_read_buf_len_
= 0;
2252 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2253 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2254 // the network task runner.
2257 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2260 base::Bind(&Core::DidNSSRead
, this, rv
));
2263 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
2266 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
2267 DCHECK(OnNSSTaskRunner());
2268 DCHECK_NE(ERR_IO_PENDING
, rv
);
2269 DCHECK(!user_write_callback_
.is_null());
2271 // Since Run may result in Write being called, clear |user_write_callback_|
2273 user_write_buf_
= NULL
;
2274 user_write_buf_len_
= 0;
2275 // Update buffer status because DoWriteLoop called DoTransportIO which may
2276 // perform read operations.
2277 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2278 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2279 // the network task runner.
2282 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2285 base::Bind(&Core::DidNSSWrite
, this, rv
));
2288 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
2291 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
2294 SECKEYPublicKey
**out_public_key
,
2295 SECKEYPrivateKey
**out_private_key
) {
2296 Core
* core
= reinterpret_cast<Core
*>(arg
);
2297 DCHECK(core
->OnNSSTaskRunner());
2299 core
->PostOrRunCallback(
2301 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
2302 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
2304 // We have negotiated the TLS channel ID extension.
2305 core
->channel_id_xtn_negotiated_
= true;
2306 std::string host
= core
->host_and_port_
.host();
2307 int error
= ERR_UNEXPECTED
;
2308 if (core
->OnNetworkTaskRunner()) {
2309 error
= core
->DoGetDomainBoundCert(host
);
2311 bool posted
= core
->network_task_runner_
->PostTask(
2314 IgnoreResult(&Core::DoGetDomainBoundCert
),
2316 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2319 if (error
== ERR_IO_PENDING
) {
2320 // Asynchronous case.
2321 core
->channel_id_needed_
= true;
2322 return SECWouldBlock
;
2325 core
->PostOrRunCallback(
2327 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
2328 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
2329 SECStatus rv
= SECSuccess
;
2331 // Synchronous success.
2332 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
2334 core
->SetChannelIDProvided();
2344 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
2345 SECKEYPrivateKey
** key
) {
2346 // Set the certificate.
2348 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
2349 cert_item
.len
= domain_bound_cert_
.size();
2350 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2356 return MapNSSError(PORT_GetError());
2358 // Set the private key.
2359 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2360 ServerBoundCertService::kEPKIPassword
,
2361 reinterpret_cast<const unsigned char*>(
2362 domain_bound_private_key_
.data()),
2363 domain_bound_private_key_
.size(),
2364 &cert
->subjectPublicKeyInfo
,
2369 int error
= MapNSSError(PORT_GetError());
2376 void SSLClientSocketNSS::Core::UpdateServerCert() {
2377 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2378 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2379 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2380 if (nss_handshake_state_
.server_cert
.get()) {
2381 // Since this will be called asynchronously on another thread, it needs to
2382 // own a reference to the certificate.
2383 NetLog::ParametersCallback net_log_callback
=
2384 base::Bind(&NetLogX509CertificateCallback
,
2385 nss_handshake_state_
.server_cert
);
2388 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2389 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2394 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2395 SSLChannelInfo channel_info
;
2396 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2397 &channel_info
, sizeof(channel_info
));
2398 if (ok
== SECSuccess
&&
2399 channel_info
.length
== sizeof(channel_info
) &&
2400 channel_info
.cipherSuite
) {
2401 nss_handshake_state_
.ssl_connection_status
|=
2402 (static_cast<int>(channel_info
.cipherSuite
) &
2403 SSL_CONNECTION_CIPHERSUITE_MASK
) <<
2404 SSL_CONNECTION_CIPHERSUITE_SHIFT
;
2406 nss_handshake_state_
.ssl_connection_status
|=
2407 (static_cast<int>(channel_info
.compressionMethod
) &
2408 SSL_CONNECTION_COMPRESSION_MASK
) <<
2409 SSL_CONNECTION_COMPRESSION_SHIFT
;
2411 // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
2412 // support it yet), so use 0x0303 directly.
2413 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2414 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2415 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2417 version
= SSL_CONNECTION_VERSION_SSL2
;
2418 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2419 version
= SSL_CONNECTION_VERSION_SSL3
;
2420 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_1_TLS
) {
2421 version
= SSL_CONNECTION_VERSION_TLS1
;
2422 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2423 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2424 } else if (channel_info
.protocolVersion
== 0x0303) {
2425 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2427 nss_handshake_state_
.ssl_connection_status
|=
2428 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2429 SSL_CONNECTION_VERSION_SHIFT
;
2432 PRBool peer_supports_renego_ext
;
2433 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2434 &peer_supports_renego_ext
);
2435 if (ok
== SECSuccess
) {
2436 if (!peer_supports_renego_ext
) {
2437 nss_handshake_state_
.ssl_connection_status
|=
2438 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2439 // Log an informational message if the server does not support secure
2440 // renegotiation (RFC 5746).
2441 VLOG(1) << "The server " << host_and_port_
.ToString()
2442 << " does not support the TLS renegotiation_info extension.";
2444 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2445 peer_supports_renego_ext
, 2);
2447 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2448 // because of security concerns. For example, Google offers forward
2449 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2450 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2453 // Yngve from Opera has suggested using the renegotiation extension as an
2454 // indicator that SSLv3 fallback was mistaken:
2455 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2457 // As a first step, measure how often clients perform version fallback
2458 // while the server advertises support secure renegotiation.
2459 if (ssl_config_
.version_fallback
&&
2460 channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2461 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2462 peer_supports_renego_ext
== PR_TRUE
);
2466 if (ssl_config_
.version_fallback
) {
2467 nss_handshake_state_
.ssl_connection_status
|=
2468 SSL_CONNECTION_VERSION_FALLBACK
;
2472 void SSLClientSocketNSS::Core::UpdateNextProto() {
2474 SSLNextProtoState state
;
2477 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2478 if (rv
!= SECSuccess
)
2481 nss_handshake_state_
.next_proto
=
2482 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2484 case SSL_NEXT_PROTO_NEGOTIATED
:
2485 case SSL_NEXT_PROTO_SELECTED
:
2486 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2488 case SSL_NEXT_PROTO_NO_OVERLAP
:
2489 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2491 case SSL_NEXT_PROTO_NO_SUPPORT
:
2492 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2500 void SSLClientSocketNSS::Core::RecordChannelIDSupport() {
2501 DCHECK(OnNSSTaskRunner());
2502 if (nss_handshake_state_
.resumed_handshake
)
2505 // Copy the NSS task runner-only state to the network task runner and
2506 // log histograms from there, since the histograms also need access to the
2507 // network task runner state.
2510 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2512 channel_id_xtn_negotiated_
,
2513 ssl_config_
.channel_id_enabled
,
2514 crypto::ECPrivateKey::IsSupported()));
2517 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2518 bool negotiated_channel_id
,
2519 bool channel_id_enabled
,
2520 bool supports_ecc
) const {
2521 DCHECK(OnNetworkTaskRunner());
2523 // Since this enum is used for a histogram, do not change or re-use values.
2527 CLIENT_AND_SERVER
= 2,
2529 CLIENT_BAD_SYSTEM_TIME
= 4,
2530 CLIENT_NO_SERVER_BOUND_CERT_SERVICE
= 5,
2531 DOMAIN_BOUND_CERT_USAGE_MAX
2532 } supported
= DISABLED
;
2533 if (negotiated_channel_id
) {
2534 supported
= CLIENT_AND_SERVER
;
2535 } else if (channel_id_enabled
) {
2536 if (!server_bound_cert_service_
)
2537 supported
= CLIENT_NO_SERVER_BOUND_CERT_SERVICE
;
2538 else if (!supports_ecc
)
2539 supported
= CLIENT_NO_ECC
;
2540 else if (!server_bound_cert_service_
->IsSystemTimeValid())
2541 supported
= CLIENT_BAD_SYSTEM_TIME
;
2543 supported
= CLIENT_ONLY
;
2545 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported
,
2546 DOMAIN_BOUND_CERT_USAGE_MAX
);
2549 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2550 DCHECK(OnNetworkTaskRunner());
2556 int rv
= transport_
->socket()->Read(
2558 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2559 scoped_refptr
<IOBuffer
>(read_buffer
)));
2561 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2562 nss_task_runner_
->PostTask(
2563 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2564 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2571 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2572 DCHECK(OnNetworkTaskRunner());
2578 int rv
= transport_
->socket()->Write(
2580 base::Bind(&Core::BufferSendComplete
,
2581 base::Unretained(this)));
2583 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2584 nss_task_runner_
->PostTask(
2586 base::Bind(&Core::BufferSendComplete
, this, rv
));
2593 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string
& host
) {
2594 DCHECK(OnNetworkTaskRunner());
2599 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2601 int rv
= server_bound_cert_service_
->GetDomainBoundCert(
2603 &domain_bound_private_key_
,
2604 &domain_bound_cert_
,
2605 base::Bind(&Core::OnGetDomainBoundCertComplete
, base::Unretained(this)),
2606 &domain_bound_cert_request_handle_
);
2608 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2609 nss_task_runner_
->PostTask(
2611 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2612 return ERR_IO_PENDING
;
2618 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2619 const HandshakeState
& state
) {
2620 DCHECK(OnNetworkTaskRunner());
2621 network_handshake_state_
= state
;
2624 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2625 DCHECK(OnNetworkTaskRunner());
2626 unhandled_buffer_size_
= amount_in_read_buffer
;
2629 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2630 DCHECK(OnNetworkTaskRunner());
2631 DCHECK(nss_waiting_read_
);
2632 nss_waiting_read_
= false;
2634 nss_is_closed_
= true;
2637 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2638 DCHECK(OnNetworkTaskRunner());
2639 DCHECK(nss_waiting_write_
);
2640 nss_waiting_write_
= false;
2642 nss_is_closed_
= true;
2645 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2646 if (!OnNSSTaskRunner()) {
2650 nss_task_runner_
->PostTask(
2651 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2655 DCHECK(OnNSSTaskRunner());
2657 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2658 transport_send_busy_
= false;
2659 OnSendComplete(result
);
2662 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2663 if (!OnNSSTaskRunner()) {
2667 nss_task_runner_
->PostTask(
2668 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2672 DCHECK(OnNSSTaskRunner());
2674 int rv
= DoHandshakeLoop(result
);
2675 if (rv
!= ERR_IO_PENDING
)
2676 DoConnectCallback(rv
);
2679 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result
) {
2680 DVLOG(1) << __FUNCTION__
<< " " << result
;
2681 DCHECK(OnNetworkTaskRunner());
2683 OnHandshakeIOComplete(result
);
2686 void SSLClientSocketNSS::Core::BufferRecvComplete(
2687 IOBuffer
* read_buffer
,
2689 DCHECK(read_buffer
);
2691 if (!OnNSSTaskRunner()) {
2695 nss_task_runner_
->PostTask(
2696 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2697 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2701 DCHECK(OnNSSTaskRunner());
2705 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2706 CHECK_GE(nb
, result
);
2707 memcpy(buf
, read_buffer
->data(), result
);
2708 } else if (result
== 0) {
2709 transport_recv_eof_
= true;
2712 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2713 transport_recv_busy_
= false;
2714 OnRecvComplete(result
);
2717 void SSLClientSocketNSS::Core::PostOrRunCallback(
2718 const tracked_objects::Location
& location
,
2719 const base::Closure
& task
) {
2720 if (!OnNetworkTaskRunner()) {
2721 network_task_runner_
->PostTask(
2723 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2727 if (detached_
|| task
.is_null())
2732 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2735 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2736 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2737 NetLog::IntegerCallback("cert_count", cert_count
)));
2740 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2742 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2743 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2744 nss_handshake_state_
.channel_id_sent
= true;
2745 // Update the network task runner's view of the handshake state now that
2746 // channel id has been sent.
2748 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2749 nss_handshake_state_
));
2752 SSLClientSocketNSS::SSLClientSocketNSS(
2753 base::SequencedTaskRunner
* nss_task_runner
,
2754 ClientSocketHandle
* transport_socket
,
2755 const HostPortPair
& host_and_port
,
2756 const SSLConfig
& ssl_config
,
2757 const SSLClientSocketContext
& context
)
2758 : nss_task_runner_(nss_task_runner
),
2759 transport_(transport_socket
),
2760 host_and_port_(host_and_port
),
2761 ssl_config_(ssl_config
),
2762 cert_verifier_(context
.cert_verifier
),
2763 server_bound_cert_service_(context
.server_bound_cert_service
),
2764 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2765 completed_handshake_(false),
2766 next_handshake_state_(STATE_NONE
),
2768 net_log_(transport_socket
->socket()->NetLog()),
2769 transport_security_state_(context
.transport_security_state
),
2770 valid_thread_id_(base::kInvalidThreadId
) {
2776 SSLClientSocketNSS::~SSLClientSocketNSS() {
2783 void SSLClientSocket::ClearSessionCache() {
2784 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2785 // bother initializing NSS just to clear an empty SSL session cache.
2786 if (!NSS_IsInitialized())
2789 SSL_ClearSessionCache();
2792 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2795 if (core_
->state().server_cert_chain
.empty() ||
2796 !core_
->state().server_cert_chain
[0]) {
2800 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2801 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2802 ssl_info
->connection_status
=
2803 core_
->state().ssl_connection_status
;
2804 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2805 for (HashValueVector::const_iterator i
= side_pinned_public_keys_
.begin();
2806 i
!= side_pinned_public_keys_
.end(); ++i
) {
2807 ssl_info
->public_key_hashes
.push_back(*i
);
2809 ssl_info
->is_issued_by_known_root
=
2810 server_cert_verify_result_
.is_issued_by_known_root
;
2811 ssl_info
->client_cert_sent
=
2812 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2813 ssl_info
->channel_id_sent
= WasChannelIDSent();
2815 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2816 core_
->state().ssl_connection_status
);
2817 SSLCipherSuiteInfo cipher_info
;
2818 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2819 &cipher_info
, sizeof(cipher_info
));
2820 if (ok
== SECSuccess
) {
2821 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2823 ssl_info
->security_bits
= -1;
2824 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2825 << " for cipherSuite " << cipher_suite
;
2828 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2829 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2835 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2836 SSLCertRequestInfo
* cert_request_info
) {
2838 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2839 cert_request_info
->host_and_port
= host_and_port_
.ToString();
2840 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2844 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2846 const base::StringPiece
& context
,
2848 unsigned int outlen
) {
2850 return ERR_SOCKET_NOT_CONNECTED
;
2852 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2853 // the midst of a handshake.
2854 SECStatus result
= SSL_ExportKeyingMaterial(
2855 nss_fd_
, label
.data(), label
.size(), has_context
,
2856 reinterpret_cast<const unsigned char*>(context
.data()),
2857 context
.length(), out
, outlen
);
2858 if (result
!= SECSuccess
) {
2859 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2860 return MapNSSError(PORT_GetError());
2865 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2867 return ERR_SOCKET_NOT_CONNECTED
;
2868 unsigned char buf
[64];
2870 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2871 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2872 buf
, &len
, arraysize(buf
));
2873 if (result
!= SECSuccess
) {
2874 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2875 return MapNSSError(PORT_GetError());
2877 out
->assign(reinterpret_cast<char*>(buf
), len
);
2881 SSLClientSocket::NextProtoStatus
2882 SSLClientSocketNSS::GetNextProto(std::string
* proto
,
2883 std::string
* server_protos
) {
2884 *proto
= core_
->state().next_proto
;
2885 *server_protos
= core_
->state().server_protos
;
2886 return core_
->state().next_proto_status
;
2889 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2891 DCHECK(transport_
.get());
2892 // It is an error to create an SSLClientSocket whose context has no
2893 // TransportSecurityState.
2894 DCHECK(transport_security_state_
);
2895 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2896 DCHECK(user_connect_callback_
.is_null());
2897 DCHECK(!callback
.is_null());
2899 EnsureThreadIdAssigned();
2901 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2905 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2909 rv
= InitializeSSLOptions();
2911 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2915 rv
= InitializeSSLPeerName();
2917 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2921 GotoState(STATE_HANDSHAKE
);
2923 rv
= DoHandshakeLoop(OK
);
2924 if (rv
== ERR_IO_PENDING
) {
2925 user_connect_callback_
= callback
;
2927 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2931 return rv
> OK
? OK
: rv
;
2934 void SSLClientSocketNSS::Disconnect() {
2937 CHECK(CalledOnValidThread());
2939 // Shut down anything that may call us back.
2942 transport_
->socket()->Disconnect();
2944 // Reset object state.
2945 user_connect_callback_
.Reset();
2946 server_cert_verify_result_
.Reset();
2947 completed_handshake_
= false;
2948 start_cert_verification_time_
= base::TimeTicks();
2954 bool SSLClientSocketNSS::IsConnected() const {
2956 bool ret
= completed_handshake_
&&
2957 (core_
->HasPendingAsyncOperation() ||
2958 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2959 transport_
->socket()->IsConnected());
2964 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2966 bool ret
= completed_handshake_
&&
2967 !core_
->HasPendingAsyncOperation() &&
2968 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2969 transport_
->socket()->IsConnectedAndIdle();
2974 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2975 return transport_
->socket()->GetPeerAddress(address
);
2978 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
2979 return transport_
->socket()->GetLocalAddress(address
);
2982 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
2986 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2987 if (transport_
.get() && transport_
->socket()) {
2988 transport_
->socket()->SetSubresourceSpeculation();
2994 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2995 if (transport_
.get() && transport_
->socket()) {
2996 transport_
->socket()->SetOmniboxSpeculation();
3002 bool SSLClientSocketNSS::WasEverUsed() const {
3003 if (transport_
.get() && transport_
->socket()) {
3004 return transport_
->socket()->WasEverUsed();
3010 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3011 if (transport_
.get() && transport_
->socket()) {
3012 return transport_
->socket()->UsingTCPFastOpen();
3018 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
3019 const CompletionCallback
& callback
) {
3020 DCHECK(core_
.get());
3021 DCHECK(!callback
.is_null());
3023 EnterFunction(buf_len
);
3024 int rv
= core_
->Read(buf
, buf_len
, callback
);
3030 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
3031 const CompletionCallback
& callback
) {
3032 DCHECK(core_
.get());
3033 DCHECK(!callback
.is_null());
3035 EnterFunction(buf_len
);
3036 int rv
= core_
->Write(buf
, buf_len
, callback
);
3042 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
3043 return transport_
->socket()->SetReceiveBufferSize(size
);
3046 bool SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
3047 return transport_
->socket()->SetSendBufferSize(size
);
3050 int SSLClientSocketNSS::Init() {
3052 // Initialize the NSS SSL library in a threadsafe way. This also
3053 // initializes the NSS base library.
3055 if (!NSS_IsInitialized())
3056 return ERR_UNEXPECTED
;
3057 #if defined(USE_NSS) || defined(OS_IOS)
3058 if (ssl_config_
.cert_io_enabled
) {
3059 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3060 // loop by MessageLoopForIO::current().
3061 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3062 EnsureNSSHttpIOInit();
3070 void SSLClientSocketNSS::InitCore() {
3071 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
3072 nss_task_runner_
.get(),
3077 server_bound_cert_service_
);
3080 int SSLClientSocketNSS::InitializeSSLOptions() {
3081 // Transport connected, now hook it up to nss
3082 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
3083 if (nss_fd_
== NULL
) {
3084 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
3087 // Grab pointer to buffers
3088 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
3090 /* Create SSL state machine */
3091 /* Push SSL onto our fake I/O socket */
3092 nss_fd_
= SSL_ImportFD(NULL
, nss_fd_
);
3093 if (nss_fd_
== NULL
) {
3094 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
3095 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
3097 // TODO(port): set more ssl options! Check errors!
3101 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
3102 if (rv
!= SECSuccess
) {
3103 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
3104 return ERR_UNEXPECTED
;
3107 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
3108 if (rv
!= SECSuccess
) {
3109 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3110 return ERR_UNEXPECTED
;
3113 // Don't do V2 compatible hellos because they don't support TLS extensions.
3114 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
3115 if (rv
!= SECSuccess
) {
3116 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3117 return ERR_UNEXPECTED
;
3120 SSLVersionRange version_range
;
3121 version_range
.min
= ssl_config_
.version_min
;
3122 version_range
.max
= ssl_config_
.version_max
;
3123 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
3124 if (rv
!= SECSuccess
) {
3125 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
3126 return ERR_NO_SSL_VERSIONS_ENABLED
;
3129 for (std::vector
<uint16
>::const_iterator it
=
3130 ssl_config_
.disabled_cipher_suites
.begin();
3131 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
3132 // This will fail if the specified cipher is not implemented by NSS, but
3133 // the failure is harmless.
3134 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
3138 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
3139 if (rv
!= SECSuccess
) {
3140 LogFailedNSSFunction(
3141 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3144 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
3145 ssl_config_
.false_start_enabled
);
3146 if (rv
!= SECSuccess
)
3147 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3149 // We allow servers to request renegotiation. Since we're a client,
3150 // prohibiting this is rather a waste of time. Only servers are in a
3151 // position to prevent renegotiation attacks.
3152 // http://extendedsubset.com/?p=8
3154 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
3155 SSL_RENEGOTIATE_TRANSITIONAL
);
3156 if (rv
!= SECSuccess
) {
3157 LogFailedNSSFunction(
3158 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3161 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
3162 if (rv
!= SECSuccess
)
3163 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3165 // Added in NSS 3.15
3166 #ifdef SSL_ENABLE_OCSP_STAPLING
3167 if (IsOCSPStaplingSupported()) {
3168 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, PR_TRUE
);
3169 if (rv
!= SECSuccess
) {
3170 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3171 "SSL_ENABLE_OCSP_STAPLING");
3176 // Chromium patch to libssl
3177 #ifdef SSL_ENABLE_CACHED_INFO
3178 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_CACHED_INFO
,
3179 ssl_config_
.cached_info_enabled
);
3180 if (rv
!= SECSuccess
)
3181 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3184 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
3185 if (rv
!= SECSuccess
) {
3186 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3187 return ERR_UNEXPECTED
;
3190 if (!core_
->Init(nss_fd_
, nss_bufs
))
3191 return ERR_UNEXPECTED
;
3193 // Tell SSL the hostname we're trying to connect to.
3194 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
3196 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3197 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
3202 int SSLClientSocketNSS::InitializeSSLPeerName() {
3203 // Tell NSS who we're connected to
3204 IPEndPoint peer_address
;
3205 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
3209 SockaddrStorage storage
;
3210 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
3211 return ERR_UNEXPECTED
;
3214 memset(&peername
, 0, sizeof(peername
));
3215 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
3216 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
3218 memcpy(&peername
, storage
.addr
, len
);
3220 // Adjust the address family field for BSD, whose sockaddr
3221 // structure has a one-byte length and one-byte address family
3222 // field at the beginning. PRNetAddr has a two-byte address
3223 // family field at the beginning.
3224 peername
.raw
.family
= storage
.addr
->sa_family
;
3226 memio_SetPeerName(nss_fd_
, &peername
);
3228 // Set the peer ID for session reuse. This is necessary when we create an
3229 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3230 // rather than the destination server's address in that case.
3231 std::string peer_id
= host_and_port_
.ToString();
3232 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3233 // This will cause session cache misses between sockets with different values
3234 // of ssl_session_cache_shard_ and this is used to partition the session cache
3235 // for incognito mode.
3236 if (!ssl_session_cache_shard_
.empty()) {
3237 peer_id
+= "/" + ssl_session_cache_shard_
;
3239 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
3240 if (rv
!= SECSuccess
)
3241 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
3246 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
3248 DCHECK_NE(ERR_IO_PENDING
, rv
);
3249 DCHECK(!user_connect_callback_
.is_null());
3251 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
3255 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
3256 EnterFunction(result
);
3257 int rv
= DoHandshakeLoop(result
);
3258 if (rv
!= ERR_IO_PENDING
) {
3259 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3260 DoConnectCallback(rv
);
3265 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
3266 EnterFunction(last_io_result
);
3267 int rv
= last_io_result
;
3269 // Default to STATE_NONE for next state.
3270 // (This is a quirk carried over from the windows
3271 // implementation. It makes reading the logs a bit harder.)
3272 // State handlers can and often do call GotoState just
3273 // to stay in the current state.
3274 State state
= next_handshake_state_
;
3275 GotoState(STATE_NONE
);
3277 case STATE_HANDSHAKE
:
3280 case STATE_HANDSHAKE_COMPLETE
:
3281 rv
= DoHandshakeComplete(rv
);
3283 case STATE_VERIFY_CERT
:
3285 rv
= DoVerifyCert(rv
);
3287 case STATE_VERIFY_CERT_COMPLETE
:
3288 rv
= DoVerifyCertComplete(rv
);
3292 rv
= ERR_UNEXPECTED
;
3293 LOG(DFATAL
) << "unexpected state " << state
;
3296 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3301 int SSLClientSocketNSS::DoHandshake() {
3303 int rv
= core_
->Connect(
3304 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3305 base::Unretained(this)));
3306 GotoState(STATE_HANDSHAKE_COMPLETE
);
3312 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3313 EnterFunction(result
);
3316 // SSL handshake is completed. Let's verify the certificate.
3317 GotoState(STATE_VERIFY_CERT
);
3320 set_channel_id_sent(core_
->state().channel_id_sent
);
3322 LeaveFunction(result
);
3327 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3328 DCHECK(!core_
->state().server_cert_chain
.empty());
3329 DCHECK(core_
->state().server_cert_chain
[0]);
3331 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3333 // If the certificate is expected to be bad we can use the expectation as
3335 base::StringPiece
der_cert(
3336 reinterpret_cast<char*>(
3337 core_
->state().server_cert_chain
[0]->derCert
.data
),
3338 core_
->state().server_cert_chain
[0]->derCert
.len
);
3339 CertStatus cert_status
;
3340 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3341 DCHECK(start_cert_verification_time_
.is_null());
3342 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3343 server_cert_verify_result_
.Reset();
3344 server_cert_verify_result_
.cert_status
= cert_status
;
3345 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3349 // We may have failed to create X509Certificate object if we are
3350 // running inside sandbox.
3351 if (!core_
->state().server_cert
.get()) {
3352 server_cert_verify_result_
.Reset();
3353 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3354 return ERR_CERT_INVALID
;
3357 start_cert_verification_time_
= base::TimeTicks::Now();
3360 if (ssl_config_
.rev_checking_enabled
)
3361 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3362 if (ssl_config_
.verify_ev_cert
)
3363 flags
|= CertVerifier::VERIFY_EV_CERT
;
3364 if (ssl_config_
.cert_io_enabled
)
3365 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3366 if (ssl_config_
.rev_checking_required_local_anchors
)
3367 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3368 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3369 return verifier_
->Verify(
3370 core_
->state().server_cert
.get(),
3371 host_and_port_
.host(),
3373 SSLConfigService::GetCRLSet().get(),
3374 &server_cert_verify_result_
,
3375 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3376 base::Unretained(this)),
3380 // Derived from AuthCertificateCallback() in
3381 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3382 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3385 if (!start_cert_verification_time_
.is_null()) {
3386 base::TimeDelta verify_time
=
3387 base::TimeTicks::Now() - start_cert_verification_time_
;
3389 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3391 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3394 // We used to remember the intermediate CA certs in the NSS database
3395 // persistently. However, NSS opens a connection to the SQLite database
3396 // during NSS initialization and doesn't close the connection until NSS
3397 // shuts down. If the file system where the database resides is gone,
3398 // the database connection goes bad. What's worse, the connection won't
3399 // recover when the file system comes back. Until this NSS or SQLite bug
3400 // is fixed, we need to avoid using the NSS database for non-essential
3401 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3402 // http://crbug.com/15630 for more info.
3404 // TODO(hclam): Skip logging if server cert was expected to be bad because
3405 // |server_cert_verify_result_| doesn't contain all the information about
3408 LogConnectionTypeMetrics();
3410 completed_handshake_
= true;
3412 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3413 // Take care of any mandates for public key pinning.
3415 // Pinning is only enabled for official builds to make sure that others don't
3416 // end up with pins that cannot be easily updated.
3418 // TODO(agl): We might have an issue here where a request for foo.example.com
3419 // merges into a SPDY connection to www.example.com, and gets a different
3422 // Perform pin validation if, and only if, all these conditions obtain:
3424 // * a TransportSecurityState object is available;
3425 // * the server's certificate chain is valid (or suffers from only a minor
3427 // * the server's certificate chain chains up to a known root (i.e. not a
3428 // user-installed trust anchor); and
3429 // * the build is recent (very old builds should fail open so that users
3430 // have some chance to recover).
3432 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3433 if (transport_security_state_
&&
3435 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3436 server_cert_verify_result_
.is_issued_by_known_root
&&
3437 TransportSecurityState::IsBuildTimely()) {
3438 bool sni_available
=
3439 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
||
3440 ssl_config_
.version_fallback
;
3441 const std::string
& host
= host_and_port_
.host();
3443 TransportSecurityState::DomainState domain_state
;
3444 if (transport_security_state_
->GetDomainState(host
, sni_available
,
3446 domain_state
.HasPublicKeyPins()) {
3447 if (!domain_state
.CheckPublicKeyPins(
3448 server_cert_verify_result_
.public_key_hashes
)) {
3449 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3450 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3451 TransportSecurityState::ReportUMAOnPinFailure(host
);
3453 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3459 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3460 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3464 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3465 UpdateConnectionTypeHistograms(CONNECTION_SSL
);
3466 int ssl_version
= SSLConnectionStatusToVersion(
3467 core_
->state().ssl_connection_status
);
3468 switch (ssl_version
) {
3469 case SSL_CONNECTION_VERSION_SSL2
:
3470 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2
);
3472 case SSL_CONNECTION_VERSION_SSL3
:
3473 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3
);
3475 case SSL_CONNECTION_VERSION_TLS1
:
3476 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1
);
3478 case SSL_CONNECTION_VERSION_TLS1_1
:
3479 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1
);
3481 case SSL_CONNECTION_VERSION_TLS1_2
:
3482 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2
);
3487 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3488 base::AutoLock
auto_lock(lock_
);
3489 if (valid_thread_id_
!= base::kInvalidThreadId
)
3491 valid_thread_id_
= base::PlatformThread::CurrentId();
3494 bool SSLClientSocketNSS::CalledOnValidThread() const {
3495 EnsureThreadIdAssigned();
3496 base::AutoLock
auto_lock(lock_
);
3497 return valid_thread_id_
== base::PlatformThread::CurrentId();
3500 ServerBoundCertService
* SSLClientSocketNSS::GetServerBoundCertService() const {
3501 return server_bound_cert_service_
;