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 CERTCertList
* list
= SSL_PeerCertificateChain(nss_fd
);
384 // The handshake on |nss_fd| may not have completed.
388 for (CERTCertListNode
* node
= CERT_LIST_HEAD(list
);
389 !CERT_LIST_END(node
, list
); node
= CERT_LIST_NEXT(node
)) {
390 certs_
.push_back(CERT_DupCertificate(node
->cert
));
392 CERT_DestroyCertList(list
);
395 std::vector
<base::StringPiece
>
396 PeerCertificateChain::AsStringPieceVector() const {
397 std::vector
<base::StringPiece
> v(certs_
.size());
398 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
399 v
[i
] = base::StringPiece(
400 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
401 certs_
[i
]->derCert
.len
);
407 // HandshakeState is a helper struct used to pass handshake state between
408 // the NSS task runner and the network task runner.
410 // It contains members that may be read or written on the NSS task runner,
411 // but which also need to be read from the network task runner. The NSS task
412 // runner will notify the network task runner whenever this state changes, so
413 // that the network task runner can safely make a copy, which avoids the need
415 struct HandshakeState
{
416 HandshakeState() { Reset(); }
419 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
421 server_protos
.clear();
422 channel_id_sent
= false;
423 server_cert_chain
.Reset(NULL
);
425 resumed_handshake
= false;
426 ssl_connection_status
= 0;
429 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
430 // negotiated protocol stored in |next_proto|.
431 SSLClientSocket::NextProtoStatus next_proto_status
;
432 std::string next_proto
;
433 // If the server supports NPN, the protocols supported by the server.
434 std::string server_protos
;
436 // True if a channel ID was sent.
437 bool channel_id_sent
;
439 // List of DER-encoded X.509 DistinguishedName of certificate authorities
440 // allowed by the server.
441 std::vector
<std::string
> cert_authorities
;
443 // Set when the handshake fully completes.
445 // The server certificate is first received from NSS as an NSS certificate
446 // chain (|server_cert_chain|) and then converted into a platform-specific
447 // X509Certificate object (|server_cert|). It's possible for some
448 // certificates to be successfully parsed by NSS, and not by the platform
449 // libraries (i.e.: when running within a sandbox, different parsing
450 // algorithms, etc), so it's not safe to assume that |server_cert| will
451 // always be non-NULL.
452 PeerCertificateChain server_cert_chain
;
453 scoped_refptr
<X509Certificate
> server_cert
;
455 // True if the current handshake was the result of TLS session resumption.
456 bool resumed_handshake
;
458 // The negotiated security parameters (TLS version, cipher, extensions) of
459 // the SSL connection.
460 int ssl_connection_status
;
463 // Client-side error mapping functions.
465 // Map NSS error code to network error code.
466 int MapNSSClientError(PRErrorCode err
) {
468 case SSL_ERROR_BAD_CERT_ALERT
:
469 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
470 case SSL_ERROR_REVOKED_CERT_ALERT
:
471 case SSL_ERROR_EXPIRED_CERT_ALERT
:
472 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
473 case SSL_ERROR_UNKNOWN_CA_ALERT
:
474 case SSL_ERROR_ACCESS_DENIED_ALERT
:
475 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
477 return MapNSSError(err
);
481 // Map NSS error code from the first SSL handshake to network error code.
482 int MapNSSClientHandshakeError(PRErrorCode err
) {
484 // If the server closed on us, it is a protocol error.
485 // Some TLS-intolerant servers do this when we request TLS.
486 case PR_END_OF_FILE_ERROR
:
487 return ERR_SSL_PROTOCOL_ERROR
;
489 return MapNSSClientError(err
);
495 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
496 // able to marshal data between NSS functions and an underlying transport
499 // All public functions are meant to be called from the network task runner,
500 // and any callbacks supplied will be invoked there as well, provided that
501 // Detach() has not been called yet.
503 /////////////////////////////////////////////////////////////////////////////
505 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
507 // Because NSS may block on either hardware or user input during operations
508 // such as signing, creating certificates, or locating private keys, the Core
509 // handles all of the interactions with the underlying NSS SSL socket, so
510 // that these blocking calls can be executed on a dedicated task runner.
512 // Note that the network task runner and the NSS task runner may be executing
513 // on the same thread. If that happens, then it's more performant to try to
514 // complete as much work as possible synchronously, even if it might block,
515 // rather than continually PostTask-ing to the same thread.
517 // Because NSS functions should only be called on the NSS task runner, while
518 // I/O resources should only be accessed on the network task runner, most
519 // public functions are implemented via three methods, each with different
520 // task runner affinities.
522 // In the single-threaded mode (where the network and NSS task runners run on
523 // the same thread), these are all attempted synchronously, while in the
524 // multi-threaded mode, message passing is used.
526 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
528 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
529 // (BufferRecv, BufferSend)
530 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
531 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
532 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
533 // data from the network task runner back to NSS (BufferRecvComplete,
534 // BufferSendComplete, OnHandshakeIOComplete)
536 /////////////////////////////////////////////////////////////////////////////
537 // Single-threaded example
539 // |--------------------------Network Task Runner--------------------------|
540 // SSLClientSocketNSS Core (Transport Socket)
542 // |-------------------------V
550 // |-------------------------V
552 // V-------------------------|
553 // BufferRecvComplete()
555 // PostOrRunCallback()
556 // V-------------------------|
559 /////////////////////////////////////////////////////////////////////////////
560 // Multi-threaded example:
562 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
563 // SSLClientSocketNSS Core Socket Core
565 // |---------------------V
567 // |-------------------------------V
573 // V-------------------------------|
575 // |----------------V
577 // V----------------|
578 // BufferRecvComplete()
579 // |-------------------------------V
580 // BufferRecvComplete()
582 // PostOrRunCallback()
583 // V-------------------------------|
584 // PostOrRunCallback()
585 // V---------------------|
588 /////////////////////////////////////////////////////////////////////////////
589 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
591 // Creates a new Core.
593 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
594 // that need to operate on the underlying transport, net log, or server
595 // bound certificate fetching will happen on the |network_task_runner|, so
596 // that their lifetimes match that of the owning SSLClientSocketNSS.
598 // The caller retains ownership of |transport|, |net_log|, and
599 // |server_bound_cert_service|, and they will not be accessed once Detach()
601 Core(base::SequencedTaskRunner
* network_task_runner
,
602 base::SequencedTaskRunner
* nss_task_runner
,
603 ClientSocketHandle
* transport
,
604 const HostPortPair
& host_and_port
,
605 const SSLConfig
& ssl_config
,
606 BoundNetLog
* net_log
,
607 ServerBoundCertService
* server_bound_cert_service
);
609 // Called on the network task runner.
610 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
611 // underlying memio implementation, to the Core. Returns true if the Core
612 // was successfully registered with the socket.
613 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
615 // Called on the network task runner.
616 // Sets the predicted certificate chain that the peer will send, for use
617 // with the TLS CachedInfo extension. If called, it must not be called
618 // before Init() or after Connect().
619 void SetPredictedCertificates(
620 const std::vector
<std::string
>& predicted_certificates
);
622 // Called on the network task runner.
624 // Attempts to perform an SSL handshake. If the handshake cannot be
625 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
626 // the network task runner once the handshake has completed. Otherwise,
627 // returns OK on success or a network error code on failure.
628 int Connect(const CompletionCallback
& callback
);
630 // Called on the network task runner.
631 // Signals that the resources owned by the network task runner are going
632 // away. No further callbacks will be invoked on the network task runner.
633 // May be called at any time.
636 // Called on the network task runner.
637 // Returns the current state of the underlying SSL socket. May be called at
639 const HandshakeState
& state() const { return network_handshake_state_
; }
641 // Called on the network task runner.
642 // Read() and Write() mirror the net::Socket functions of the same name.
643 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
644 // task runner at a later point, unless the caller calls Detach().
645 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
646 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
648 // Called on the network task runner.
650 bool HasPendingAsyncOperation();
651 bool HasUnhandledReceivedData();
654 friend class base::RefCountedThreadSafe
<Core
>;
660 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
663 bool OnNSSTaskRunner() const;
664 bool OnNetworkTaskRunner() const;
666 ////////////////////////////////////////////////////////////////////////////
667 // Methods that are ONLY called on the NSS task runner:
668 ////////////////////////////////////////////////////////////////////////////
670 // Called by NSS during full handshakes to allow the application to
671 // verify the certificate. Instead of verifying the certificate in the midst
672 // of the handshake, SECSuccess is always returned and the peer's certificate
673 // is verified afterwards.
674 // This behaviour is an artifact of the original SSLClientSocketWin
675 // implementation, which could not verify the peer's certificate until after
676 // the handshake had completed, as well as bugs in NSS that prevent
677 // SSL_RestartHandshakeAfterCertReq from working.
678 static SECStatus
OwnAuthCertHandler(void* arg
,
683 // Callbacks called by NSS when the peer requests client certificate
685 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
687 #if defined(NSS_PLATFORM_CLIENT_AUTH)
688 // When NSS has been integrated with awareness of the underlying system
689 // cryptographic libraries, this callback allows the caller to supply a
690 // native platform certificate and key for use by NSS. At most, one of
691 // either (result_certs, result_private_key) or (result_nss_certificate,
692 // result_nss_private_key) should be set.
693 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
694 static SECStatus
PlatformClientAuthHandler(
697 CERTDistNames
* ca_names
,
698 CERTCertList
** result_certs
,
699 void** result_private_key
,
700 CERTCertificate
** result_nss_certificate
,
701 SECKEYPrivateKey
** result_nss_private_key
);
703 static SECStatus
ClientAuthHandler(void* arg
,
705 CERTDistNames
* ca_names
,
706 CERTCertificate
** result_certificate
,
707 SECKEYPrivateKey
** result_private_key
);
710 // Called by NSS once the handshake has completed.
711 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
712 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
714 // Handles an NSS error generated while handshaking or performing IO.
715 // Returns a network error code mapped from the original NSS error.
716 int HandleNSSError(PRErrorCode error
, bool handshake_error
);
718 int DoHandshakeLoop(int last_io_result
);
719 int DoReadLoop(int result
);
720 int DoWriteLoop(int result
);
723 int DoGetDBCertComplete(int result
);
726 int DoPayloadWrite();
728 bool DoTransportIO();
732 void OnRecvComplete(int result
);
733 void OnSendComplete(int result
);
735 void DoConnectCallback(int result
);
736 void DoReadCallback(int result
);
737 void DoWriteCallback(int result
);
739 // Client channel ID handler.
740 static SECStatus
ClientChannelIDHandler(
743 SECKEYPublicKey
**out_public_key
,
744 SECKEYPrivateKey
**out_private_key
);
746 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
747 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
748 // and an error code otherwise.
749 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
750 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
751 // takes ownership of the |*cert| and |*key|.
752 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
754 // Updates the NSS and platform specific certificates.
755 void UpdateServerCert();
756 // Updates the nss_handshake_state_ with the negotiated security parameters.
757 void UpdateConnectionStatus();
758 // Record histograms for channel id support during full handshakes - resumed
759 // handshakes are ignored.
760 void RecordChannelIDSupportOnNSSTaskRunner();
761 // UpdateNextProto gets any application-layer protocol that may have been
762 // negotiated by the TLS connection.
763 void UpdateNextProto();
765 ////////////////////////////////////////////////////////////////////////////
766 // Methods that are ONLY called on the network task runner:
767 ////////////////////////////////////////////////////////////////////////////
768 int DoBufferRecv(IOBuffer
* buffer
, int len
);
769 int DoBufferSend(IOBuffer
* buffer
, int len
);
770 int DoGetDomainBoundCert(const std::string
& host
);
772 void OnGetDomainBoundCertComplete(int result
);
773 void OnHandshakeStateUpdated(const HandshakeState
& state
);
774 void OnNSSBufferUpdated(int amount_in_read_buffer
);
775 void DidNSSRead(int result
);
776 void DidNSSWrite(int result
);
777 void RecordChannelIDSupportOnNetworkTaskRunner(
778 bool negotiated_channel_id
,
779 bool channel_id_enabled
,
780 bool supports_ecc
) const;
782 ////////////////////////////////////////////////////////////////////////////
783 // Methods that are called on both the network task runner and the NSS
785 ////////////////////////////////////////////////////////////////////////////
786 void OnHandshakeIOComplete(int result
);
787 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
788 void BufferSendComplete(int result
);
790 // PostOrRunCallback is a helper function to ensure that |callback| is
791 // invoked on the network task runner, but only if Detach() has not yet
793 void PostOrRunCallback(const tracked_objects::Location
& location
,
794 const base::Closure
& callback
);
796 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
797 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
798 void AddCertProvidedEvent(int cert_count
);
800 // Sets the handshake state |channel_id_sent| flag and logs the
801 // SSL_CHANNEL_ID_PROVIDED event.
802 void SetChannelIDProvided();
804 ////////////////////////////////////////////////////////////////////////////
805 // Members that are ONLY accessed on the network task runner:
806 ////////////////////////////////////////////////////////////////////////////
808 // True if the owning SSLClientSocketNSS has called Detach(). No further
809 // callbacks will be invoked nor access to members owned by the network
813 // The underlying transport to use for network IO.
814 ClientSocketHandle
* transport_
;
815 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
817 // The current handshake state. Mirrors |nss_handshake_state_|.
818 HandshakeState network_handshake_state_
;
820 // The service for retrieving Channel ID keys. May be NULL.
821 ServerBoundCertService
* server_bound_cert_service_
;
822 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_
;
824 // The information about NSS task runner.
825 int unhandled_buffer_size_
;
826 bool nss_waiting_read_
;
827 bool nss_waiting_write_
;
830 ////////////////////////////////////////////////////////////////////////////
831 // Members that are ONLY accessed on the NSS task runner:
832 ////////////////////////////////////////////////////////////////////////////
833 HostPortPair host_and_port_
;
834 SSLConfig ssl_config_
;
839 // Buffers for the network end of the SSL state machine
840 memio_Private
* nss_bufs_
;
842 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
843 // as much data as possible, without blocking.
844 // If DoPayloadRead() encounters an error after having read some data, stores
845 // the results to return on the *next* call to DoPayloadRead(). A value of
846 // kNoPendingReadResult indicates there is no pending result, otherwise 0
847 // indicates EOF and < 0 indicates an error.
848 int pending_read_result_
;
849 // Contains the previously observed NSS error. Only valid when
850 // pending_read_result_ != kNoPendingReadResult.
851 PRErrorCode pending_read_nss_error_
;
853 // The certificate chain, in DER form, that is expected to be received from
855 std::vector
<std::string
> predicted_certs_
;
857 State next_handshake_state_
;
859 // True if channel ID extension was negotiated.
860 bool channel_id_xtn_negotiated_
;
861 // True if the handshake state machine was interrupted for channel ID.
862 bool channel_id_needed_
;
863 // True if the handshake state machine was interrupted for client auth.
864 bool client_auth_cert_needed_
;
865 // True if NSS has called HandshakeCallback.
866 bool handshake_callback_called_
;
868 HandshakeState nss_handshake_state_
;
870 bool transport_recv_busy_
;
871 bool transport_recv_eof_
;
872 bool transport_send_busy_
;
874 // Used by Read function.
875 scoped_refptr
<IOBuffer
> user_read_buf_
;
876 int user_read_buf_len_
;
878 // Used by Write function.
879 scoped_refptr
<IOBuffer
> user_write_buf_
;
880 int user_write_buf_len_
;
882 CompletionCallback user_connect_callback_
;
883 CompletionCallback user_read_callback_
;
884 CompletionCallback user_write_callback_
;
886 ////////////////////////////////////////////////////////////////////////////
887 // Members that are accessed on both the network task runner and the NSS
889 ////////////////////////////////////////////////////////////////////////////
890 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
891 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
893 // Dereferenced only on the network task runner, but bound to tasks destined
894 // for the network task runner from the NSS task runner.
895 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
897 // Written on the network task runner by the |server_bound_cert_service_|,
898 // prior to invoking OnHandshakeIOComplete.
899 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
900 // on the NSS task runner.
901 std::string domain_bound_private_key_
;
902 std::string domain_bound_cert_
;
904 DISALLOW_COPY_AND_ASSIGN(Core
);
907 SSLClientSocketNSS::Core::Core(
908 base::SequencedTaskRunner
* network_task_runner
,
909 base::SequencedTaskRunner
* nss_task_runner
,
910 ClientSocketHandle
* transport
,
911 const HostPortPair
& host_and_port
,
912 const SSLConfig
& ssl_config
,
913 BoundNetLog
* net_log
,
914 ServerBoundCertService
* server_bound_cert_service
)
916 transport_(transport
),
917 weak_net_log_factory_(net_log
),
918 server_bound_cert_service_(server_bound_cert_service
),
919 unhandled_buffer_size_(0),
920 nss_waiting_read_(false),
921 nss_waiting_write_(false),
922 nss_is_closed_(false),
923 host_and_port_(host_and_port
),
924 ssl_config_(ssl_config
),
927 pending_read_result_(kNoPendingReadResult
),
928 pending_read_nss_error_(0),
929 next_handshake_state_(STATE_NONE
),
930 channel_id_xtn_negotiated_(false),
931 channel_id_needed_(false),
932 client_auth_cert_needed_(false),
933 handshake_callback_called_(false),
934 transport_recv_busy_(false),
935 transport_recv_eof_(false),
936 transport_send_busy_(false),
937 user_read_buf_len_(0),
938 user_write_buf_len_(0),
939 network_task_runner_(network_task_runner
),
940 nss_task_runner_(nss_task_runner
),
941 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
944 SSLClientSocketNSS::Core::~Core() {
945 // TODO(wtc): Send SSL close_notify alert.
946 if (nss_fd_
!= NULL
) {
952 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
953 memio_Private
* buffers
) {
954 DCHECK(OnNetworkTaskRunner());
961 SECStatus rv
= SECSuccess
;
963 if (!ssl_config_
.next_protos
.empty()) {
964 size_t wire_length
= 0;
965 for (std::vector
<std::string
>::const_iterator
966 i
= ssl_config_
.next_protos
.begin();
967 i
!= ssl_config_
.next_protos
.end(); ++i
) {
968 if (i
->size() > 255) {
969 LOG(WARNING
) << "Ignoring overlong NPN/ALPN protocol: " << *i
;
972 wire_length
+= i
->size();
975 scoped_ptr
<uint8
[]> wire_protos(new uint8
[wire_length
]);
976 uint8
* dst
= wire_protos
.get();
977 for (std::vector
<std::string
>::const_iterator
978 i
= ssl_config_
.next_protos
.begin();
979 i
!= ssl_config_
.next_protos
.end(); i
++) {
983 memcpy(dst
, i
->data(), i
->size());
986 DCHECK_EQ(dst
, wire_protos
.get() + wire_length
);
987 rv
= SSL_SetNextProtoNego(nss_fd_
, wire_protos
.get(), wire_length
);
988 if (rv
!= SECSuccess
)
989 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoCallback", "");
992 rv
= SSL_AuthCertificateHook(
993 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
994 if (rv
!= SECSuccess
) {
995 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
999 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1000 rv
= SSL_GetPlatformClientAuthDataHook(
1001 nss_fd_
, SSLClientSocketNSS::Core::PlatformClientAuthHandler
,
1004 rv
= SSL_GetClientAuthDataHook(
1005 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
1007 if (rv
!= SECSuccess
) {
1008 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
1012 if (IsChannelIDEnabled(ssl_config_
, server_bound_cert_service_
)) {
1013 rv
= SSL_SetClientChannelIDCallback(
1014 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
1015 if (rv
!= SECSuccess
) {
1016 LogFailedNSSFunction(
1017 *weak_net_log_
, "SSL_SetClientChannelIDCallback", "");
1021 rv
= SSL_HandshakeCallback(
1022 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
1023 if (rv
!= SECSuccess
) {
1024 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
1031 void SSLClientSocketNSS::Core::SetPredictedCertificates(
1032 const std::vector
<std::string
>& predicted_certs
) {
1033 if (predicted_certs
.empty())
1036 if (!OnNSSTaskRunner()) {
1038 nss_task_runner_
->PostTask(
1040 base::Bind(&Core::SetPredictedCertificates
, this, predicted_certs
));
1046 predicted_certs_
= predicted_certs
;
1048 scoped_ptr
<CERTCertificate
*[]> certs(
1049 new CERTCertificate
*[predicted_certs
.size()]);
1051 for (size_t i
= 0; i
< predicted_certs
.size(); i
++) {
1053 derCert
.data
= const_cast<uint8
*>(reinterpret_cast<const uint8
*>(
1054 predicted_certs
[i
].data()));
1055 derCert
.len
= predicted_certs
[i
].size();
1056 certs
[i
] = CERT_NewTempCertificate(
1057 CERT_GetDefaultCertDB(), &derCert
, NULL
/* no nickname given */,
1058 PR_FALSE
/* not permanent */, PR_TRUE
/* copy DER data */);
1060 DestroyCertificates(&certs
[0], i
);
1067 #ifdef SSL_ENABLE_CACHED_INFO
1068 rv
= SSL_SetPredictedPeerCertificates(nss_fd_
, certs
.get(),
1069 predicted_certs
.size());
1070 DCHECK_EQ(SECSuccess
, rv
);
1072 rv
= SECFailure
; // Not implemented.
1074 DestroyCertificates(&certs
[0], predicted_certs
.size());
1076 if (rv
!= SECSuccess
) {
1077 LOG(WARNING
) << "SetPredictedCertificates failed: "
1078 << host_and_port_
.ToString();
1082 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
1083 if (!OnNSSTaskRunner()) {
1085 bool posted
= nss_task_runner_
->PostTask(
1087 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
1088 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1091 DCHECK(OnNSSTaskRunner());
1092 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1093 DCHECK(user_read_callback_
.is_null());
1094 DCHECK(user_write_callback_
.is_null());
1095 DCHECK(user_connect_callback_
.is_null());
1096 DCHECK(!user_read_buf_
.get());
1097 DCHECK(!user_write_buf_
.get());
1099 next_handshake_state_
= STATE_HANDSHAKE
;
1100 int rv
= DoHandshakeLoop(OK
);
1101 if (rv
== ERR_IO_PENDING
) {
1102 user_connect_callback_
= callback
;
1103 } else if (rv
> OK
) {
1106 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
1107 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1108 return ERR_IO_PENDING
;
1114 void SSLClientSocketNSS::Core::Detach() {
1115 DCHECK(OnNetworkTaskRunner());
1119 weak_net_log_factory_
.InvalidateWeakPtrs();
1121 network_handshake_state_
.Reset();
1123 domain_bound_cert_request_handle_
.Cancel();
1126 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1127 const CompletionCallback
& callback
) {
1128 if (!OnNSSTaskRunner()) {
1129 DCHECK(OnNetworkTaskRunner());
1132 DCHECK(!nss_waiting_read_
);
1134 nss_waiting_read_
= true;
1135 bool posted
= nss_task_runner_
->PostTask(
1137 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1138 buf_len
, callback
));
1140 nss_is_closed_
= true;
1141 nss_waiting_read_
= false;
1143 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1146 DCHECK(OnNSSTaskRunner());
1147 DCHECK(handshake_callback_called_
);
1148 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1149 DCHECK(user_read_callback_
.is_null());
1150 DCHECK(user_connect_callback_
.is_null());
1151 DCHECK(!user_read_buf_
.get());
1154 user_read_buf_
= buf
;
1155 user_read_buf_len_
= buf_len
;
1157 int rv
= DoReadLoop(OK
);
1158 if (rv
== ERR_IO_PENDING
) {
1159 if (OnNetworkTaskRunner())
1160 nss_waiting_read_
= true;
1161 user_read_callback_
= callback
;
1163 user_read_buf_
= NULL
;
1164 user_read_buf_len_
= 0;
1166 if (!OnNetworkTaskRunner()) {
1167 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1168 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1169 return ERR_IO_PENDING
;
1171 DCHECK(!nss_waiting_read_
);
1173 nss_is_closed_
= true;
1180 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1181 const CompletionCallback
& callback
) {
1182 if (!OnNSSTaskRunner()) {
1183 DCHECK(OnNetworkTaskRunner());
1186 DCHECK(!nss_waiting_write_
);
1188 nss_waiting_write_
= true;
1189 bool posted
= nss_task_runner_
->PostTask(
1191 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1192 buf_len
, callback
));
1194 nss_is_closed_
= true;
1195 nss_waiting_write_
= false;
1197 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1200 DCHECK(OnNSSTaskRunner());
1201 DCHECK(handshake_callback_called_
);
1202 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1203 DCHECK(user_write_callback_
.is_null());
1204 DCHECK(user_connect_callback_
.is_null());
1205 DCHECK(!user_write_buf_
.get());
1208 user_write_buf_
= buf
;
1209 user_write_buf_len_
= buf_len
;
1211 int rv
= DoWriteLoop(OK
);
1212 if (rv
== ERR_IO_PENDING
) {
1213 if (OnNetworkTaskRunner())
1214 nss_waiting_write_
= true;
1215 user_write_callback_
= callback
;
1217 user_write_buf_
= NULL
;
1218 user_write_buf_len_
= 0;
1220 if (!OnNetworkTaskRunner()) {
1221 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1222 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1223 return ERR_IO_PENDING
;
1225 DCHECK(!nss_waiting_write_
);
1227 nss_is_closed_
= true;
1234 bool SSLClientSocketNSS::Core::IsConnected() {
1235 DCHECK(OnNetworkTaskRunner());
1236 return !nss_is_closed_
;
1239 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
1240 DCHECK(OnNetworkTaskRunner());
1241 return nss_waiting_read_
|| nss_waiting_write_
;
1244 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
1245 DCHECK(OnNetworkTaskRunner());
1246 return unhandled_buffer_size_
!= 0;
1249 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1250 return nss_task_runner_
->RunsTasksOnCurrentThread();
1253 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1254 return network_task_runner_
->RunsTasksOnCurrentThread();
1258 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1263 Core
* core
= reinterpret_cast<Core
*>(arg
);
1264 if (!core
->handshake_callback_called_
) {
1265 // Only need to turn off False Start in the initial handshake. Also, it is
1266 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1267 // handshake" lock isn't already held, which will result in an assertion
1268 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1269 PRBool negotiated_extension
;
1270 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1271 ssl_app_layer_protocol_xtn
,
1272 &negotiated_extension
);
1273 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1274 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1275 ssl_next_proto_nego_xtn
,
1276 &negotiated_extension
);
1278 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1279 // If the server doesn't support NPN or ALPN, then we don't do False
1281 SSL_OptionSet(socket
, SSL_ENABLE_FALSE_START
, PR_FALSE
);
1284 // Disallow the server certificate to change in a renegotiation.
1285 CERTCertificate
* old_cert
= core
->nss_handshake_state_
.server_cert_chain
[0];
1286 CERTCertificate
* new_cert
= SSL_PeerCertificate(socket
);
1287 if (new_cert
->derCert
.len
!= old_cert
->derCert
.len
||
1288 memcmp(new_cert
->derCert
.data
, old_cert
->derCert
.data
,
1289 new_cert
->derCert
.len
) != 0) {
1290 // NSS doesn't have an error code that indicates the server certificate
1291 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1292 // for this purpose.
1293 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE
);
1298 // Tell NSS to not verify the certificate.
1302 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1304 SECStatus
SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1307 CERTDistNames
* ca_names
,
1308 CERTCertList
** result_certs
,
1309 void** result_private_key
,
1310 CERTCertificate
** result_nss_certificate
,
1311 SECKEYPrivateKey
** result_nss_private_key
) {
1312 Core
* core
= reinterpret_cast<Core
*>(arg
);
1313 DCHECK(core
->OnNSSTaskRunner());
1315 core
->PostOrRunCallback(
1317 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1318 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1320 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1322 if (core
->ssl_config_
.send_client_cert
) {
1323 if (core
->ssl_config_
.client_cert
) {
1324 PCCERT_CONTEXT cert_context
=
1325 core
->ssl_config_
.client_cert
->os_cert_handle();
1327 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
1329 BOOL must_free
= FALSE
;
1331 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
1332 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
1334 BOOL acquired_key
= CryptAcquireCertificatePrivateKey(
1335 cert_context
, flags
, NULL
, &crypt_prov
, &key_spec
, &must_free
);
1338 // Should never get a cached handle back - ownership must always be
1340 CHECK_EQ(must_free
, TRUE
);
1343 der_cert
.type
= siDERCertBuffer
;
1344 der_cert
.data
= cert_context
->pbCertEncoded
;
1345 der_cert
.len
= cert_context
->cbCertEncoded
;
1347 // TODO(rsleevi): Error checking for NSS allocation errors.
1348 CERTCertDBHandle
* db_handle
= CERT_GetDefaultCertDB();
1349 CERTCertificate
* user_cert
= CERT_NewTempCertificate(
1350 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1352 // Importing the certificate can fail for reasons including a serial
1353 // number collision. See crbug.com/97355.
1354 core
->AddCertProvidedEvent(0);
1357 CERTCertList
* cert_chain
= CERT_NewCertList();
1358 CERT_AddCertToListTail(cert_chain
, user_cert
);
1360 // Add the intermediates.
1361 X509Certificate::OSCertHandles intermediates
=
1362 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1363 for (X509Certificate::OSCertHandles::const_iterator it
=
1364 intermediates
.begin(); it
!= intermediates
.end(); ++it
) {
1365 der_cert
.data
= (*it
)->pbCertEncoded
;
1366 der_cert
.len
= (*it
)->cbCertEncoded
;
1368 CERTCertificate
* intermediate
= CERT_NewTempCertificate(
1369 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1370 if (!intermediate
) {
1371 CERT_DestroyCertList(cert_chain
);
1372 core
->AddCertProvidedEvent(0);
1375 CERT_AddCertToListTail(cert_chain
, intermediate
);
1377 PCERT_KEY_CONTEXT key_context
= reinterpret_cast<PCERT_KEY_CONTEXT
>(
1378 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT
)));
1379 key_context
->cbSize
= sizeof(*key_context
);
1380 // NSS will free this context when no longer in use.
1381 key_context
->hCryptProv
= crypt_prov
;
1382 key_context
->dwKeySpec
= key_spec
;
1383 *result_private_key
= key_context
;
1384 *result_certs
= cert_chain
;
1386 int cert_count
= 1 + intermediates
.size();
1387 core
->AddCertProvidedEvent(cert_count
);
1390 LOG(WARNING
) << "Client cert found without private key";
1393 // Send no client certificate.
1394 core
->AddCertProvidedEvent(0);
1398 core
->nss_handshake_state_
.cert_authorities
.clear();
1400 std::vector
<CERT_NAME_BLOB
> issuer_list(ca_names
->nnames
);
1401 for (int i
= 0; i
< ca_names
->nnames
; ++i
) {
1402 issuer_list
[i
].cbData
= ca_names
->names
[i
].len
;
1403 issuer_list
[i
].pbData
= ca_names
->names
[i
].data
;
1404 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1405 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1406 static_cast<size_t>(ca_names
->names
[i
].len
)));
1409 // Update the network task runner's view of the handshake state now that
1410 // server certificate request has been recorded.
1411 core
->PostOrRunCallback(
1412 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1413 core
->nss_handshake_state_
));
1415 // Tell NSS to suspend the client authentication. We will then abort the
1416 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1417 return SECWouldBlock
;
1418 #elif defined(OS_MACOSX)
1419 if (core
->ssl_config_
.send_client_cert
) {
1420 if (core
->ssl_config_
.client_cert
.get()) {
1421 OSStatus os_error
= noErr
;
1422 SecIdentityRef identity
= NULL
;
1423 SecKeyRef private_key
= NULL
;
1424 X509Certificate::OSCertHandles chain
;
1426 base::AutoLock
lock(crypto::GetMacSecurityServicesLock());
1427 os_error
= SecIdentityCreateWithCertificate(
1428 NULL
, core
->ssl_config_
.client_cert
->os_cert_handle(), &identity
);
1430 if (os_error
== noErr
) {
1431 os_error
= SecIdentityCopyPrivateKey(identity
, &private_key
);
1432 CFRelease(identity
);
1435 if (os_error
== noErr
) {
1436 // TODO(rsleevi): Error checking for NSS allocation errors.
1437 *result_certs
= CERT_NewCertList();
1438 *result_private_key
= private_key
;
1440 chain
.push_back(core
->ssl_config_
.client_cert
->os_cert_handle());
1441 const X509Certificate::OSCertHandles
& intermediates
=
1442 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1443 if (!intermediates
.empty())
1444 chain
.insert(chain
.end(), intermediates
.begin(), intermediates
.end());
1446 for (size_t i
= 0, chain_count
= chain
.size(); i
< chain_count
; ++i
) {
1447 CSSM_DATA cert_data
;
1448 SecCertificateRef cert_ref
= chain
[i
];
1449 os_error
= SecCertificateGetData(cert_ref
, &cert_data
);
1450 if (os_error
!= noErr
)
1454 der_cert
.type
= siDERCertBuffer
;
1455 der_cert
.data
= cert_data
.Data
;
1456 der_cert
.len
= cert_data
.Length
;
1457 CERTCertificate
* nss_cert
= CERT_NewTempCertificate(
1458 CERT_GetDefaultCertDB(), &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1460 // In the event of an NSS error, make up an OS error and reuse
1461 // the error handling below.
1462 os_error
= errSecCreateChainFailed
;
1465 CERT_AddCertToListTail(*result_certs
, nss_cert
);
1469 if (os_error
== noErr
) {
1470 core
->AddCertProvidedEvent(chain
.size());
1474 OSSTATUS_LOG(WARNING
, os_error
)
1475 << "Client cert found, but could not be used";
1476 if (*result_certs
) {
1477 CERT_DestroyCertList(*result_certs
);
1478 *result_certs
= NULL
;
1480 if (*result_private_key
)
1481 *result_private_key
= NULL
;
1483 CFRelease(private_key
);
1486 // Send no client certificate.
1487 core
->AddCertProvidedEvent(0);
1491 core
->nss_handshake_state_
.cert_authorities
.clear();
1493 // Retrieve the cert issuers accepted by the server.
1494 std::vector
<CertPrincipal
> valid_issuers
;
1495 int n
= ca_names
->nnames
;
1496 for (int i
= 0; i
< n
; i
++) {
1497 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1498 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1499 static_cast<size_t>(ca_names
->names
[i
].len
)));
1502 // Update the network task runner's view of the handshake state now that
1503 // server certificate request has been recorded.
1504 core
->PostOrRunCallback(
1505 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1506 core
->nss_handshake_state_
));
1508 // Tell NSS to suspend the client authentication. We will then abort the
1509 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1510 return SECWouldBlock
;
1516 #elif defined(OS_IOS)
1518 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1521 CERTDistNames
* ca_names
,
1522 CERTCertificate
** result_certificate
,
1523 SECKEYPrivateKey
** result_private_key
) {
1524 Core
* core
= reinterpret_cast<Core
*>(arg
);
1525 DCHECK(core
->OnNSSTaskRunner());
1527 core
->PostOrRunCallback(
1529 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1530 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1532 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1533 LOG(WARNING
) << "Client auth is not supported";
1535 // Never send a certificate.
1536 core
->AddCertProvidedEvent(0);
1540 #else // NSS_PLATFORM_CLIENT_AUTH
1543 // Based on Mozilla's NSS_GetClientAuthData.
1544 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1547 CERTDistNames
* ca_names
,
1548 CERTCertificate
** result_certificate
,
1549 SECKEYPrivateKey
** result_private_key
) {
1550 Core
* core
= reinterpret_cast<Core
*>(arg
);
1551 DCHECK(core
->OnNSSTaskRunner());
1553 core
->PostOrRunCallback(
1555 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1556 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1558 // Regular client certificate requested.
1559 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1560 void* wincx
= SSL_RevealPinArg(socket
);
1562 if (core
->ssl_config_
.send_client_cert
) {
1563 // Second pass: a client certificate should have been selected.
1564 if (core
->ssl_config_
.client_cert
.get()) {
1565 CERTCertificate
* cert
=
1566 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1567 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1569 // TODO(jsorianopastor): We should wait for server certificate
1570 // verification before sending our credentials. See
1571 // http://crbug.com/13934.
1572 *result_certificate
= cert
;
1573 *result_private_key
= privkey
;
1574 // A cert_count of -1 means the number of certificates is unknown.
1575 // NSS will construct the certificate chain.
1576 core
->AddCertProvidedEvent(-1);
1580 LOG(WARNING
) << "Client cert found without private key";
1582 // Send no client certificate.
1583 core
->AddCertProvidedEvent(0);
1587 // First pass: client certificate is needed.
1588 core
->nss_handshake_state_
.cert_authorities
.clear();
1590 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1591 // the server and save them in |cert_authorities|.
1592 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1593 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1594 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1595 static_cast<size_t>(ca_names
->names
[i
].len
)));
1598 // Update the network task runner's view of the handshake state now that
1599 // server certificate request has been recorded.
1600 core
->PostOrRunCallback(
1601 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1602 core
->nss_handshake_state_
));
1604 // Tell NSS to suspend the client authentication. We will then abort the
1605 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1606 return SECWouldBlock
;
1608 #endif // NSS_PLATFORM_CLIENT_AUTH
1611 void SSLClientSocketNSS::Core::HandshakeCallback(
1614 Core
* core
= reinterpret_cast<Core
*>(arg
);
1615 DCHECK(core
->OnNSSTaskRunner());
1617 core
->handshake_callback_called_
= true;
1619 HandshakeState
* nss_state
= &core
->nss_handshake_state_
;
1621 PRBool last_handshake_resumed
;
1622 SECStatus rv
= SSL_HandshakeResumedSession(socket
, &last_handshake_resumed
);
1623 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1624 nss_state
->resumed_handshake
= true;
1626 nss_state
->resumed_handshake
= false;
1629 core
->RecordChannelIDSupportOnNSSTaskRunner();
1630 core
->UpdateServerCert();
1631 core
->UpdateConnectionStatus();
1632 core
->UpdateNextProto();
1634 // Update the network task runners view of the handshake state whenever
1635 // a handshake has completed.
1636 core
->PostOrRunCallback(
1637 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1641 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
,
1642 bool handshake_error
) {
1643 DCHECK(OnNSSTaskRunner());
1645 int net_error
= handshake_error
? MapNSSClientHandshakeError(nss_error
) :
1646 MapNSSClientError(nss_error
);
1649 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1650 // os_cert_handle() as an optimization. However, if the certificate
1651 // private key is stored on a smart card, and the smart card is removed,
1652 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1653 // preventing client certificate authentication. Because the
1654 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1655 // caching in X509Certificate, this failure ends up preventing client
1656 // certificate authentication with the same certificate for all future
1657 // attempts, even after the smart card has been re-inserted. By setting
1658 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1659 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1660 // the certificate on the next attempt, which should succeed if the smart
1661 // card has been re-inserted, or will typically prompt the user to
1662 // re-insert the smart card if not.
1663 if ((net_error
== ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
||
1664 net_error
== ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
) &&
1665 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
) {
1666 CertSetCertificateContextProperty(
1667 ssl_config_
.client_cert
->os_cert_handle(),
1668 CERT_KEY_PROV_HANDLE_PROP_ID
, 0, NULL
);
1675 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1676 DCHECK(OnNSSTaskRunner());
1678 int rv
= last_io_result
;
1680 // Default to STATE_NONE for next state.
1681 State state
= next_handshake_state_
;
1682 GotoState(STATE_NONE
);
1685 case STATE_HANDSHAKE
:
1688 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1689 rv
= DoGetDBCertComplete(rv
);
1693 rv
= ERR_UNEXPECTED
;
1694 LOG(DFATAL
) << "unexpected state " << state
;
1698 // Do the actual network I/O
1699 bool network_moved
= DoTransportIO();
1700 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1701 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1702 // special case we keep looping even if rv is ERR_IO_PENDING because
1703 // the transport IO may allow DoHandshake to make progress.
1704 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1705 rv
= OK
; // This causes us to stay in the loop.
1707 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1711 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1712 DCHECK(OnNSSTaskRunner());
1713 DCHECK(handshake_callback_called_
);
1714 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1720 LOG(DFATAL
) << "!nss_bufs_";
1721 int rv
= ERR_UNEXPECTED
;
1724 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1725 NetLog::TYPE_SSL_READ_ERROR
,
1726 CreateNetLogSSLErrorCallback(rv
, 0)));
1733 rv
= DoPayloadRead();
1734 network_moved
= DoTransportIO();
1735 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1740 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1741 DCHECK(OnNSSTaskRunner());
1742 DCHECK(handshake_callback_called_
);
1743 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1749 LOG(DFATAL
) << "!nss_bufs_";
1750 int rv
= ERR_UNEXPECTED
;
1753 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1754 NetLog::TYPE_SSL_READ_ERROR
,
1755 CreateNetLogSSLErrorCallback(rv
, 0)));
1762 rv
= DoPayloadWrite();
1763 network_moved
= DoTransportIO();
1764 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1770 int SSLClientSocketNSS::Core::DoHandshake() {
1771 DCHECK(OnNSSTaskRunner());
1773 int net_error
= net::OK
;
1774 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1776 // Note: this function may be called multiple times during the handshake, so
1777 // even though channel id and client auth are separate else cases, they can
1778 // both be used during a single SSL handshake.
1779 if (channel_id_needed_
) {
1780 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1781 net_error
= ERR_IO_PENDING
;
1782 } else if (client_auth_cert_needed_
) {
1783 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1786 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1787 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1788 CreateNetLogSSLErrorCallback(net_error
, 0)));
1790 // If the handshake already succeeded (because the server requests but
1791 // doesn't require a client cert), we need to invalidate the SSL session
1792 // so that we won't try to resume the non-client-authenticated session in
1793 // the next handshake. This will cause the server to ask for a client
1795 if (rv
== SECSuccess
&& SSL_InvalidateSession(nss_fd_
) != SECSuccess
)
1796 LOG(WARNING
) << "Couldn't invalidate SSL session: " << PR_GetError();
1797 } else if (rv
== SECSuccess
) {
1798 if (!handshake_callback_called_
) {
1799 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1800 // SSL_ForceHandshake returned SECSuccess prematurely.
1802 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1805 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1806 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1807 CreateNetLogSSLErrorCallback(net_error
, 0)));
1809 #if defined(SSL_ENABLE_OCSP_STAPLING)
1810 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1811 // system library and update IsOCSPStaplingSupported for Mac.
1812 if (IsOCSPStaplingSupported()) {
1813 const SECItemArray
* ocsp_responses
=
1814 SSL_PeerStapledOCSPResponses(nss_fd_
);
1815 if (ocsp_responses
->len
) {
1817 if (nss_handshake_state_
.server_cert
) {
1818 CRYPT_DATA_BLOB ocsp_response_blob
;
1819 ocsp_response_blob
.cbData
= ocsp_responses
->items
[0].len
;
1820 ocsp_response_blob
.pbData
= ocsp_responses
->items
[0].data
;
1821 BOOL ok
= CertSetCertificateContextProperty(
1822 nss_handshake_state_
.server_cert
->os_cert_handle(),
1823 CERT_OCSP_RESPONSE_PROP_ID
,
1824 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1825 &ocsp_response_blob
);
1827 VLOG(1) << "Failed to set OCSP response property: "
1831 #elif defined(USE_NSS)
1832 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
1833 GetCacheOCSPResponseFromSideChannelFunction();
1835 cache_ocsp_response(
1836 CERT_GetDefaultCertDB(),
1837 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
1838 &ocsp_responses
->items
[0], NULL
);
1846 PRErrorCode prerr
= PR_GetError();
1847 net_error
= HandleNSSError(prerr
, true);
1849 // Some network devices that inspect application-layer packets seem to
1850 // inject TCP reset packets to break the connections when they see
1851 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1853 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1854 // 1.2. We don't lose much in this fallback because the explicit IV for CBC
1855 // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
1856 // fallback will be more painful for TLS 1.2 when we have GCM support.
1858 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1859 // to trigger a version fallback in general, especially the TLS 1.0 ->
1860 // SSL 3.0 fallback, which would drop TLS extensions.
1861 if (prerr
== PR_CONNECT_RESET_ERROR
&&
1862 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1_1
) {
1863 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1866 // If not done, stay in this state
1867 if (net_error
== ERR_IO_PENDING
) {
1868 GotoState(STATE_HANDSHAKE
);
1872 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1873 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1874 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1881 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1885 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1886 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1888 channel_id_needed_
= false;
1893 SECKEYPublicKey
* public_key
;
1894 SECKEYPrivateKey
* private_key
;
1895 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1899 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1900 if (rv
!= SECSuccess
)
1901 return MapNSSError(PORT_GetError());
1903 SetChannelIDProvided();
1904 GotoState(STATE_HANDSHAKE
);
1908 int SSLClientSocketNSS::Core::DoPayloadRead() {
1909 DCHECK(OnNSSTaskRunner());
1910 DCHECK(user_read_buf_
.get());
1911 DCHECK_GT(user_read_buf_len_
, 0);
1914 // If a previous greedy read resulted in an error that was not consumed (eg:
1915 // due to the caller having read some data successfully), then return that
1916 // pending error now.
1917 if (pending_read_result_
!= kNoPendingReadResult
) {
1918 rv
= pending_read_result_
;
1919 PRErrorCode prerr
= pending_read_nss_error_
;
1920 pending_read_result_
= kNoPendingReadResult
;
1921 pending_read_nss_error_
= 0;
1926 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1927 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1928 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1932 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1933 NetLog::TYPE_SSL_READ_ERROR
,
1934 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1939 // Perform a greedy read, attempting to read as much as the caller has
1940 // requested. In the current NSS implementation, PR_Read will return
1941 // exactly one SSL application data record's worth of data per invocation.
1942 // The record size is dictated by the server, and may be noticeably smaller
1943 // than the caller's buffer. This may be as little as a single byte, if the
1944 // server is performing 1/n-1 record splitting.
1946 // However, this greedy read may result in renegotiations/re-handshakes
1947 // happening or may lead to some data being read, followed by an EOF (such as
1948 // a TLS close-notify). If at least some data was read, then that result
1949 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1950 // data was read, it's safe to return the error or EOF immediately.
1951 int total_bytes_read
= 0;
1953 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1954 user_read_buf_len_
- total_bytes_read
);
1956 total_bytes_read
+= rv
;
1957 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1958 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1959 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1960 amount_in_read_buffer
));
1962 if (total_bytes_read
== user_read_buf_len_
) {
1963 // The caller's entire request was satisfied without error. No further
1964 // processing needed.
1965 rv
= total_bytes_read
;
1967 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1968 // immediately, while the NSPR/NSS errors are still available in
1969 // thread-local storage. However, the handled/remapped error code should
1970 // only be returned if no application data was already read; if it was, the
1971 // error code should be deferred until the next call of DoPayloadRead.
1973 // If no data was read, |*next_result| will point to the return value of
1974 // this function. If at least some data was read, |*next_result| will point
1975 // to |pending_read_error_|, to be returned in a future call to
1976 // DoPayloadRead() (e.g.: after the current data is handled).
1977 int* next_result
= &rv
;
1978 if (total_bytes_read
> 0) {
1979 pending_read_result_
= rv
;
1980 rv
= total_bytes_read
;
1981 next_result
= &pending_read_result_
;
1984 if (client_auth_cert_needed_
) {
1985 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1986 pending_read_nss_error_
= 0;
1987 } else if (*next_result
< 0) {
1988 // If *next_result == 0, then that indicates EOF, and no special error
1989 // handling is needed.
1990 pending_read_nss_error_
= PR_GetError();
1991 *next_result
= HandleNSSError(pending_read_nss_error_
, false);
1992 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1993 // If at least some data was read from PR_Read(), do not treat
1994 // insufficient data as an error to return in the next call to
1995 // DoPayloadRead() - instead, let the call fall through to check
1996 // PR_Read() again. This is because DoTransportIO() may complete
1997 // in between the next call to DoPayloadRead(), and thus it is
1998 // important to check PR_Read() on subsequent invocations to see
1999 // if a complete record may now be read.
2000 pending_read_nss_error_
= 0;
2001 pending_read_result_
= kNoPendingReadResult
;
2006 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
2011 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2012 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
2013 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
2014 } else if (rv
!= ERR_IO_PENDING
) {
2017 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2018 NetLog::TYPE_SSL_READ_ERROR
,
2019 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
2020 pending_read_nss_error_
= 0;
2025 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2026 DCHECK(OnNSSTaskRunner());
2028 DCHECK(user_write_buf_
.get());
2030 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2031 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
2032 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2033 // PR_Write could potentially consume the unhandled data in the memio read
2034 // buffer if a renegotiation is in progress. If the buffer is consumed,
2035 // notify the latest buffer size to NetworkRunner.
2036 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
2039 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
2044 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2045 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
2046 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
2049 PRErrorCode prerr
= PR_GetError();
2050 if (prerr
== PR_WOULD_BLOCK_ERROR
)
2051 return ERR_IO_PENDING
;
2053 rv
= HandleNSSError(prerr
, false);
2056 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2057 NetLog::TYPE_SSL_WRITE_ERROR
,
2058 CreateNetLogSSLErrorCallback(rv
, prerr
)));
2062 // Do as much network I/O as possible between the buffer and the
2063 // transport socket. Return true if some I/O performed, false
2064 // otherwise (error or ERR_IO_PENDING).
2065 bool SSLClientSocketNSS::Core::DoTransportIO() {
2066 DCHECK(OnNSSTaskRunner());
2068 bool network_moved
= false;
2069 if (nss_bufs_
!= NULL
) {
2071 // Read and write as much data as we can. The loop is neccessary
2072 // because Write() may return synchronously.
2075 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
2076 network_moved
= true;
2078 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
2079 network_moved
= true;
2081 return network_moved
;
2084 int SSLClientSocketNSS::Core::BufferRecv() {
2085 DCHECK(OnNSSTaskRunner());
2087 if (transport_recv_busy_
)
2088 return ERR_IO_PENDING
;
2090 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2091 // determine how much data NSS wants to read. If NSS was not blocked,
2092 // this will return 0.
2093 int requested
= memio_GetReadRequest(nss_bufs_
);
2094 if (requested
== 0) {
2095 // This is not a perfect match of error codes, as no operation is
2096 // actually pending. However, returning 0 would be interpreted as a
2097 // possible sign of EOF, which is also an inappropriate match.
2098 return ERR_IO_PENDING
;
2102 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2105 // buffer too full to read into, so no I/O possible at moment
2106 rv
= ERR_IO_PENDING
;
2108 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
2109 if (OnNetworkTaskRunner()) {
2110 rv
= DoBufferRecv(read_buffer
.get(), nb
);
2112 bool posted
= network_task_runner_
->PostTask(
2114 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
2116 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2119 if (rv
== ERR_IO_PENDING
) {
2120 transport_recv_busy_
= true;
2123 memcpy(buf
, read_buffer
->data(), rv
);
2124 } else if (rv
== 0) {
2125 transport_recv_eof_
= true;
2127 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
2133 // Return 0 if nss_bufs_ was empty,
2134 // > 0 for bytes transferred immediately,
2135 // < 0 for error (or the non-error ERR_IO_PENDING).
2136 int SSLClientSocketNSS::Core::BufferSend() {
2137 DCHECK(OnNSSTaskRunner());
2139 if (transport_send_busy_
)
2140 return ERR_IO_PENDING
;
2144 unsigned int len1
, len2
;
2145 memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
);
2146 const unsigned int len
= len1
+ len2
;
2150 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
2151 memcpy(send_buffer
->data(), buf1
, len1
);
2152 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
2154 if (OnNetworkTaskRunner()) {
2155 rv
= DoBufferSend(send_buffer
.get(), len
);
2157 bool posted
= network_task_runner_
->PostTask(
2159 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
2161 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2164 if (rv
== ERR_IO_PENDING
) {
2165 transport_send_busy_
= true;
2167 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
2174 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
2175 DCHECK(OnNSSTaskRunner());
2177 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2178 OnHandshakeIOComplete(result
);
2182 // Network layer received some data, check if client requested to read
2184 if (!user_read_buf_
.get())
2187 int rv
= DoReadLoop(result
);
2188 if (rv
!= ERR_IO_PENDING
)
2192 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
2193 DCHECK(OnNSSTaskRunner());
2195 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2196 OnHandshakeIOComplete(result
);
2200 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2201 // handshake is in progress.
2202 int rv_read
= ERR_IO_PENDING
;
2203 int rv_write
= ERR_IO_PENDING
;
2206 if (user_read_buf_
.get())
2207 rv_read
= DoPayloadRead();
2208 if (user_write_buf_
.get())
2209 rv_write
= DoPayloadWrite();
2210 network_moved
= DoTransportIO();
2211 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
2212 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
2214 // If the parent SSLClientSocketNSS is deleted during the processing of the
2215 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2216 // will be detached (and possibly deleted). Guard against deletion by taking
2217 // an extra reference, then check if the Core was detached before invoking the
2219 scoped_refptr
<Core
> guard(this);
2220 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
2221 DoReadCallback(rv_read
);
2223 if (OnNetworkTaskRunner() && detached_
)
2226 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
2227 DoWriteCallback(rv_write
);
2230 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2231 // handshake. This requires network IO, which in turn calls
2232 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2233 // winds its way through the state machine and ends up being passed to the
2234 // callback. For Read() and Write(), that's what we want. But for Connect(),
2235 // the caller expects OK (i.e. 0) for success.
2236 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
2237 DCHECK(OnNSSTaskRunner());
2238 DCHECK_NE(rv
, ERR_IO_PENDING
);
2239 DCHECK(!user_connect_callback_
.is_null());
2241 base::Closure c
= base::Bind(
2242 base::ResetAndReturn(&user_connect_callback_
),
2244 PostOrRunCallback(FROM_HERE
, c
);
2247 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
2248 DCHECK(OnNSSTaskRunner());
2249 DCHECK_NE(ERR_IO_PENDING
, rv
);
2250 DCHECK(!user_read_callback_
.is_null());
2252 user_read_buf_
= NULL
;
2253 user_read_buf_len_
= 0;
2254 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2255 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2256 // the network task runner.
2259 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2262 base::Bind(&Core::DidNSSRead
, this, rv
));
2265 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
2268 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
2269 DCHECK(OnNSSTaskRunner());
2270 DCHECK_NE(ERR_IO_PENDING
, rv
);
2271 DCHECK(!user_write_callback_
.is_null());
2273 // Since Run may result in Write being called, clear |user_write_callback_|
2275 user_write_buf_
= NULL
;
2276 user_write_buf_len_
= 0;
2277 // Update buffer status because DoWriteLoop called DoTransportIO which may
2278 // perform read operations.
2279 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2280 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2281 // the network task runner.
2284 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2287 base::Bind(&Core::DidNSSWrite
, this, rv
));
2290 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
2293 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
2296 SECKEYPublicKey
**out_public_key
,
2297 SECKEYPrivateKey
**out_private_key
) {
2298 Core
* core
= reinterpret_cast<Core
*>(arg
);
2299 DCHECK(core
->OnNSSTaskRunner());
2301 core
->PostOrRunCallback(
2303 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
2304 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
2306 // We have negotiated the TLS channel ID extension.
2307 core
->channel_id_xtn_negotiated_
= true;
2308 std::string host
= core
->host_and_port_
.host();
2309 int error
= ERR_UNEXPECTED
;
2310 if (core
->OnNetworkTaskRunner()) {
2311 error
= core
->DoGetDomainBoundCert(host
);
2313 bool posted
= core
->network_task_runner_
->PostTask(
2316 IgnoreResult(&Core::DoGetDomainBoundCert
),
2318 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2321 if (error
== ERR_IO_PENDING
) {
2322 // Asynchronous case.
2323 core
->channel_id_needed_
= true;
2324 return SECWouldBlock
;
2327 core
->PostOrRunCallback(
2329 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
2330 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
2331 SECStatus rv
= SECSuccess
;
2333 // Synchronous success.
2334 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
2336 core
->SetChannelIDProvided();
2346 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
2347 SECKEYPrivateKey
** key
) {
2348 // Set the certificate.
2350 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
2351 cert_item
.len
= domain_bound_cert_
.size();
2352 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2358 return MapNSSError(PORT_GetError());
2360 // Set the private key.
2361 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2362 ServerBoundCertService::kEPKIPassword
,
2363 reinterpret_cast<const unsigned char*>(
2364 domain_bound_private_key_
.data()),
2365 domain_bound_private_key_
.size(),
2366 &cert
->subjectPublicKeyInfo
,
2371 int error
= MapNSSError(PORT_GetError());
2378 void SSLClientSocketNSS::Core::UpdateServerCert() {
2379 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2380 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2381 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2382 if (nss_handshake_state_
.server_cert
.get()) {
2383 // Since this will be called asynchronously on another thread, it needs to
2384 // own a reference to the certificate.
2385 NetLog::ParametersCallback net_log_callback
=
2386 base::Bind(&NetLogX509CertificateCallback
,
2387 nss_handshake_state_
.server_cert
);
2390 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2391 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2396 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2397 SSLChannelInfo channel_info
;
2398 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2399 &channel_info
, sizeof(channel_info
));
2400 if (ok
== SECSuccess
&&
2401 channel_info
.length
== sizeof(channel_info
) &&
2402 channel_info
.cipherSuite
) {
2403 nss_handshake_state_
.ssl_connection_status
|=
2404 (static_cast<int>(channel_info
.cipherSuite
) &
2405 SSL_CONNECTION_CIPHERSUITE_MASK
) <<
2406 SSL_CONNECTION_CIPHERSUITE_SHIFT
;
2408 nss_handshake_state_
.ssl_connection_status
|=
2409 (static_cast<int>(channel_info
.compressionMethod
) &
2410 SSL_CONNECTION_COMPRESSION_MASK
) <<
2411 SSL_CONNECTION_COMPRESSION_SHIFT
;
2413 // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
2414 // support it yet), so use 0x0303 directly.
2415 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2416 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2417 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2419 version
= SSL_CONNECTION_VERSION_SSL2
;
2420 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2421 version
= SSL_CONNECTION_VERSION_SSL3
;
2422 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_1_TLS
) {
2423 version
= SSL_CONNECTION_VERSION_TLS1
;
2424 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2425 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2426 } else if (channel_info
.protocolVersion
== 0x0303) {
2427 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2429 nss_handshake_state_
.ssl_connection_status
|=
2430 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2431 SSL_CONNECTION_VERSION_SHIFT
;
2434 PRBool peer_supports_renego_ext
;
2435 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2436 &peer_supports_renego_ext
);
2437 if (ok
== SECSuccess
) {
2438 if (!peer_supports_renego_ext
) {
2439 nss_handshake_state_
.ssl_connection_status
|=
2440 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2441 // Log an informational message if the server does not support secure
2442 // renegotiation (RFC 5746).
2443 VLOG(1) << "The server " << host_and_port_
.ToString()
2444 << " does not support the TLS renegotiation_info extension.";
2446 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2447 peer_supports_renego_ext
, 2);
2449 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2450 // because of security concerns. For example, Google offers forward
2451 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2452 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2455 // Yngve from Opera has suggested using the renegotiation extension as an
2456 // indicator that SSLv3 fallback was mistaken:
2457 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2459 // As a first step, measure how often clients perform version fallback
2460 // while the server advertises support secure renegotiation.
2461 if (ssl_config_
.version_fallback
&&
2462 channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2463 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2464 peer_supports_renego_ext
== PR_TRUE
);
2468 if (ssl_config_
.version_fallback
) {
2469 nss_handshake_state_
.ssl_connection_status
|=
2470 SSL_CONNECTION_VERSION_FALLBACK
;
2474 void SSLClientSocketNSS::Core::UpdateNextProto() {
2476 SSLNextProtoState state
;
2479 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2480 if (rv
!= SECSuccess
)
2483 nss_handshake_state_
.next_proto
=
2484 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2486 case SSL_NEXT_PROTO_NEGOTIATED
:
2487 case SSL_NEXT_PROTO_SELECTED
:
2488 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2490 case SSL_NEXT_PROTO_NO_OVERLAP
:
2491 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2493 case SSL_NEXT_PROTO_NO_SUPPORT
:
2494 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2502 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2503 DCHECK(OnNSSTaskRunner());
2504 if (nss_handshake_state_
.resumed_handshake
)
2507 // Copy the NSS task runner-only state to the network task runner and
2508 // log histograms from there, since the histograms also need access to the
2509 // network task runner state.
2512 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2514 channel_id_xtn_negotiated_
,
2515 ssl_config_
.channel_id_enabled
,
2516 crypto::ECPrivateKey::IsSupported()));
2519 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2520 bool negotiated_channel_id
,
2521 bool channel_id_enabled
,
2522 bool supports_ecc
) const {
2523 DCHECK(OnNetworkTaskRunner());
2525 RecordChannelIDSupport(server_bound_cert_service_
,
2526 negotiated_channel_id
,
2531 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2532 DCHECK(OnNetworkTaskRunner());
2538 int rv
= transport_
->socket()->Read(
2540 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2541 scoped_refptr
<IOBuffer
>(read_buffer
)));
2543 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2544 nss_task_runner_
->PostTask(
2545 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2546 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2553 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2554 DCHECK(OnNetworkTaskRunner());
2560 int rv
= transport_
->socket()->Write(
2562 base::Bind(&Core::BufferSendComplete
,
2563 base::Unretained(this)));
2565 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2566 nss_task_runner_
->PostTask(
2568 base::Bind(&Core::BufferSendComplete
, this, rv
));
2575 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string
& host
) {
2576 DCHECK(OnNetworkTaskRunner());
2581 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2583 int rv
= server_bound_cert_service_
->GetOrCreateDomainBoundCert(
2585 &domain_bound_private_key_
,
2586 &domain_bound_cert_
,
2587 base::Bind(&Core::OnGetDomainBoundCertComplete
, base::Unretained(this)),
2588 &domain_bound_cert_request_handle_
);
2590 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2591 nss_task_runner_
->PostTask(
2593 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2594 return ERR_IO_PENDING
;
2600 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2601 const HandshakeState
& state
) {
2602 DCHECK(OnNetworkTaskRunner());
2603 network_handshake_state_
= state
;
2606 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2607 DCHECK(OnNetworkTaskRunner());
2608 unhandled_buffer_size_
= amount_in_read_buffer
;
2611 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2612 DCHECK(OnNetworkTaskRunner());
2613 DCHECK(nss_waiting_read_
);
2614 nss_waiting_read_
= false;
2616 nss_is_closed_
= true;
2619 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2620 DCHECK(OnNetworkTaskRunner());
2621 DCHECK(nss_waiting_write_
);
2622 nss_waiting_write_
= false;
2624 nss_is_closed_
= true;
2627 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2628 if (!OnNSSTaskRunner()) {
2632 nss_task_runner_
->PostTask(
2633 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2637 DCHECK(OnNSSTaskRunner());
2639 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2640 transport_send_busy_
= false;
2641 OnSendComplete(result
);
2644 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2645 if (!OnNSSTaskRunner()) {
2649 nss_task_runner_
->PostTask(
2650 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2654 DCHECK(OnNSSTaskRunner());
2656 int rv
= DoHandshakeLoop(result
);
2657 if (rv
!= ERR_IO_PENDING
)
2658 DoConnectCallback(rv
);
2661 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result
) {
2662 DVLOG(1) << __FUNCTION__
<< " " << result
;
2663 DCHECK(OnNetworkTaskRunner());
2665 OnHandshakeIOComplete(result
);
2668 void SSLClientSocketNSS::Core::BufferRecvComplete(
2669 IOBuffer
* read_buffer
,
2671 DCHECK(read_buffer
);
2673 if (!OnNSSTaskRunner()) {
2677 nss_task_runner_
->PostTask(
2678 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2679 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2683 DCHECK(OnNSSTaskRunner());
2687 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2688 CHECK_GE(nb
, result
);
2689 memcpy(buf
, read_buffer
->data(), result
);
2690 } else if (result
== 0) {
2691 transport_recv_eof_
= true;
2694 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2695 transport_recv_busy_
= false;
2696 OnRecvComplete(result
);
2699 void SSLClientSocketNSS::Core::PostOrRunCallback(
2700 const tracked_objects::Location
& location
,
2701 const base::Closure
& task
) {
2702 if (!OnNetworkTaskRunner()) {
2703 network_task_runner_
->PostTask(
2705 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2709 if (detached_
|| task
.is_null())
2714 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2717 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2718 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2719 NetLog::IntegerCallback("cert_count", cert_count
)));
2722 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2724 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2725 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2726 nss_handshake_state_
.channel_id_sent
= true;
2727 // Update the network task runner's view of the handshake state now that
2728 // channel id has been sent.
2730 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2731 nss_handshake_state_
));
2734 SSLClientSocketNSS::SSLClientSocketNSS(
2735 base::SequencedTaskRunner
* nss_task_runner
,
2736 scoped_ptr
<ClientSocketHandle
> transport_socket
,
2737 const HostPortPair
& host_and_port
,
2738 const SSLConfig
& ssl_config
,
2739 const SSLClientSocketContext
& context
)
2740 : nss_task_runner_(nss_task_runner
),
2741 transport_(transport_socket
.Pass()),
2742 host_and_port_(host_and_port
),
2743 ssl_config_(ssl_config
),
2744 cert_verifier_(context
.cert_verifier
),
2745 server_bound_cert_service_(context
.server_bound_cert_service
),
2746 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2747 completed_handshake_(false),
2748 next_handshake_state_(STATE_NONE
),
2750 net_log_(transport_
->socket()->NetLog()),
2751 transport_security_state_(context
.transport_security_state
),
2752 valid_thread_id_(base::kInvalidThreadId
) {
2758 SSLClientSocketNSS::~SSLClientSocketNSS() {
2765 void SSLClientSocket::ClearSessionCache() {
2766 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2767 // bother initializing NSS just to clear an empty SSL session cache.
2768 if (!NSS_IsInitialized())
2771 SSL_ClearSessionCache();
2774 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2777 if (core_
->state().server_cert_chain
.empty() ||
2778 !core_
->state().server_cert_chain
[0]) {
2782 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2783 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2784 ssl_info
->connection_status
=
2785 core_
->state().ssl_connection_status
;
2786 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2787 for (HashValueVector::const_iterator i
= side_pinned_public_keys_
.begin();
2788 i
!= side_pinned_public_keys_
.end(); ++i
) {
2789 ssl_info
->public_key_hashes
.push_back(*i
);
2791 ssl_info
->is_issued_by_known_root
=
2792 server_cert_verify_result_
.is_issued_by_known_root
;
2793 ssl_info
->client_cert_sent
=
2794 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2795 ssl_info
->channel_id_sent
= WasChannelIDSent();
2797 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2798 core_
->state().ssl_connection_status
);
2799 SSLCipherSuiteInfo cipher_info
;
2800 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2801 &cipher_info
, sizeof(cipher_info
));
2802 if (ok
== SECSuccess
) {
2803 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2805 ssl_info
->security_bits
= -1;
2806 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2807 << " for cipherSuite " << cipher_suite
;
2810 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2811 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2817 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2818 SSLCertRequestInfo
* cert_request_info
) {
2820 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2821 cert_request_info
->host_and_port
= host_and_port_
.ToString();
2822 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2826 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2828 const base::StringPiece
& context
,
2830 unsigned int outlen
) {
2832 return ERR_SOCKET_NOT_CONNECTED
;
2834 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2835 // the midst of a handshake.
2836 SECStatus result
= SSL_ExportKeyingMaterial(
2837 nss_fd_
, label
.data(), label
.size(), has_context
,
2838 reinterpret_cast<const unsigned char*>(context
.data()),
2839 context
.length(), out
, outlen
);
2840 if (result
!= SECSuccess
) {
2841 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2842 return MapNSSError(PORT_GetError());
2847 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2849 return ERR_SOCKET_NOT_CONNECTED
;
2850 unsigned char buf
[64];
2852 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2853 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2854 buf
, &len
, arraysize(buf
));
2855 if (result
!= SECSuccess
) {
2856 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2857 return MapNSSError(PORT_GetError());
2859 out
->assign(reinterpret_cast<char*>(buf
), len
);
2863 SSLClientSocket::NextProtoStatus
2864 SSLClientSocketNSS::GetNextProto(std::string
* proto
,
2865 std::string
* server_protos
) {
2866 *proto
= core_
->state().next_proto
;
2867 *server_protos
= core_
->state().server_protos
;
2868 return core_
->state().next_proto_status
;
2871 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2873 DCHECK(transport_
.get());
2874 // It is an error to create an SSLClientSocket whose context has no
2875 // TransportSecurityState.
2876 DCHECK(transport_security_state_
);
2877 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2878 DCHECK(user_connect_callback_
.is_null());
2879 DCHECK(!callback
.is_null());
2881 EnsureThreadIdAssigned();
2883 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2887 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2891 rv
= InitializeSSLOptions();
2893 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2897 rv
= InitializeSSLPeerName();
2899 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2903 GotoState(STATE_HANDSHAKE
);
2905 rv
= DoHandshakeLoop(OK
);
2906 if (rv
== ERR_IO_PENDING
) {
2907 user_connect_callback_
= callback
;
2909 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2913 return rv
> OK
? OK
: rv
;
2916 void SSLClientSocketNSS::Disconnect() {
2919 CHECK(CalledOnValidThread());
2921 // Shut down anything that may call us back.
2924 transport_
->socket()->Disconnect();
2926 // Reset object state.
2927 user_connect_callback_
.Reset();
2928 server_cert_verify_result_
.Reset();
2929 completed_handshake_
= false;
2930 start_cert_verification_time_
= base::TimeTicks();
2936 bool SSLClientSocketNSS::IsConnected() const {
2938 bool ret
= completed_handshake_
&&
2939 (core_
->HasPendingAsyncOperation() ||
2940 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2941 transport_
->socket()->IsConnected());
2946 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2948 bool ret
= completed_handshake_
&&
2949 !core_
->HasPendingAsyncOperation() &&
2950 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2951 transport_
->socket()->IsConnectedAndIdle();
2956 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2957 return transport_
->socket()->GetPeerAddress(address
);
2960 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
2961 return transport_
->socket()->GetLocalAddress(address
);
2964 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
2968 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2969 if (transport_
.get() && transport_
->socket()) {
2970 transport_
->socket()->SetSubresourceSpeculation();
2976 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2977 if (transport_
.get() && transport_
->socket()) {
2978 transport_
->socket()->SetOmniboxSpeculation();
2984 bool SSLClientSocketNSS::WasEverUsed() const {
2985 if (transport_
.get() && transport_
->socket()) {
2986 return transport_
->socket()->WasEverUsed();
2992 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2993 if (transport_
.get() && transport_
->socket()) {
2994 return transport_
->socket()->UsingTCPFastOpen();
3000 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
3001 const CompletionCallback
& callback
) {
3002 DCHECK(core_
.get());
3003 DCHECK(!callback
.is_null());
3005 EnterFunction(buf_len
);
3006 int rv
= core_
->Read(buf
, buf_len
, callback
);
3012 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
3013 const CompletionCallback
& callback
) {
3014 DCHECK(core_
.get());
3015 DCHECK(!callback
.is_null());
3017 EnterFunction(buf_len
);
3018 int rv
= core_
->Write(buf
, buf_len
, callback
);
3024 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
3025 return transport_
->socket()->SetReceiveBufferSize(size
);
3028 bool SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
3029 return transport_
->socket()->SetSendBufferSize(size
);
3032 int SSLClientSocketNSS::Init() {
3034 // Initialize the NSS SSL library in a threadsafe way. This also
3035 // initializes the NSS base library.
3037 if (!NSS_IsInitialized())
3038 return ERR_UNEXPECTED
;
3039 #if defined(USE_NSS) || defined(OS_IOS)
3040 if (ssl_config_
.cert_io_enabled
) {
3041 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3042 // loop by MessageLoopForIO::current().
3043 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3044 EnsureNSSHttpIOInit();
3052 void SSLClientSocketNSS::InitCore() {
3053 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
3054 nss_task_runner_
.get(),
3059 server_bound_cert_service_
);
3062 int SSLClientSocketNSS::InitializeSSLOptions() {
3063 // Transport connected, now hook it up to nss
3064 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
3065 if (nss_fd_
== NULL
) {
3066 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
3069 // Grab pointer to buffers
3070 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
3072 /* Create SSL state machine */
3073 /* Push SSL onto our fake I/O socket */
3074 nss_fd_
= SSL_ImportFD(NULL
, nss_fd_
);
3075 if (nss_fd_
== NULL
) {
3076 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
3077 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
3079 // TODO(port): set more ssl options! Check errors!
3083 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
3084 if (rv
!= SECSuccess
) {
3085 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
3086 return ERR_UNEXPECTED
;
3089 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
3090 if (rv
!= SECSuccess
) {
3091 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3092 return ERR_UNEXPECTED
;
3095 // Don't do V2 compatible hellos because they don't support TLS extensions.
3096 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
3097 if (rv
!= SECSuccess
) {
3098 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3099 return ERR_UNEXPECTED
;
3102 SSLVersionRange version_range
;
3103 version_range
.min
= ssl_config_
.version_min
;
3104 version_range
.max
= ssl_config_
.version_max
;
3105 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
3106 if (rv
!= SECSuccess
) {
3107 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
3108 return ERR_NO_SSL_VERSIONS_ENABLED
;
3111 for (std::vector
<uint16
>::const_iterator it
=
3112 ssl_config_
.disabled_cipher_suites
.begin();
3113 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
3114 // This will fail if the specified cipher is not implemented by NSS, but
3115 // the failure is harmless.
3116 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
3120 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
3121 if (rv
!= SECSuccess
) {
3122 LogFailedNSSFunction(
3123 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3126 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
3127 ssl_config_
.false_start_enabled
);
3128 if (rv
!= SECSuccess
)
3129 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3131 // We allow servers to request renegotiation. Since we're a client,
3132 // prohibiting this is rather a waste of time. Only servers are in a
3133 // position to prevent renegotiation attacks.
3134 // http://extendedsubset.com/?p=8
3136 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
3137 SSL_RENEGOTIATE_TRANSITIONAL
);
3138 if (rv
!= SECSuccess
) {
3139 LogFailedNSSFunction(
3140 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3143 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
3144 if (rv
!= SECSuccess
)
3145 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3147 // Added in NSS 3.15
3148 #ifdef SSL_ENABLE_OCSP_STAPLING
3149 if (IsOCSPStaplingSupported()) {
3150 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, PR_TRUE
);
3151 if (rv
!= SECSuccess
) {
3152 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3153 "SSL_ENABLE_OCSP_STAPLING");
3158 // Chromium patch to libssl
3159 #ifdef SSL_ENABLE_CACHED_INFO
3160 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_CACHED_INFO
,
3161 ssl_config_
.cached_info_enabled
);
3162 if (rv
!= SECSuccess
)
3163 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3166 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
3167 if (rv
!= SECSuccess
) {
3168 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3169 return ERR_UNEXPECTED
;
3172 if (!core_
->Init(nss_fd_
, nss_bufs
))
3173 return ERR_UNEXPECTED
;
3175 // Tell SSL the hostname we're trying to connect to.
3176 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
3178 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3179 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
3184 int SSLClientSocketNSS::InitializeSSLPeerName() {
3185 // Tell NSS who we're connected to
3186 IPEndPoint peer_address
;
3187 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
3191 SockaddrStorage storage
;
3192 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
3193 return ERR_UNEXPECTED
;
3196 memset(&peername
, 0, sizeof(peername
));
3197 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
3198 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
3200 memcpy(&peername
, storage
.addr
, len
);
3202 // Adjust the address family field for BSD, whose sockaddr
3203 // structure has a one-byte length and one-byte address family
3204 // field at the beginning. PRNetAddr has a two-byte address
3205 // family field at the beginning.
3206 peername
.raw
.family
= storage
.addr
->sa_family
;
3208 memio_SetPeerName(nss_fd_
, &peername
);
3210 // Set the peer ID for session reuse. This is necessary when we create an
3211 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3212 // rather than the destination server's address in that case.
3213 std::string peer_id
= host_and_port_
.ToString();
3214 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3215 // This will cause session cache misses between sockets with different values
3216 // of ssl_session_cache_shard_ and this is used to partition the session cache
3217 // for incognito mode.
3218 if (!ssl_session_cache_shard_
.empty()) {
3219 peer_id
+= "/" + ssl_session_cache_shard_
;
3221 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
3222 if (rv
!= SECSuccess
)
3223 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
3228 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
3230 DCHECK_NE(ERR_IO_PENDING
, rv
);
3231 DCHECK(!user_connect_callback_
.is_null());
3233 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
3237 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
3238 EnterFunction(result
);
3239 int rv
= DoHandshakeLoop(result
);
3240 if (rv
!= ERR_IO_PENDING
) {
3241 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3242 DoConnectCallback(rv
);
3247 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
3248 EnterFunction(last_io_result
);
3249 int rv
= last_io_result
;
3251 // Default to STATE_NONE for next state.
3252 // (This is a quirk carried over from the windows
3253 // implementation. It makes reading the logs a bit harder.)
3254 // State handlers can and often do call GotoState just
3255 // to stay in the current state.
3256 State state
= next_handshake_state_
;
3257 GotoState(STATE_NONE
);
3259 case STATE_HANDSHAKE
:
3262 case STATE_HANDSHAKE_COMPLETE
:
3263 rv
= DoHandshakeComplete(rv
);
3265 case STATE_VERIFY_CERT
:
3267 rv
= DoVerifyCert(rv
);
3269 case STATE_VERIFY_CERT_COMPLETE
:
3270 rv
= DoVerifyCertComplete(rv
);
3274 rv
= ERR_UNEXPECTED
;
3275 LOG(DFATAL
) << "unexpected state " << state
;
3278 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3283 int SSLClientSocketNSS::DoHandshake() {
3285 int rv
= core_
->Connect(
3286 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3287 base::Unretained(this)));
3288 GotoState(STATE_HANDSHAKE_COMPLETE
);
3294 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3295 EnterFunction(result
);
3298 // SSL handshake is completed. Let's verify the certificate.
3299 GotoState(STATE_VERIFY_CERT
);
3302 set_channel_id_sent(core_
->state().channel_id_sent
);
3304 LeaveFunction(result
);
3309 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3310 DCHECK(!core_
->state().server_cert_chain
.empty());
3311 DCHECK(core_
->state().server_cert_chain
[0]);
3313 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3315 // If the certificate is expected to be bad we can use the expectation as
3317 base::StringPiece
der_cert(
3318 reinterpret_cast<char*>(
3319 core_
->state().server_cert_chain
[0]->derCert
.data
),
3320 core_
->state().server_cert_chain
[0]->derCert
.len
);
3321 CertStatus cert_status
;
3322 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3323 DCHECK(start_cert_verification_time_
.is_null());
3324 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3325 server_cert_verify_result_
.Reset();
3326 server_cert_verify_result_
.cert_status
= cert_status
;
3327 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3331 // We may have failed to create X509Certificate object if we are
3332 // running inside sandbox.
3333 if (!core_
->state().server_cert
.get()) {
3334 server_cert_verify_result_
.Reset();
3335 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3336 return ERR_CERT_INVALID
;
3339 start_cert_verification_time_
= base::TimeTicks::Now();
3342 if (ssl_config_
.rev_checking_enabled
)
3343 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3344 if (ssl_config_
.verify_ev_cert
)
3345 flags
|= CertVerifier::VERIFY_EV_CERT
;
3346 if (ssl_config_
.cert_io_enabled
)
3347 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3348 if (ssl_config_
.rev_checking_required_local_anchors
)
3349 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3350 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3351 return verifier_
->Verify(
3352 core_
->state().server_cert
.get(),
3353 host_and_port_
.host(),
3355 SSLConfigService::GetCRLSet().get(),
3356 &server_cert_verify_result_
,
3357 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3358 base::Unretained(this)),
3362 // Derived from AuthCertificateCallback() in
3363 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3364 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3367 if (!start_cert_verification_time_
.is_null()) {
3368 base::TimeDelta verify_time
=
3369 base::TimeTicks::Now() - start_cert_verification_time_
;
3371 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3373 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3376 // We used to remember the intermediate CA certs in the NSS database
3377 // persistently. However, NSS opens a connection to the SQLite database
3378 // during NSS initialization and doesn't close the connection until NSS
3379 // shuts down. If the file system where the database resides is gone,
3380 // the database connection goes bad. What's worse, the connection won't
3381 // recover when the file system comes back. Until this NSS or SQLite bug
3382 // is fixed, we need to avoid using the NSS database for non-essential
3383 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3384 // http://crbug.com/15630 for more info.
3386 // TODO(hclam): Skip logging if server cert was expected to be bad because
3387 // |server_cert_verify_result_| doesn't contain all the information about
3390 LogConnectionTypeMetrics();
3392 completed_handshake_
= true;
3394 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3395 // Take care of any mandates for public key pinning.
3397 // Pinning is only enabled for official builds to make sure that others don't
3398 // end up with pins that cannot be easily updated.
3400 // TODO(agl): We might have an issue here where a request for foo.example.com
3401 // merges into a SPDY connection to www.example.com, and gets a different
3404 // Perform pin validation if, and only if, all these conditions obtain:
3406 // * a TransportSecurityState object is available;
3407 // * the server's certificate chain is valid (or suffers from only a minor
3409 // * the server's certificate chain chains up to a known root (i.e. not a
3410 // user-installed trust anchor); and
3411 // * the build is recent (very old builds should fail open so that users
3412 // have some chance to recover).
3414 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3415 if (transport_security_state_
&&
3417 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3418 server_cert_verify_result_
.is_issued_by_known_root
&&
3419 TransportSecurityState::IsBuildTimely()) {
3420 bool sni_available
=
3421 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
||
3422 ssl_config_
.version_fallback
;
3423 const std::string
& host
= host_and_port_
.host();
3425 TransportSecurityState::DomainState domain_state
;
3426 if (transport_security_state_
->GetDomainState(host
, sni_available
,
3428 domain_state
.HasPublicKeyPins()) {
3429 if (!domain_state
.CheckPublicKeyPins(
3430 server_cert_verify_result_
.public_key_hashes
)) {
3431 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3432 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3433 TransportSecurityState::ReportUMAOnPinFailure(host
);
3435 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3441 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3442 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3446 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3447 UpdateConnectionTypeHistograms(CONNECTION_SSL
);
3448 int ssl_version
= SSLConnectionStatusToVersion(
3449 core_
->state().ssl_connection_status
);
3450 switch (ssl_version
) {
3451 case SSL_CONNECTION_VERSION_SSL2
:
3452 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2
);
3454 case SSL_CONNECTION_VERSION_SSL3
:
3455 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3
);
3457 case SSL_CONNECTION_VERSION_TLS1
:
3458 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1
);
3460 case SSL_CONNECTION_VERSION_TLS1_1
:
3461 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1
);
3463 case SSL_CONNECTION_VERSION_TLS1_2
:
3464 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2
);
3469 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3470 base::AutoLock
auto_lock(lock_
);
3471 if (valid_thread_id_
!= base::kInvalidThreadId
)
3473 valid_thread_id_
= base::PlatformThread::CurrentId();
3476 bool SSLClientSocketNSS::CalledOnValidThread() const {
3477 EnsureThreadIdAssigned();
3478 base::AutoLock
auto_lock(lock_
);
3479 return valid_thread_id_
== base::PlatformThread::CurrentId();
3482 ServerBoundCertService
* SSLClientSocketNSS::GetServerBoundCertService() const {
3483 return server_bound_cert_service_
;