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/string_number_conversions.h"
77 #include "base/string_util.h"
78 #include "base/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/connection_type_histograms.h"
89 #include "net/base/dns_util.h"
90 #include "net/base/io_buffer.h"
91 #include "net/base/net_errors.h"
92 #include "net/base/net_log.h"
93 #include "net/cert/asn1_util.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/single_request_cert_verifier.h"
97 #include "net/cert/x509_certificate_net_log_param.h"
98 #include "net/cert/x509_util.h"
99 #include "net/http/transport_security_state.h"
100 #include "net/ocsp/nss_ocsp.h"
101 #include "net/socket/client_socket_handle.h"
102 #include "net/socket/nss_ssl_util.h"
103 #include "net/socket/ssl_error_params.h"
104 #include "net/ssl/ssl_cert_request_info.h"
105 #include "net/ssl/ssl_connection_status_flags.h"
106 #include "net/ssl/ssl_info.h"
110 #include <wincrypt.h>
111 #elif defined(OS_MACOSX)
112 #include <Security/SecBase.h>
113 #include <Security/SecCertificate.h>
114 #include <Security/SecIdentity.h>
116 #include "base/mac/mac_logging.h"
117 #include "base/synchronization/lock.h"
118 #include "crypto/mac_security_services_lock.h"
119 #elif defined(USE_NSS)
125 // State machines are easier to debug if you log state transitions.
126 // Enable these if you want to see what's going on.
128 #define EnterFunction(x)
129 #define LeaveFunction(x)
130 #define GotoState(s) next_handshake_state_ = s
132 #define EnterFunction(x)\
133 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
134 << "; next_handshake_state " << next_handshake_state_
135 #define LeaveFunction(x)\
136 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
137 << "; next_handshake_state " << next_handshake_state_
138 #define GotoState(s)\
140 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
141 next_handshake_state_ = s;\
147 // SSL plaintext fragments are shorter than 16KB. Although the record layer
148 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
149 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
150 // entire SSL record.
151 const int kRecvBufferSize
= 17 * 1024;
152 const int kSendBufferSize
= 17 * 1024;
154 // Used by SSLClientSocketNSS::Core to indicate there is no read result
155 // obtained by a previous operation waiting to be returned to the caller.
156 // This constant can be any non-negative/non-zero value (eg: it does not
157 // overlap with any value of the net::Error range, including net::OK).
158 const int kNoPendingReadResult
= 1;
161 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
162 // set on Windows XP without error. There is some overhead from the server
163 // sending the OCSP response if it supports the extension, for the subset of
164 // XP clients who will request it but be unable to use it, but this is an
165 // acceptable trade-off for simplicity of implementation.
166 bool IsOCSPStaplingSupported() {
169 #elif defined(USE_NSS)
171 (*CacheOCSPResponseFromSideChannelFunction
)(
172 CERTCertDBHandle
*handle
, CERTCertificate
*cert
, PRTime time
,
173 SECItem
*encodedResponse
, void *pwArg
);
175 // On Linux, we dynamically link against the system version of libnss3.so. In
176 // order to continue working on systems without up-to-date versions of NSS we
177 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
179 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
180 // runtime symbol resolution that we need.
181 class RuntimeLibNSSFunctionPointers
{
183 CacheOCSPResponseFromSideChannelFunction
184 GetCacheOCSPResponseFromSideChannelFunction() {
185 return cache_ocsp_response_from_side_channel_
;
188 static RuntimeLibNSSFunctionPointers
* GetInstance() {
189 return Singleton
<RuntimeLibNSSFunctionPointers
>::get();
193 friend struct DefaultSingletonTraits
<RuntimeLibNSSFunctionPointers
>;
195 RuntimeLibNSSFunctionPointers() {
196 cache_ocsp_response_from_side_channel_
=
197 (CacheOCSPResponseFromSideChannelFunction
)
198 dlsym(RTLD_DEFAULT
, "CERT_CacheOCSPResponseFromSideChannel");
201 CacheOCSPResponseFromSideChannelFunction
202 cache_ocsp_response_from_side_channel_
;
205 CacheOCSPResponseFromSideChannelFunction
206 GetCacheOCSPResponseFromSideChannelFunction() {
207 return RuntimeLibNSSFunctionPointers::GetInstance()
208 ->GetCacheOCSPResponseFromSideChannelFunction();
211 bool IsOCSPStaplingSupported() {
212 return GetCacheOCSPResponseFromSideChannelFunction() != NULL
;
215 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
216 // certificate validation functions.
217 bool IsOCSPStaplingSupported() {
222 class FreeCERTCertificate
{
224 inline void operator()(CERTCertificate
* x
) const {
225 CERT_DestroyCertificate(x
);
228 typedef scoped_ptr_malloc
<CERTCertificate
, FreeCERTCertificate
>
229 ScopedCERTCertificate
;
233 // This callback is intended to be used with CertFindChainInStore. In addition
234 // to filtering by extended/enhanced key usage, we do not show expired
235 // certificates and require digital signature usage in the key usage
238 // This matches our behavior on Mac OS X and that of NSS. It also matches the
239 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
240 // 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
241 BOOL WINAPI
ClientCertFindCallback(PCCERT_CONTEXT cert_context
,
243 VLOG(1) << "Calling ClientCertFindCallback from _nss";
244 // Verify the certificate's KU is good.
246 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING
, cert_context
->pCertInfo
,
248 if (!(key_usage
& CERT_DIGITAL_SIGNATURE_KEY_USAGE
))
251 DWORD err
= GetLastError();
252 // If |err| is non-zero, it's an actual error. Otherwise the extension
253 // just isn't present, and we treat it as if everything was allowed.
255 DLOG(ERROR
) << "CertGetIntendedKeyUsage failed: " << err
;
260 // Verify the current time is within the certificate's validity period.
261 if (CertVerifyTimeValidity(NULL
, cert_context
->pCertInfo
) != 0)
264 // Verify private key metadata is associated with this certificate.
266 if (!CertGetCertificateContextProperty(
267 cert_context
, CERT_KEY_PROV_INFO_PROP_ID
, NULL
, &size
)) {
276 void DestroyCertificates(CERTCertificate
** certs
, size_t len
) {
277 for (size_t i
= 0; i
< len
; i
++)
278 CERT_DestroyCertificate(certs
[i
]);
281 // Helper functions to make it possible to log events from within the
282 // SSLClientSocketNSS::Core.
283 void AddLogEvent(BoundNetLog
* net_log
, NetLog::EventType event_type
) {
286 net_log
->AddEvent(event_type
);
289 // Helper function to make it possible to log events from within the
290 // SSLClientSocketNSS::Core.
291 void AddLogEventWithCallback(BoundNetLog
* net_log
,
292 NetLog::EventType event_type
,
293 const NetLog::ParametersCallback
& callback
) {
296 net_log
->AddEvent(event_type
, callback
);
299 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
300 // from within the SSLClientSocketNSS::Core.
301 // AddByteTransferEvent expects to receive a const char*, which within the
302 // Core is backed by an IOBuffer. If the "const char*" is bound via
303 // base::Bind and posted to another thread, and the IOBuffer that backs that
304 // pointer then goes out of scope on the origin thread, this would result in
305 // an invalid read of a stale pointer.
306 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
307 // to the owning IOBuffer can be bound to the Callback. This ensures that the
308 // IOBuffer will stay alive long enough to cross threads if needed.
309 void LogByteTransferEvent(BoundNetLog
* net_log
, NetLog::EventType event_type
,
310 int len
, IOBuffer
* buffer
) {
313 net_log
->AddByteTransferEvent(event_type
, len
, buffer
->data());
316 // PeerCertificateChain is a helper object which extracts the certificate
317 // chain, as given by the server, from an NSS socket and performs the needed
318 // resource management. The first element of the chain is the leaf certificate
319 // and the other elements are in the order given by the server.
320 class PeerCertificateChain
{
322 PeerCertificateChain() {}
323 PeerCertificateChain(const PeerCertificateChain
& other
);
324 ~PeerCertificateChain();
325 PeerCertificateChain
& operator=(const PeerCertificateChain
& other
);
327 // Resets the current chain, freeing any resources, and updates the current
328 // chain to be a copy of the chain stored in |nss_fd|.
329 // If |nss_fd| is NULL, then the current certificate chain will be freed.
330 void Reset(PRFileDesc
* nss_fd
);
332 // Returns the current certificate chain as a vector of DER-encoded
333 // base::StringPieces. The returned vector remains valid until Reset is
335 std::vector
<base::StringPiece
> AsStringPieceVector() const;
337 bool empty() const { return certs_
.empty(); }
338 size_t size() const { return certs_
.size(); }
340 CERTCertificate
* operator[](size_t index
) const {
341 DCHECK_LT(index
, certs_
.size());
342 return certs_
[index
];
346 std::vector
<CERTCertificate
*> certs_
;
349 PeerCertificateChain::PeerCertificateChain(
350 const PeerCertificateChain
& other
) {
354 PeerCertificateChain::~PeerCertificateChain() {
358 PeerCertificateChain
& PeerCertificateChain::operator=(
359 const PeerCertificateChain
& other
) {
364 certs_
.reserve(other
.certs_
.size());
365 for (size_t i
= 0; i
< other
.certs_
.size(); ++i
)
366 certs_
.push_back(CERT_DupCertificate(other
.certs_
[i
]));
371 void PeerCertificateChain::Reset(PRFileDesc
* nss_fd
) {
372 for (size_t i
= 0; i
< certs_
.size(); ++i
)
373 CERT_DestroyCertificate(certs_
[i
]);
379 unsigned int num_certs
= 0;
380 SECStatus rv
= SSL_PeerCertificateChain(nss_fd
, NULL
, &num_certs
, 0);
381 DCHECK_EQ(SECSuccess
, rv
);
383 // The handshake on |nss_fd| may not have completed.
387 certs_
.resize(num_certs
);
388 const unsigned int expected_num_certs
= num_certs
;
389 rv
= SSL_PeerCertificateChain(nss_fd
, vector_as_array(&certs_
),
390 &num_certs
, expected_num_certs
);
391 DCHECK_EQ(SECSuccess
, rv
);
392 DCHECK_EQ(expected_num_certs
, num_certs
);
395 std::vector
<base::StringPiece
>
396 PeerCertificateChain::AsStringPieceVector() const {
397 std::vector
<base::StringPiece
> v(certs_
.size());
398 for (unsigned i
= 0; i
< certs_
.size(); i
++) {
399 v
[i
] = base::StringPiece(
400 reinterpret_cast<const char*>(certs_
[i
]->derCert
.data
),
401 certs_
[i
]->derCert
.len
);
407 // HandshakeState is a helper struct used to pass handshake state between
408 // the NSS task runner and the network task runner.
410 // It contains members that may be read or written on the NSS task runner,
411 // but which also need to be read from the network task runner. The NSS task
412 // runner will notify the network task runner whenever this state changes, so
413 // that the network task runner can safely make a copy, which avoids the need
415 struct HandshakeState
{
416 HandshakeState() { Reset(); }
419 next_proto_status
= SSLClientSocket::kNextProtoUnsupported
;
421 server_protos
.clear();
422 channel_id_sent
= false;
423 server_cert_chain
.Reset(NULL
);
425 resumed_handshake
= false;
426 ssl_connection_status
= 0;
429 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
430 // negotiated protocol stored in |next_proto|.
431 SSLClientSocket::NextProtoStatus next_proto_status
;
432 std::string next_proto
;
433 // If the server supports NPN, the protocols supported by the server.
434 std::string server_protos
;
436 // True if a channel ID was sent.
437 bool channel_id_sent
;
439 // List of DER-encoded X.509 DistinguishedName of certificate authorities
440 // allowed by the server.
441 std::vector
<std::string
> cert_authorities
;
443 // Set when the handshake fully completes.
445 // The server certificate is first received from NSS as an NSS certificate
446 // chain (|server_cert_chain|) and then converted into a platform-specific
447 // X509Certificate object (|server_cert|). It's possible for some
448 // certificates to be successfully parsed by NSS, and not by the platform
449 // libraries (i.e.: when running within a sandbox, different parsing
450 // algorithms, etc), so it's not safe to assume that |server_cert| will
451 // always be non-NULL.
452 PeerCertificateChain server_cert_chain
;
453 scoped_refptr
<X509Certificate
> server_cert
;
455 // True if the current handshake was the result of TLS session resumption.
456 bool resumed_handshake
;
458 // The negotiated security parameters (TLS version, cipher, extensions) of
459 // the SSL connection.
460 int ssl_connection_status
;
463 // Client-side error mapping functions.
465 // Map NSS error code to network error code.
466 int MapNSSClientError(PRErrorCode err
) {
468 case SSL_ERROR_BAD_CERT_ALERT
:
469 case SSL_ERROR_UNSUPPORTED_CERT_ALERT
:
470 case SSL_ERROR_REVOKED_CERT_ALERT
:
471 case SSL_ERROR_EXPIRED_CERT_ALERT
:
472 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT
:
473 case SSL_ERROR_UNKNOWN_CA_ALERT
:
474 case SSL_ERROR_ACCESS_DENIED_ALERT
:
475 return ERR_BAD_SSL_CLIENT_AUTH_CERT
;
477 return MapNSSError(err
);
481 // Map NSS error code from the first SSL handshake to network error code.
482 int MapNSSClientHandshakeError(PRErrorCode err
) {
484 // If the server closed on us, it is a protocol error.
485 // Some TLS-intolerant servers do this when we request TLS.
486 case PR_END_OF_FILE_ERROR
:
487 return ERR_SSL_PROTOCOL_ERROR
;
489 return MapNSSClientError(err
);
495 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
496 // able to marshal data between NSS functions and an underlying transport
499 // All public functions are meant to be called from the network task runner,
500 // and any callbacks supplied will be invoked there as well, provided that
501 // Detach() has not been called yet.
503 /////////////////////////////////////////////////////////////////////////////
505 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
507 // Because NSS may block on either hardware or user input during operations
508 // such as signing, creating certificates, or locating private keys, the Core
509 // handles all of the interactions with the underlying NSS SSL socket, so
510 // that these blocking calls can be executed on a dedicated task runner.
512 // Note that the network task runner and the NSS task runner may be executing
513 // on the same thread. If that happens, then it's more performant to try to
514 // complete as much work as possible synchronously, even if it might block,
515 // rather than continually PostTask-ing to the same thread.
517 // Because NSS functions should only be called on the NSS task runner, while
518 // I/O resources should only be accessed on the network task runner, most
519 // public functions are implemented via three methods, each with different
520 // task runner affinities.
522 // In the single-threaded mode (where the network and NSS task runners run on
523 // the same thread), these are all attempted synchronously, while in the
524 // multi-threaded mode, message passing is used.
526 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
528 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
529 // (BufferRecv, BufferSend)
530 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
531 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
532 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
533 // data from the network task runner back to NSS (BufferRecvComplete,
534 // BufferSendComplete, OnHandshakeIOComplete)
536 /////////////////////////////////////////////////////////////////////////////
537 // Single-threaded example
539 // |--------------------------Network Task Runner--------------------------|
540 // SSLClientSocketNSS Core (Transport Socket)
542 // |-------------------------V
550 // |-------------------------V
552 // V-------------------------|
553 // BufferRecvComplete()
555 // PostOrRunCallback()
556 // V-------------------------|
559 /////////////////////////////////////////////////////////////////////////////
560 // Multi-threaded example:
562 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
563 // SSLClientSocketNSS Core Socket Core
565 // |---------------------V
567 // |-------------------------------V
573 // V-------------------------------|
575 // |----------------V
577 // V----------------|
578 // BufferRecvComplete()
579 // |-------------------------------V
580 // BufferRecvComplete()
582 // PostOrRunCallback()
583 // V-------------------------------|
584 // PostOrRunCallback()
585 // V---------------------|
588 /////////////////////////////////////////////////////////////////////////////
589 class SSLClientSocketNSS::Core
: public base::RefCountedThreadSafe
<Core
> {
591 // Creates a new Core.
593 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
594 // that need to operate on the underlying transport, net log, or server
595 // bound certificate fetching will happen on the |network_task_runner|, so
596 // that their lifetimes match that of the owning SSLClientSocketNSS.
598 // The caller retains ownership of |transport|, |net_log|, and
599 // |server_bound_cert_service|, and they will not be accessed once Detach()
601 Core(base::SequencedTaskRunner
* network_task_runner
,
602 base::SequencedTaskRunner
* nss_task_runner
,
603 ClientSocketHandle
* transport
,
604 const HostPortPair
& host_and_port
,
605 const SSLConfig
& ssl_config
,
606 BoundNetLog
* net_log
,
607 ServerBoundCertService
* server_bound_cert_service
);
609 // Called on the network task runner.
610 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
611 // underlying memio implementation, to the Core. Returns true if the Core
612 // was successfully registered with the socket.
613 bool Init(PRFileDesc
* socket
, memio_Private
* buffers
);
615 // Called on the network task runner.
616 // Sets the predicted certificate chain that the peer will send, for use
617 // with the TLS CachedInfo extension. If called, it must not be called
618 // before Init() or after Connect().
619 void SetPredictedCertificates(
620 const std::vector
<std::string
>& predicted_certificates
);
622 // Called on the network task runner.
624 // Attempts to perform an SSL handshake. If the handshake cannot be
625 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
626 // the network task runner once the handshake has completed. Otherwise,
627 // returns OK on success or a network error code on failure.
628 int Connect(const CompletionCallback
& callback
);
630 // Called on the network task runner.
631 // Signals that the resources owned by the network task runner are going
632 // away. No further callbacks will be invoked on the network task runner.
633 // May be called at any time.
636 // Called on the network task runner.
637 // Returns the current state of the underlying SSL socket. May be called at
639 const HandshakeState
& state() const { return network_handshake_state_
; }
641 // Called on the network task runner.
642 // Read() and Write() mirror the net::Socket functions of the same name.
643 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
644 // task runner at a later point, unless the caller calls Detach().
645 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
646 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
648 // Called on the network task runner.
650 bool HasPendingAsyncOperation();
651 bool HasUnhandledReceivedData();
654 friend class base::RefCountedThreadSafe
<Core
>;
660 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
,
663 bool OnNSSTaskRunner() const;
664 bool OnNetworkTaskRunner() const;
666 ////////////////////////////////////////////////////////////////////////////
667 // Methods that are ONLY called on the NSS task runner:
668 ////////////////////////////////////////////////////////////////////////////
670 // Called by NSS during full handshakes to allow the application to
671 // verify the certificate. Instead of verifying the certificate in the midst
672 // of the handshake, SECSuccess is always returned and the peer's certificate
673 // is verified afterwards.
674 // This behaviour is an artifact of the original SSLClientSocketWin
675 // implementation, which could not verify the peer's certificate until after
676 // the handshake had completed, as well as bugs in NSS that prevent
677 // SSL_RestartHandshakeAfterCertReq from working.
678 static SECStatus
OwnAuthCertHandler(void* arg
,
683 // Callbacks called by NSS when the peer requests client certificate
685 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
687 #if defined(NSS_PLATFORM_CLIENT_AUTH)
688 // When NSS has been integrated with awareness of the underlying system
689 // cryptographic libraries, this callback allows the caller to supply a
690 // native platform certificate and key for use by NSS. At most, one of
691 // either (result_certs, result_private_key) or (result_nss_certificate,
692 // result_nss_private_key) should be set.
693 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
694 static SECStatus
PlatformClientAuthHandler(
697 CERTDistNames
* ca_names
,
698 CERTCertList
** result_certs
,
699 void** result_private_key
,
700 CERTCertificate
** result_nss_certificate
,
701 SECKEYPrivateKey
** result_nss_private_key
);
703 static SECStatus
ClientAuthHandler(void* arg
,
705 CERTDistNames
* ca_names
,
706 CERTCertificate
** result_certificate
,
707 SECKEYPrivateKey
** result_private_key
);
710 // Called by NSS once the handshake has completed.
711 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
712 static void HandshakeCallback(PRFileDesc
* socket
, void* arg
);
714 // Called by NSS if the peer supports the NPN handshake extension, to allow
715 // the application to select the protocol to use.
716 // See the documentation for SSLNextProtocolCallback in
717 // third_party/nss/ssl/ssl.h for the meanings of the arguments.
718 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
719 static SECStatus
NextProtoCallback(void* arg
,
721 const unsigned char* protos
,
722 unsigned int protos_len
,
723 unsigned char* proto_out
,
724 unsigned int* proto_out_len
,
725 unsigned int proto_max_len
);
727 // Handles an NSS error generated while handshaking or performing IO.
728 // Returns a network error code mapped from the original NSS error.
729 int HandleNSSError(PRErrorCode error
, bool handshake_error
);
731 int DoHandshakeLoop(int last_io_result
);
732 int DoReadLoop(int result
);
733 int DoWriteLoop(int result
);
736 int DoGetDBCertComplete(int result
);
739 int DoPayloadWrite();
741 bool DoTransportIO();
745 void OnRecvComplete(int result
);
746 void OnSendComplete(int result
);
748 void DoConnectCallback(int result
);
749 void DoReadCallback(int result
);
750 void DoWriteCallback(int result
);
752 // Client channel ID handler.
753 static SECStatus
ClientChannelIDHandler(
756 SECKEYPublicKey
**out_public_key
,
757 SECKEYPrivateKey
**out_private_key
);
759 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
760 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
761 // and an error code otherwise.
762 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
763 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
764 // takes ownership of the |*cert| and |*key|.
765 int ImportChannelIDKeys(SECKEYPublicKey
** public_key
, SECKEYPrivateKey
** key
);
767 // Updates the NSS and platform specific certificates.
768 void UpdateServerCert();
769 // Updates the nss_handshake_state_ with the negotiated security parameters.
770 void UpdateConnectionStatus();
771 // Record histograms for channel id support during full handshakes - resumed
772 // handshakes are ignored.
773 void RecordChannelIDSupport() const;
775 ////////////////////////////////////////////////////////////////////////////
776 // Methods that are ONLY called on the network task runner:
777 ////////////////////////////////////////////////////////////////////////////
778 int DoBufferRecv(IOBuffer
* buffer
, int len
);
779 int DoBufferSend(IOBuffer
* buffer
, int len
);
780 int DoGetDomainBoundCert(const std::string
& origin
,
781 const std::vector
<uint8
>& requested_cert_types
);
783 void OnGetDomainBoundCertComplete(int result
);
784 void OnHandshakeStateUpdated(const HandshakeState
& state
);
785 void OnNSSBufferUpdated(int amount_in_read_buffer
);
786 void DidNSSRead(int result
);
787 void DidNSSWrite(int result
);
789 ////////////////////////////////////////////////////////////////////////////
790 // Methods that are called on both the network task runner and the NSS
792 ////////////////////////////////////////////////////////////////////////////
793 void OnHandshakeIOComplete(int result
);
794 void BufferRecvComplete(IOBuffer
* buffer
, int result
);
795 void BufferSendComplete(int result
);
797 // PostOrRunCallback is a helper function to ensure that |callback| is
798 // invoked on the network task runner, but only if Detach() has not yet
800 void PostOrRunCallback(const tracked_objects::Location
& location
,
801 const base::Closure
& callback
);
803 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
804 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
805 void AddCertProvidedEvent(int cert_count
);
807 // Sets the handshake state |channel_id_sent| flag and logs the
808 // SSL_CHANNEL_ID_PROVIDED event.
809 void SetChannelIDProvided();
811 ////////////////////////////////////////////////////////////////////////////
812 // Members that are ONLY accessed on the network task runner:
813 ////////////////////////////////////////////////////////////////////////////
815 // True if the owning SSLClientSocketNSS has called Detach(). No further
816 // callbacks will be invoked nor access to members owned by the network
820 // The underlying transport to use for network IO.
821 ClientSocketHandle
* transport_
;
822 base::WeakPtrFactory
<BoundNetLog
> weak_net_log_factory_
;
824 // The current handshake state. Mirrors |nss_handshake_state_|.
825 HandshakeState network_handshake_state_
;
827 // The service for retrieving Channel ID keys. May be NULL.
828 ServerBoundCertService
* server_bound_cert_service_
;
829 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_
;
831 // The information about NSS task runner.
832 int unhandled_buffer_size_
;
833 bool nss_waiting_read_
;
834 bool nss_waiting_write_
;
837 ////////////////////////////////////////////////////////////////////////////
838 // Members that are ONLY accessed on the NSS task runner:
839 ////////////////////////////////////////////////////////////////////////////
840 HostPortPair host_and_port_
;
841 SSLConfig ssl_config_
;
846 // Buffers for the network end of the SSL state machine
847 memio_Private
* nss_bufs_
;
849 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
850 // as much data as possible, without blocking.
851 // If DoPayloadRead() encounters an error after having read some data, stores
852 // the results to return on the *next* call to DoPayloadRead(). A value of
853 // kNoPendingReadResult indicates there is no pending result, otherwise 0
854 // indicates EOF and < 0 indicates an error.
855 int pending_read_result_
;
856 // Contains the previously observed NSS error. Only valid when
857 // pending_read_result_ != kNoPendingReadResult.
858 PRErrorCode pending_read_nss_error_
;
860 // The certificate chain, in DER form, that is expected to be received from
862 std::vector
<std::string
> predicted_certs_
;
864 State next_handshake_state_
;
866 // True if channel ID extension was negotiated.
867 bool channel_id_xtn_negotiated_
;
868 // True if the handshake state machine was interrupted for channel ID.
869 bool channel_id_needed_
;
870 // True if the handshake state machine was interrupted for client auth.
871 bool client_auth_cert_needed_
;
872 // True if NSS has called HandshakeCallback.
873 bool handshake_callback_called_
;
875 HandshakeState nss_handshake_state_
;
877 bool transport_recv_busy_
;
878 bool transport_recv_eof_
;
879 bool transport_send_busy_
;
881 // Used by Read function.
882 scoped_refptr
<IOBuffer
> user_read_buf_
;
883 int user_read_buf_len_
;
885 // Used by Write function.
886 scoped_refptr
<IOBuffer
> user_write_buf_
;
887 int user_write_buf_len_
;
889 CompletionCallback user_connect_callback_
;
890 CompletionCallback user_read_callback_
;
891 CompletionCallback user_write_callback_
;
893 ////////////////////////////////////////////////////////////////////////////
894 // Members that are accessed on both the network task runner and the NSS
896 ////////////////////////////////////////////////////////////////////////////
897 scoped_refptr
<base::SequencedTaskRunner
> network_task_runner_
;
898 scoped_refptr
<base::SequencedTaskRunner
> nss_task_runner_
;
900 // Dereferenced only on the network task runner, but bound to tasks destined
901 // for the network task runner from the NSS task runner.
902 base::WeakPtr
<BoundNetLog
> weak_net_log_
;
904 // Written on the network task runner by the |server_bound_cert_service_|,
905 // prior to invoking OnHandshakeIOComplete.
906 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
907 // on the NSS task runner.
908 SSLClientCertType domain_bound_cert_type_
;
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 host_and_port_(host_and_port
),
932 ssl_config_(ssl_config
),
935 pending_read_result_(kNoPendingReadResult
),
936 pending_read_nss_error_(0),
937 next_handshake_state_(STATE_NONE
),
938 channel_id_xtn_negotiated_(false),
939 channel_id_needed_(false),
940 client_auth_cert_needed_(false),
941 handshake_callback_called_(false),
942 transport_recv_busy_(false),
943 transport_recv_eof_(false),
944 transport_send_busy_(false),
945 user_read_buf_len_(0),
946 user_write_buf_len_(0),
947 network_task_runner_(network_task_runner
),
948 nss_task_runner_(nss_task_runner
),
949 weak_net_log_(weak_net_log_factory_
.GetWeakPtr()),
950 domain_bound_cert_type_(CLIENT_CERT_INVALID_TYPE
) {
953 SSLClientSocketNSS::Core::~Core() {
954 // TODO(wtc): Send SSL close_notify alert.
955 if (nss_fd_
!= NULL
) {
961 bool SSLClientSocketNSS::Core::Init(PRFileDesc
* socket
,
962 memio_Private
* buffers
) {
963 DCHECK(OnNetworkTaskRunner());
970 SECStatus rv
= SECSuccess
;
972 if (!ssl_config_
.next_protos
.empty()) {
973 rv
= SSL_SetNextProtoCallback(
974 nss_fd_
, SSLClientSocketNSS::Core::NextProtoCallback
, this);
975 if (rv
!= SECSuccess
)
976 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetNextProtoCallback", "");
979 rv
= SSL_AuthCertificateHook(
980 nss_fd_
, SSLClientSocketNSS::Core::OwnAuthCertHandler
, this);
981 if (rv
!= SECSuccess
) {
982 LogFailedNSSFunction(*weak_net_log_
, "SSL_AuthCertificateHook", "");
986 #if defined(NSS_PLATFORM_CLIENT_AUTH)
987 rv
= SSL_GetPlatformClientAuthDataHook(
988 nss_fd_
, SSLClientSocketNSS::Core::PlatformClientAuthHandler
,
991 rv
= SSL_GetClientAuthDataHook(
992 nss_fd_
, SSLClientSocketNSS::Core::ClientAuthHandler
, this);
994 if (rv
!= SECSuccess
) {
995 LogFailedNSSFunction(*weak_net_log_
, "SSL_GetClientAuthDataHook", "");
999 if (ssl_config_
.channel_id_enabled
) {
1000 if (!server_bound_cert_service_
) {
1001 DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
1002 } else if (!crypto::ECPrivateKey::IsSupported()) {
1003 DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
1004 } else if (!server_bound_cert_service_
->IsSystemTimeValid()) {
1005 DVLOG(1) << "System time is weird, not enabling channel ID.";
1007 rv
= SSL_SetClientChannelIDCallback(
1008 nss_fd_
, SSLClientSocketNSS::Core::ClientChannelIDHandler
, this);
1009 if (rv
!= SECSuccess
)
1010 LogFailedNSSFunction(*weak_net_log_
, "SSL_SetClientChannelIDCallback",
1015 rv
= SSL_HandshakeCallback(
1016 nss_fd_
, SSLClientSocketNSS::Core::HandshakeCallback
, this);
1017 if (rv
!= SECSuccess
) {
1018 LogFailedNSSFunction(*weak_net_log_
, "SSL_HandshakeCallback", "");
1025 void SSLClientSocketNSS::Core::SetPredictedCertificates(
1026 const std::vector
<std::string
>& predicted_certs
) {
1027 if (predicted_certs
.empty())
1030 if (!OnNSSTaskRunner()) {
1032 nss_task_runner_
->PostTask(
1034 base::Bind(&Core::SetPredictedCertificates
, this, predicted_certs
));
1040 predicted_certs_
= predicted_certs
;
1042 scoped_ptr
<CERTCertificate
*[]> certs(
1043 new CERTCertificate
*[predicted_certs
.size()]);
1045 for (size_t i
= 0; i
< predicted_certs
.size(); i
++) {
1047 derCert
.data
= const_cast<uint8
*>(reinterpret_cast<const uint8
*>(
1048 predicted_certs
[i
].data()));
1049 derCert
.len
= predicted_certs
[i
].size();
1050 certs
[i
] = CERT_NewTempCertificate(
1051 CERT_GetDefaultCertDB(), &derCert
, NULL
/* no nickname given */,
1052 PR_FALSE
/* not permanent */, PR_TRUE
/* copy DER data */);
1054 DestroyCertificates(&certs
[0], i
);
1061 #ifdef SSL_ENABLE_CACHED_INFO
1062 rv
= SSL_SetPredictedPeerCertificates(nss_fd_
, certs
.get(),
1063 predicted_certs
.size());
1064 DCHECK_EQ(SECSuccess
, rv
);
1066 rv
= SECFailure
; // Not implemented.
1068 DestroyCertificates(&certs
[0], predicted_certs
.size());
1070 if (rv
!= SECSuccess
) {
1071 LOG(WARNING
) << "SetPredictedCertificates failed: "
1072 << host_and_port_
.ToString();
1076 int SSLClientSocketNSS::Core::Connect(const CompletionCallback
& callback
) {
1077 if (!OnNSSTaskRunner()) {
1079 bool posted
= nss_task_runner_
->PostTask(
1081 base::Bind(IgnoreResult(&Core::Connect
), this, callback
));
1082 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1085 DCHECK(OnNSSTaskRunner());
1086 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1087 DCHECK(user_read_callback_
.is_null());
1088 DCHECK(user_write_callback_
.is_null());
1089 DCHECK(user_connect_callback_
.is_null());
1090 DCHECK(!user_read_buf_
);
1091 DCHECK(!user_write_buf_
);
1093 next_handshake_state_
= STATE_HANDSHAKE
;
1094 int rv
= DoHandshakeLoop(OK
);
1095 if (rv
== ERR_IO_PENDING
) {
1096 user_connect_callback_
= callback
;
1097 } else if (rv
> OK
) {
1100 if (rv
!= ERR_IO_PENDING
&& !OnNetworkTaskRunner()) {
1101 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1102 return ERR_IO_PENDING
;
1108 void SSLClientSocketNSS::Core::Detach() {
1109 DCHECK(OnNetworkTaskRunner());
1113 weak_net_log_factory_
.InvalidateWeakPtrs();
1115 network_handshake_state_
.Reset();
1117 domain_bound_cert_request_handle_
.Cancel();
1120 int SSLClientSocketNSS::Core::Read(IOBuffer
* buf
, int buf_len
,
1121 const CompletionCallback
& callback
) {
1122 if (!OnNSSTaskRunner()) {
1123 DCHECK(OnNetworkTaskRunner());
1126 DCHECK(!nss_waiting_read_
);
1128 nss_waiting_read_
= true;
1129 bool posted
= nss_task_runner_
->PostTask(
1131 base::Bind(IgnoreResult(&Core::Read
), this, make_scoped_refptr(buf
),
1132 buf_len
, callback
));
1134 nss_is_closed_
= true;
1135 nss_waiting_read_
= false;
1137 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1140 DCHECK(OnNSSTaskRunner());
1141 DCHECK(handshake_callback_called_
);
1142 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1143 DCHECK(user_read_callback_
.is_null());
1144 DCHECK(user_connect_callback_
.is_null());
1145 DCHECK(!user_read_buf_
);
1148 user_read_buf_
= buf
;
1149 user_read_buf_len_
= buf_len
;
1151 int rv
= DoReadLoop(OK
);
1152 if (rv
== ERR_IO_PENDING
) {
1153 if (OnNetworkTaskRunner())
1154 nss_waiting_read_
= true;
1155 user_read_callback_
= callback
;
1157 user_read_buf_
= NULL
;
1158 user_read_buf_len_
= 0;
1160 if (!OnNetworkTaskRunner()) {
1161 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSRead
, this, rv
));
1162 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1163 return ERR_IO_PENDING
;
1165 DCHECK(!nss_waiting_read_
);
1167 nss_is_closed_
= true;
1174 int SSLClientSocketNSS::Core::Write(IOBuffer
* buf
, int buf_len
,
1175 const CompletionCallback
& callback
) {
1176 if (!OnNSSTaskRunner()) {
1177 DCHECK(OnNetworkTaskRunner());
1180 DCHECK(!nss_waiting_write_
);
1182 nss_waiting_write_
= true;
1183 bool posted
= nss_task_runner_
->PostTask(
1185 base::Bind(IgnoreResult(&Core::Write
), this, make_scoped_refptr(buf
),
1186 buf_len
, callback
));
1188 nss_is_closed_
= true;
1189 nss_waiting_write_
= false;
1191 return posted
? ERR_IO_PENDING
: ERR_ABORTED
;
1194 DCHECK(OnNSSTaskRunner());
1195 DCHECK(handshake_callback_called_
);
1196 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1197 DCHECK(user_write_callback_
.is_null());
1198 DCHECK(user_connect_callback_
.is_null());
1199 DCHECK(!user_write_buf_
);
1202 user_write_buf_
= buf
;
1203 user_write_buf_len_
= buf_len
;
1205 int rv
= DoWriteLoop(OK
);
1206 if (rv
== ERR_IO_PENDING
) {
1207 if (OnNetworkTaskRunner())
1208 nss_waiting_write_
= true;
1209 user_write_callback_
= callback
;
1211 user_write_buf_
= NULL
;
1212 user_write_buf_len_
= 0;
1214 if (!OnNetworkTaskRunner()) {
1215 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::DidNSSWrite
, this, rv
));
1216 PostOrRunCallback(FROM_HERE
, base::Bind(callback
, rv
));
1217 return ERR_IO_PENDING
;
1219 DCHECK(!nss_waiting_write_
);
1221 nss_is_closed_
= true;
1228 bool SSLClientSocketNSS::Core::IsConnected() {
1229 DCHECK(OnNetworkTaskRunner());
1230 return !nss_is_closed_
;
1233 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
1234 DCHECK(OnNetworkTaskRunner());
1235 return nss_waiting_read_
|| nss_waiting_write_
;
1238 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
1239 DCHECK(OnNetworkTaskRunner());
1240 return unhandled_buffer_size_
!= 0;
1243 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1244 return nss_task_runner_
->RunsTasksOnCurrentThread();
1247 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1248 return network_task_runner_
->RunsTasksOnCurrentThread();
1252 SECStatus
SSLClientSocketNSS::Core::OwnAuthCertHandler(
1257 #ifdef SSL_ENABLE_FALSE_START
1258 Core
* core
= reinterpret_cast<Core
*>(arg
);
1259 if (!core
->handshake_callback_called_
) {
1260 // Only need to turn off False Start in the initial handshake. Also, it is
1261 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1262 // handshake" lock isn't already held, which will result in an assertion
1263 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1265 SECStatus rv
= SSL_HandshakeNegotiatedExtension(socket
,
1266 ssl_next_proto_nego_xtn
,
1268 if (rv
!= SECSuccess
|| !npn
) {
1269 // If the server doesn't support NPN, then we don't do False Start with
1271 SSL_OptionSet(socket
, SSL_ENABLE_FALSE_START
, PR_FALSE
);
1276 // Tell NSS to not verify the certificate.
1280 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1282 SECStatus
SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1285 CERTDistNames
* ca_names
,
1286 CERTCertList
** result_certs
,
1287 void** result_private_key
,
1288 CERTCertificate
** result_nss_certificate
,
1289 SECKEYPrivateKey
** result_nss_private_key
) {
1290 Core
* core
= reinterpret_cast<Core
*>(arg
);
1291 DCHECK(core
->OnNSSTaskRunner());
1293 core
->PostOrRunCallback(
1295 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1296 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1298 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1300 if (core
->ssl_config_
.send_client_cert
) {
1301 if (core
->ssl_config_
.client_cert
) {
1302 PCCERT_CONTEXT cert_context
=
1303 core
->ssl_config_
.client_cert
->os_cert_handle();
1305 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov
= 0;
1307 BOOL must_free
= FALSE
;
1308 BOOL acquired_key
= CryptAcquireCertificatePrivateKey(
1309 cert_context
, CRYPT_ACQUIRE_CACHE_FLAG
, NULL
,
1310 &crypt_prov
, &key_spec
, &must_free
);
1313 // Since we passed CRYPT_ACQUIRE_CACHE_FLAG, |must_free| must be false
1314 // according to the MSDN documentation.
1315 CHECK_EQ(must_free
, FALSE
);
1316 DCHECK_NE(key_spec
, CERT_NCRYPT_KEY_SPEC
);
1319 der_cert
.type
= siDERCertBuffer
;
1320 der_cert
.data
= cert_context
->pbCertEncoded
;
1321 der_cert
.len
= cert_context
->cbCertEncoded
;
1323 // TODO(rsleevi): Error checking for NSS allocation errors.
1324 CERTCertDBHandle
* db_handle
= CERT_GetDefaultCertDB();
1325 CERTCertificate
* user_cert
= CERT_NewTempCertificate(
1326 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1328 // Importing the certificate can fail for reasons including a serial
1329 // number collision. See crbug.com/97355.
1330 core
->AddCertProvidedEvent(0);
1333 CERTCertList
* cert_chain
= CERT_NewCertList();
1334 CERT_AddCertToListTail(cert_chain
, user_cert
);
1336 // Add the intermediates.
1337 X509Certificate::OSCertHandles intermediates
=
1338 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1339 for (X509Certificate::OSCertHandles::const_iterator it
=
1340 intermediates
.begin(); it
!= intermediates
.end(); ++it
) {
1341 der_cert
.data
= (*it
)->pbCertEncoded
;
1342 der_cert
.len
= (*it
)->cbCertEncoded
;
1344 CERTCertificate
* intermediate
= CERT_NewTempCertificate(
1345 db_handle
, &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1346 if (!intermediate
) {
1347 CERT_DestroyCertList(cert_chain
);
1348 core
->AddCertProvidedEvent(0);
1351 CERT_AddCertToListTail(cert_chain
, intermediate
);
1353 PCERT_KEY_CONTEXT key_context
= reinterpret_cast<PCERT_KEY_CONTEXT
>(
1354 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT
)));
1355 key_context
->cbSize
= sizeof(*key_context
);
1356 // NSS will free this context when no longer in use, but the
1357 // |must_free| result from CryptAcquireCertificatePrivateKey was false
1358 // so we increment the refcount to negate NSS's future decrement.
1359 CryptContextAddRef(crypt_prov
, NULL
, 0);
1360 key_context
->hCryptProv
= crypt_prov
;
1361 key_context
->dwKeySpec
= key_spec
;
1362 *result_private_key
= key_context
;
1363 *result_certs
= cert_chain
;
1365 int cert_count
= 1 + intermediates
.size();
1366 core
->AddCertProvidedEvent(cert_count
);
1369 LOG(WARNING
) << "Client cert found without private key";
1372 // Send no client certificate.
1373 core
->AddCertProvidedEvent(0);
1377 core
->nss_handshake_state_
.cert_authorities
.clear();
1379 std::vector
<CERT_NAME_BLOB
> issuer_list(ca_names
->nnames
);
1380 for (int i
= 0; i
< ca_names
->nnames
; ++i
) {
1381 issuer_list
[i
].cbData
= ca_names
->names
[i
].len
;
1382 issuer_list
[i
].pbData
= ca_names
->names
[i
].data
;
1383 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1384 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1385 static_cast<size_t>(ca_names
->names
[i
].len
)));
1388 // Update the network task runner's view of the handshake state now that
1389 // server certificate request has been recorded.
1390 core
->PostOrRunCallback(
1391 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1392 core
->nss_handshake_state_
));
1394 // Tell NSS to suspend the client authentication. We will then abort the
1395 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1396 return SECWouldBlock
;
1397 #elif defined(OS_MACOSX)
1398 if (core
->ssl_config_
.send_client_cert
) {
1399 if (core
->ssl_config_
.client_cert
) {
1400 OSStatus os_error
= noErr
;
1401 SecIdentityRef identity
= NULL
;
1402 SecKeyRef private_key
= NULL
;
1403 X509Certificate::OSCertHandles chain
;
1405 base::AutoLock
lock(crypto::GetMacSecurityServicesLock());
1406 os_error
= SecIdentityCreateWithCertificate(
1407 NULL
, core
->ssl_config_
.client_cert
->os_cert_handle(), &identity
);
1409 if (os_error
== noErr
) {
1410 os_error
= SecIdentityCopyPrivateKey(identity
, &private_key
);
1411 CFRelease(identity
);
1414 if (os_error
== noErr
) {
1415 // TODO(rsleevi): Error checking for NSS allocation errors.
1416 *result_certs
= CERT_NewCertList();
1417 *result_private_key
= private_key
;
1419 chain
.push_back(core
->ssl_config_
.client_cert
->os_cert_handle());
1420 const X509Certificate::OSCertHandles
& intermediates
=
1421 core
->ssl_config_
.client_cert
->GetIntermediateCertificates();
1422 if (!intermediates
.empty())
1423 chain
.insert(chain
.end(), intermediates
.begin(), intermediates
.end());
1425 for (size_t i
= 0, chain_count
= chain
.size(); i
< chain_count
; ++i
) {
1426 CSSM_DATA cert_data
;
1427 SecCertificateRef cert_ref
= chain
[i
];
1428 os_error
= SecCertificateGetData(cert_ref
, &cert_data
);
1429 if (os_error
!= noErr
)
1433 der_cert
.type
= siDERCertBuffer
;
1434 der_cert
.data
= cert_data
.Data
;
1435 der_cert
.len
= cert_data
.Length
;
1436 CERTCertificate
* nss_cert
= CERT_NewTempCertificate(
1437 CERT_GetDefaultCertDB(), &der_cert
, NULL
, PR_FALSE
, PR_TRUE
);
1439 // In the event of an NSS error, make up an OS error and reuse
1440 // the error handling below.
1441 os_error
= errSecCreateChainFailed
;
1444 CERT_AddCertToListTail(*result_certs
, nss_cert
);
1448 if (os_error
== noErr
) {
1449 core
->AddCertProvidedEvent(chain
.size());
1453 OSSTATUS_LOG(WARNING
, os_error
)
1454 << "Client cert found, but could not be used";
1455 if (*result_certs
) {
1456 CERT_DestroyCertList(*result_certs
);
1457 *result_certs
= NULL
;
1459 if (*result_private_key
)
1460 *result_private_key
= NULL
;
1462 CFRelease(private_key
);
1465 // Send no client certificate.
1466 core
->AddCertProvidedEvent(0);
1470 core
->nss_handshake_state_
.cert_authorities
.clear();
1472 // Retrieve the cert issuers accepted by the server.
1473 std::vector
<CertPrincipal
> valid_issuers
;
1474 int n
= ca_names
->nnames
;
1475 for (int i
= 0; i
< n
; i
++) {
1476 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1477 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1478 static_cast<size_t>(ca_names
->names
[i
].len
)));
1481 // Update the network task runner's view of the handshake state now that
1482 // server certificate request has been recorded.
1483 core
->PostOrRunCallback(
1484 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1485 core
->nss_handshake_state_
));
1487 // Tell NSS to suspend the client authentication. We will then abort the
1488 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1489 return SECWouldBlock
;
1495 #elif defined(OS_IOS)
1497 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1500 CERTDistNames
* ca_names
,
1501 CERTCertificate
** result_certificate
,
1502 SECKEYPrivateKey
** result_private_key
) {
1503 Core
* core
= reinterpret_cast<Core
*>(arg
);
1504 DCHECK(core
->OnNSSTaskRunner());
1506 core
->PostOrRunCallback(
1508 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1509 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1511 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1512 LOG(WARNING
) << "Client auth is not supported";
1514 // Never send a certificate.
1515 core
->AddCertProvidedEvent(0);
1519 #else // NSS_PLATFORM_CLIENT_AUTH
1522 // Based on Mozilla's NSS_GetClientAuthData.
1523 SECStatus
SSLClientSocketNSS::Core::ClientAuthHandler(
1526 CERTDistNames
* ca_names
,
1527 CERTCertificate
** result_certificate
,
1528 SECKEYPrivateKey
** result_private_key
) {
1529 Core
* core
= reinterpret_cast<Core
*>(arg
);
1530 DCHECK(core
->OnNSSTaskRunner());
1532 core
->PostOrRunCallback(
1534 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
1535 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED
));
1537 // Regular client certificate requested.
1538 core
->client_auth_cert_needed_
= !core
->ssl_config_
.send_client_cert
;
1539 void* wincx
= SSL_RevealPinArg(socket
);
1541 if (core
->ssl_config_
.send_client_cert
) {
1542 // Second pass: a client certificate should have been selected.
1543 if (core
->ssl_config_
.client_cert
) {
1544 CERTCertificate
* cert
= CERT_DupCertificate(
1545 core
->ssl_config_
.client_cert
->os_cert_handle());
1546 SECKEYPrivateKey
* privkey
= PK11_FindKeyByAnyCert(cert
, wincx
);
1548 // TODO(jsorianopastor): We should wait for server certificate
1549 // verification before sending our credentials. See
1550 // http://crbug.com/13934.
1551 *result_certificate
= cert
;
1552 *result_private_key
= privkey
;
1553 // A cert_count of -1 means the number of certificates is unknown.
1554 // NSS will construct the certificate chain.
1555 core
->AddCertProvidedEvent(-1);
1559 LOG(WARNING
) << "Client cert found without private key";
1561 // Send no client certificate.
1562 core
->AddCertProvidedEvent(0);
1566 // First pass: client certificate is needed.
1567 core
->nss_handshake_state_
.cert_authorities
.clear();
1569 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1570 // the server and save them in |cert_authorities|.
1571 for (int i
= 0; i
< ca_names
->nnames
; i
++) {
1572 core
->nss_handshake_state_
.cert_authorities
.push_back(std::string(
1573 reinterpret_cast<const char*>(ca_names
->names
[i
].data
),
1574 static_cast<size_t>(ca_names
->names
[i
].len
)));
1577 // Update the network task runner's view of the handshake state now that
1578 // server certificate request has been recorded.
1579 core
->PostOrRunCallback(
1580 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1581 core
->nss_handshake_state_
));
1583 // Tell NSS to suspend the client authentication. We will then abort the
1584 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1585 return SECWouldBlock
;
1587 #endif // NSS_PLATFORM_CLIENT_AUTH
1590 void SSLClientSocketNSS::Core::HandshakeCallback(
1593 Core
* core
= reinterpret_cast<Core
*>(arg
);
1594 DCHECK(core
->OnNSSTaskRunner());
1596 core
->handshake_callback_called_
= true;
1598 HandshakeState
* nss_state
= &core
->nss_handshake_state_
;
1600 PRBool last_handshake_resumed
;
1601 SECStatus rv
= SSL_HandshakeResumedSession(socket
, &last_handshake_resumed
);
1602 if (rv
== SECSuccess
&& last_handshake_resumed
) {
1603 nss_state
->resumed_handshake
= true;
1605 nss_state
->resumed_handshake
= false;
1608 core
->RecordChannelIDSupport();
1609 core
->UpdateServerCert();
1610 core
->UpdateConnectionStatus();
1612 // Update the network task runners view of the handshake state whenever
1613 // a handshake has completed.
1614 core
->PostOrRunCallback(
1615 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1620 SECStatus
SSLClientSocketNSS::Core::NextProtoCallback(
1623 const unsigned char* protos
,
1624 unsigned int protos_len
,
1625 unsigned char* proto_out
,
1626 unsigned int* proto_out_len
,
1627 unsigned int proto_max_len
) {
1628 Core
* core
= reinterpret_cast<Core
*>(arg
);
1629 DCHECK(core
->OnNSSTaskRunner());
1631 HandshakeState
* nss_state
= &core
->nss_handshake_state_
;
1633 // For each protocol in server preference, see if we support it.
1634 for (unsigned int i
= 0; i
< protos_len
; ) {
1635 const size_t len
= protos
[i
];
1636 for (std::vector
<std::string
>::const_iterator
1637 j
= core
->ssl_config_
.next_protos
.begin();
1638 j
!= core
->ssl_config_
.next_protos
.end(); j
++) {
1639 // Having very long elements in the |next_protos| vector isn't a disaster
1640 // because they'll never be selected, but it does indicate an error
1642 DCHECK_LT(j
->size(), 256u);
1644 if (j
->size() == len
&&
1645 memcmp(&protos
[i
+ 1], j
->data(), len
) == 0) {
1646 nss_state
->next_proto_status
= kNextProtoNegotiated
;
1647 nss_state
->next_proto
= *j
;
1652 if (nss_state
->next_proto_status
== kNextProtoNegotiated
)
1655 // NSS ensures that the data in |protos| is well formed, so this will not
1656 // cause a jump past the end of the buffer.
1660 nss_state
->server_protos
.assign(
1661 reinterpret_cast<const char*>(protos
), protos_len
);
1663 // If we didn't find a protocol, we select the first one from our list.
1664 if (nss_state
->next_proto_status
!= kNextProtoNegotiated
) {
1665 nss_state
->next_proto_status
= kNextProtoNoOverlap
;
1666 nss_state
->next_proto
= core
->ssl_config_
.next_protos
[0];
1669 if (nss_state
->next_proto
.size() > proto_max_len
) {
1670 PORT_SetError(SEC_ERROR_OUTPUT_LEN
);
1673 memcpy(proto_out
, nss_state
->next_proto
.data(),
1674 nss_state
->next_proto
.size());
1675 *proto_out_len
= nss_state
->next_proto
.size();
1677 // Update the network task runner's view of the handshake state now that
1678 // NPN negotiation has occurred.
1679 core
->PostOrRunCallback(
1680 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, core
,
1686 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error
,
1687 bool handshake_error
) {
1688 DCHECK(OnNSSTaskRunner());
1690 int net_error
= handshake_error
? MapNSSClientHandshakeError(nss_error
) :
1691 MapNSSClientError(nss_error
);
1694 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1695 // os_cert_handle() as an optimization. However, if the certificate
1696 // private key is stored on a smart card, and the smart card is removed,
1697 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1698 // preventing client certificate authentication. Because the
1699 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1700 // caching in X509Certificate, this failure ends up preventing client
1701 // certificate authentication with the same certificate for all future
1702 // attempts, even after the smart card has been re-inserted. By setting
1703 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1704 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1705 // the certificate on the next attempt, which should succeed if the smart
1706 // card has been re-inserted, or will typically prompt the user to
1707 // re-insert the smart card if not.
1708 if ((net_error
== ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
||
1709 net_error
== ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED
) &&
1710 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
) {
1711 CertSetCertificateContextProperty(
1712 ssl_config_
.client_cert
->os_cert_handle(),
1713 CERT_KEY_PROV_HANDLE_PROP_ID
, 0, NULL
);
1720 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result
) {
1721 DCHECK(OnNSSTaskRunner());
1723 int rv
= last_io_result
;
1725 // Default to STATE_NONE for next state.
1726 State state
= next_handshake_state_
;
1727 GotoState(STATE_NONE
);
1730 case STATE_HANDSHAKE
:
1733 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
:
1734 rv
= DoGetDBCertComplete(rv
);
1738 rv
= ERR_UNEXPECTED
;
1739 LOG(DFATAL
) << "unexpected state " << state
;
1743 // Do the actual network I/O
1744 bool network_moved
= DoTransportIO();
1745 if (network_moved
&& next_handshake_state_
== STATE_HANDSHAKE
) {
1746 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1747 // special case we keep looping even if rv is ERR_IO_PENDING because
1748 // the transport IO may allow DoHandshake to make progress.
1749 DCHECK(rv
== OK
|| rv
== ERR_IO_PENDING
);
1750 rv
= OK
; // This causes us to stay in the loop.
1752 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
1756 int SSLClientSocketNSS::Core::DoReadLoop(int result
) {
1757 DCHECK(OnNSSTaskRunner());
1758 DCHECK(handshake_callback_called_
);
1759 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1765 LOG(DFATAL
) << "!nss_bufs_";
1766 int rv
= ERR_UNEXPECTED
;
1769 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1770 NetLog::TYPE_SSL_READ_ERROR
,
1771 CreateNetLogSSLErrorCallback(rv
, 0)));
1778 rv
= DoPayloadRead();
1779 network_moved
= DoTransportIO();
1780 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1785 int SSLClientSocketNSS::Core::DoWriteLoop(int result
) {
1786 DCHECK(OnNSSTaskRunner());
1787 DCHECK(handshake_callback_called_
);
1788 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
1794 LOG(DFATAL
) << "!nss_bufs_";
1795 int rv
= ERR_UNEXPECTED
;
1798 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1799 NetLog::TYPE_SSL_READ_ERROR
,
1800 CreateNetLogSSLErrorCallback(rv
, 0)));
1807 rv
= DoPayloadWrite();
1808 network_moved
= DoTransportIO();
1809 } while (rv
== ERR_IO_PENDING
&& network_moved
);
1815 int SSLClientSocketNSS::Core::DoHandshake() {
1816 DCHECK(OnNSSTaskRunner());
1818 int net_error
= net::OK
;
1819 SECStatus rv
= SSL_ForceHandshake(nss_fd_
);
1821 // Note: this function may be called multiple times during the handshake, so
1822 // even though channel id and client auth are separate else cases, they can
1823 // both be used during a single SSL handshake.
1824 if (channel_id_needed_
) {
1825 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE
);
1826 net_error
= ERR_IO_PENDING
;
1827 } else if (client_auth_cert_needed_
) {
1828 net_error
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
1831 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1832 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1833 CreateNetLogSSLErrorCallback(net_error
, 0)));
1835 // If the handshake already succeeded (because the server requests but
1836 // doesn't require a client cert), we need to invalidate the SSL session
1837 // so that we won't try to resume the non-client-authenticated session in
1838 // the next handshake. This will cause the server to ask for a client
1840 if (rv
== SECSuccess
&& SSL_InvalidateSession(nss_fd_
) != SECSuccess
)
1841 LOG(WARNING
) << "Couldn't invalidate SSL session: " << PR_GetError();
1842 } else if (rv
== SECSuccess
) {
1843 if (!handshake_callback_called_
) {
1844 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1845 // SSL_ForceHandshake returned SECSuccess prematurely.
1847 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1850 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1851 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1852 CreateNetLogSSLErrorCallback(net_error
, 0)));
1854 #if defined(SSL_ENABLE_OCSP_STAPLING)
1855 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1856 // system library and update IsOCSPStaplingSupported for Mac.
1857 if (IsOCSPStaplingSupported()) {
1858 unsigned int len
= 0;
1859 SSL_GetStapledOCSPResponse(nss_fd_
, NULL
, &len
);
1861 const unsigned int orig_len
= len
;
1862 scoped_ptr
<uint8
[]> ocsp_response(new uint8
[orig_len
]);
1863 SSL_GetStapledOCSPResponse(nss_fd_
, ocsp_response
.get(), &len
);
1864 DCHECK_EQ(orig_len
, len
);
1867 if (nss_handshake_state_
.server_cert
) {
1868 CRYPT_DATA_BLOB ocsp_response_blob
;
1869 ocsp_response_blob
.cbData
= len
;
1870 ocsp_response_blob
.pbData
= ocsp_response
.get();
1871 BOOL ok
= CertSetCertificateContextProperty(
1872 nss_handshake_state_
.server_cert
->os_cert_handle(),
1873 CERT_OCSP_RESPONSE_PROP_ID
,
1874 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG
,
1875 &ocsp_response_blob
);
1877 VLOG(1) << "Failed to set OCSP response property: "
1881 #elif defined(USE_NSS)
1882 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response
=
1883 GetCacheOCSPResponseFromSideChannelFunction();
1884 SECItem ocsp_response_item
;
1885 ocsp_response_item
.type
= siBuffer
;
1886 ocsp_response_item
.data
= ocsp_response
.get();
1887 ocsp_response_item
.len
= len
;
1889 cache_ocsp_response(
1890 CERT_GetDefaultCertDB(),
1891 nss_handshake_state_
.server_cert_chain
[0], PR_Now(),
1892 &ocsp_response_item
, NULL
);
1900 PRErrorCode prerr
= PR_GetError();
1901 net_error
= HandleNSSError(prerr
, true);
1903 // Some network devices that inspect application-layer packets seem to
1904 // inject TCP reset packets to break the connections when they see
1905 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1907 // Only allow ERR_CONNECTION_RESET to trigger a TLS 1.1 -> TLS 1.0
1908 // fallback. We don't lose much in this fallback because the explicit
1909 // IV for CBC mode in TLS 1.1 is approximated by record splitting in
1912 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1913 // to trigger a version fallback in general, especially the TLS 1.0 ->
1914 // SSL 3.0 fallback, which would drop TLS extensions.
1915 if (prerr
== PR_CONNECT_RESET_ERROR
&&
1916 ssl_config_
.version_max
== SSL_PROTOCOL_VERSION_TLS1_1
) {
1917 net_error
= ERR_SSL_PROTOCOL_ERROR
;
1920 // If not done, stay in this state
1921 if (net_error
== ERR_IO_PENDING
) {
1922 GotoState(STATE_HANDSHAKE
);
1926 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1927 NetLog::TYPE_SSL_HANDSHAKE_ERROR
,
1928 CreateNetLogSSLErrorCallback(net_error
, prerr
)));
1935 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result
) {
1939 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, weak_net_log_
,
1940 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, result
));
1942 channel_id_needed_
= false;
1947 SECKEYPublicKey
* public_key
;
1948 SECKEYPrivateKey
* private_key
;
1949 int error
= ImportChannelIDKeys(&public_key
, &private_key
);
1953 rv
= SSL_RestartHandshakeAfterChannelIDReq(nss_fd_
, public_key
, private_key
);
1954 if (rv
!= SECSuccess
)
1955 return MapNSSError(PORT_GetError());
1957 SetChannelIDProvided();
1958 GotoState(STATE_HANDSHAKE
);
1962 int SSLClientSocketNSS::Core::DoPayloadRead() {
1963 DCHECK(OnNSSTaskRunner());
1964 DCHECK(user_read_buf_
);
1965 DCHECK_GT(user_read_buf_len_
, 0);
1968 // If a previous greedy read resulted in an error that was not consumed (eg:
1969 // due to the caller having read some data successfully), then return that
1970 // pending error now.
1971 if (pending_read_result_
!= kNoPendingReadResult
) {
1972 rv
= pending_read_result_
;
1973 PRErrorCode prerr
= pending_read_nss_error_
;
1974 pending_read_result_
= kNoPendingReadResult
;
1975 pending_read_nss_error_
= 0;
1980 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
1981 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
1982 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
1986 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
1987 NetLog::TYPE_SSL_READ_ERROR
,
1988 CreateNetLogSSLErrorCallback(rv
, prerr
)));
1993 // Perform a greedy read, attempting to read as much as the caller has
1994 // requested. In the current NSS implementation, PR_Read will return
1995 // exactly one SSL application data record's worth of data per invocation.
1996 // The record size is dictated by the server, and may be noticeably smaller
1997 // than the caller's buffer. This may be as little as a single byte, if the
1998 // server is performing 1/n-1 record splitting.
2000 // However, this greedy read may result in renegotiations/re-handshakes
2001 // happening or may lead to some data being read, followed by an EOF (such as
2002 // a TLS close-notify). If at least some data was read, then that result
2003 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
2004 // data was read, it's safe to return the error or EOF immediately.
2005 int total_bytes_read
= 0;
2007 rv
= PR_Read(nss_fd_
, user_read_buf_
->data() + total_bytes_read
,
2008 user_read_buf_len_
- total_bytes_read
);
2010 total_bytes_read
+= rv
;
2011 } while (total_bytes_read
< user_read_buf_len_
&& rv
> 0);
2012 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2013 PostOrRunCallback(FROM_HERE
, base::Bind(&Core::OnNSSBufferUpdated
, this,
2014 amount_in_read_buffer
));
2016 if (total_bytes_read
== user_read_buf_len_
) {
2017 // The caller's entire request was satisfied without error. No further
2018 // processing needed.
2019 rv
= total_bytes_read
;
2021 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
2022 // immediately, while the NSPR/NSS errors are still available in
2023 // thread-local storage. However, the handled/remapped error code should
2024 // only be returned if no application data was already read; if it was, the
2025 // error code should be deferred until the next call of DoPayloadRead.
2027 // If no data was read, |*next_result| will point to the return value of
2028 // this function. If at least some data was read, |*next_result| will point
2029 // to |pending_read_error_|, to be returned in a future call to
2030 // DoPayloadRead() (e.g.: after the current data is handled).
2031 int* next_result
= &rv
;
2032 if (total_bytes_read
> 0) {
2033 pending_read_result_
= rv
;
2034 rv
= total_bytes_read
;
2035 next_result
= &pending_read_result_
;
2038 if (client_auth_cert_needed_
) {
2039 *next_result
= ERR_SSL_CLIENT_AUTH_CERT_NEEDED
;
2040 pending_read_nss_error_
= 0;
2041 } else if (*next_result
< 0) {
2042 // If *next_result == 0, then that indicates EOF, and no special error
2043 // handling is needed.
2044 pending_read_nss_error_
= PR_GetError();
2045 *next_result
= HandleNSSError(pending_read_nss_error_
, false);
2046 if (rv
> 0 && *next_result
== ERR_IO_PENDING
) {
2047 // If at least some data was read from PR_Read(), do not treat
2048 // insufficient data as an error to return in the next call to
2049 // DoPayloadRead() - instead, let the call fall through to check
2050 // PR_Read() again. This is because DoTransportIO() may complete
2051 // in between the next call to DoPayloadRead(), and thus it is
2052 // important to check PR_Read() on subsequent invocations to see
2053 // if a complete record may now be read.
2054 pending_read_nss_error_
= 0;
2055 pending_read_result_
= kNoPendingReadResult
;
2060 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
2065 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2066 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
, rv
,
2067 scoped_refptr
<IOBuffer
>(user_read_buf_
)));
2068 } else if (rv
!= ERR_IO_PENDING
) {
2071 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2072 NetLog::TYPE_SSL_READ_ERROR
,
2073 CreateNetLogSSLErrorCallback(rv
, pending_read_nss_error_
)));
2074 pending_read_nss_error_
= 0;
2079 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2080 DCHECK(OnNSSTaskRunner());
2082 DCHECK(user_write_buf_
);
2084 int old_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2085 int rv
= PR_Write(nss_fd_
, user_write_buf_
->data(), user_write_buf_len_
);
2086 int new_amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2087 // PR_Write could potentially consume the unhandled data in the memio read
2088 // buffer if a renegotiation is in progress. If the buffer is consumed,
2089 // notify the latest buffer size to NetworkRunner.
2090 if (old_amount_in_read_buffer
!= new_amount_in_read_buffer
) {
2093 base::Bind(&Core::OnNSSBufferUpdated
, this, new_amount_in_read_buffer
));
2098 base::Bind(&LogByteTransferEvent
, weak_net_log_
,
2099 NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, rv
,
2100 scoped_refptr
<IOBuffer
>(user_write_buf_
)));
2103 PRErrorCode prerr
= PR_GetError();
2104 if (prerr
== PR_WOULD_BLOCK_ERROR
)
2105 return ERR_IO_PENDING
;
2107 rv
= HandleNSSError(prerr
, false);
2110 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2111 NetLog::TYPE_SSL_WRITE_ERROR
,
2112 CreateNetLogSSLErrorCallback(rv
, prerr
)));
2116 // Do as much network I/O as possible between the buffer and the
2117 // transport socket. Return true if some I/O performed, false
2118 // otherwise (error or ERR_IO_PENDING).
2119 bool SSLClientSocketNSS::Core::DoTransportIO() {
2120 DCHECK(OnNSSTaskRunner());
2122 bool network_moved
= false;
2123 if (nss_bufs_
!= NULL
) {
2125 // Read and write as much data as we can. The loop is neccessary
2126 // because Write() may return synchronously.
2130 network_moved
= true;
2132 if (!transport_recv_eof_
&& BufferRecv() >= 0)
2133 network_moved
= true;
2135 return network_moved
;
2138 int SSLClientSocketNSS::Core::BufferRecv() {
2139 DCHECK(OnNSSTaskRunner());
2141 if (transport_recv_busy_
)
2142 return ERR_IO_PENDING
;
2144 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2145 // determine how much data NSS wants to read. If NSS was not blocked,
2146 // this will return 0.
2147 int requested
= memio_GetReadRequest(nss_bufs_
);
2148 if (requested
== 0) {
2149 // This is not a perfect match of error codes, as no operation is
2150 // actually pending. However, returning 0 would be interpreted as a
2151 // possible sign of EOF, which is also an inappropriate match.
2152 return ERR_IO_PENDING
;
2156 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2159 // buffer too full to read into, so no I/O possible at moment
2160 rv
= ERR_IO_PENDING
;
2162 scoped_refptr
<IOBuffer
> read_buffer(new IOBuffer(nb
));
2163 if (OnNetworkTaskRunner()) {
2164 rv
= DoBufferRecv(read_buffer
, nb
);
2166 bool posted
= network_task_runner_
->PostTask(
2168 base::Bind(IgnoreResult(&Core::DoBufferRecv
), this, read_buffer
,
2170 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2173 if (rv
== ERR_IO_PENDING
) {
2174 transport_recv_busy_
= true;
2177 memcpy(buf
, read_buffer
->data(), rv
);
2178 } else if (rv
== 0) {
2179 transport_recv_eof_
= true;
2181 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(rv
));
2187 // Return 0 for EOF,
2188 // > 0 for bytes transferred immediately,
2189 // < 0 for error (or the non-error ERR_IO_PENDING).
2190 int SSLClientSocketNSS::Core::BufferSend() {
2191 DCHECK(OnNSSTaskRunner());
2193 if (transport_send_busy_
)
2194 return ERR_IO_PENDING
;
2198 unsigned int len1
, len2
;
2199 memio_GetWriteParams(nss_bufs_
, &buf1
, &len1
, &buf2
, &len2
);
2200 const unsigned int len
= len1
+ len2
;
2204 scoped_refptr
<IOBuffer
> send_buffer(new IOBuffer(len
));
2205 memcpy(send_buffer
->data(), buf1
, len1
);
2206 memcpy(send_buffer
->data() + len1
, buf2
, len2
);
2208 if (OnNetworkTaskRunner()) {
2209 rv
= DoBufferSend(send_buffer
, len
);
2211 bool posted
= network_task_runner_
->PostTask(
2213 base::Bind(IgnoreResult(&Core::DoBufferSend
), this, send_buffer
,
2215 rv
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2218 if (rv
== ERR_IO_PENDING
) {
2219 transport_send_busy_
= true;
2221 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(rv
));
2228 void SSLClientSocketNSS::Core::OnRecvComplete(int result
) {
2229 DCHECK(OnNSSTaskRunner());
2231 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2232 OnHandshakeIOComplete(result
);
2236 // Network layer received some data, check if client requested to read
2238 if (!user_read_buf_
)
2241 int rv
= DoReadLoop(result
);
2242 if (rv
!= ERR_IO_PENDING
)
2246 void SSLClientSocketNSS::Core::OnSendComplete(int result
) {
2247 DCHECK(OnNSSTaskRunner());
2249 if (next_handshake_state_
== STATE_HANDSHAKE
) {
2250 OnHandshakeIOComplete(result
);
2254 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2255 // handshake is in progress.
2256 int rv_read
= ERR_IO_PENDING
;
2257 int rv_write
= ERR_IO_PENDING
;
2261 rv_read
= DoPayloadRead();
2262 if (user_write_buf_
)
2263 rv_write
= DoPayloadWrite();
2264 network_moved
= DoTransportIO();
2265 } while (rv_read
== ERR_IO_PENDING
&&
2266 rv_write
== ERR_IO_PENDING
&&
2267 (user_read_buf_
|| user_write_buf_
) &&
2270 if (user_read_buf_
&& rv_read
!= ERR_IO_PENDING
)
2271 DoReadCallback(rv_read
);
2272 if (user_write_buf_
&& rv_write
!= ERR_IO_PENDING
)
2273 DoWriteCallback(rv_write
);
2276 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2277 // handshake. This requires network IO, which in turn calls
2278 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2279 // winds its way through the state machine and ends up being passed to the
2280 // callback. For Read() and Write(), that's what we want. But for Connect(),
2281 // the caller expects OK (i.e. 0) for success.
2282 void SSLClientSocketNSS::Core::DoConnectCallback(int rv
) {
2283 DCHECK(OnNSSTaskRunner());
2284 DCHECK_NE(rv
, ERR_IO_PENDING
);
2285 DCHECK(!user_connect_callback_
.is_null());
2287 base::Closure c
= base::Bind(
2288 base::ResetAndReturn(&user_connect_callback_
),
2290 PostOrRunCallback(FROM_HERE
, c
);
2293 void SSLClientSocketNSS::Core::DoReadCallback(int rv
) {
2294 DCHECK(OnNSSTaskRunner());
2295 DCHECK_NE(ERR_IO_PENDING
, rv
);
2296 DCHECK(!user_read_callback_
.is_null());
2298 user_read_buf_
= NULL
;
2299 user_read_buf_len_
= 0;
2300 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2301 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2302 // the network task runner.
2305 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2308 base::Bind(&Core::DidNSSRead
, this, rv
));
2311 base::Bind(base::ResetAndReturn(&user_read_callback_
), rv
));
2314 void SSLClientSocketNSS::Core::DoWriteCallback(int rv
) {
2315 DCHECK(OnNSSTaskRunner());
2316 DCHECK_NE(ERR_IO_PENDING
, rv
);
2317 DCHECK(!user_write_callback_
.is_null());
2319 // Since Run may result in Write being called, clear |user_write_callback_|
2321 user_write_buf_
= NULL
;
2322 user_write_buf_len_
= 0;
2323 // Update buffer status because DoWriteLoop called DoTransportIO which may
2324 // perform read operations.
2325 int amount_in_read_buffer
= memio_GetReadableBufferSize(nss_bufs_
);
2326 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2327 // the network task runner.
2330 base::Bind(&Core::OnNSSBufferUpdated
, this, amount_in_read_buffer
));
2333 base::Bind(&Core::DidNSSWrite
, this, rv
));
2336 base::Bind(base::ResetAndReturn(&user_write_callback_
), rv
));
2339 SECStatus
SSLClientSocketNSS::Core::ClientChannelIDHandler(
2342 SECKEYPublicKey
**out_public_key
,
2343 SECKEYPrivateKey
**out_private_key
) {
2344 Core
* core
= reinterpret_cast<Core
*>(arg
);
2345 DCHECK(core
->OnNSSTaskRunner());
2347 core
->PostOrRunCallback(
2349 base::Bind(&AddLogEvent
, core
->weak_net_log_
,
2350 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED
));
2352 // We have negotiated the TLS channel ID extension.
2353 core
->channel_id_xtn_negotiated_
= true;
2354 std::string origin
= "https://" + core
->host_and_port_
.ToString();
2355 std::vector
<uint8
> requested_cert_types
;
2356 requested_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2357 int error
= ERR_UNEXPECTED
;
2358 if (core
->OnNetworkTaskRunner()) {
2359 error
= core
->DoGetDomainBoundCert(origin
, requested_cert_types
);
2361 bool posted
= core
->network_task_runner_
->PostTask(
2364 IgnoreResult(&Core::DoGetDomainBoundCert
),
2365 core
, origin
, requested_cert_types
));
2366 error
= posted
? ERR_IO_PENDING
: ERR_ABORTED
;
2369 if (error
== ERR_IO_PENDING
) {
2370 // Asynchronous case.
2371 core
->channel_id_needed_
= true;
2372 return SECWouldBlock
;
2375 core
->PostOrRunCallback(
2377 base::Bind(&BoundNetLog::EndEventWithNetErrorCode
, core
->weak_net_log_
,
2378 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
, error
));
2379 SECStatus rv
= SECSuccess
;
2381 // Synchronous success.
2382 int result
= core
->ImportChannelIDKeys(out_public_key
, out_private_key
);
2384 core
->SetChannelIDProvided();
2394 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey
** public_key
,
2395 SECKEYPrivateKey
** key
) {
2396 // Set the certificate.
2398 cert_item
.data
= (unsigned char*) domain_bound_cert_
.data();
2399 cert_item
.len
= domain_bound_cert_
.size();
2400 ScopedCERTCertificate
cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2406 return MapNSSError(PORT_GetError());
2408 // Set the private key.
2409 switch (domain_bound_cert_type_
) {
2410 case CLIENT_CERT_ECDSA_SIGN
: {
2411 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2412 ServerBoundCertService::kEPKIPassword
,
2413 reinterpret_cast<const unsigned char*>(
2414 domain_bound_private_key_
.data()),
2415 domain_bound_private_key_
.size(),
2416 &cert
->subjectPublicKeyInfo
,
2421 int error
= MapNSSError(PORT_GetError());
2429 return ERR_INVALID_ARGUMENT
;
2435 void SSLClientSocketNSS::Core::UpdateServerCert() {
2436 nss_handshake_state_
.server_cert_chain
.Reset(nss_fd_
);
2437 nss_handshake_state_
.server_cert
= X509Certificate::CreateFromDERCertChain(
2438 nss_handshake_state_
.server_cert_chain
.AsStringPieceVector());
2439 if (nss_handshake_state_
.server_cert
) {
2440 // Since this will be called asynchronously on another thread, it needs to
2441 // own a reference to the certificate.
2442 NetLog::ParametersCallback net_log_callback
=
2443 base::Bind(&NetLogX509CertificateCallback
,
2444 nss_handshake_state_
.server_cert
);
2447 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2448 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED
,
2453 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2454 SSLChannelInfo channel_info
;
2455 SECStatus ok
= SSL_GetChannelInfo(nss_fd_
,
2456 &channel_info
, sizeof(channel_info
));
2457 if (ok
== SECSuccess
&&
2458 channel_info
.length
== sizeof(channel_info
) &&
2459 channel_info
.cipherSuite
) {
2460 nss_handshake_state_
.ssl_connection_status
|=
2461 (static_cast<int>(channel_info
.cipherSuite
) &
2462 SSL_CONNECTION_CIPHERSUITE_MASK
) <<
2463 SSL_CONNECTION_CIPHERSUITE_SHIFT
;
2465 nss_handshake_state_
.ssl_connection_status
|=
2466 (static_cast<int>(channel_info
.compressionMethod
) &
2467 SSL_CONNECTION_COMPRESSION_MASK
) <<
2468 SSL_CONNECTION_COMPRESSION_SHIFT
;
2470 // NSS 3.12.x doesn't have version macros for TLS 1.1 and 1.2 (because NSS
2471 // doesn't support them yet), so we use 0x0302 and 0x0303 directly.
2472 int version
= SSL_CONNECTION_VERSION_UNKNOWN
;
2473 if (channel_info
.protocolVersion
< SSL_LIBRARY_VERSION_3_0
) {
2474 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2476 version
= SSL_CONNECTION_VERSION_SSL2
;
2477 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2478 version
= SSL_CONNECTION_VERSION_SSL3
;
2479 } else if (channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_1_TLS
) {
2480 version
= SSL_CONNECTION_VERSION_TLS1
;
2481 } else if (channel_info
.protocolVersion
== 0x0302) {
2482 version
= SSL_CONNECTION_VERSION_TLS1_1
;
2483 } else if (channel_info
.protocolVersion
== 0x0303) {
2484 version
= SSL_CONNECTION_VERSION_TLS1_2
;
2486 nss_handshake_state_
.ssl_connection_status
|=
2487 (version
& SSL_CONNECTION_VERSION_MASK
) <<
2488 SSL_CONNECTION_VERSION_SHIFT
;
2491 // SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6.
2492 // Since SSL_MAX_EXTENSIONS was added at the same time, we can test
2493 // SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension.
2494 #if defined(SSL_MAX_EXTENSIONS)
2495 PRBool peer_supports_renego_ext
;
2496 ok
= SSL_HandshakeNegotiatedExtension(nss_fd_
, ssl_renegotiation_info_xtn
,
2497 &peer_supports_renego_ext
);
2498 if (ok
== SECSuccess
) {
2499 if (!peer_supports_renego_ext
) {
2500 nss_handshake_state_
.ssl_connection_status
|=
2501 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION
;
2502 // Log an informational message if the server does not support secure
2503 // renegotiation (RFC 5746).
2504 VLOG(1) << "The server " << host_and_port_
.ToString()
2505 << " does not support the TLS renegotiation_info extension.";
2507 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2508 peer_supports_renego_ext
, 2);
2510 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2511 // because of security concerns. For example, Google offers forward
2512 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2513 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2516 // Yngve from Opera has suggested using the renegotiation extension as an
2517 // indicator that SSLv3 fallback was mistaken:
2518 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2520 // As a first step, measure how often clients perform version fallback
2521 // while the server advertises support secure renegotiation.
2522 if (ssl_config_
.version_fallback
&&
2523 channel_info
.protocolVersion
== SSL_LIBRARY_VERSION_3_0
) {
2524 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2525 peer_supports_renego_ext
== PR_TRUE
);
2530 if (ssl_config_
.version_fallback
) {
2531 nss_handshake_state_
.ssl_connection_status
|=
2532 SSL_CONNECTION_VERSION_FALLBACK
;
2536 void SSLClientSocketNSS::Core::RecordChannelIDSupport() const {
2537 if (nss_handshake_state_
.resumed_handshake
)
2540 // Since this enum is used for a histogram, do not change or re-use values.
2544 CLIENT_AND_SERVER
= 2,
2546 CLIENT_BAD_SYSTEM_TIME
= 4,
2547 CLIENT_NO_SERVER_BOUND_CERT_SERVICE
= 5,
2548 DOMAIN_BOUND_CERT_USAGE_MAX
2549 } supported
= DISABLED
;
2550 if (channel_id_xtn_negotiated_
) {
2551 supported
= CLIENT_AND_SERVER
;
2552 } else if (ssl_config_
.channel_id_enabled
) {
2553 if (!server_bound_cert_service_
)
2554 supported
= CLIENT_NO_SERVER_BOUND_CERT_SERVICE
;
2555 else if (!crypto::ECPrivateKey::IsSupported())
2556 supported
= CLIENT_NO_ECC
;
2557 else if (!server_bound_cert_service_
->IsSystemTimeValid())
2558 supported
= CLIENT_BAD_SYSTEM_TIME
;
2560 supported
= CLIENT_ONLY
;
2562 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported
,
2563 DOMAIN_BOUND_CERT_USAGE_MAX
);
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(
2611 const std::string
& origin
,
2612 const std::vector
<uint8
>& requested_cert_types
) {
2613 DCHECK(OnNetworkTaskRunner());
2618 weak_net_log_
->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT
);
2620 int rv
= server_bound_cert_service_
->GetDomainBoundCert(
2622 requested_cert_types
,
2623 &domain_bound_cert_type_
,
2624 &domain_bound_private_key_
,
2625 &domain_bound_cert_
,
2626 base::Bind(&Core::OnGetDomainBoundCertComplete
, base::Unretained(this)),
2627 &domain_bound_cert_request_handle_
);
2629 if (rv
!= ERR_IO_PENDING
&& !OnNSSTaskRunner()) {
2630 nss_task_runner_
->PostTask(
2632 base::Bind(&Core::OnHandshakeIOComplete
, this, rv
));
2633 return ERR_IO_PENDING
;
2639 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2640 const HandshakeState
& state
) {
2641 DCHECK(OnNetworkTaskRunner());
2642 network_handshake_state_
= state
;
2645 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer
) {
2646 DCHECK(OnNetworkTaskRunner());
2647 unhandled_buffer_size_
= amount_in_read_buffer
;
2650 void SSLClientSocketNSS::Core::DidNSSRead(int result
) {
2651 DCHECK(OnNetworkTaskRunner());
2652 DCHECK(nss_waiting_read_
);
2653 nss_waiting_read_
= false;
2655 nss_is_closed_
= true;
2658 void SSLClientSocketNSS::Core::DidNSSWrite(int result
) {
2659 DCHECK(OnNetworkTaskRunner());
2660 DCHECK(nss_waiting_write_
);
2661 nss_waiting_write_
= false;
2663 nss_is_closed_
= true;
2666 void SSLClientSocketNSS::Core::BufferSendComplete(int result
) {
2667 if (!OnNSSTaskRunner()) {
2671 nss_task_runner_
->PostTask(
2672 FROM_HERE
, base::Bind(&Core::BufferSendComplete
, this, result
));
2676 DCHECK(OnNSSTaskRunner());
2678 memio_PutWriteResult(nss_bufs_
, MapErrorToNSS(result
));
2679 transport_send_busy_
= false;
2680 OnSendComplete(result
);
2683 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result
) {
2684 if (!OnNSSTaskRunner()) {
2688 nss_task_runner_
->PostTask(
2689 FROM_HERE
, base::Bind(&Core::OnHandshakeIOComplete
, this, result
));
2693 DCHECK(OnNSSTaskRunner());
2695 int rv
= DoHandshakeLoop(result
);
2696 if (rv
!= ERR_IO_PENDING
)
2697 DoConnectCallback(rv
);
2700 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result
) {
2701 DVLOG(1) << __FUNCTION__
<< " " << result
;
2702 DCHECK(OnNetworkTaskRunner());
2704 OnHandshakeIOComplete(result
);
2707 void SSLClientSocketNSS::Core::BufferRecvComplete(
2708 IOBuffer
* read_buffer
,
2710 DCHECK(read_buffer
);
2712 if (!OnNSSTaskRunner()) {
2716 nss_task_runner_
->PostTask(
2717 FROM_HERE
, base::Bind(&Core::BufferRecvComplete
, this,
2718 scoped_refptr
<IOBuffer
>(read_buffer
), result
));
2722 DCHECK(OnNSSTaskRunner());
2726 int nb
= memio_GetReadParams(nss_bufs_
, &buf
);
2727 CHECK_GE(nb
, result
);
2728 memcpy(buf
, read_buffer
->data(), result
);
2729 } else if (result
== 0) {
2730 transport_recv_eof_
= true;
2733 memio_PutReadResult(nss_bufs_
, MapErrorToNSS(result
));
2734 transport_recv_busy_
= false;
2735 OnRecvComplete(result
);
2738 void SSLClientSocketNSS::Core::PostOrRunCallback(
2739 const tracked_objects::Location
& location
,
2740 const base::Closure
& task
) {
2741 if (!OnNetworkTaskRunner()) {
2742 network_task_runner_
->PostTask(
2744 base::Bind(&Core::PostOrRunCallback
, this, location
, task
));
2748 if (detached_
|| task
.is_null())
2753 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count
) {
2756 base::Bind(&AddLogEventWithCallback
, weak_net_log_
,
2757 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED
,
2758 NetLog::IntegerCallback("cert_count", cert_count
)));
2761 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2763 FROM_HERE
, base::Bind(&AddLogEvent
, weak_net_log_
,
2764 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED
));
2765 nss_handshake_state_
.channel_id_sent
= true;
2766 // Update the network task runner's view of the handshake state now that
2767 // channel id has been sent.
2769 FROM_HERE
, base::Bind(&Core::OnHandshakeStateUpdated
, this,
2770 nss_handshake_state_
));
2773 SSLClientSocketNSS::SSLClientSocketNSS(
2774 base::SequencedTaskRunner
* nss_task_runner
,
2775 ClientSocketHandle
* transport_socket
,
2776 const HostPortPair
& host_and_port
,
2777 const SSLConfig
& ssl_config
,
2778 const SSLClientSocketContext
& context
)
2779 : nss_task_runner_(nss_task_runner
),
2780 transport_(transport_socket
),
2781 host_and_port_(host_and_port
),
2782 ssl_config_(ssl_config
),
2783 cert_verifier_(context
.cert_verifier
),
2784 server_bound_cert_service_(context
.server_bound_cert_service
),
2785 ssl_session_cache_shard_(context
.ssl_session_cache_shard
),
2786 completed_handshake_(false),
2787 next_handshake_state_(STATE_NONE
),
2789 net_log_(transport_socket
->socket()->NetLog()),
2790 transport_security_state_(context
.transport_security_state
),
2791 valid_thread_id_(base::kInvalidThreadId
) {
2797 SSLClientSocketNSS::~SSLClientSocketNSS() {
2804 void SSLClientSocket::ClearSessionCache() {
2805 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2806 // bother initializing NSS just to clear an empty SSL session cache.
2807 if (!NSS_IsInitialized())
2810 SSL_ClearSessionCache();
2813 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo
* ssl_info
) {
2816 if (core_
->state().server_cert_chain
.empty() ||
2817 !core_
->state().server_cert_chain
[0]) {
2821 ssl_info
->cert_status
= server_cert_verify_result_
.cert_status
;
2822 ssl_info
->cert
= server_cert_verify_result_
.verified_cert
;
2823 ssl_info
->connection_status
=
2824 core_
->state().ssl_connection_status
;
2825 ssl_info
->public_key_hashes
= server_cert_verify_result_
.public_key_hashes
;
2826 for (HashValueVector::const_iterator i
= side_pinned_public_keys_
.begin();
2827 i
!= side_pinned_public_keys_
.end(); ++i
) {
2828 ssl_info
->public_key_hashes
.push_back(*i
);
2830 ssl_info
->is_issued_by_known_root
=
2831 server_cert_verify_result_
.is_issued_by_known_root
;
2832 ssl_info
->client_cert_sent
=
2833 ssl_config_
.send_client_cert
&& ssl_config_
.client_cert
;
2834 ssl_info
->channel_id_sent
= WasChannelIDSent();
2836 PRUint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
2837 core_
->state().ssl_connection_status
);
2838 SSLCipherSuiteInfo cipher_info
;
2839 SECStatus ok
= SSL_GetCipherSuiteInfo(cipher_suite
,
2840 &cipher_info
, sizeof(cipher_info
));
2841 if (ok
== SECSuccess
) {
2842 ssl_info
->security_bits
= cipher_info
.effectiveKeyBits
;
2844 ssl_info
->security_bits
= -1;
2845 LOG(DFATAL
) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2846 << " for cipherSuite " << cipher_suite
;
2849 ssl_info
->handshake_type
= core_
->state().resumed_handshake
?
2850 SSLInfo::HANDSHAKE_RESUME
: SSLInfo::HANDSHAKE_FULL
;
2856 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2857 SSLCertRequestInfo
* cert_request_info
) {
2859 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2860 cert_request_info
->host_and_port
= host_and_port_
.ToString();
2861 cert_request_info
->cert_authorities
= core_
->state().cert_authorities
;
2865 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece
& label
,
2867 const base::StringPiece
& context
,
2869 unsigned int outlen
) {
2871 return ERR_SOCKET_NOT_CONNECTED
;
2873 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2874 // the midst of a handshake.
2875 SECStatus result
= SSL_ExportKeyingMaterial(
2876 nss_fd_
, label
.data(), label
.size(), has_context
,
2877 reinterpret_cast<const unsigned char*>(context
.data()),
2878 context
.length(), out
, outlen
);
2879 if (result
!= SECSuccess
) {
2880 LogFailedNSSFunction(net_log_
, "SSL_ExportKeyingMaterial", "");
2881 return MapNSSError(PORT_GetError());
2886 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string
* out
) {
2888 return ERR_SOCKET_NOT_CONNECTED
;
2889 unsigned char buf
[64];
2891 SECStatus result
= SSL_GetChannelBinding(nss_fd_
,
2892 SSL_CHANNEL_BINDING_TLS_UNIQUE
,
2893 buf
, &len
, arraysize(buf
));
2894 if (result
!= SECSuccess
) {
2895 LogFailedNSSFunction(net_log_
, "SSL_GetChannelBinding", "");
2896 return MapNSSError(PORT_GetError());
2898 out
->assign(reinterpret_cast<char*>(buf
), len
);
2902 SSLClientSocket::NextProtoStatus
2903 SSLClientSocketNSS::GetNextProto(std::string
* proto
,
2904 std::string
* server_protos
) {
2905 *proto
= core_
->state().next_proto
;
2906 *server_protos
= core_
->state().server_protos
;
2907 return core_
->state().next_proto_status
;
2910 int SSLClientSocketNSS::Connect(const CompletionCallback
& callback
) {
2912 DCHECK(transport_
.get());
2913 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
2914 DCHECK(user_connect_callback_
.is_null());
2915 DCHECK(!callback
.is_null());
2917 EnsureThreadIdAssigned();
2919 net_log_
.BeginEvent(NetLog::TYPE_SSL_CONNECT
);
2923 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2927 rv
= InitializeSSLOptions();
2929 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2933 rv
= InitializeSSLPeerName();
2935 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2939 GotoState(STATE_HANDSHAKE
);
2941 rv
= DoHandshakeLoop(OK
);
2942 if (rv
== ERR_IO_PENDING
) {
2943 user_connect_callback_
= callback
;
2945 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
2949 return rv
> OK
? OK
: rv
;
2952 void SSLClientSocketNSS::Disconnect() {
2955 CHECK(CalledOnValidThread());
2957 // Shut down anything that may call us back.
2960 transport_
->socket()->Disconnect();
2962 // Reset object state.
2963 user_connect_callback_
.Reset();
2964 server_cert_verify_result_
.Reset();
2965 completed_handshake_
= false;
2966 start_cert_verification_time_
= base::TimeTicks();
2972 bool SSLClientSocketNSS::IsConnected() const {
2974 bool ret
= completed_handshake_
&&
2975 (core_
->HasPendingAsyncOperation() ||
2976 (core_
->IsConnected() && core_
->HasUnhandledReceivedData()) ||
2977 transport_
->socket()->IsConnected());
2982 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2984 bool ret
= completed_handshake_
&&
2985 !core_
->HasPendingAsyncOperation() &&
2986 !(core_
->IsConnected() && core_
->HasUnhandledReceivedData()) &&
2987 transport_
->socket()->IsConnectedAndIdle();
2992 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint
* address
) const {
2993 return transport_
->socket()->GetPeerAddress(address
);
2996 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint
* address
) const {
2997 return transport_
->socket()->GetLocalAddress(address
);
3000 const BoundNetLog
& SSLClientSocketNSS::NetLog() const {
3004 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3005 if (transport_
.get() && transport_
->socket()) {
3006 transport_
->socket()->SetSubresourceSpeculation();
3012 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3013 if (transport_
.get() && transport_
->socket()) {
3014 transport_
->socket()->SetOmniboxSpeculation();
3020 bool SSLClientSocketNSS::WasEverUsed() const {
3021 if (transport_
.get() && transport_
->socket()) {
3022 return transport_
->socket()->WasEverUsed();
3028 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3029 if (transport_
.get() && transport_
->socket()) {
3030 return transport_
->socket()->UsingTCPFastOpen();
3036 int SSLClientSocketNSS::Read(IOBuffer
* buf
, int buf_len
,
3037 const CompletionCallback
& callback
) {
3039 DCHECK(!callback
.is_null());
3041 EnterFunction(buf_len
);
3042 int rv
= core_
->Read(buf
, buf_len
, callback
);
3048 int SSLClientSocketNSS::Write(IOBuffer
* buf
, int buf_len
,
3049 const CompletionCallback
& callback
) {
3051 DCHECK(!callback
.is_null());
3053 EnterFunction(buf_len
);
3054 int rv
= core_
->Write(buf
, buf_len
, callback
);
3060 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size
) {
3061 return transport_
->socket()->SetReceiveBufferSize(size
);
3064 bool SSLClientSocketNSS::SetSendBufferSize(int32 size
) {
3065 return transport_
->socket()->SetSendBufferSize(size
);
3068 int SSLClientSocketNSS::Init() {
3070 // Initialize the NSS SSL library in a threadsafe way. This also
3071 // initializes the NSS base library.
3073 if (!NSS_IsInitialized())
3074 return ERR_UNEXPECTED
;
3075 #if defined(USE_NSS) || defined(OS_IOS)
3076 if (ssl_config_
.cert_io_enabled
) {
3077 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3078 // loop by MessageLoopForIO::current().
3079 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3080 EnsureNSSHttpIOInit();
3088 void SSLClientSocketNSS::InitCore() {
3089 core_
= new Core(base::ThreadTaskRunnerHandle::Get(), nss_task_runner_
,
3090 transport_
.get(), host_and_port_
, ssl_config_
, &net_log_
,
3091 server_bound_cert_service_
);
3094 int SSLClientSocketNSS::InitializeSSLOptions() {
3095 // Transport connected, now hook it up to nss
3096 nss_fd_
= memio_CreateIOLayer(kRecvBufferSize
, kSendBufferSize
);
3097 if (nss_fd_
== NULL
) {
3098 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR error code.
3101 // Grab pointer to buffers
3102 memio_Private
* nss_bufs
= memio_GetSecret(nss_fd_
);
3104 /* Create SSL state machine */
3105 /* Push SSL onto our fake I/O socket */
3106 nss_fd_
= SSL_ImportFD(NULL
, nss_fd_
);
3107 if (nss_fd_
== NULL
) {
3108 LogFailedNSSFunction(net_log_
, "SSL_ImportFD", "");
3109 return ERR_OUT_OF_MEMORY
; // TODO(port): map NSPR/NSS error code.
3111 // TODO(port): set more ssl options! Check errors!
3115 rv
= SSL_OptionSet(nss_fd_
, SSL_SECURITY
, PR_TRUE
);
3116 if (rv
!= SECSuccess
) {
3117 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_SECURITY");
3118 return ERR_UNEXPECTED
;
3121 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SSL2
, PR_FALSE
);
3122 if (rv
!= SECSuccess
) {
3123 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3124 return ERR_UNEXPECTED
;
3127 // Don't do V2 compatible hellos because they don't support TLS extensions.
3128 rv
= SSL_OptionSet(nss_fd_
, SSL_V2_COMPATIBLE_HELLO
, PR_FALSE
);
3129 if (rv
!= SECSuccess
) {
3130 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3131 return ERR_UNEXPECTED
;
3134 SSLVersionRange version_range
;
3135 version_range
.min
= ssl_config_
.version_min
;
3136 version_range
.max
= ssl_config_
.version_max
;
3137 rv
= SSL_VersionRangeSet(nss_fd_
, &version_range
);
3138 if (rv
!= SECSuccess
) {
3139 LogFailedNSSFunction(net_log_
, "SSL_VersionRangeSet", "");
3140 return ERR_NO_SSL_VERSIONS_ENABLED
;
3143 for (std::vector
<uint16
>::const_iterator it
=
3144 ssl_config_
.disabled_cipher_suites
.begin();
3145 it
!= ssl_config_
.disabled_cipher_suites
.end(); ++it
) {
3146 // This will fail if the specified cipher is not implemented by NSS, but
3147 // the failure is harmless.
3148 SSL_CipherPrefSet(nss_fd_
, *it
, PR_FALSE
);
3151 #ifdef SSL_ENABLE_SESSION_TICKETS
3153 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_SESSION_TICKETS
, PR_TRUE
);
3154 if (rv
!= SECSuccess
) {
3155 LogFailedNSSFunction(
3156 net_log_
, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3159 #error "You need to install NSS-3.12 or later to build chromium"
3162 #ifdef SSL_ENABLE_FALSE_START
3163 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_FALSE_START
,
3164 ssl_config_
.false_start_enabled
);
3165 if (rv
!= SECSuccess
)
3166 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3169 #ifdef SSL_ENABLE_RENEGOTIATION
3170 // We allow servers to request renegotiation. Since we're a client,
3171 // prohibiting this is rather a waste of time. Only servers are in a
3172 // position to prevent renegotiation attacks.
3173 // http://extendedsubset.com/?p=8
3175 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_RENEGOTIATION
,
3176 SSL_RENEGOTIATE_TRANSITIONAL
);
3177 if (rv
!= SECSuccess
) {
3178 LogFailedNSSFunction(
3179 net_log_
, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3181 #endif // SSL_ENABLE_RENEGOTIATION
3183 #ifdef SSL_CBC_RANDOM_IV
3184 rv
= SSL_OptionSet(nss_fd_
, SSL_CBC_RANDOM_IV
, PR_TRUE
);
3185 if (rv
!= SECSuccess
)
3186 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3189 #ifdef SSL_ENABLE_OCSP_STAPLING
3190 if (IsOCSPStaplingSupported()) {
3191 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_OCSP_STAPLING
, PR_TRUE
);
3192 if (rv
!= SECSuccess
) {
3193 LogFailedNSSFunction(net_log_
, "SSL_OptionSet",
3194 "SSL_ENABLE_OCSP_STAPLING");
3199 #ifdef SSL_ENABLE_CACHED_INFO
3200 rv
= SSL_OptionSet(nss_fd_
, SSL_ENABLE_CACHED_INFO
,
3201 ssl_config_
.cached_info_enabled
);
3202 if (rv
!= SECSuccess
)
3203 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3206 rv
= SSL_OptionSet(nss_fd_
, SSL_HANDSHAKE_AS_CLIENT
, PR_TRUE
);
3207 if (rv
!= SECSuccess
) {
3208 LogFailedNSSFunction(net_log_
, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3209 return ERR_UNEXPECTED
;
3212 if (!core_
->Init(nss_fd_
, nss_bufs
))
3213 return ERR_UNEXPECTED
;
3215 // Tell SSL the hostname we're trying to connect to.
3216 SSL_SetURL(nss_fd_
, host_and_port_
.host().c_str());
3218 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3219 SSL_ResetHandshake(nss_fd_
, PR_FALSE
);
3224 int SSLClientSocketNSS::InitializeSSLPeerName() {
3225 // Tell NSS who we're connected to
3226 IPEndPoint peer_address
;
3227 int err
= transport_
->socket()->GetPeerAddress(&peer_address
);
3231 SockaddrStorage storage
;
3232 if (!peer_address
.ToSockAddr(storage
.addr
, &storage
.addr_len
))
3233 return ERR_UNEXPECTED
;
3236 memset(&peername
, 0, sizeof(peername
));
3237 DCHECK_LE(static_cast<size_t>(storage
.addr_len
), sizeof(peername
));
3238 size_t len
= std::min(static_cast<size_t>(storage
.addr_len
),
3240 memcpy(&peername
, storage
.addr
, len
);
3242 // Adjust the address family field for BSD, whose sockaddr
3243 // structure has a one-byte length and one-byte address family
3244 // field at the beginning. PRNetAddr has a two-byte address
3245 // family field at the beginning.
3246 peername
.raw
.family
= storage
.addr
->sa_family
;
3248 memio_SetPeerName(nss_fd_
, &peername
);
3250 // Set the peer ID for session reuse. This is necessary when we create an
3251 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3252 // rather than the destination server's address in that case.
3253 std::string peer_id
= host_and_port_
.ToString();
3254 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3255 // This will cause session cache misses between sockets with different values
3256 // of ssl_session_cache_shard_ and this is used to partition the session cache
3257 // for incognito mode.
3258 if (!ssl_session_cache_shard_
.empty()) {
3259 peer_id
+= "/" + ssl_session_cache_shard_
;
3261 SECStatus rv
= SSL_SetSockPeerID(nss_fd_
, const_cast<char*>(peer_id
.c_str()));
3262 if (rv
!= SECSuccess
)
3263 LogFailedNSSFunction(net_log_
, "SSL_SetSockPeerID", peer_id
.c_str());
3268 void SSLClientSocketNSS::DoConnectCallback(int rv
) {
3270 DCHECK_NE(ERR_IO_PENDING
, rv
);
3271 DCHECK(!user_connect_callback_
.is_null());
3273 base::ResetAndReturn(&user_connect_callback_
).Run(rv
> OK
? OK
: rv
);
3277 void SSLClientSocketNSS::OnHandshakeIOComplete(int result
) {
3278 EnterFunction(result
);
3279 int rv
= DoHandshakeLoop(result
);
3280 if (rv
!= ERR_IO_PENDING
) {
3281 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT
, rv
);
3282 DoConnectCallback(rv
);
3287 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result
) {
3288 EnterFunction(last_io_result
);
3289 int rv
= last_io_result
;
3291 // Default to STATE_NONE for next state.
3292 // (This is a quirk carried over from the windows
3293 // implementation. It makes reading the logs a bit harder.)
3294 // State handlers can and often do call GotoState just
3295 // to stay in the current state.
3296 State state
= next_handshake_state_
;
3297 GotoState(STATE_NONE
);
3299 case STATE_HANDSHAKE
:
3302 case STATE_HANDSHAKE_COMPLETE
:
3303 rv
= DoHandshakeComplete(rv
);
3305 case STATE_VERIFY_CERT
:
3307 rv
= DoVerifyCert(rv
);
3309 case STATE_VERIFY_CERT_COMPLETE
:
3310 rv
= DoVerifyCertComplete(rv
);
3314 rv
= ERR_UNEXPECTED
;
3315 LOG(DFATAL
) << "unexpected state " << state
;
3318 } while (rv
!= ERR_IO_PENDING
&& next_handshake_state_
!= STATE_NONE
);
3323 int SSLClientSocketNSS::DoHandshake() {
3325 int rv
= core_
->Connect(
3326 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3327 base::Unretained(this)));
3328 GotoState(STATE_HANDSHAKE_COMPLETE
);
3334 int SSLClientSocketNSS::DoHandshakeComplete(int result
) {
3335 EnterFunction(result
);
3338 // SSL handshake is completed. Let's verify the certificate.
3339 GotoState(STATE_VERIFY_CERT
);
3342 set_channel_id_sent(core_
->state().channel_id_sent
);
3344 LeaveFunction(result
);
3349 int SSLClientSocketNSS::DoVerifyCert(int result
) {
3350 DCHECK(!core_
->state().server_cert_chain
.empty());
3351 DCHECK(core_
->state().server_cert_chain
[0]);
3353 GotoState(STATE_VERIFY_CERT_COMPLETE
);
3355 // If the certificate is expected to be bad we can use the expectation as
3357 base::StringPiece
der_cert(
3358 reinterpret_cast<char*>(
3359 core_
->state().server_cert_chain
[0]->derCert
.data
),
3360 core_
->state().server_cert_chain
[0]->derCert
.len
);
3361 CertStatus cert_status
;
3362 if (ssl_config_
.IsAllowedBadCert(der_cert
, &cert_status
)) {
3363 DCHECK(start_cert_verification_time_
.is_null());
3364 VLOG(1) << "Received an expected bad cert with status: " << cert_status
;
3365 server_cert_verify_result_
.Reset();
3366 server_cert_verify_result_
.cert_status
= cert_status
;
3367 server_cert_verify_result_
.verified_cert
= core_
->state().server_cert
;
3371 // We may have failed to create X509Certificate object if we are
3372 // running inside sandbox.
3373 if (!core_
->state().server_cert
) {
3374 server_cert_verify_result_
.Reset();
3375 server_cert_verify_result_
.cert_status
= CERT_STATUS_INVALID
;
3376 return ERR_CERT_INVALID
;
3379 start_cert_verification_time_
= base::TimeTicks::Now();
3382 if (ssl_config_
.rev_checking_enabled
)
3383 flags
|= CertVerifier::VERIFY_REV_CHECKING_ENABLED
;
3384 if (ssl_config_
.verify_ev_cert
)
3385 flags
|= CertVerifier::VERIFY_EV_CERT
;
3386 if (ssl_config_
.cert_io_enabled
)
3387 flags
|= CertVerifier::VERIFY_CERT_IO_ENABLED
;
3388 verifier_
.reset(new SingleRequestCertVerifier(cert_verifier_
));
3389 return verifier_
->Verify(
3390 core_
->state().server_cert
, host_and_port_
.host(), flags
,
3391 SSLConfigService::GetCRLSet(), &server_cert_verify_result_
,
3392 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete
,
3393 base::Unretained(this)),
3397 // Derived from AuthCertificateCallback() in
3398 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3399 int SSLClientSocketNSS::DoVerifyCertComplete(int result
) {
3402 if (!start_cert_verification_time_
.is_null()) {
3403 base::TimeDelta verify_time
=
3404 base::TimeTicks::Now() - start_cert_verification_time_
;
3406 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time
);
3408 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time
);
3411 // We used to remember the intermediate CA certs in the NSS database
3412 // persistently. However, NSS opens a connection to the SQLite database
3413 // during NSS initialization and doesn't close the connection until NSS
3414 // shuts down. If the file system where the database resides is gone,
3415 // the database connection goes bad. What's worse, the connection won't
3416 // recover when the file system comes back. Until this NSS or SQLite bug
3417 // is fixed, we need to avoid using the NSS database for non-essential
3418 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3419 // http://crbug.com/15630 for more info.
3421 // TODO(hclam): Skip logging if server cert was expected to be bad because
3422 // |server_cert_verify_result_| doesn't contain all the information about
3425 LogConnectionTypeMetrics();
3427 completed_handshake_
= true;
3429 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3430 // Take care of any mandates for public key pinning.
3432 // Pinning is only enabled for official builds to make sure that others don't
3433 // end up with pins that cannot be easily updated.
3435 // TODO(agl): We might have an issue here where a request for foo.example.com
3436 // merges into a SPDY connection to www.example.com, and gets a different
3439 // Perform pin validation if, and only if, all these conditions obtain:
3441 // * a TransportSecurityState object is available;
3442 // * the server's certificate chain is valid (or suffers from only a minor
3444 // * the server's certificate chain chains up to a known root (i.e. not a
3445 // user-installed trust anchor); and
3446 // * the build is recent (very old builds should fail open so that users
3447 // have some chance to recover).
3449 const CertStatus cert_status
= server_cert_verify_result_
.cert_status
;
3450 if (transport_security_state_
&&
3452 (IsCertificateError(result
) && IsCertStatusMinorError(cert_status
))) &&
3453 server_cert_verify_result_
.is_issued_by_known_root
&&
3454 TransportSecurityState::IsBuildTimely()) {
3455 bool sni_available
=
3456 ssl_config_
.version_max
>= SSL_PROTOCOL_VERSION_TLS1
||
3457 ssl_config_
.version_fallback
;
3458 const std::string
& host
= host_and_port_
.host();
3460 TransportSecurityState::DomainState domain_state
;
3461 if (transport_security_state_
->GetDomainState(host
, sni_available
,
3463 domain_state
.HasPublicKeyPins()) {
3464 if (!domain_state
.CheckPublicKeyPins(
3465 server_cert_verify_result_
.public_key_hashes
)) {
3466 result
= ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
;
3467 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3468 TransportSecurityState::ReportUMAOnPinFailure(host
);
3470 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3476 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3477 DCHECK_EQ(STATE_NONE
, next_handshake_state_
);
3481 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3482 UpdateConnectionTypeHistograms(CONNECTION_SSL
);
3483 if (server_cert_verify_result_
.has_md5
)
3484 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5
);
3485 if (server_cert_verify_result_
.has_md2
)
3486 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2
);
3487 if (server_cert_verify_result_
.has_md4
)
3488 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4
);
3489 if (server_cert_verify_result_
.has_md5_ca
)
3490 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA
);
3491 if (server_cert_verify_result_
.has_md2_ca
)
3492 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA
);
3493 int ssl_version
= SSLConnectionStatusToVersion(
3494 core_
->state().ssl_connection_status
);
3495 switch (ssl_version
) {
3496 case SSL_CONNECTION_VERSION_SSL2
:
3497 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2
);
3499 case SSL_CONNECTION_VERSION_SSL3
:
3500 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3
);
3502 case SSL_CONNECTION_VERSION_TLS1
:
3503 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1
);
3505 case SSL_CONNECTION_VERSION_TLS1_1
:
3506 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1
);
3508 case SSL_CONNECTION_VERSION_TLS1_2
:
3509 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2
);
3514 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3515 base::AutoLock
auto_lock(lock_
);
3516 if (valid_thread_id_
!= base::kInvalidThreadId
)
3518 valid_thread_id_
= base::PlatformThread::CurrentId();
3521 bool SSLClientSocketNSS::CalledOnValidThread() const {
3522 EnsureThreadIdAssigned();
3523 base::AutoLock
auto_lock(lock_
);
3524 return valid_thread_id_
== base::PlatformThread::CurrentId();
3527 ServerBoundCertService
* SSLClientSocketNSS::GetServerBoundCertService() const {
3528 return server_bound_cert_service_
;