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/ct_objects_extractor.h"
97 #include "net/cert/ct_verifier.h"
98 #include "net/cert/ct_verify_result.h"
99 #include "net/cert/scoped_nss_types.h"
100 #include "net/cert/sct_status_flags.h"
101 #include "net/cert/single_request_cert_verifier.h"
102 #include "net/cert/x509_certificate_net_log_param.h"
103 #include "net/cert/x509_util.h"
104 #include "net/http/transport_security_state.h"
105 #include "net/ocsp/nss_ocsp.h"
106 #include "net/socket/client_socket_handle.h"
107 #include "net/socket/nss_ssl_util.h"
108 #include "net/socket/ssl_error_params.h"
109 #include "net/ssl/ssl_cert_request_info.h"
110 #include "net/ssl/ssl_connection_status_flags.h"
111 #include "net/ssl/ssl_info.h"
115 #include <wincrypt.h>
117 #include "base/win/windows_version.h"
118 #elif defined(OS_MACOSX)
119 #include <Security/SecBase.h>
120 #include <Security/SecCertificate.h>
121 #include <Security/SecIdentity.h>
123 #include "base/mac/mac_logging.h"
124 #include "base/synchronization/lock.h"
125 #include "crypto/mac_security_services_lock.h"
126 #elif defined(USE_NSS)
132 // State machines are easier to debug if you log state transitions.
133 // Enable these if you want to see what's going on.
135 #define EnterFunction(x)
136 #define LeaveFunction(x)
137 #define GotoState(s) next_handshake_state_ = s
139 #define EnterFunction(x)\
140 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
141 << "; next_handshake_state " << next_handshake_state_
142 #define LeaveFunction(x)\
143 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
144 << "; next_handshake_state " << next_handshake_state_
145 #define GotoState(s)\
147 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
148 next_handshake_state_ = s;\
154 // SSL plaintext fragments are shorter than 16KB. Although the record layer
155 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
156 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
157 // entire SSL record.
158 const int kRecvBufferSize
= 17 * 1024;
159 const int kSendBufferSize
= 17 * 1024;
161 // Used by SSLClientSocketNSS::Core to indicate there is no read result
162 // obtained by a previous operation waiting to be returned to the caller.
163 // This constant can be any non-negative/non-zero value (eg: it does not
164 // overlap with any value of the net::Error range, including net::OK).
165 const int kNoPendingReadResult
= 1;
168 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
169 // set on Windows XP without error. There is some overhead from the server
170 // sending the OCSP response if it supports the extension, for the subset of
171 // XP clients who will request it but be unable to use it, but this is an
172 // acceptable trade-off for simplicity of implementation.
173 bool IsOCSPStaplingSupported() {
176 #elif defined(USE_NSS)
178 (*CacheOCSPResponseFromSideChannelFunction
)(
179 CERTCertDBHandle
*handle
, CERTCertificate
*cert
, PRTime time
,
180 SECItem
*encodedResponse
, void *pwArg
);
182 // On Linux, we dynamically link against the system version of libnss3.so. In
183 // order to continue working on systems without up-to-date versions of NSS we
184 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
186 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
187 // runtime symbol resolution that we need.
188 class RuntimeLibNSSFunctionPointers
{
190 CacheOCSPResponseFromSideChannelFunction
191 GetCacheOCSPResponseFromSideChannelFunction() {
192 return cache_ocsp_response_from_side_channel_
;
195 static RuntimeLibNSSFunctionPointers
* GetInstance() {
196 return Singleton
<RuntimeLibNSSFunctionPointers
>::get();
200 friend struct DefaultSingletonTraits
<RuntimeLibNSSFunctionPointers
>;
202 RuntimeLibNSSFunctionPointers() {
203 cache_ocsp_response_from_side_channel_
=
204 (CacheOCSPResponseFromSideChannelFunction
)
205 dlsym(RTLD_DEFAULT
, "CERT_CacheOCSPResponseFromSideChannel");
208 CacheOCSPResponseFromSideChannelFunction
209 cache_ocsp_response_from_side_channel_
;
212 CacheOCSPResponseFromSideChannelFunction
213 GetCacheOCSPResponseFromSideChannelFunction() {
214 return RuntimeLibNSSFunctionPointers::GetInstance()
215 ->GetCacheOCSPResponseFromSideChannelFunction();
218 bool IsOCSPStaplingSupported() {
219 return GetCacheOCSPResponseFromSideChannelFunction() != NULL
;
222 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
223 // certificate validation functions.
224 bool IsOCSPStaplingSupported() {
231 // This callback is intended to be used with CertFindChainInStore. In addition
232 // to filtering by extended/enhanced key usage, we do not show expired
233 // certificates and require digital signature usage in the key usage
236 // This matches our behavior on Mac OS X and that of NSS. It also matches the
237 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
238 // 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
239 BOOL WINAPI
ClientCertFindCallback(PCCERT_CONTEXT cert_context
,
241 VLOG(1) << "Calling ClientCertFindCallback from _nss";
242 // Verify the certificate's KU is good.
244 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING
, cert_context
->pCertInfo
,
246 if (!(key_usage
& CERT_DIGITAL_SIGNATURE_KEY_USAGE
))
249 DWORD err
= GetLastError();
250 // If |err| is non-zero, it's an actual error. Otherwise the extension
251 // just isn't present, and we treat it as if everything was allowed.
253 DLOG(ERROR
) << "CertGetIntendedKeyUsage failed: " << err
;
258 // Verify the current time is within the certificate's validity period.
259 if (CertVerifyTimeValidity(NULL
, cert_context
->pCertInfo
) != 0)
262 // Verify private key metadata is associated with this certificate.
264 if (!CertGetCertificateContextProperty(
265 cert_context
, CERT_KEY_PROV_INFO_PROP_ID
, NULL
, &size
)) {
274 // Helper functions to make it possible to log events from within the
275 // SSLClientSocketNSS::Core.
276 void AddLogEvent(const base::WeakPtr
<BoundNetLog
>& net_log
,
277 NetLog::EventType event_type
) {
280 net_log
->AddEvent(event_type
);
283 // Helper function to make it possible to log events from within the
284 // SSLClientSocketNSS::Core.
285 void AddLogEventWithCallback(const base::WeakPtr
<BoundNetLog
>& net_log
,
286 NetLog::EventType event_type
,
287 const NetLog::ParametersCallback
& callback
) {
290 net_log
->AddEvent(event_type
, callback
);
293 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
294 // from within the SSLClientSocketNSS::Core.
295 // AddByteTransferEvent expects to receive a const char*, which within the
296 // Core is backed by an IOBuffer. If the "const char*" is bound via
297 // base::Bind and posted to another thread, and the IOBuffer that backs that
298 // pointer then goes out of scope on the origin thread, this would result in
299 // an invalid read of a stale pointer.
300 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
301 // to the owning IOBuffer can be bound to the Callback. This ensures that the
302 // IOBuffer will stay alive long enough to cross threads if needed.
303 void LogByteTransferEvent(
304 const base::WeakPtr
<BoundNetLog
>& net_log
, NetLog::EventType event_type
,
305 int len
, IOBuffer
* buffer
) {
308 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
311 // PeerCertificateChain is a helper object which extracts the certificate
312 // chain, as given by the server, from an NSS socket and performs the needed
313 // resource management. The first element of the chain is the leaf certificate
314 // and the other elements are in the order given by the server.
315 class PeerCertificateChain
{
317 PeerCertificateChain() {}
318 PeerCertificateChain(const PeerCertificateChain
& other
);
319 ~PeerCertificateChain();
320 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
322 // Resets the current chain, freeing any resources, and updates the current
323 // chain to be a copy of the chain stored in |nss_fd|.
324 // If |nss_fd| is NULL, then the current certificate chain will be freed.
325 void Reset(PRFileDesc
* nss_fd
);
327 // Returns the current certificate chain as a vector of DER-encoded
328 // base::StringPieces. The returned vector remains valid until Reset is
330 std::vector
<base::StringPiece
> AsStringPieceVector() const;
332 bool empty() const { return certs_
.empty(); }
334 CERTCertificate
* operator[](size_t index
) const {
335 DCHECK_LT(index
, certs_
.size());
336 return certs_
[index
];
340 std::vector
<CERTCertificate
*> certs_
;
343 PeerCertificateChain::PeerCertificateChain(
344 const PeerCertificateChain
& other
) {
348 PeerCertificateChain::~PeerCertificateChain() {
352 PeerCertificateChain
& PeerCertificateChain::operator=(
353 const PeerCertificateChain
& other
) {
358 certs_
.reserve(other
.certs_
.size());
359 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
360 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
365 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
366 for (size_t i
= 0; i
< certs_
.size(); ++i
)
367 CERT_DestroyCertificate(certs_
[i
]);
373 CERTCertList
* list
= SSL_PeerCertificateChain(nss_fd
);
374 // The handshake on |nss_fd| may not have completed.
378 for (CERTCertListNode
* node
= CERT_LIST_HEAD(list
);
379 !CERT_LIST_END(node
, list
); node
= CERT_LIST_NEXT(node
)) {
380 certs_
.push_back(CERT_DupCertificate(node
->cert
));
382 CERT_DestroyCertList(list
);
385 std::vector
<base::StringPiece
>
386 PeerCertificateChain::AsStringPieceVector() const {
387 std::vector
<base::StringPiece
> v(certs_
.size());
388 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
389 v
[i
] = base::StringPiece(
390 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
391 certs_
[i
]->derCert
.len
);
397 // HandshakeState is a helper struct used to pass handshake state between
398 // the NSS task runner and the network task runner.
400 // It contains members that may be read or written on the NSS task runner,
401 // but which also need to be read from the network task runner. The NSS task
402 // runner will notify the network task runner whenever this state changes, so
403 // that the network task runner can safely make a copy, which avoids the need
405 struct HandshakeState
{
406 HandshakeState() { Reset(); }
409 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
411 server_protos
.clear();
412 channel_id_sent
= false;
413 server_cert_chain
.Reset(NULL
);
415 sct_list_from_tls_extension
.clear();
416 stapled_ocsp_response
.clear();
417 resumed_handshake
= false;
418 ssl_connection_status
= 0;
421 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
422 // negotiated protocol stored in |next_proto|.
423 SSLClientSocket::NextProtoStatus next_proto_status
;
424 std::string next_proto
;
425 // If the server supports NPN, the protocols supported by the server.
426 std::string server_protos
;
428 // True if a channel ID was sent.
429 bool channel_id_sent
;
431 // List of DER-encoded X.509 DistinguishedName of certificate authorities
432 // allowed by the server.
433 std::vector
<std::string
> cert_authorities
;
435 // Set when the handshake fully completes.
437 // The server certificate is first received from NSS as an NSS certificate
438 // chain (|server_cert_chain|) and then converted into a platform-specific
439 // X509Certificate object (|server_cert|). It's possible for some
440 // certificates to be successfully parsed by NSS, and not by the platform
441 // libraries (i.e.: when running within a sandbox, different parsing
442 // algorithms, etc), so it's not safe to assume that |server_cert| will
443 // always be non-NULL.
444 PeerCertificateChain server_cert_chain
;
445 scoped_refptr
<X509Certificate
> server_cert
;
446 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
447 std::string sct_list_from_tls_extension
;
448 // Stapled OCSP response received.
449 std::string stapled_ocsp_response
;
451 // True if the current handshake was the result of TLS session resumption.
452 bool resumed_handshake
;
454 // The negotiated security parameters (TLS version, cipher, extensions) of
455 // the SSL connection.
456 int ssl_connection_status
;
459 // Client-side error mapping functions.
461 // Map NSS error code to network error code.
462 int MapNSSClientError(PRErrorCode err
) {
464 case SSL_ERROR_BAD_CERT_ALERT
:
465 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
466 case SSL_ERROR_REVOKED_CERT_ALERT
:
467 case SSL_ERROR_EXPIRED_CERT_ALERT
:
468 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
469 case SSL_ERROR_UNKNOWN_CA_ALERT
:
470 case SSL_ERROR_ACCESS_DENIED_ALERT
:
471 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
473 return MapNSSError(err
);
479 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
480 // able to marshal data between NSS functions and an underlying transport
483 // All public functions are meant to be called from the network task runner,
484 // and any callbacks supplied will be invoked there as well, provided that
485 // Detach() has not been called yet.
487 /////////////////////////////////////////////////////////////////////////////
489 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
491 // Because NSS may block on either hardware or user input during operations
492 // such as signing, creating certificates, or locating private keys, the Core
493 // handles all of the interactions with the underlying NSS SSL socket, so
494 // that these blocking calls can be executed on a dedicated task runner.
496 // Note that the network task runner and the NSS task runner may be executing
497 // on the same thread. If that happens, then it's more performant to try to
498 // complete as much work as possible synchronously, even if it might block,
499 // rather than continually PostTask-ing to the same thread.
501 // Because NSS functions should only be called on the NSS task runner, while
502 // I/O resources should only be accessed on the network task runner, most
503 // public functions are implemented via three methods, each with different
504 // task runner affinities.
506 // In the single-threaded mode (where the network and NSS task runners run on
507 // the same thread), these are all attempted synchronously, while in the
508 // multi-threaded mode, message passing is used.
510 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
512 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
513 // (BufferRecv, BufferSend)
514 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
515 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
516 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
517 // data from the network task runner back to NSS (BufferRecvComplete,
518 // BufferSendComplete, OnHandshakeIOComplete)
520 /////////////////////////////////////////////////////////////////////////////
521 // Single-threaded example
523 // |--------------------------Network Task Runner--------------------------|
524 // SSLClientSocketNSS Core (Transport Socket)
526 // |-------------------------V
534 // |-------------------------V
536 // V-------------------------|
537 // BufferRecvComplete()
539 // PostOrRunCallback()
540 // V-------------------------|
543 /////////////////////////////////////////////////////////////////////////////
544 // Multi-threaded example:
546 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
547 // SSLClientSocketNSS Core Socket Core
549 // |---------------------V
551 // |-------------------------------V
557 // V-------------------------------|
559 // |----------------V
561 // V----------------|
562 // BufferRecvComplete()
563 // |-------------------------------V
564 // BufferRecvComplete()
566 // PostOrRunCallback()
567 // V-------------------------------|
568 // PostOrRunCallback()
569 // V---------------------|
572 /////////////////////////////////////////////////////////////////////////////
573 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
575 // Creates a new Core.
577 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
578 // that need to operate on the underlying transport, net log, or server
579 // bound certificate fetching will happen on the |network_task_runner|, so
580 // that their lifetimes match that of the owning SSLClientSocketNSS.
582 // The caller retains ownership of |transport|, |net_log|, and
583 // |server_bound_cert_service|, and they will not be accessed once Detach()
585 Core(base::SequencedTaskRunner
* network_task_runner
,
586 base::SequencedTaskRunner
* nss_task_runner
,
587 ClientSocketHandle
* transport
,
588 const HostPortPair
& host_and_port
,
589 const SSLConfig
& ssl_config
,
590 BoundNetLog
* net_log
,
591 ServerBoundCertService
* server_bound_cert_service
);
593 // Called on the network task runner.
594 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
595 // underlying memio implementation, to the Core. Returns true if the Core
596 // was successfully registered with the socket.
597 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
599 // Called on the network task runner.
601 // Attempts to perform an SSL handshake. If the handshake cannot be
602 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
603 // the network task runner once the handshake has completed. Otherwise,
604 // returns OK on success or a network error code on failure.
605 int Connect(const CompletionCallback
& callback
);
607 // Called on the network task runner.
608 // Signals that the resources owned by the network task runner are going
609 // away. No further callbacks will be invoked on the network task runner.
610 // May be called at any time.
613 // Called on the network task runner.
614 // Returns the current state of the underlying SSL socket. May be called at
616 const HandshakeState
& state() const { return network_handshake_state_
; }
618 // Called on the network task runner.
619 // Read() and Write() mirror the net::Socket functions of the same name.
620 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
621 // task runner at a later point, unless the caller calls Detach().
622 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
623 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
625 // Called on the network task runner.
626 bool IsConnected() const;
627 bool HasPendingAsyncOperation() const;
628 bool HasUnhandledReceivedData() const;
629 bool WasEverUsed() const;
631 // Called on the network task runner.
632 // Causes the associated SSL/TLS session ID to be added to NSS's session
633 // cache, but only if the connection has not been False Started.
635 // This should only be called after the server's certificate has been
636 // verified, and may not be called within an NSS callback.
637 void CacheSessionIfNecessary();
640 friend class base::RefCountedThreadSafe
<Core
>;
646 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
649 bool OnNSSTaskRunner() const;
650 bool OnNetworkTaskRunner() const;
652 ////////////////////////////////////////////////////////////////////////////
653 // Methods that are ONLY called on the NSS task runner:
654 ////////////////////////////////////////////////////////////////////////////
656 // Called by NSS during full handshakes to allow the application to
657 // verify the certificate. Instead of verifying the certificate in the midst
658 // of the handshake, SECSuccess is always returned and the peer's certificate
659 // is verified afterwards.
660 // This behaviour is an artifact of the original SSLClientSocketWin
661 // implementation, which could not verify the peer's certificate until after
662 // the handshake had completed, as well as bugs in NSS that prevent
663 // SSL_RestartHandshakeAfterCertReq from working.
664 static SECStatus
OwnAuthCertHandler(void* arg
,
669 // Callbacks called by NSS when the peer requests client certificate
671 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
673 #if defined(NSS_PLATFORM_CLIENT_AUTH)
674 // When NSS has been integrated with awareness of the underlying system
675 // cryptographic libraries, this callback allows the caller to supply a
676 // native platform certificate and key for use by NSS. At most, one of
677 // either (result_certs, result_private_key) or (result_nss_certificate,
678 // result_nss_private_key) should be set.
679 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
680 static SECStatus
PlatformClientAuthHandler(
683 CERTDistNames
* ca_names
,
684 CERTCertList
** result_certs
,
685 void** result_private_key
,
686 CERTCertificate
** result_nss_certificate
,
687 SECKEYPrivateKey
** result_nss_private_key
);
689 static SECStatus
ClientAuthHandler(void* arg
,
691 CERTDistNames
* ca_names
,
692 CERTCertificate
** result_certificate
,
693 SECKEYPrivateKey
** result_private_key
);
696 // Called by NSS to determine if we can False Start.
697 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
698 static SECStatus
CanFalseStartCallback(PRFileDesc
* socket
,
700 PRBool
* can_false_start
);
702 // Called by NSS once the handshake has completed.
703 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
704 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
706 // Called once the handshake has succeeded.
707 void HandshakeSucceeded();
709 // Handles an NSS error generated while handshaking or performing IO.
710 // Returns a network error code mapped from the original NSS error.
711 int HandleNSSError(PRErrorCode error
);
713 int DoHandshakeLoop(int last_io_result
);
714 int DoReadLoop(int result
);
715 int DoWriteLoop(int result
);
718 int DoGetDBCertComplete(int result
);
721 int DoPayloadWrite();
723 bool DoTransportIO();
727 void OnRecvComplete(int result
);
728 void OnSendComplete(int result
);
730 void DoConnectCallback(int result
);
731 void DoReadCallback(int result
);
732 void DoWriteCallback(int result
);
734 // Client channel ID handler.
735 static SECStatus
ClientChannelIDHandler(
738 SECKEYPublicKey
**out_public_key
,
739 SECKEYPrivateKey
**out_private_key
);
741 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
742 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
743 // and an error code otherwise.
744 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
745 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
746 // takes ownership of the |*cert| and |*key|.
747 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
749 // Updates the NSS and platform specific certificates.
750 void UpdateServerCert();
751 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
752 // received in the handshake via a TLS extension.
753 void UpdateSignedCertTimestamps();
754 // Update the OCSP response cache with the stapled response received in the
755 // handshake, and update nss_handshake_state_ with
756 // the SignedCertificateTimestampList received in the stapled OCSP response.
757 void UpdateStapledOCSPResponse();
758 // Updates the nss_handshake_state_ with the negotiated security parameters.
759 void UpdateConnectionStatus();
760 // Record histograms for channel id support during full handshakes - resumed
761 // handshakes are ignored.
762 void RecordChannelIDSupportOnNSSTaskRunner();
763 // UpdateNextProto gets any application-layer protocol that may have been
764 // negotiated by the TLS connection.
765 void UpdateNextProto();
767 ////////////////////////////////////////////////////////////////////////////
768 // Methods that are ONLY called on the network task runner:
769 ////////////////////////////////////////////////////////////////////////////
770 int DoBufferRecv(IOBuffer
* buffer
, int len
);
771 int DoBufferSend(IOBuffer
* buffer
, int len
);
772 int DoGetDomainBoundCert(const std::string
& host
);
774 void OnGetDomainBoundCertComplete(int result
);
775 void OnHandshakeStateUpdated(const HandshakeState
& state
);
776 void OnNSSBufferUpdated(int amount_in_read_buffer
);
777 void DidNSSRead(int result
);
778 void DidNSSWrite(int result
);
779 void RecordChannelIDSupportOnNetworkTaskRunner(
780 bool negotiated_channel_id
,
781 bool channel_id_enabled
,
782 bool supports_ecc
) const;
784 ////////////////////////////////////////////////////////////////////////////
785 // Methods that are called on both the network task runner and the NSS
787 ////////////////////////////////////////////////////////////////////////////
788 void OnHandshakeIOComplete(int result
);
789 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
790 void BufferSendComplete(int result
);
792 // PostOrRunCallback is a helper function to ensure that |callback| is
793 // invoked on the network task runner, but only if Detach() has not yet
795 void PostOrRunCallback(const tracked_objects::Location
& location
,
796 const base::Closure
& callback
);
798 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
799 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
800 void AddCertProvidedEvent(int cert_count
);
802 // Sets the handshake state |channel_id_sent| flag and logs the
803 // SSL_CHANNEL_ID_PROVIDED event.
804 void SetChannelIDProvided();
806 ////////////////////////////////////////////////////////////////////////////
807 // Members that are ONLY accessed on the network task runner:
808 ////////////////////////////////////////////////////////////////////////////
810 // True if the owning SSLClientSocketNSS has called Detach(). No further
811 // callbacks will be invoked nor access to members owned by the network
815 // The underlying transport to use for network IO.
816 ClientSocketHandle
* transport_
;
817 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
819 // The current handshake state. Mirrors |nss_handshake_state_|.
820 HandshakeState network_handshake_state_
;
822 // The service for retrieving Channel ID keys. May be NULL.
823 ServerBoundCertService
* server_bound_cert_service_
;
824 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_
;
826 // The information about NSS task runner.
827 int unhandled_buffer_size_
;
828 bool nss_waiting_read_
;
829 bool nss_waiting_write_
;
832 // Set when Read() or Write() successfully reads or writes data to or from the
836 ////////////////////////////////////////////////////////////////////////////
837 // Members that are ONLY accessed on the NSS task runner:
838 ////////////////////////////////////////////////////////////////////////////
839 HostPortPair host_and_port_
;
840 SSLConfig ssl_config_
;
845 // Buffers for the network end of the SSL state machine
846 memio_Private
* nss_bufs_
;
848 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
849 // as much data as possible, without blocking.
850 // If DoPayloadRead() encounters an error after having read some data, stores
851 // the results to return on the *next* call to DoPayloadRead(). A value of
852 // kNoPendingReadResult indicates there is no pending result, otherwise 0
853 // indicates EOF and < 0 indicates an error.
854 int pending_read_result_
;
855 // Contains the previously observed NSS error. Only valid when
856 // pending_read_result_ != kNoPendingReadResult.
857 PRErrorCode pending_read_nss_error_
;
859 // The certificate chain, in DER form, that is expected to be received from
861 std::vector
<std::string
> predicted_certs_
;
863 State next_handshake_state_
;
865 // True if channel ID extension was negotiated.
866 bool channel_id_xtn_negotiated_
;
867 // True if the handshake state machine was interrupted for channel ID.
868 bool channel_id_needed_
;
869 // True if the handshake state machine was interrupted for client auth.
870 bool client_auth_cert_needed_
;
871 // True if NSS has False Started.
873 // True if NSS has called HandshakeCallback.
874 bool handshake_callback_called_
;
876 HandshakeState nss_handshake_state_
;
878 bool transport_recv_busy_
;
879 bool transport_recv_eof_
;
880 bool transport_send_busy_
;
882 // Used by Read function.
883 scoped_refptr
<IOBuffer
> user_read_buf_
;
884 int user_read_buf_len_
;
886 // Used by Write function.
887 scoped_refptr
<IOBuffer
> user_write_buf_
;
888 int user_write_buf_len_
;
890 CompletionCallback user_connect_callback_
;
891 CompletionCallback user_read_callback_
;
892 CompletionCallback user_write_callback_
;
894 ////////////////////////////////////////////////////////////////////////////
895 // Members that are accessed on both the network task runner and the NSS
897 ////////////////////////////////////////////////////////////////////////////
898 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
899 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
901 // Dereferenced only on the network task runner, but bound to tasks destined
902 // for the network task runner from the NSS task runner.
903 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
905 // Written on the network task runner by the |server_bound_cert_service_|,
906 // prior to invoking OnHandshakeIOComplete.
907 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
908 // on the NSS task runner.
909 std::string domain_bound_private_key_
;
910 std::string domain_bound_cert_
;
912 DISALLOW_COPY_AND_ASSIGN(Core
);
915 SSLClientSocketNSS::Core::Core(
916 base::SequencedTaskRunner
* network_task_runner
,
917 base::SequencedTaskRunner
* nss_task_runner
,
918 ClientSocketHandle
* transport
,
919 const HostPortPair
& host_and_port
,
920 const SSLConfig
& ssl_config
,
921 BoundNetLog
* net_log
,
922 ServerBoundCertService
* server_bound_cert_service
)
924 transport_(transport
),
925 weak_net_log_factory_(net_log
),
926 server_bound_cert_service_(server_bound_cert_service
),
927 unhandled_buffer_size_(0),
928 nss_waiting_read_(false),
929 nss_waiting_write_(false),
930 nss_is_closed_(false),
931 was_ever_used_(false),
932 host_and_port_(host_and_port
),
933 ssl_config_(ssl_config
),
936 pending_read_result_(kNoPendingReadResult
),
937 pending_read_nss_error_(0),
938 next_handshake_state_(STATE_NONE
),
939 channel_id_xtn_negotiated_(false),
940 channel_id_needed_(false),
941 client_auth_cert_needed_(false),
942 false_started_(false),
943 handshake_callback_called_(false),
944 transport_recv_busy_(false),
945 transport_recv_eof_(false),
946 transport_send_busy_(false),
947 user_read_buf_len_(0),
948 user_write_buf_len_(0),
949 network_task_runner_(network_task_runner
),
950 nss_task_runner_(nss_task_runner
),
951 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()) {
954 SSLClientSocketNSS::Core::~Core() {
955 // TODO(wtc): Send SSL close_notify alert.
956 if (nss_fd_
!= NULL
) {
963 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
964 memio_Private
* buffers
) {
965 DCHECK(OnNetworkTaskRunner());
972 SECStatus rv
= SECSuccess
;
974 if (!ssl_config_
.next_protos
.empty()) {
975 size_t wire_length
= 0;
976 for (std::vector
<std::string
>::const_iterator
977 i
= ssl_config_
.next_protos
.begin();
978 i
!= ssl_config_
.next_protos
.end(); ++i
) {
979 if (i
->size() > 255) {
980 LOG(WARNING
) << "Ignoring overlong NPN/ALPN protocol: " << *i
;
983 wire_length
+= i
->size();
986 scoped_ptr
<uint8
[]> wire_protos(new uint8
[wire_length
]);
987 uint8
* dst
= wire_protos
.get();
988 for (std::vector
<std::string
>::const_iterator
989 i
= ssl_config_
.next_protos
.begin();
990 i
!= ssl_config_
.next_protos
.end(); i
++) {
994 memcpy(dst
, i
->data(), i
->size());
997 DCHECK_EQ(dst
, wire_protos
.get() + wire_length
);
998 rv
= SSL_SetNextProtoNego(nss_fd_
, wire_protos
.get(), wire_length
);
999 if (rv
!= SECSuccess
)
1000 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoNego", "");
1001 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_ALPN
, PR_TRUE
);
1002 if (rv
!= SECSuccess
)
1003 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_ALPN");
1004 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_NPN
, PR_TRUE
);
1005 if (rv
!= SECSuccess
)
1006 LogFailedNSSFunction(*weak_net_log_
, "SSL_OptionSet", "SSL_ENABLE_NPN");
1009 rv
= SSL_AuthCertificateHook(
1010 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
1011 if (rv
!= SECSuccess
) {
1012 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
1016 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1017 rv
= SSL_GetPlatformClientAuthDataHook(
1018 nss_fd_
, SSLClientSocketNSS::Core::PlatformClientAuthHandler
,
1021 rv
= SSL_GetClientAuthDataHook(
1022 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
1024 if (rv
!= SECSuccess
) {
1025 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
1029 if (IsChannelIDEnabled(ssl_config_
, server_bound_cert_service_
)) {
1030 rv
= SSL_SetClientChannelIDCallback(
1031 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
1032 if (rv
!= SECSuccess
) {
1033 LogFailedNSSFunction(
1034 *weak_net_log_
, "SSL_SetClientChannelIDCallback", "");
1038 rv
= SSL_SetCanFalseStartCallback(
1039 nss_fd_
, SSLClientSocketNSS::Core::CanFalseStartCallback
, this);
1040 if (rv
!= SECSuccess
) {
1041 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetCanFalseStartCallback", "");
1045 rv
= SSL_HandshakeCallback(
1046 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
1047 if (rv
!= SECSuccess
) {
1048 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
1055 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
1056 if (!OnNSSTaskRunner()) {
1058 bool posted
= nss_task_runner_
->PostTask(
1060 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
1061 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1064 DCHECK(OnNSSTaskRunner());
1065 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1066 DCHECK(user_read_callback_
.is_null());
1067 DCHECK(user_write_callback_
.is_null());
1068 DCHECK(user_connect_callback_
.is_null());
1069 DCHECK(!user_read_buf_
.get());
1070 DCHECK(!user_write_buf_
.get());
1072 next_handshake_state_
= STATE_HANDSHAKE
;
1073 int rv
= DoHandshakeLoop(OK
);
1074 if (rv
== ERR_IO_PENDING
) {
1075 user_connect_callback_
= callback
;
1076 } else if (rv
> OK
) {
1079 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
1080 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1081 return ERR_IO_PENDING
;
1087 void SSLClientSocketNSS::Core::Detach() {
1088 DCHECK(OnNetworkTaskRunner());
1092 weak_net_log_factory_
.InvalidateWeakPtrs();
1094 network_handshake_state_
.Reset();
1096 domain_bound_cert_request_handle_
.Cancel();
1099 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1100 const CompletionCallback
& callback
) {
1101 if (!OnNSSTaskRunner()) {
1102 DCHECK(OnNetworkTaskRunner());
1105 DCHECK(!nss_waiting_read_
);
1107 nss_waiting_read_
= true;
1108 bool posted
= nss_task_runner_
->PostTask(
1110 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1111 buf_len
, callback
));
1113 nss_is_closed_
= true;
1114 nss_waiting_read_
= false;
1116 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1119 DCHECK(OnNSSTaskRunner());
1120 DCHECK(false_started_
|| handshake_callback_called_
);
1121 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1122 DCHECK(user_read_callback_
.is_null());
1123 DCHECK(user_connect_callback_
.is_null());
1124 DCHECK(!user_read_buf_
.get());
1127 user_read_buf_
= buf
;
1128 user_read_buf_len_
= buf_len
;
1130 int rv
= DoReadLoop(OK
);
1131 if (rv
== ERR_IO_PENDING
) {
1132 if (OnNetworkTaskRunner())
1133 nss_waiting_read_
= true;
1134 user_read_callback_
= callback
;
1136 user_read_buf_
= NULL
;
1137 user_read_buf_len_
= 0;
1139 if (!OnNetworkTaskRunner()) {
1140 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1141 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1142 return ERR_IO_PENDING
;
1144 DCHECK(!nss_waiting_read_
);
1146 nss_is_closed_
= true;
1148 was_ever_used_
= true;
1156 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1157 const CompletionCallback
& callback
) {
1158 if (!OnNSSTaskRunner()) {
1159 DCHECK(OnNetworkTaskRunner());
1162 DCHECK(!nss_waiting_write_
);
1164 nss_waiting_write_
= true;
1165 bool posted
= nss_task_runner_
->PostTask(
1167 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1168 buf_len
, callback
));
1170 nss_is_closed_
= true;
1171 nss_waiting_write_
= false;
1173 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1176 DCHECK(OnNSSTaskRunner());
1177 DCHECK(false_started_
|| handshake_callback_called_
);
1178 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1179 DCHECK(user_write_callback_
.is_null());
1180 DCHECK(user_connect_callback_
.is_null());
1181 DCHECK(!user_write_buf_
.get());
1184 user_write_buf_
= buf
;
1185 user_write_buf_len_
= buf_len
;
1187 int rv
= DoWriteLoop(OK
);
1188 if (rv
== ERR_IO_PENDING
) {
1189 if (OnNetworkTaskRunner())
1190 nss_waiting_write_
= true;
1191 user_write_callback_
= callback
;
1193 user_write_buf_
= NULL
;
1194 user_write_buf_len_
= 0;
1196 if (!OnNetworkTaskRunner()) {
1197 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1198 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1199 return ERR_IO_PENDING
;
1201 DCHECK(!nss_waiting_write_
);
1203 nss_is_closed_
= true;
1204 } else if (rv
> 0) {
1205 was_ever_used_
= true;
1213 bool SSLClientSocketNSS::Core::IsConnected() const {
1214 DCHECK(OnNetworkTaskRunner());
1215 return !nss_is_closed_
;
1218 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1219 DCHECK(OnNetworkTaskRunner());
1220 return nss_waiting_read_
|| nss_waiting_write_
;
1223 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1224 DCHECK(OnNetworkTaskRunner());
1225 return unhandled_buffer_size_
!= 0;
1228 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1229 DCHECK(OnNetworkTaskRunner());
1230 return was_ever_used_
;
1233 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1234 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1235 // nss_fd_. However, it happens on the network task runner in order to match
1236 // the buggy behavior of ExportKeyingMaterial.
1238 // Once http://crbug.com/330360 is fixed, this should be moved to an
1239 // implementation that exclusively does this work on the NSS TaskRunner. This
1240 // is "safe" because it is only called during the certificate verification
1241 // state machine of the main socket, which is safe because no underlying
1242 // transport IO will be occuring in that state, and NSS will not be blocking
1243 // on any PKCS#11 related locks that might block the Network TaskRunner.
1244 DCHECK(OnNetworkTaskRunner());
1246 // Only cache the session if the connection was not False Started, because
1247 // sessions should only be cached *after* the peer's Finished message is
1249 // In the case of False Start, the session will be cached once the
1250 // HandshakeCallback is called, which signals the receipt and processing of
1251 // the Finished message, and which will happen during a call to
1252 // PR_Read/PR_Write.
1253 if (!false_started_
)
1254 SSL_CacheSession(nss_fd_
);
1257 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1258 return nss_task_runner_
->RunsTasksOnCurrentThread();
1261 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1262 return network_task_runner_
->RunsTasksOnCurrentThread();
1266 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1271 Core
* core
= reinterpret_cast<Core
*>(arg
);
1272 if (core
->handshake_callback_called_
) {
1273 // Disallow the server certificate to change in a renegotiation.
1274 CERTCertificate
* old_cert
= core
->nss_handshake_state_
.server_cert_chain
[0];
1275 ScopedCERTCertificate
new_cert(SSL_PeerCertificate(socket
));
1276 if (new_cert
->derCert
.len
!= old_cert
->derCert
.len
||
1277 memcmp(new_cert
->derCert
.data
, old_cert
->derCert
.data
,
1278 new_cert
->derCert
.len
) != 0) {
1279 // NSS doesn't have an error code that indicates the server certificate
1280 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1281 // for this purpose.
1282 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE
);
1287 // Tell NSS to not verify the certificate.
1291 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1293 SECStatus
SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1296 CERTDistNames
* ca_names
,
1297 CERTCertList
** result_certs
,
1298 void** result_private_key
,
1299 CERTCertificate
** result_nss_certificate
,
1300 SECKEYPrivateKey
** result_nss_private_key
) {
1301 Core
* core
= reinterpret_cast<Core
*>(arg
);
1302 DCHECK(core
->OnNSSTaskRunner());
1304 core
->PostOrRunCallback(
1306 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1307 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1309 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1311 if (core
->ssl_config_
.send_client_cert
) {
1312 if (core
->ssl_config_
.client_cert
) {
1313 PCCERT_CONTEXT cert_context
=
1314 core
->ssl_config_
.client_cert
->os_cert_handle();
1316 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
1318 BOOL must_free
= FALSE
;
1320 if (base::win::GetVersion() >= base::win::VERSION_VISTA
)
1321 flags
|= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
;
1323 BOOL acquired_key
= CryptAcquireCertificatePrivateKey(
1324 cert_context
, flags
, NULL
, &crypt_prov
, &key_spec
, &must_free
);
1327 // Should never get a cached handle back - ownership must always be
1329 CHECK_EQ(must_free
, TRUE
);
1332 der_cert
.type
= siDERCertBuffer
;
1333 der_cert
.data
= cert_context
->pbCertEncoded
;
1334 der_cert
.len
= cert_context
->cbCertEncoded
;
1336 // TODO(rsleevi): Error checking for NSS allocation errors.
1337 CERTCertDBHandle
* db_handle
= CERT_GetDefaultCertDB();
1338 CERTCertificate
* user_cert
= CERT_NewTempCertificate(
1339 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1341 // Importing the certificate can fail for reasons including a serial
1342 // number collision. See crbug.com/97355.
1343 core
->AddCertProvidedEvent(0);
1346 CERTCertList
* cert_chain
= CERT_NewCertList();
1347 CERT_AddCertToListTail(cert_chain
, user_cert
);
1349 // Add the intermediates.
1350 X509Certificate::OSCertHandles intermediates
=
1351 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1352 for (X509Certificate::OSCertHandles::const_iterator it
=
1353 intermediates
.begin(); it
!= intermediates
.end(); ++it
) {
1354 der_cert
.data
= (*it
)->pbCertEncoded
;
1355 der_cert
.len
= (*it
)->cbCertEncoded
;
1357 CERTCertificate
* intermediate
= CERT_NewTempCertificate(
1358 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1359 if (!intermediate
) {
1360 CERT_DestroyCertList(cert_chain
);
1361 core
->AddCertProvidedEvent(0);
1364 CERT_AddCertToListTail(cert_chain
, intermediate
);
1366 PCERT_KEY_CONTEXT key_context
= reinterpret_cast<PCERT_KEY_CONTEXT
>(
1367 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT
)));
1368 key_context
->cbSize
= sizeof(*key_context
);
1369 // NSS will free this context when no longer in use.
1370 key_context
->hCryptProv
= crypt_prov
;
1371 key_context
->dwKeySpec
= key_spec
;
1372 *result_private_key
= key_context
;
1373 *result_certs
= cert_chain
;
1375 int cert_count
= 1 + intermediates
.size();
1376 core
->AddCertProvidedEvent(cert_count
);
1379 LOG(WARNING
) << "Client cert found without private key";
1382 // Send no client certificate.
1383 core
->AddCertProvidedEvent(0);
1387 core
->nss_handshake_state_
.cert_authorities
.clear();
1389 std::vector
<CERT_NAME_BLOB
> issuer_list(ca_names
->nnames
);
1390 for (int i
= 0; i
< ca_names
->nnames
; ++i
) {
1391 issuer_list
[i
].cbData
= ca_names
->names
[i
].len
;
1392 issuer_list
[i
].pbData
= ca_names
->names
[i
].data
;
1393 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1394 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1395 static_cast<size_t>(ca_names
->names
[i
].len
)));
1398 // Update the network task runner's view of the handshake state now that
1399 // server certificate request has been recorded.
1400 core
->PostOrRunCallback(
1401 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1402 core
->nss_handshake_state_
));
1404 // Tell NSS to suspend the client authentication. We will then abort the
1405 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1406 return SECWouldBlock
;
1407 #elif defined(OS_MACOSX)
1408 if (core
->ssl_config_
.send_client_cert
) {
1409 if (core
->ssl_config_
.client_cert
.get()) {
1410 OSStatus os_error
= noErr
;
1411 SecIdentityRef identity
= NULL
;
1412 SecKeyRef private_key
= NULL
;
1413 X509Certificate::OSCertHandles chain
;
1415 base::AutoLock
lock(crypto::GetMacSecurityServicesLock());
1416 os_error
= SecIdentityCreateWithCertificate(
1417 NULL
, core
->ssl_config_
.client_cert
->os_cert_handle(), &identity
);
1419 if (os_error
== noErr
) {
1420 os_error
= SecIdentityCopyPrivateKey(identity
, &private_key
);
1421 CFRelease(identity
);
1424 if (os_error
== noErr
) {
1425 // TODO(rsleevi): Error checking for NSS allocation errors.
1426 *result_certs
= CERT_NewCertList();
1427 *result_private_key
= private_key
;
1429 chain
.push_back(core
->ssl_config_
.client_cert
->os_cert_handle());
1430 const X509Certificate::OSCertHandles
& intermediates
=
1431 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1432 if (!intermediates
.empty())
1433 chain
.insert(chain
.end(), intermediates
.begin(), intermediates
.end());
1435 for (size_t i
= 0, chain_count
= chain
.size(); i
< chain_count
; ++i
) {
1436 CSSM_DATA cert_data
;
1437 SecCertificateRef cert_ref
= chain
[i
];
1438 os_error
= SecCertificateGetData(cert_ref
, &cert_data
);
1439 if (os_error
!= noErr
)
1443 der_cert
.type
= siDERCertBuffer
;
1444 der_cert
.data
= cert_data
.Data
;
1445 der_cert
.len
= cert_data
.Length
;
1446 CERTCertificate
* nss_cert
= CERT_NewTempCertificate(
1447 CERT_GetDefaultCertDB(), &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1449 // In the event of an NSS error, make up an OS error and reuse
1450 // the error handling below.
1451 os_error
= errSecCreateChainFailed
;
1454 CERT_AddCertToListTail(*result_certs
, nss_cert
);
1458 if (os_error
== noErr
) {
1459 core
->AddCertProvidedEvent(chain
.size());
1463 OSSTATUS_LOG(WARNING
, os_error
)
1464 << "Client cert found, but could not be used";
1465 if (*result_certs
) {
1466 CERT_DestroyCertList(*result_certs
);
1467 *result_certs
= NULL
;
1469 if (*result_private_key
)
1470 *result_private_key
= NULL
;
1472 CFRelease(private_key
);
1475 // Send no client certificate.
1476 core
->AddCertProvidedEvent(0);
1480 core
->nss_handshake_state_
.cert_authorities
.clear();
1482 // Retrieve the cert issuers accepted by the server.
1483 std::vector
<CertPrincipal
> valid_issuers
;
1484 int n
= ca_names
->nnames
;
1485 for (int i
= 0; i
< n
; i
++) {
1486 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1487 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1488 static_cast<size_t>(ca_names
->names
[i
].len
)));
1491 // Update the network task runner's view of the handshake state now that
1492 // server certificate request has been recorded.
1493 core
->PostOrRunCallback(
1494 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1495 core
->nss_handshake_state_
));
1497 // Tell NSS to suspend the client authentication. We will then abort the
1498 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1499 return SECWouldBlock
;
1505 #elif defined(OS_IOS)
1507 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1510 CERTDistNames
* ca_names
,
1511 CERTCertificate
** result_certificate
,
1512 SECKEYPrivateKey
** result_private_key
) {
1513 Core
* core
= reinterpret_cast<Core
*>(arg
);
1514 DCHECK(core
->OnNSSTaskRunner());
1516 core
->PostOrRunCallback(
1518 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1519 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1521 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1522 LOG(WARNING
) << "Client auth is not supported";
1524 // Never send a certificate.
1525 core
->AddCertProvidedEvent(0);
1529 #else // NSS_PLATFORM_CLIENT_AUTH
1532 // Based on Mozilla's NSS_GetClientAuthData.
1533 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1536 CERTDistNames
* ca_names
,
1537 CERTCertificate
** result_certificate
,
1538 SECKEYPrivateKey
** result_private_key
) {
1539 Core
* core
= reinterpret_cast<Core
*>(arg
);
1540 DCHECK(core
->OnNSSTaskRunner());
1542 core
->PostOrRunCallback(
1544 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1545 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1547 // Regular client certificate requested.
1548 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1549 void* wincx
= SSL_RevealPinArg(socket
);
1551 if (core
->ssl_config_
.send_client_cert
) {
1552 // Second pass: a client certificate should have been selected.
1553 if (core
->ssl_config_
.client_cert
.get()) {
1554 CERTCertificate
* cert
=
1555 CERT_DupCertificate(core
->ssl_config_
.client_cert
->os_cert_handle());
1556 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1558 // TODO(jsorianopastor): We should wait for server certificate
1559 // verification before sending our credentials. See
1560 // http://crbug.com/13934.
1561 *result_certificate
= cert
;
1562 *result_private_key
= privkey
;
1563 // A cert_count of -1 means the number of certificates is unknown.
1564 // NSS will construct the certificate chain.
1565 core
->AddCertProvidedEvent(-1);
1569 LOG(WARNING
) << "Client cert found without private key";
1571 // Send no client certificate.
1572 core
->AddCertProvidedEvent(0);
1576 // First pass: client certificate is needed.
1577 core
->nss_handshake_state_
.cert_authorities
.clear();
1579 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1580 // the server and save them in |cert_authorities|.
1581 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1582 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1583 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1584 static_cast<size_t>(ca_names
->names
[i
].len
)));
1587 // Update the network task runner's view of the handshake state now that
1588 // server certificate request has been recorded.
1589 core
->PostOrRunCallback(
1590 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1591 core
->nss_handshake_state_
));
1593 // Tell NSS to suspend the client authentication. We will then abort the
1594 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1595 return SECWouldBlock
;
1597 #endif // NSS_PLATFORM_CLIENT_AUTH
1600 SECStatus
SSLClientSocketNSS::Core::CanFalseStartCallback(
1603 PRBool
* can_false_start
) {
1604 // If the server doesn't support NPN or ALPN, then we don't do False
1606 PRBool negotiated_extension
;
1607 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1608 ssl_app_layer_protocol_xtn
,
1609 &negotiated_extension
);
1610 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1611 rv
= SSL_HandshakeNegotiatedExtension(socket
,
1612 ssl_next_proto_nego_xtn
,
1613 &negotiated_extension
);
1615 if (rv
!= SECSuccess
|| !negotiated_extension
) {
1616 *can_false_start
= PR_FALSE
;
1620 return SSL_RecommendedCanFalseStart(socket
, can_false_start
);
1624 void SSLClientSocketNSS::Core::HandshakeCallback(
1627 Core
* core
= reinterpret_cast<Core
*>(arg
);
1628 DCHECK(core
->OnNSSTaskRunner());
1630 core
->handshake_callback_called_
= true;
1631 if (core
->false_started_
) {
1632 core
->false_started_
= false;
1633 // If the connection was False Started, then at the time of this callback,
1634 // the peer's certificate will have been verified or the caller will have
1635 // accepted the error.
1636 // This is guaranteed when using False Start because this callback will
1637 // not be invoked until processing the peer's Finished message, which
1638 // will only happen in a PR_Read/PR_Write call, which can only happen
1639 // after the peer's certificate is verified.
1640 SSL_CacheSessionUnlocked(socket
);
1642 // Additionally, when False Starting, DoHandshake() will have already
1643 // called HandshakeSucceeded(), so return now.
1646 core
->HandshakeSucceeded();
1649 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1650 DCHECK(OnNSSTaskRunner());
1652 PRBool last_handshake_resumed
;
1653 SECStatus rv
= SSL_HandshakeResumedSession(nss_fd_
, &last_handshake_resumed
);
1654 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1655 nss_handshake_state_
.resumed_handshake
= true;
1657 nss_handshake_state_
.resumed_handshake
= false;
1660 RecordChannelIDSupportOnNSSTaskRunner();
1662 UpdateSignedCertTimestamps();
1663 UpdateStapledOCSPResponse();
1664 UpdateConnectionStatus();
1667 // Update the network task runners view of the handshake state whenever
1668 // a handshake has completed.
1670 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
1671 nss_handshake_state_
));
1674 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
) {
1675 DCHECK(OnNSSTaskRunner());
1677 int net_error
= MapNSSClientError(nss_error
);
1680 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1681 // os_cert_handle() as an optimization. However, if the certificate
1682 // private key is stored on a smart card, and the smart card is removed,
1683 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1684 // preventing client certificate authentication. Because the
1685 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1686 // caching in X509Certificate, this failure ends up preventing client
1687 // certificate authentication with the same certificate for all future
1688 // attempts, even after the smart card has been re-inserted. By setting
1689 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1690 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1691 // the certificate on the next attempt, which should succeed if the smart
1692 // card has been re-inserted, or will typically prompt the user to
1693 // re-insert the smart card if not.
1694 if ((net_error
== ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
||
1695 net_error
== ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
) &&
1696 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
) {
1697 CertSetCertificateContextProperty(
1698 ssl_config_
.client_cert
->os_cert_handle(),
1699 CERT_KEY_PROV_HANDLE_PROP_ID
, 0, NULL
);
1706 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1707 DCHECK(OnNSSTaskRunner());
1709 int rv
= last_io_result
;
1711 // Default to STATE_NONE for next state.
1712 State state
= next_handshake_state_
;
1713 GotoState(STATE_NONE
);
1716 case STATE_HANDSHAKE
:
1719 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1720 rv
= DoGetDBCertComplete(rv
);
1724 rv
= ERR_UNEXPECTED
;
1725 LOG(DFATAL
) << "unexpected state " << state
;
1729 // Do the actual network I/O
1730 bool network_moved
= DoTransportIO();
1731 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1732 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1733 // special case we keep looping even if rv is ERR_IO_PENDING because
1734 // the transport IO may allow DoHandshake to make progress.
1735 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1736 rv
= OK
; // This causes us to stay in the loop.
1738 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1742 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1743 DCHECK(OnNSSTaskRunner());
1744 DCHECK(false_started_
|| handshake_callback_called_
);
1745 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1751 LOG(DFATAL
) << "!nss_bufs_";
1752 int rv
= ERR_UNEXPECTED
;
1755 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1756 NetLog::TYPE_SSL_READ_ERROR
,
1757 CreateNetLogSSLErrorCallback(rv
, 0)));
1764 rv
= DoPayloadRead();
1765 network_moved
= DoTransportIO();
1766 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1771 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1772 DCHECK(OnNSSTaskRunner());
1773 DCHECK(false_started_
|| handshake_callback_called_
);
1774 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1780 LOG(DFATAL
) << "!nss_bufs_";
1781 int rv
= ERR_UNEXPECTED
;
1784 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1785 NetLog::TYPE_SSL_READ_ERROR
,
1786 CreateNetLogSSLErrorCallback(rv
, 0)));
1793 rv
= DoPayloadWrite();
1794 network_moved
= DoTransportIO();
1795 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1801 int SSLClientSocketNSS::Core::DoHandshake() {
1802 DCHECK(OnNSSTaskRunner());
1804 int net_error
= net::OK
;
1805 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1807 // Note: this function may be called multiple times during the handshake, so
1808 // even though channel id and client auth are separate else cases, they can
1809 // both be used during a single SSL handshake.
1810 if (channel_id_needed_
) {
1811 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1812 net_error
= ERR_IO_PENDING
;
1813 } else if (client_auth_cert_needed_
) {
1814 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1817 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1818 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1819 CreateNetLogSSLErrorCallback(net_error
, 0)));
1821 // If the handshake already succeeded (because the server requests but
1822 // doesn't require a client cert), we need to invalidate the SSL session
1823 // so that we won't try to resume the non-client-authenticated session in
1824 // the next handshake. This will cause the server to ask for a client
1826 if (rv
== SECSuccess
&& SSL_InvalidateSession(nss_fd_
) != SECSuccess
)
1827 LOG(WARNING
) << "Couldn't invalidate SSL session: " << PR_GetError();
1828 } else if (rv
== SECSuccess
) {
1829 if (!handshake_callback_called_
) {
1830 false_started_
= true;
1831 HandshakeSucceeded();
1834 PRErrorCode prerr
= PR_GetError();
1835 net_error
= HandleNSSError(prerr
);
1837 // If not done, stay in this state
1838 if (net_error
== ERR_IO_PENDING
) {
1839 GotoState(STATE_HANDSHAKE
);
1843 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1844 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1845 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1852 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1856 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1857 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1859 channel_id_needed_
= false;
1864 SECKEYPublicKey
* public_key
;
1865 SECKEYPrivateKey
* private_key
;
1866 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1870 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1871 if (rv
!= SECSuccess
)
1872 return MapNSSError(PORT_GetError());
1874 SetChannelIDProvided();
1875 GotoState(STATE_HANDSHAKE
);
1879 int SSLClientSocketNSS::Core::DoPayloadRead() {
1880 DCHECK(OnNSSTaskRunner());
1881 DCHECK(user_read_buf_
.get());
1882 DCHECK_GT(user_read_buf_len_
, 0);
1885 // If a previous greedy read resulted in an error that was not consumed (eg:
1886 // due to the caller having read some data successfully), then return that
1887 // pending error now.
1888 if (pending_read_result_
!= kNoPendingReadResult
) {
1889 rv
= pending_read_result_
;
1890 PRErrorCode prerr
= pending_read_nss_error_
;
1891 pending_read_result_
= kNoPendingReadResult
;
1892 pending_read_nss_error_
= 0;
1897 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1898 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1899 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1903 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1904 NetLog::TYPE_SSL_READ_ERROR
,
1905 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1910 // Perform a greedy read, attempting to read as much as the caller has
1911 // requested. In the current NSS implementation, PR_Read will return
1912 // exactly one SSL application data record's worth of data per invocation.
1913 // The record size is dictated by the server, and may be noticeably smaller
1914 // than the caller's buffer. This may be as little as a single byte, if the
1915 // server is performing 1/n-1 record splitting.
1917 // However, this greedy read may result in renegotiations/re-handshakes
1918 // happening or may lead to some data being read, followed by an EOF (such as
1919 // a TLS close-notify). If at least some data was read, then that result
1920 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1921 // data was read, it's safe to return the error or EOF immediately.
1922 int total_bytes_read
= 0;
1924 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
1925 user_read_buf_len_
- total_bytes_read
);
1927 total_bytes_read
+= rv
;
1928 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
1929 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
1930 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
1931 amount_in_read_buffer
));
1933 if (total_bytes_read
== user_read_buf_len_
) {
1934 // The caller's entire request was satisfied without error. No further
1935 // processing needed.
1936 rv
= total_bytes_read
;
1938 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1939 // immediately, while the NSPR/NSS errors are still available in
1940 // thread-local storage. However, the handled/remapped error code should
1941 // only be returned if no application data was already read; if it was, the
1942 // error code should be deferred until the next call of DoPayloadRead.
1944 // If no data was read, |*next_result| will point to the return value of
1945 // this function. If at least some data was read, |*next_result| will point
1946 // to |pending_read_error_|, to be returned in a future call to
1947 // DoPayloadRead() (e.g.: after the current data is handled).
1948 int* next_result
= &rv
;
1949 if (total_bytes_read
> 0) {
1950 pending_read_result_
= rv
;
1951 rv
= total_bytes_read
;
1952 next_result
= &pending_read_result_
;
1955 if (client_auth_cert_needed_
) {
1956 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1957 pending_read_nss_error_
= 0;
1958 } else if (*next_result
< 0) {
1959 // If *next_result == 0, then that indicates EOF, and no special error
1960 // handling is needed.
1961 pending_read_nss_error_
= PR_GetError();
1962 *next_result
= HandleNSSError(pending_read_nss_error_
);
1963 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
1964 // If at least some data was read from PR_Read(), do not treat
1965 // insufficient data as an error to return in the next call to
1966 // DoPayloadRead() - instead, let the call fall through to check
1967 // PR_Read() again. This is because DoTransportIO() may complete
1968 // in between the next call to DoPayloadRead(), and thus it is
1969 // important to check PR_Read() on subsequent invocations to see
1970 // if a complete record may now be read.
1971 pending_read_nss_error_
= 0;
1972 pending_read_result_
= kNoPendingReadResult
;
1977 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
1982 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1983 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1984 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1985 } else if (rv
!= ERR_IO_PENDING
) {
1988 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1989 NetLog::TYPE_SSL_READ_ERROR
,
1990 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
1991 pending_read_nss_error_
= 0;
1996 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1997 DCHECK(OnNSSTaskRunner());
1999 DCHECK(user_write_buf_
.get());
2001 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2002 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
2003 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2004 // PR_Write could potentially consume the unhandled data in the memio read
2005 // buffer if a renegotiation is in progress. If the buffer is consumed,
2006 // notify the latest buffer size to NetworkRunner.
2007 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
2010 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
2015 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2016 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
2017 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
2020 PRErrorCode prerr
= PR_GetError();
2021 if (prerr
== PR_WOULD_BLOCK_ERROR
)
2022 return ERR_IO_PENDING
;
2024 rv
= HandleNSSError(prerr
);
2027 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2028 NetLog::TYPE_SSL_WRITE_ERROR
,
2029 CreateNetLogSSLErrorCallback(rv
, prerr
)));
2033 // Do as much network I/O as possible between the buffer and the
2034 // transport socket. Return true if some I/O performed, false
2035 // otherwise (error or ERR_IO_PENDING).
2036 bool SSLClientSocketNSS::Core::DoTransportIO() {
2037 DCHECK(OnNSSTaskRunner());
2039 bool network_moved
= false;
2040 if (nss_bufs_
!= NULL
) {
2042 // Read and write as much data as we can. The loop is neccessary
2043 // because Write() may return synchronously.
2046 if (rv
!= ERR_IO_PENDING
&& rv
!= 0)
2047 network_moved
= true;
2049 if (!transport_recv_eof_
&& BufferRecv() != ERR_IO_PENDING
)
2050 network_moved
= true;
2052 return network_moved
;
2055 int SSLClientSocketNSS::Core::BufferRecv() {
2056 DCHECK(OnNSSTaskRunner());
2058 if (transport_recv_busy_
)
2059 return ERR_IO_PENDING
;
2061 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2062 // determine how much data NSS wants to read. If NSS was not blocked,
2063 // this will return 0.
2064 int requested
= memio_GetReadRequest(nss_bufs_
);
2065 if (requested
== 0) {
2066 // This is not a perfect match of error codes, as no operation is
2067 // actually pending. However, returning 0 would be interpreted as a
2068 // possible sign of EOF, which is also an inappropriate match.
2069 return ERR_IO_PENDING
;
2073 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2076 // buffer too full to read into, so no I/O possible at moment
2077 rv
= ERR_IO_PENDING
;
2079 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
2080 if (OnNetworkTaskRunner()) {
2081 rv
= DoBufferRecv(read_buffer
.get(), nb
);
2083 bool posted
= network_task_runner_
->PostTask(
2085 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
2087 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2090 if (rv
== ERR_IO_PENDING
) {
2091 transport_recv_busy_
= true;
2094 memcpy(buf
, read_buffer
->data(), rv
);
2095 } else if (rv
== 0) {
2096 transport_recv_eof_
= true;
2098 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
2104 // Return 0 if nss_bufs_ was empty,
2105 // > 0 for bytes transferred immediately,
2106 // < 0 for error (or the non-error ERR_IO_PENDING).
2107 int SSLClientSocketNSS::Core::BufferSend() {
2108 DCHECK(OnNSSTaskRunner());
2110 if (transport_send_busy_
)
2111 return ERR_IO_PENDING
;
2115 unsigned int len1
, len2
;
2116 if (memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
)) {
2117 // It is important this return synchronously to prevent spinning infinitely
2118 // in the off-thread NSS case. The error code itself is ignored, so just
2119 // return ERR_ABORTED. See https://crbug.com/381160.
2122 const unsigned int len
= len1
+ len2
;
2126 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
2127 memcpy(send_buffer
->data(), buf1
, len1
);
2128 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
2130 if (OnNetworkTaskRunner()) {
2131 rv
= DoBufferSend(send_buffer
.get(), len
);
2133 bool posted
= network_task_runner_
->PostTask(
2135 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
2137 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2140 if (rv
== ERR_IO_PENDING
) {
2141 transport_send_busy_
= true;
2143 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
2150 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
2151 DCHECK(OnNSSTaskRunner());
2153 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2154 OnHandshakeIOComplete(result
);
2158 // Network layer received some data, check if client requested to read
2160 if (!user_read_buf_
.get())
2163 int rv
= DoReadLoop(result
);
2164 if (rv
!= ERR_IO_PENDING
)
2168 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
2169 DCHECK(OnNSSTaskRunner());
2171 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2172 OnHandshakeIOComplete(result
);
2176 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2177 // handshake is in progress.
2178 int rv_read
= ERR_IO_PENDING
;
2179 int rv_write
= ERR_IO_PENDING
;
2182 if (user_read_buf_
.get())
2183 rv_read
= DoPayloadRead();
2184 if (user_write_buf_
.get())
2185 rv_write
= DoPayloadWrite();
2186 network_moved
= DoTransportIO();
2187 } while (rv_read
== ERR_IO_PENDING
&& rv_write
== ERR_IO_PENDING
&&
2188 (user_read_buf_
.get() || user_write_buf_
.get()) && network_moved
);
2190 // If the parent SSLClientSocketNSS is deleted during the processing of the
2191 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2192 // will be detached (and possibly deleted). Guard against deletion by taking
2193 // an extra reference, then check if the Core was detached before invoking the
2195 scoped_refptr
<Core
> guard(this);
2196 if (user_read_buf_
.get() && rv_read
!= ERR_IO_PENDING
)
2197 DoReadCallback(rv_read
);
2199 if (OnNetworkTaskRunner() && detached_
)
2202 if (user_write_buf_
.get() && rv_write
!= ERR_IO_PENDING
)
2203 DoWriteCallback(rv_write
);
2206 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2207 // handshake. This requires network IO, which in turn calls
2208 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2209 // winds its way through the state machine and ends up being passed to the
2210 // callback. For Read() and Write(), that's what we want. But for Connect(),
2211 // the caller expects OK (i.e. 0) for success.
2212 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
2213 DCHECK(OnNSSTaskRunner());
2214 DCHECK_NE(rv
, ERR_IO_PENDING
);
2215 DCHECK(!user_connect_callback_
.is_null());
2217 base::Closure c
= base::Bind(
2218 base::ResetAndReturn(&user_connect_callback_
),
2220 PostOrRunCallback(FROM_HERE
, c
);
2223 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
2224 DCHECK(OnNSSTaskRunner());
2225 DCHECK_NE(ERR_IO_PENDING
, rv
);
2226 DCHECK(!user_read_callback_
.is_null());
2228 user_read_buf_
= NULL
;
2229 user_read_buf_len_
= 0;
2230 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2231 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2232 // the network task runner.
2235 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2238 base::Bind(&Core::DidNSSRead
, this, rv
));
2241 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
2244 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
2245 DCHECK(OnNSSTaskRunner());
2246 DCHECK_NE(ERR_IO_PENDING
, rv
);
2247 DCHECK(!user_write_callback_
.is_null());
2249 // Since Run may result in Write being called, clear |user_write_callback_|
2251 user_write_buf_
= NULL
;
2252 user_write_buf_len_
= 0;
2253 // Update buffer status because DoWriteLoop called DoTransportIO which may
2254 // perform read operations.
2255 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2256 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2257 // the network task runner.
2260 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2263 base::Bind(&Core::DidNSSWrite
, this, rv
));
2266 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
2269 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
2272 SECKEYPublicKey
**out_public_key
,
2273 SECKEYPrivateKey
**out_private_key
) {
2274 Core
* core
= reinterpret_cast<Core
*>(arg
);
2275 DCHECK(core
->OnNSSTaskRunner());
2277 core
->PostOrRunCallback(
2279 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
2280 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
2282 // We have negotiated the TLS channel ID extension.
2283 core
->channel_id_xtn_negotiated_
= true;
2284 std::string host
= core
->host_and_port_
.host();
2285 int error
= ERR_UNEXPECTED
;
2286 if (core
->OnNetworkTaskRunner()) {
2287 error
= core
->DoGetDomainBoundCert(host
);
2289 bool posted
= core
->network_task_runner_
->PostTask(
2292 IgnoreResult(&Core::DoGetDomainBoundCert
),
2294 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2297 if (error
== ERR_IO_PENDING
) {
2298 // Asynchronous case.
2299 core
->channel_id_needed_
= true;
2300 return SECWouldBlock
;
2303 core
->PostOrRunCallback(
2305 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
2306 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
2307 SECStatus rv
= SECSuccess
;
2309 // Synchronous success.
2310 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
2312 core
->SetChannelIDProvided();
2322 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
2323 SECKEYPrivateKey
** key
) {
2324 // Set the certificate.
2326 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
2327 cert_item
.len
= domain_bound_cert_
.size();
2328 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2334 return MapNSSError(PORT_GetError());
2336 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
2337 // Set the private key.
2338 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2340 ServerBoundCertService::kEPKIPassword
,
2341 reinterpret_cast<const unsigned char*>(
2342 domain_bound_private_key_
.data()),
2343 domain_bound_private_key_
.size(),
2344 &cert
->subjectPublicKeyInfo
,
2349 int error
= MapNSSError(PORT_GetError());
2356 void SSLClientSocketNSS::Core::UpdateServerCert() {
2357 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2358 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2359 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2360 if (nss_handshake_state_
.server_cert
.get()) {
2361 // Since this will be called asynchronously on another thread, it needs to
2362 // own a reference to the certificate.
2363 NetLog::ParametersCallback net_log_callback
=
2364 base::Bind(&NetLogX509CertificateCallback
,
2365 nss_handshake_state_
.server_cert
);
2368 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2369 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2374 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2375 const SECItem
* signed_cert_timestamps
=
2376 SSL_PeerSignedCertTimestamps(nss_fd_
);
2378 if (!signed_cert_timestamps
|| !signed_cert_timestamps
->len
)
2381 nss_handshake_state_
.sct_list_from_tls_extension
= std::string(
2382 reinterpret_cast<char*>(signed_cert_timestamps
->data
),
2383 signed_cert_timestamps
->len
);
2386 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2387 PRBool ocsp_requested
= PR_FALSE
;
2388 SSL_OptionGet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, &ocsp_requested
);
2389 const SECItemArray
* ocsp_responses
=
2390 SSL_PeerStapledOCSPResponses(nss_fd_
);
2391 bool ocsp_responses_present
= ocsp_responses
&& ocsp_responses
->len
;
2393 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present
);
2394 if (!ocsp_responses_present
)
2397 nss_handshake_state_
.stapled_ocsp_response
= std::string(
2398 reinterpret_cast<char*>(ocsp_responses
->items
[0].data
),
2399 ocsp_responses
->items
[0].len
);
2401 // TODO(agl): figure out how to plumb an OCSP response into the Mac
2402 // system library and update IsOCSPStaplingSupported for Mac.
2403 if (IsOCSPStaplingSupported()) {
2405 if (nss_handshake_state_
.server_cert
) {
2406 CRYPT_DATA_BLOB ocsp_response_blob
;
2407 ocsp_response_blob
.cbData
= ocsp_responses
->items
[0].len
;
2408 ocsp_response_blob
.pbData
= ocsp_responses
->items
[0].data
;
2409 BOOL ok
= CertSetCertificateContextProperty(
2410 nss_handshake_state_
.server_cert
->os_cert_handle(),
2411 CERT_OCSP_RESPONSE_PROP_ID
,
2412 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
2413 &ocsp_response_blob
);
2415 VLOG(1) << "Failed to set OCSP response property: "
2419 #elif defined(USE_NSS)
2420 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
2421 GetCacheOCSPResponseFromSideChannelFunction();
2423 cache_ocsp_response(
2424 CERT_GetDefaultCertDB(),
2425 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
2426 &ocsp_responses
->items
[0], NULL
);
2428 } // IsOCSPStaplingSupported()
2431 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2432 SSLChannelInfo channel_info
;
2433 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2434 &channel_info
, sizeof(channel_info
));
2435 if (ok
== SECSuccess
&&
2436 channel_info
.length
== sizeof(channel_info
) &&
2437 channel_info
.cipherSuite
) {
2438 nss_handshake_state_
.ssl_connection_status
|=
2439 (static_cast<int>(channel_info
.cipherSuite
) &
2440 SSL_CONNECTION_CIPHERSUITE_MASK
) <<
2441 SSL_CONNECTION_CIPHERSUITE_SHIFT
;
2443 nss_handshake_state_
.ssl_connection_status
|=
2444 (static_cast<int>(channel_info
.compressionMethod
) &
2445 SSL_CONNECTION_COMPRESSION_MASK
) <<
2446 SSL_CONNECTION_COMPRESSION_SHIFT
;
2448 // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
2449 // support it yet), so use 0x0303 directly.
2450 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2451 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2452 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2454 version
= SSL_CONNECTION_VERSION_SSL2
;
2455 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2456 version
= SSL_CONNECTION_VERSION_SSL3
;
2457 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_1_TLS
) {
2458 version
= SSL_CONNECTION_VERSION_TLS1
;
2459 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_TLS_1_1
) {
2460 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2461 } else if (channel_info
.protocolVersion
== 0x0303) {
2462 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2464 nss_handshake_state_
.ssl_connection_status
|=
2465 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2466 SSL_CONNECTION_VERSION_SHIFT
;
2469 PRBool peer_supports_renego_ext
;
2470 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2471 &peer_supports_renego_ext
);
2472 if (ok
== SECSuccess
) {
2473 if (!peer_supports_renego_ext
) {
2474 nss_handshake_state_
.ssl_connection_status
|=
2475 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2476 // Log an informational message if the server does not support secure
2477 // renegotiation (RFC 5746).
2478 VLOG(1) << "The server " << host_and_port_
.ToString()
2479 << " does not support the TLS renegotiation_info extension.";
2481 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2482 peer_supports_renego_ext
, 2);
2484 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2485 // because of security concerns. For example, Google offers forward
2486 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2487 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2490 // Yngve from Opera has suggested using the renegotiation extension as an
2491 // indicator that SSLv3 fallback was mistaken:
2492 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2494 // As a first step, measure how often clients perform version fallback
2495 // while the server advertises support secure renegotiation.
2496 if (ssl_config_
.version_fallback
&&
2497 channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2498 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2499 peer_supports_renego_ext
== PR_TRUE
);
2503 if (ssl_config_
.version_fallback
) {
2504 nss_handshake_state_
.ssl_connection_status
|=
2505 SSL_CONNECTION_VERSION_FALLBACK
;
2509 void SSLClientSocketNSS::Core::UpdateNextProto() {
2511 SSLNextProtoState state
;
2514 SECStatus rv
= SSL_GetNextProto(nss_fd_
, &state
, buf
, &buf_len
, sizeof(buf
));
2515 if (rv
!= SECSuccess
)
2518 nss_handshake_state_
.next_proto
=
2519 std::string(reinterpret_cast<char*>(buf
), buf_len
);
2521 case SSL_NEXT_PROTO_NEGOTIATED
:
2522 case SSL_NEXT_PROTO_SELECTED
:
2523 nss_handshake_state_
.next_proto_status
= kNextProtoNegotiated
;
2525 case SSL_NEXT_PROTO_NO_OVERLAP
:
2526 nss_handshake_state_
.next_proto_status
= kNextProtoNoOverlap
;
2528 case SSL_NEXT_PROTO_NO_SUPPORT
:
2529 nss_handshake_state_
.next_proto_status
= kNextProtoUnsupported
;
2537 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2538 DCHECK(OnNSSTaskRunner());
2539 if (nss_handshake_state_
.resumed_handshake
)
2542 // Copy the NSS task runner-only state to the network task runner and
2543 // log histograms from there, since the histograms also need access to the
2544 // network task runner state.
2547 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner
,
2549 channel_id_xtn_negotiated_
,
2550 ssl_config_
.channel_id_enabled
,
2551 crypto::ECPrivateKey::IsSupported()));
2554 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2555 bool negotiated_channel_id
,
2556 bool channel_id_enabled
,
2557 bool supports_ecc
) const {
2558 DCHECK(OnNetworkTaskRunner());
2560 RecordChannelIDSupport(server_bound_cert_service_
,
2561 negotiated_channel_id
,
2566 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer
* read_buffer
, int len
) {
2567 DCHECK(OnNetworkTaskRunner());
2573 int rv
= transport_
->socket()->Read(
2575 base::Bind(&Core::BufferRecvComplete
, base::Unretained(this),
2576 scoped_refptr
<IOBuffer
>(read_buffer
)));
2578 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2579 nss_task_runner_
->PostTask(
2580 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2581 scoped_refptr
<IOBuffer
>(read_buffer
), rv
));
2588 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer
* send_buffer
, int len
) {
2589 DCHECK(OnNetworkTaskRunner());
2595 int rv
= transport_
->socket()->Write(
2597 base::Bind(&Core::BufferSendComplete
,
2598 base::Unretained(this)));
2600 if (!OnNSSTaskRunner() && rv
!= ERR_IO_PENDING
) {
2601 nss_task_runner_
->PostTask(
2603 base::Bind(&Core::BufferSendComplete
, this, rv
));
2610 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string
& host
) {
2611 DCHECK(OnNetworkTaskRunner());
2616 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2618 int rv
= server_bound_cert_service_
->GetOrCreateDomainBoundCert(
2620 &domain_bound_private_key_
,
2621 &domain_bound_cert_
,
2622 base::Bind(&Core::OnGetDomainBoundCertComplete
, base::Unretained(this)),
2623 &domain_bound_cert_request_handle_
);
2625 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2626 nss_task_runner_
->PostTask(
2628 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2629 return ERR_IO_PENDING
;
2635 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2636 const HandshakeState
& state
) {
2637 DCHECK(OnNetworkTaskRunner());
2638 network_handshake_state_
= state
;
2641 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2642 DCHECK(OnNetworkTaskRunner());
2643 unhandled_buffer_size_
= amount_in_read_buffer
;
2646 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2647 DCHECK(OnNetworkTaskRunner());
2648 DCHECK(nss_waiting_read_
);
2649 nss_waiting_read_
= false;
2651 nss_is_closed_
= true;
2653 was_ever_used_
= true;
2657 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2658 DCHECK(OnNetworkTaskRunner());
2659 DCHECK(nss_waiting_write_
);
2660 nss_waiting_write_
= false;
2662 nss_is_closed_
= true;
2663 } else if (result
> 0) {
2664 was_ever_used_
= true;
2668 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2669 if (!OnNSSTaskRunner()) {
2673 nss_task_runner_
->PostTask(
2674 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2678 DCHECK(OnNSSTaskRunner());
2680 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2681 transport_send_busy_
= false;
2682 OnSendComplete(result
);
2685 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2686 if (!OnNSSTaskRunner()) {
2690 nss_task_runner_
->PostTask(
2691 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2695 DCHECK(OnNSSTaskRunner());
2697 int rv
= DoHandshakeLoop(result
);
2698 if (rv
!= ERR_IO_PENDING
)
2699 DoConnectCallback(rv
);
2702 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result
) {
2703 DVLOG(1) << __FUNCTION__
<< " " << result
;
2704 DCHECK(OnNetworkTaskRunner());
2706 OnHandshakeIOComplete(result
);
2709 void SSLClientSocketNSS::Core::BufferRecvComplete(
2710 IOBuffer
* read_buffer
,
2712 DCHECK(read_buffer
);
2714 if (!OnNSSTaskRunner()) {
2718 nss_task_runner_
->PostTask(
2719 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2720 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2724 DCHECK(OnNSSTaskRunner());
2728 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2729 CHECK_GE(nb
, result
);
2730 memcpy(buf
, read_buffer
->data(), result
);
2731 } else if (result
== 0) {
2732 transport_recv_eof_
= true;
2735 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2736 transport_recv_busy_
= false;
2737 OnRecvComplete(result
);
2740 void SSLClientSocketNSS::Core::PostOrRunCallback(
2741 const tracked_objects::Location
& location
,
2742 const base::Closure
& task
) {
2743 if (!OnNetworkTaskRunner()) {
2744 network_task_runner_
->PostTask(
2746 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2750 if (detached_
|| task
.is_null())
2755 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2758 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2759 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2760 NetLog::IntegerCallback("cert_count", cert_count
)));
2763 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2765 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2766 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2767 nss_handshake_state_
.channel_id_sent
= true;
2768 // Update the network task runner's view of the handshake state now that
2769 // channel id has been sent.
2771 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2772 nss_handshake_state_
));
2775 SSLClientSocketNSS::SSLClientSocketNSS(
2776 base::SequencedTaskRunner
* nss_task_runner
,
2777 scoped_ptr
<ClientSocketHandle
> transport_socket
,
2778 const HostPortPair
& host_and_port
,
2779 const SSLConfig
& ssl_config
,
2780 const SSLClientSocketContext
& context
)
2781 : nss_task_runner_(nss_task_runner
),
2782 transport_(transport_socket
.Pass()),
2783 host_and_port_(host_and_port
),
2784 ssl_config_(ssl_config
),
2785 cert_verifier_(context
.cert_verifier
),
2786 cert_transparency_verifier_(context
.cert_transparency_verifier
),
2787 server_bound_cert_service_(context
.server_bound_cert_service
),
2788 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2789 completed_handshake_(false),
2790 next_handshake_state_(STATE_NONE
),
2792 net_log_(transport_
->socket()->NetLog()),
2793 transport_security_state_(context
.transport_security_state
),
2794 valid_thread_id_(base::kInvalidThreadId
) {
2800 SSLClientSocketNSS::~SSLClientSocketNSS() {
2807 void SSLClientSocket::ClearSessionCache() {
2808 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2809 // bother initializing NSS just to clear an empty SSL session cache.
2810 if (!NSS_IsInitialized())
2813 SSL_ClearSessionCache();
2816 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2819 if (core_
->state().server_cert_chain
.empty() ||
2820 !core_
->state().server_cert_chain
[0]) {
2824 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2825 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2827 AddSCTInfoToSSLInfo(ssl_info
);
2829 ssl_info
->connection_status
=
2830 core_
->state().ssl_connection_status
;
2831 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2832 ssl_info
->is_issued_by_known_root
=
2833 server_cert_verify_result_
.is_issued_by_known_root
;
2834 ssl_info
->client_cert_sent
=
2835 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
.get();
2836 ssl_info
->channel_id_sent
= WasChannelIDSent();
2837 ssl_info
->pinning_failure_log
= pinning_failure_log_
;
2839 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2840 core_
->state().ssl_connection_status
);
2841 SSLCipherSuiteInfo cipher_info
;
2842 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2843 &cipher_info
, sizeof(cipher_info
));
2844 if (ok
== SECSuccess
) {
2845 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2847 ssl_info
->security_bits
= -1;
2848 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2849 << " for cipherSuite " << cipher_suite
;
2852 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2853 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2859 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2860 SSLCertRequestInfo
* cert_request_info
) {
2862 cert_request_info
->host_and_port
= host_and_port_
;
2863 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2867 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2869 const base::StringPiece
& context
,
2871 unsigned int outlen
) {
2873 return ERR_SOCKET_NOT_CONNECTED
;
2875 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2876 // the midst of a handshake.
2877 SECStatus result
= SSL_ExportKeyingMaterial(
2878 nss_fd_
, label
.data(), label
.size(), has_context
,
2879 reinterpret_cast<const unsigned char*>(context
.data()),
2880 context
.length(), out
, outlen
);
2881 if (result
!= SECSuccess
) {
2882 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2883 return MapNSSError(PORT_GetError());
2888 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2890 return ERR_SOCKET_NOT_CONNECTED
;
2891 unsigned char buf
[64];
2893 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2894 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2895 buf
, &len
, arraysize(buf
));
2896 if (result
!= SECSuccess
) {
2897 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2898 return MapNSSError(PORT_GetError());
2900 out
->assign(reinterpret_cast<char*>(buf
), len
);
2904 SSLClientSocket::NextProtoStatus
2905 SSLClientSocketNSS::GetNextProto(std::string
* proto
,
2906 std::string
* server_protos
) {
2907 *proto
= core_
->state().next_proto
;
2908 *server_protos
= core_
->state().server_protos
;
2909 return core_
->state().next_proto_status
;
2912 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2914 DCHECK(transport_
.get());
2915 // It is an error to create an SSLClientSocket whose context has no
2916 // TransportSecurityState.
2917 DCHECK(transport_security_state_
);
2918 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2919 DCHECK(user_connect_callback_
.is_null());
2920 DCHECK(!callback
.is_null());
2922 EnsureThreadIdAssigned();
2924 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2928 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2932 rv
= InitializeSSLOptions();
2934 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2938 rv
= InitializeSSLPeerName();
2940 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2944 GotoState(STATE_HANDSHAKE
);
2946 rv
= DoHandshakeLoop(OK
);
2947 if (rv
== ERR_IO_PENDING
) {
2948 user_connect_callback_
= callback
;
2950 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2954 return rv
> OK
? OK
: rv
;
2957 void SSLClientSocketNSS::Disconnect() {
2960 CHECK(CalledOnValidThread());
2962 // Shut down anything that may call us back.
2965 transport_
->socket()->Disconnect();
2967 // Reset object state.
2968 user_connect_callback_
.Reset();
2969 server_cert_verify_result_
.Reset();
2970 completed_handshake_
= false;
2971 start_cert_verification_time_
= base::TimeTicks();
2977 bool SSLClientSocketNSS::IsConnected() const {
2979 bool ret
= completed_handshake_
&&
2980 (core_
->HasPendingAsyncOperation() ||
2981 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2982 transport_
->socket()->IsConnected());
2987 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2989 bool ret
= completed_handshake_
&&
2990 !core_
->HasPendingAsyncOperation() &&
2991 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2992 transport_
->socket()->IsConnectedAndIdle();
2997 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2998 return transport_
->socket()->GetPeerAddress(address
);
3001 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
3002 return transport_
->socket()->GetLocalAddress(address
);
3005 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
3009 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3010 if (transport_
.get() && transport_
->socket()) {
3011 transport_
->socket()->SetSubresourceSpeculation();
3017 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3018 if (transport_
.get() && transport_
->socket()) {
3019 transport_
->socket()->SetOmniboxSpeculation();
3025 bool SSLClientSocketNSS::WasEverUsed() const {
3026 DCHECK(core_
.get());
3028 return core_
->WasEverUsed();
3031 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3032 if (transport_
.get() && transport_
->socket()) {
3033 return transport_
->socket()->UsingTCPFastOpen();
3039 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
3040 const CompletionCallback
& callback
) {
3041 DCHECK(core_
.get());
3042 DCHECK(!callback
.is_null());
3044 EnterFunction(buf_len
);
3045 int rv
= core_
->Read(buf
, buf_len
, callback
);
3051 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
3052 const CompletionCallback
& callback
) {
3053 DCHECK(core_
.get());
3054 DCHECK(!callback
.is_null());
3056 EnterFunction(buf_len
);
3057 int rv
= core_
->Write(buf
, buf_len
, callback
);
3063 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
3064 return transport_
->socket()->SetReceiveBufferSize(size
);
3067 int SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
3068 return transport_
->socket()->SetSendBufferSize(size
);
3071 int SSLClientSocketNSS::Init() {
3073 // Initialize the NSS SSL library in a threadsafe way. This also
3074 // initializes the NSS base library.
3076 if (!NSS_IsInitialized())
3077 return ERR_UNEXPECTED
;
3078 #if defined(USE_NSS) || defined(OS_IOS)
3079 if (ssl_config_
.cert_io_enabled
) {
3080 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3081 // loop by MessageLoopForIO::current().
3082 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3083 EnsureNSSHttpIOInit();
3091 void SSLClientSocketNSS::InitCore() {
3092 core_
= new Core(base::ThreadTaskRunnerHandle::Get().get(),
3093 nss_task_runner_
.get(),
3098 server_bound_cert_service_
);
3101 int SSLClientSocketNSS::InitializeSSLOptions() {
3102 // Transport connected, now hook it up to nss
3103 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
3104 if (nss_fd_
== NULL
) {
3105 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
3108 // Grab pointer to buffers
3109 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
3111 /* Create SSL state machine */
3112 /* Push SSL onto our fake I/O socket */
3113 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_
) == NULL
) {
3114 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
3117 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
3119 // TODO(port): set more ssl options! Check errors!
3123 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
3124 if (rv
!= SECSuccess
) {
3125 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
3126 return ERR_UNEXPECTED
;
3129 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
3130 if (rv
!= SECSuccess
) {
3131 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3132 return ERR_UNEXPECTED
;
3135 // Don't do V2 compatible hellos because they don't support TLS extensions.
3136 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
3137 if (rv
!= SECSuccess
) {
3138 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3139 return ERR_UNEXPECTED
;
3142 SSLVersionRange version_range
;
3143 version_range
.min
= ssl_config_
.version_min
;
3144 version_range
.max
= ssl_config_
.version_max
;
3145 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
3146 if (rv
!= SECSuccess
) {
3147 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
3148 return ERR_NO_SSL_VERSIONS_ENABLED
;
3151 if (ssl_config_
.version_fallback
) {
3152 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALLBACK_SCSV
, PR_TRUE
);
3153 if (rv
!= SECSuccess
) {
3154 LogFailedNSSFunction(
3155 net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
3159 for (std::vector
<uint16
>::const_iterator it
=
3160 ssl_config_
.disabled_cipher_suites
.begin();
3161 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
3162 // This will fail if the specified cipher is not implemented by NSS, but
3163 // the failure is harmless.
3164 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
3168 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
3169 if (rv
!= SECSuccess
) {
3170 LogFailedNSSFunction(
3171 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3174 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
3175 ssl_config_
.false_start_enabled
);
3176 if (rv
!= SECSuccess
)
3177 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3179 // We allow servers to request renegotiation. Since we're a client,
3180 // prohibiting this is rather a waste of time. Only servers are in a
3181 // position to prevent renegotiation attacks.
3182 // http://extendedsubset.com/?p=8
3184 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
3185 SSL_RENEGOTIATE_TRANSITIONAL
);
3186 if (rv
!= SECSuccess
) {
3187 LogFailedNSSFunction(
3188 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3191 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
3192 if (rv
!= SECSuccess
)
3193 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3195 // Added in NSS 3.15
3196 #ifdef SSL_ENABLE_OCSP_STAPLING
3197 // Request OCSP stapling even on platforms that don't support it, in
3198 // order to extract Certificate Transparency information.
3199 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
,
3200 (IsOCSPStaplingSupported() ||
3201 ssl_config_
.signed_cert_timestamps_enabled
));
3202 if (rv
!= SECSuccess
) {
3203 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3204 "SSL_ENABLE_OCSP_STAPLING");
3208 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS
,
3209 ssl_config_
.signed_cert_timestamps_enabled
);
3210 if (rv
!= SECSuccess
) {
3211 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3212 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
3215 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
3216 if (rv
!= SECSuccess
) {
3217 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3218 return ERR_UNEXPECTED
;
3221 if (!core_
->Init(nss_fd_
, nss_bufs
))
3222 return ERR_UNEXPECTED
;
3224 // Tell SSL the hostname we're trying to connect to.
3225 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
3227 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3228 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
3233 int SSLClientSocketNSS::InitializeSSLPeerName() {
3234 // Tell NSS who we're connected to
3235 IPEndPoint peer_address
;
3236 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
3240 SockaddrStorage storage
;
3241 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
3242 return ERR_ADDRESS_INVALID
;
3245 memset(&peername
, 0, sizeof(peername
));
3246 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
3247 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
3249 memcpy(&peername
, storage
.addr
, len
);
3251 // Adjust the address family field for BSD, whose sockaddr
3252 // structure has a one-byte length and one-byte address family
3253 // field at the beginning. PRNetAddr has a two-byte address
3254 // family field at the beginning.
3255 peername
.raw
.family
= storage
.addr
->sa_family
;
3257 memio_SetPeerName(nss_fd_
, &peername
);
3259 // Set the peer ID for session reuse. This is necessary when we create an
3260 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3261 // rather than the destination server's address in that case.
3262 std::string peer_id
= host_and_port_
.ToString();
3263 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3264 // This will cause session cache misses between sockets with different values
3265 // of ssl_session_cache_shard_ and this is used to partition the session cache
3266 // for incognito mode.
3267 if (!ssl_session_cache_shard_
.empty()) {
3268 peer_id
+= "/" + ssl_session_cache_shard_
;
3270 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
3271 if (rv
!= SECSuccess
)
3272 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
3277 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
3279 DCHECK_NE(ERR_IO_PENDING
, rv
);
3280 DCHECK(!user_connect_callback_
.is_null());
3282 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
3286 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
3287 EnterFunction(result
);
3288 int rv
= DoHandshakeLoop(result
);
3289 if (rv
!= ERR_IO_PENDING
) {
3290 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3291 DoConnectCallback(rv
);
3296 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
3297 EnterFunction(last_io_result
);
3298 int rv
= last_io_result
;
3300 // Default to STATE_NONE for next state.
3301 // (This is a quirk carried over from the windows
3302 // implementation. It makes reading the logs a bit harder.)
3303 // State handlers can and often do call GotoState just
3304 // to stay in the current state.
3305 State state
= next_handshake_state_
;
3306 GotoState(STATE_NONE
);
3308 case STATE_HANDSHAKE
:
3311 case STATE_HANDSHAKE_COMPLETE
:
3312 rv
= DoHandshakeComplete(rv
);
3314 case STATE_VERIFY_CERT
:
3316 rv
= DoVerifyCert(rv
);
3318 case STATE_VERIFY_CERT_COMPLETE
:
3319 rv
= DoVerifyCertComplete(rv
);
3323 rv
= ERR_UNEXPECTED
;
3324 LOG(DFATAL
) << "unexpected state " << state
;
3327 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3332 int SSLClientSocketNSS::DoHandshake() {
3334 int rv
= core_
->Connect(
3335 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3336 base::Unretained(this)));
3337 GotoState(STATE_HANDSHAKE_COMPLETE
);
3343 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3344 EnterFunction(result
);
3347 // SSL handshake is completed. Let's verify the certificate.
3348 GotoState(STATE_VERIFY_CERT
);
3351 set_channel_id_sent(core_
->state().channel_id_sent
);
3352 set_signed_cert_timestamps_received(
3353 !core_
->state().sct_list_from_tls_extension
.empty());
3354 set_stapled_ocsp_response_received(
3355 !core_
->state().stapled_ocsp_response
.empty());
3357 LeaveFunction(result
);
3361 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3362 DCHECK(!core_
->state().server_cert_chain
.empty());
3363 DCHECK(core_
->state().server_cert_chain
[0]);
3365 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3367 // If the certificate is expected to be bad we can use the expectation as
3369 base::StringPiece
der_cert(
3370 reinterpret_cast<char*>(
3371 core_
->state().server_cert_chain
[0]->derCert
.data
),
3372 core_
->state().server_cert_chain
[0]->derCert
.len
);
3373 CertStatus cert_status
;
3374 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3375 DCHECK(start_cert_verification_time_
.is_null());
3376 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3377 server_cert_verify_result_
.Reset();
3378 server_cert_verify_result_
.cert_status
= cert_status
;
3379 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3383 // We may have failed to create X509Certificate object if we are
3384 // running inside sandbox.
3385 if (!core_
->state().server_cert
.get()) {
3386 server_cert_verify_result_
.Reset();
3387 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3388 return ERR_CERT_INVALID
;
3391 start_cert_verification_time_
= base::TimeTicks::Now();
3394 if (ssl_config_
.rev_checking_enabled
)
3395 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3396 if (ssl_config_
.verify_ev_cert
)
3397 flags
|= CertVerifier::VERIFY_EV_CERT
;
3398 if (ssl_config_
.cert_io_enabled
)
3399 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3400 if (ssl_config_
.rev_checking_required_local_anchors
)
3401 flags
|= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS
;
3402 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3403 return verifier_
->Verify(
3404 core_
->state().server_cert
.get(),
3405 host_and_port_
.host(),
3407 SSLConfigService::GetCRLSet().get(),
3408 &server_cert_verify_result_
,
3409 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3410 base::Unretained(this)),
3414 // Derived from AuthCertificateCallback() in
3415 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3416 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3419 if (!start_cert_verification_time_
.is_null()) {
3420 base::TimeDelta verify_time
=
3421 base::TimeTicks::Now() - start_cert_verification_time_
;
3423 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3425 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3428 // We used to remember the intermediate CA certs in the NSS database
3429 // persistently. However, NSS opens a connection to the SQLite database
3430 // during NSS initialization and doesn't close the connection until NSS
3431 // shuts down. If the file system where the database resides is gone,
3432 // the database connection goes bad. What's worse, the connection won't
3433 // recover when the file system comes back. Until this NSS or SQLite bug
3434 // is fixed, we need to avoid using the NSS database for non-essential
3435 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3436 // http://crbug.com/15630 for more info.
3438 // TODO(hclam): Skip logging if server cert was expected to be bad because
3439 // |server_cert_verify_result_| doesn't contain all the information about
3442 LogConnectionTypeMetrics();
3444 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3445 // Take care of any mandates for public key pinning.
3447 // Pinning is only enabled for official builds to make sure that others don't
3448 // end up with pins that cannot be easily updated.
3450 // TODO(agl): We might have an issue here where a request for foo.example.com
3451 // merges into a SPDY connection to www.example.com, and gets a different
3454 // Perform pin validation if, and only if, all these conditions obtain:
3456 // * a TransportSecurityState object is available;
3457 // * the server's certificate chain is valid (or suffers from only a minor
3459 // * the server's certificate chain chains up to a known root (i.e. not a
3460 // user-installed trust anchor); and
3461 // * the build is recent (very old builds should fail open so that users
3462 // have some chance to recover).
3464 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3465 if (transport_security_state_
&&
3467 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3468 server_cert_verify_result_
.is_issued_by_known_root
&&
3469 TransportSecurityState::IsBuildTimely()) {
3470 bool sni_available
=
3471 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
||
3472 ssl_config_
.version_fallback
;
3473 const std::string
& host
= host_and_port_
.host();
3475 if (transport_security_state_
->HasPublicKeyPins(host
, sni_available
)) {
3476 if (!transport_security_state_
->CheckPublicKeyPins(
3479 server_cert_verify_result_
.public_key_hashes
,
3480 &pinning_failure_log_
)) {
3481 LOG(ERROR
) << pinning_failure_log_
;
3482 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3483 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3484 TransportSecurityState::ReportUMAOnPinFailure(host
);
3486 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3493 // Only check Certificate Transparency if there were no other errors with
3497 // Only cache the session if the certificate verified successfully.
3498 core_
->CacheSessionIfNecessary();
3501 completed_handshake_
= true;
3503 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3504 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3508 void SSLClientSocketNSS::VerifyCT() {
3509 if (!cert_transparency_verifier_
)
3512 // Note that this is a completely synchronous operation: The CT Log Verifier
3513 // gets all the data it needs for SCT verification and does not do any
3514 // external communication.
3515 int result
= cert_transparency_verifier_
->Verify(
3516 server_cert_verify_result_
.verified_cert
,
3517 core_
->state().stapled_ocsp_response
,
3518 core_
->state().sct_list_from_tls_extension
,
3521 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3522 // from the state after verification is complete, to conserve memory.
3524 VLOG(1) << "CT Verification complete: result " << result
3525 << " Invalid scts: " << ct_verify_result_
.invalid_scts
.size()
3526 << " Verified scts: " << ct_verify_result_
.verified_scts
.size()
3527 << " scts from unknown logs: "
3528 << ct_verify_result_
.unknown_logs_scts
.size();
3531 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3532 UpdateConnectionTypeHistograms(CONNECTION_SSL
);
3533 int ssl_version
= SSLConnectionStatusToVersion(
3534 core_
->state().ssl_connection_status
);
3535 switch (ssl_version
) {
3536 case SSL_CONNECTION_VERSION_SSL2
:
3537 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2
);
3539 case SSL_CONNECTION_VERSION_SSL3
:
3540 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3
);
3542 case SSL_CONNECTION_VERSION_TLS1
:
3543 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1
);
3545 case SSL_CONNECTION_VERSION_TLS1_1
:
3546 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1
);
3548 case SSL_CONNECTION_VERSION_TLS1_2
:
3549 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2
);
3554 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3555 base::AutoLock
auto_lock(lock_
);
3556 if (valid_thread_id_
!= base::kInvalidThreadId
)
3558 valid_thread_id_
= base::PlatformThread::CurrentId();
3561 bool SSLClientSocketNSS::CalledOnValidThread() const {
3562 EnsureThreadIdAssigned();
3563 base::AutoLock
auto_lock(lock_
);
3564 return valid_thread_id_
== base::PlatformThread::CurrentId();
3567 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo
* ssl_info
) const {
3568 for (ct::SCTList::const_iterator iter
=
3569 ct_verify_result_
.verified_scts
.begin();
3570 iter
!= ct_verify_result_
.verified_scts
.end(); ++iter
) {
3571 ssl_info
->signed_certificate_timestamps
.push_back(
3572 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_OK
));
3574 for (ct::SCTList::const_iterator iter
=
3575 ct_verify_result_
.invalid_scts
.begin();
3576 iter
!= ct_verify_result_
.invalid_scts
.end(); ++iter
) {
3577 ssl_info
->signed_certificate_timestamps
.push_back(
3578 SignedCertificateTimestampAndStatus(*iter
, ct::SCT_STATUS_INVALID
));
3580 for (ct::SCTList::const_iterator iter
=
3581 ct_verify_result_
.unknown_logs_scts
.begin();
3582 iter
!= ct_verify_result_
.unknown_logs_scts
.end(); ++iter
) {
3583 ssl_info
->signed_certificate_timestamps
.push_back(
3584 SignedCertificateTimestampAndStatus(*iter
,
3585 ct::SCT_STATUS_LOG_UNKNOWN
));
3589 scoped_refptr
<X509Certificate
>
3590 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3591 return core_
->state().server_cert
.get();
3594 ServerBoundCertService
* SSLClientSocketNSS::GetServerBoundCertService() const {
3595 return server_bound_cert_service_
;