Revert 233414 "x11: Move XInput2 availability information out of..."
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blob343bd204eabb85d42782be965e56dde4e0ff09ce
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
20 * License.
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.
29 * Contributor(s):
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"
50 #include <certdb.h>
51 #include <hasht.h>
52 #include <keyhi.h>
53 #include <nspr.h>
54 #include <nss.h>
55 #include <ocsp.h>
56 #include <pk11pub.h>
57 #include <secerr.h>
58 #include <sechash.h>
59 #include <ssl.h>
60 #include <sslerr.h>
61 #include <sslproto.h>
63 #include <algorithm>
64 #include <limits>
65 #include <map>
67 #include "base/bind.h"
68 #include "base/bind_helpers.h"
69 #include "base/callback_helpers.h"
70 #include "base/compiler_specific.h"
71 #include "base/logging.h"
72 #include "base/memory/singleton.h"
73 #include "base/metrics/histogram.h"
74 #include "base/single_thread_task_runner.h"
75 #include "base/stl_util.h"
76 #include "base/strings/string_number_conversions.h"
77 #include "base/strings/string_util.h"
78 #include "base/strings/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/connection_type_histograms.h"
89 #include "net/base/dns_util.h"
90 #include "net/base/io_buffer.h"
91 #include "net/base/net_errors.h"
92 #include "net/base/net_log.h"
93 #include "net/cert/asn1_util.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/single_request_cert_verifier.h"
97 #include "net/cert/x509_certificate_net_log_param.h"
98 #include "net/cert/x509_util.h"
99 #include "net/http/transport_security_state.h"
100 #include "net/ocsp/nss_ocsp.h"
101 #include "net/socket/client_socket_handle.h"
102 #include "net/socket/nss_ssl_util.h"
103 #include "net/socket/ssl_error_params.h"
104 #include "net/ssl/ssl_cert_request_info.h"
105 #include "net/ssl/ssl_connection_status_flags.h"
106 #include "net/ssl/ssl_info.h"
108 #if defined(OS_WIN)
109 #include <windows.h>
110 #include <wincrypt.h>
112 #include "base/win/windows_version.h"
113 #elif defined(OS_MACOSX)
114 #include <Security/SecBase.h>
115 #include <Security/SecCertificate.h>
116 #include <Security/SecIdentity.h>
118 #include "base/mac/mac_logging.h"
119 #include "base/synchronization/lock.h"
120 #include "crypto/mac_security_services_lock.h"
121 #elif defined(USE_NSS)
122 #include <dlfcn.h>
123 #endif
125 namespace net {
127 // State machines are easier to debug if you log state transitions.
128 // Enable these if you want to see what's going on.
129 #if 1
130 #define EnterFunction(x)
131 #define LeaveFunction(x)
132 #define GotoState(s) next_handshake_state_ = s
133 #else
134 #define EnterFunction(x)\
135 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
136 << "; next_handshake_state " << next_handshake_state_
137 #define LeaveFunction(x)\
138 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
139 << "; next_handshake_state " << next_handshake_state_
140 #define GotoState(s)\
141 do {\
142 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
143 next_handshake_state_ = s;\
144 } while (0)
145 #endif
147 namespace {
149 // SSL plaintext fragments are shorter than 16KB. Although the record layer
150 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
151 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
152 // entire SSL record.
153 const int kRecvBufferSize = 17 * 1024;
154 const int kSendBufferSize = 17 * 1024;
156 // Used by SSLClientSocketNSS::Core to indicate there is no read result
157 // obtained by a previous operation waiting to be returned to the caller.
158 // This constant can be any non-negative/non-zero value (eg: it does not
159 // overlap with any value of the net::Error range, including net::OK).
160 const int kNoPendingReadResult = 1;
162 #if defined(OS_WIN)
163 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
164 // set on Windows XP without error. There is some overhead from the server
165 // sending the OCSP response if it supports the extension, for the subset of
166 // XP clients who will request it but be unable to use it, but this is an
167 // acceptable trade-off for simplicity of implementation.
168 bool IsOCSPStaplingSupported() {
169 return true;
171 #elif defined(USE_NSS)
172 typedef SECStatus
173 (*CacheOCSPResponseFromSideChannelFunction)(
174 CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
175 SECItem *encodedResponse, void *pwArg);
177 // On Linux, we dynamically link against the system version of libnss3.so. In
178 // order to continue working on systems without up-to-date versions of NSS we
179 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
181 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
182 // runtime symbol resolution that we need.
183 class RuntimeLibNSSFunctionPointers {
184 public:
185 CacheOCSPResponseFromSideChannelFunction
186 GetCacheOCSPResponseFromSideChannelFunction() {
187 return cache_ocsp_response_from_side_channel_;
190 static RuntimeLibNSSFunctionPointers* GetInstance() {
191 return Singleton<RuntimeLibNSSFunctionPointers>::get();
194 private:
195 friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
197 RuntimeLibNSSFunctionPointers() {
198 cache_ocsp_response_from_side_channel_ =
199 (CacheOCSPResponseFromSideChannelFunction)
200 dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
203 CacheOCSPResponseFromSideChannelFunction
204 cache_ocsp_response_from_side_channel_;
207 CacheOCSPResponseFromSideChannelFunction
208 GetCacheOCSPResponseFromSideChannelFunction() {
209 return RuntimeLibNSSFunctionPointers::GetInstance()
210 ->GetCacheOCSPResponseFromSideChannelFunction();
213 bool IsOCSPStaplingSupported() {
214 return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
216 #else
217 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
218 // certificate validation functions.
219 bool IsOCSPStaplingSupported() {
220 return false;
222 #endif
224 class FreeCERTCertificate {
225 public:
226 inline void operator()(CERTCertificate* x) const {
227 CERT_DestroyCertificate(x);
230 typedef scoped_ptr_malloc<CERTCertificate, FreeCERTCertificate>
231 ScopedCERTCertificate;
233 #if defined(OS_WIN)
235 // This callback is intended to be used with CertFindChainInStore. In addition
236 // to filtering by extended/enhanced key usage, we do not show expired
237 // certificates and require digital signature usage in the key usage
238 // extension.
240 // This matches our behavior on Mac OS X and that of NSS. It also matches the
241 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
242 // http://blogs.msdn.com/b/askie/archive/2009/06/09/my-expired-client-certificates-no-longer-display-when-connecting-to-my-web-server-using-ie8.aspx
243 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
244 void* find_arg) {
245 VLOG(1) << "Calling ClientCertFindCallback from _nss";
246 // Verify the certificate's KU is good.
247 BYTE key_usage;
248 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
249 &key_usage, 1)) {
250 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
251 return FALSE;
252 } else {
253 DWORD err = GetLastError();
254 // If |err| is non-zero, it's an actual error. Otherwise the extension
255 // just isn't present, and we treat it as if everything was allowed.
256 if (err) {
257 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
258 return FALSE;
262 // Verify the current time is within the certificate's validity period.
263 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
264 return FALSE;
266 // Verify private key metadata is associated with this certificate.
267 DWORD size = 0;
268 if (!CertGetCertificateContextProperty(
269 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
270 return FALSE;
273 return TRUE;
276 #endif
278 void DestroyCertificates(CERTCertificate** certs, size_t len) {
279 for (size_t i = 0; i < len; i++)
280 CERT_DestroyCertificate(certs[i]);
283 // Helper functions to make it possible to log events from within the
284 // SSLClientSocketNSS::Core.
285 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
286 NetLog::EventType event_type) {
287 if (!net_log)
288 return;
289 net_log->AddEvent(event_type);
292 // Helper function to make it possible to log events from within the
293 // SSLClientSocketNSS::Core.
294 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
295 NetLog::EventType event_type,
296 const NetLog::ParametersCallback& callback) {
297 if (!net_log)
298 return;
299 net_log->AddEvent(event_type, callback);
302 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
303 // from within the SSLClientSocketNSS::Core.
304 // AddByteTransferEvent expects to receive a const char*, which within the
305 // Core is backed by an IOBuffer. If the "const char*" is bound via
306 // base::Bind and posted to another thread, and the IOBuffer that backs that
307 // pointer then goes out of scope on the origin thread, this would result in
308 // an invalid read of a stale pointer.
309 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
310 // to the owning IOBuffer can be bound to the Callback. This ensures that the
311 // IOBuffer will stay alive long enough to cross threads if needed.
312 void LogByteTransferEvent(
313 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
314 int len, IOBuffer* buffer) {
315 if (!net_log)
316 return;
317 net_log->AddByteTransferEvent(event_type, len, buffer->data());
320 // PeerCertificateChain is a helper object which extracts the certificate
321 // chain, as given by the server, from an NSS socket and performs the needed
322 // resource management. The first element of the chain is the leaf certificate
323 // and the other elements are in the order given by the server.
324 class PeerCertificateChain {
325 public:
326 PeerCertificateChain() {}
327 PeerCertificateChain(const PeerCertificateChain& other);
328 ~PeerCertificateChain();
329 PeerCertificateChain& operator=(const PeerCertificateChain& other);
331 // Resets the current chain, freeing any resources, and updates the current
332 // chain to be a copy of the chain stored in |nss_fd|.
333 // If |nss_fd| is NULL, then the current certificate chain will be freed.
334 void Reset(PRFileDesc* nss_fd);
336 // Returns the current certificate chain as a vector of DER-encoded
337 // base::StringPieces. The returned vector remains valid until Reset is
338 // called.
339 std::vector<base::StringPiece> AsStringPieceVector() const;
341 bool empty() const { return certs_.empty(); }
342 size_t size() const { return certs_.size(); }
344 CERTCertificate* operator[](size_t index) const {
345 DCHECK_LT(index, certs_.size());
346 return certs_[index];
349 private:
350 std::vector<CERTCertificate*> certs_;
353 PeerCertificateChain::PeerCertificateChain(
354 const PeerCertificateChain& other) {
355 *this = other;
358 PeerCertificateChain::~PeerCertificateChain() {
359 Reset(NULL);
362 PeerCertificateChain& PeerCertificateChain::operator=(
363 const PeerCertificateChain& other) {
364 if (this == &other)
365 return *this;
367 Reset(NULL);
368 certs_.reserve(other.certs_.size());
369 for (size_t i = 0; i < other.certs_.size(); ++i)
370 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
372 return *this;
375 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
376 for (size_t i = 0; i < certs_.size(); ++i)
377 CERT_DestroyCertificate(certs_[i]);
378 certs_.clear();
380 if (nss_fd == NULL)
381 return;
383 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
384 // The handshake on |nss_fd| may not have completed.
385 if (list == NULL)
386 return;
388 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
389 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
390 certs_.push_back(CERT_DupCertificate(node->cert));
392 CERT_DestroyCertList(list);
395 std::vector<base::StringPiece>
396 PeerCertificateChain::AsStringPieceVector() const {
397 std::vector<base::StringPiece> v(certs_.size());
398 for (unsigned i = 0; i < certs_.size(); i++) {
399 v[i] = base::StringPiece(
400 reinterpret_cast<const char*>(certs_[i]->derCert.data),
401 certs_[i]->derCert.len);
404 return v;
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
414 // for locking.
415 struct HandshakeState {
416 HandshakeState() { Reset(); }
418 void Reset() {
419 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
420 next_proto.clear();
421 server_protos.clear();
422 channel_id_sent = false;
423 server_cert_chain.Reset(NULL);
424 server_cert = 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) {
467 switch (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;
476 default:
477 return MapNSSError(err);
481 // Map NSS error code from the first SSL handshake to network error code.
482 int MapNSSClientHandshakeError(PRErrorCode err) {
483 switch (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;
488 default:
489 return MapNSSClientError(err);
493 } // namespace
495 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
496 // able to marshal data between NSS functions and an underlying transport
497 // socket.
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,
527 // DoHandshake)
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)
541 // Read()
542 // |-------------------------V
543 // Read()
544 // |
545 // DoPayloadRead()
546 // |
547 // BufferRecv()
548 // |
549 // DoBufferRecv()
550 // |-------------------------V
551 // Read()
552 // V-------------------------|
553 // BufferRecvComplete()
554 // |
555 // PostOrRunCallback()
556 // V-------------------------|
557 // (Read Callback)
559 /////////////////////////////////////////////////////////////////////////////
560 // Multi-threaded example:
562 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
563 // SSLClientSocketNSS Core Socket Core
564 // Read()
565 // |---------------------V
566 // Read()
567 // |-------------------------------V
568 // Read()
569 // |
570 // DoPayloadRead()
571 // |
572 // BufferRecv
573 // V-------------------------------|
574 // DoBufferRecv
575 // |----------------V
576 // Read()
577 // V----------------|
578 // BufferRecvComplete()
579 // |-------------------------------V
580 // BufferRecvComplete()
581 // |
582 // PostOrRunCallback()
583 // V-------------------------------|
584 // PostOrRunCallback()
585 // V---------------------|
586 // (Read Callback)
588 /////////////////////////////////////////////////////////////////////////////
589 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
590 public:
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()
600 // has been called.
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.
634 void Detach();
636 // Called on the network task runner.
637 // Returns the current state of the underlying SSL socket. May be called at
638 // any time.
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.
649 bool IsConnected();
650 bool HasPendingAsyncOperation();
651 bool HasUnhandledReceivedData();
653 private:
654 friend class base::RefCountedThreadSafe<Core>;
655 ~Core();
657 enum State {
658 STATE_NONE,
659 STATE_HANDSHAKE,
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,
679 PRFileDesc* socket,
680 PRBool checksig,
681 PRBool is_server);
683 // Callbacks called by NSS when the peer requests client certificate
684 // authentication.
685 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
686 // the arguments.
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(
695 void* arg,
696 PRFileDesc* socket,
697 CERTDistNames* ca_names,
698 CERTCertList** result_certs,
699 void** result_private_key,
700 CERTCertificate** result_nss_certificate,
701 SECKEYPrivateKey** result_nss_private_key);
702 #else
703 static SECStatus ClientAuthHandler(void* arg,
704 PRFileDesc* socket,
705 CERTDistNames* ca_names,
706 CERTCertificate** result_certificate,
707 SECKEYPrivateKey** result_private_key);
708 #endif
710 // Called by NSS once the handshake has completed.
711 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
712 static void HandshakeCallback(PRFileDesc* socket, void* arg);
714 // Handles an NSS error generated while handshaking or performing IO.
715 // Returns a network error code mapped from the original NSS error.
716 int HandleNSSError(PRErrorCode error, bool handshake_error);
718 int DoHandshakeLoop(int last_io_result);
719 int DoReadLoop(int result);
720 int DoWriteLoop(int result);
722 int DoHandshake();
723 int DoGetDBCertComplete(int result);
725 int DoPayloadRead();
726 int DoPayloadWrite();
728 bool DoTransportIO();
729 int BufferRecv();
730 int BufferSend();
732 void OnRecvComplete(int result);
733 void OnSendComplete(int result);
735 void DoConnectCallback(int result);
736 void DoReadCallback(int result);
737 void DoWriteCallback(int result);
739 // Client channel ID handler.
740 static SECStatus ClientChannelIDHandler(
741 void* arg,
742 PRFileDesc* socket,
743 SECKEYPublicKey **out_public_key,
744 SECKEYPrivateKey **out_private_key);
746 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
747 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
748 // and an error code otherwise.
749 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
750 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
751 // takes ownership of the |*cert| and |*key|.
752 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
754 // Updates the NSS and platform specific certificates.
755 void UpdateServerCert();
756 // Updates the nss_handshake_state_ with the negotiated security parameters.
757 void UpdateConnectionStatus();
758 // Record histograms for channel id support during full handshakes - resumed
759 // handshakes are ignored.
760 void RecordChannelIDSupportOnNSSTaskRunner();
761 // UpdateNextProto gets any application-layer protocol that may have been
762 // negotiated by the TLS connection.
763 void UpdateNextProto();
765 ////////////////////////////////////////////////////////////////////////////
766 // Methods that are ONLY called on the network task runner:
767 ////////////////////////////////////////////////////////////////////////////
768 int DoBufferRecv(IOBuffer* buffer, int len);
769 int DoBufferSend(IOBuffer* buffer, int len);
770 int DoGetDomainBoundCert(const std::string& host);
772 void OnGetDomainBoundCertComplete(int result);
773 void OnHandshakeStateUpdated(const HandshakeState& state);
774 void OnNSSBufferUpdated(int amount_in_read_buffer);
775 void DidNSSRead(int result);
776 void DidNSSWrite(int result);
777 void RecordChannelIDSupportOnNetworkTaskRunner(
778 bool negotiated_channel_id,
779 bool channel_id_enabled,
780 bool supports_ecc) const;
782 ////////////////////////////////////////////////////////////////////////////
783 // Methods that are called on both the network task runner and the NSS
784 // task runner.
785 ////////////////////////////////////////////////////////////////////////////
786 void OnHandshakeIOComplete(int result);
787 void BufferRecvComplete(IOBuffer* buffer, int result);
788 void BufferSendComplete(int result);
790 // PostOrRunCallback is a helper function to ensure that |callback| is
791 // invoked on the network task runner, but only if Detach() has not yet
792 // been called.
793 void PostOrRunCallback(const tracked_objects::Location& location,
794 const base::Closure& callback);
796 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
797 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
798 void AddCertProvidedEvent(int cert_count);
800 // Sets the handshake state |channel_id_sent| flag and logs the
801 // SSL_CHANNEL_ID_PROVIDED event.
802 void SetChannelIDProvided();
804 ////////////////////////////////////////////////////////////////////////////
805 // Members that are ONLY accessed on the network task runner:
806 ////////////////////////////////////////////////////////////////////////////
808 // True if the owning SSLClientSocketNSS has called Detach(). No further
809 // callbacks will be invoked nor access to members owned by the network
810 // task runner.
811 bool detached_;
813 // The underlying transport to use for network IO.
814 ClientSocketHandle* transport_;
815 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
817 // The current handshake state. Mirrors |nss_handshake_state_|.
818 HandshakeState network_handshake_state_;
820 // The service for retrieving Channel ID keys. May be NULL.
821 ServerBoundCertService* server_bound_cert_service_;
822 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_;
824 // The information about NSS task runner.
825 int unhandled_buffer_size_;
826 bool nss_waiting_read_;
827 bool nss_waiting_write_;
828 bool nss_is_closed_;
830 ////////////////////////////////////////////////////////////////////////////
831 // Members that are ONLY accessed on the NSS task runner:
832 ////////////////////////////////////////////////////////////////////////////
833 HostPortPair host_and_port_;
834 SSLConfig ssl_config_;
836 // NSS SSL socket.
837 PRFileDesc* nss_fd_;
839 // Buffers for the network end of the SSL state machine
840 memio_Private* nss_bufs_;
842 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
843 // as much data as possible, without blocking.
844 // If DoPayloadRead() encounters an error after having read some data, stores
845 // the results to return on the *next* call to DoPayloadRead(). A value of
846 // kNoPendingReadResult indicates there is no pending result, otherwise 0
847 // indicates EOF and < 0 indicates an error.
848 int pending_read_result_;
849 // Contains the previously observed NSS error. Only valid when
850 // pending_read_result_ != kNoPendingReadResult.
851 PRErrorCode pending_read_nss_error_;
853 // The certificate chain, in DER form, that is expected to be received from
854 // the server.
855 std::vector<std::string> predicted_certs_;
857 State next_handshake_state_;
859 // True if channel ID extension was negotiated.
860 bool channel_id_xtn_negotiated_;
861 // True if the handshake state machine was interrupted for channel ID.
862 bool channel_id_needed_;
863 // True if the handshake state machine was interrupted for client auth.
864 bool client_auth_cert_needed_;
865 // True if NSS has called HandshakeCallback.
866 bool handshake_callback_called_;
868 HandshakeState nss_handshake_state_;
870 bool transport_recv_busy_;
871 bool transport_recv_eof_;
872 bool transport_send_busy_;
874 // Used by Read function.
875 scoped_refptr<IOBuffer> user_read_buf_;
876 int user_read_buf_len_;
878 // Used by Write function.
879 scoped_refptr<IOBuffer> user_write_buf_;
880 int user_write_buf_len_;
882 CompletionCallback user_connect_callback_;
883 CompletionCallback user_read_callback_;
884 CompletionCallback user_write_callback_;
886 ////////////////////////////////////////////////////////////////////////////
887 // Members that are accessed on both the network task runner and the NSS
888 // task runner.
889 ////////////////////////////////////////////////////////////////////////////
890 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
891 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
893 // Dereferenced only on the network task runner, but bound to tasks destined
894 // for the network task runner from the NSS task runner.
895 base::WeakPtr<BoundNetLog> weak_net_log_;
897 // Written on the network task runner by the |server_bound_cert_service_|,
898 // prior to invoking OnHandshakeIOComplete.
899 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
900 // on the NSS task runner.
901 std::string domain_bound_private_key_;
902 std::string domain_bound_cert_;
904 DISALLOW_COPY_AND_ASSIGN(Core);
907 SSLClientSocketNSS::Core::Core(
908 base::SequencedTaskRunner* network_task_runner,
909 base::SequencedTaskRunner* nss_task_runner,
910 ClientSocketHandle* transport,
911 const HostPortPair& host_and_port,
912 const SSLConfig& ssl_config,
913 BoundNetLog* net_log,
914 ServerBoundCertService* server_bound_cert_service)
915 : detached_(false),
916 transport_(transport),
917 weak_net_log_factory_(net_log),
918 server_bound_cert_service_(server_bound_cert_service),
919 unhandled_buffer_size_(0),
920 nss_waiting_read_(false),
921 nss_waiting_write_(false),
922 nss_is_closed_(false),
923 host_and_port_(host_and_port),
924 ssl_config_(ssl_config),
925 nss_fd_(NULL),
926 nss_bufs_(NULL),
927 pending_read_result_(kNoPendingReadResult),
928 pending_read_nss_error_(0),
929 next_handshake_state_(STATE_NONE),
930 channel_id_xtn_negotiated_(false),
931 channel_id_needed_(false),
932 client_auth_cert_needed_(false),
933 handshake_callback_called_(false),
934 transport_recv_busy_(false),
935 transport_recv_eof_(false),
936 transport_send_busy_(false),
937 user_read_buf_len_(0),
938 user_write_buf_len_(0),
939 network_task_runner_(network_task_runner),
940 nss_task_runner_(nss_task_runner),
941 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
944 SSLClientSocketNSS::Core::~Core() {
945 // TODO(wtc): Send SSL close_notify alert.
946 if (nss_fd_ != NULL) {
947 PR_Close(nss_fd_);
948 nss_fd_ = NULL;
952 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
953 memio_Private* buffers) {
954 DCHECK(OnNetworkTaskRunner());
955 DCHECK(!nss_fd_);
956 DCHECK(!nss_bufs_);
958 nss_fd_ = socket;
959 nss_bufs_ = buffers;
961 SECStatus rv = SECSuccess;
963 if (!ssl_config_.next_protos.empty()) {
964 size_t wire_length = 0;
965 for (std::vector<std::string>::const_iterator
966 i = ssl_config_.next_protos.begin();
967 i != ssl_config_.next_protos.end(); ++i) {
968 if (i->size() > 255) {
969 LOG(WARNING) << "Ignoring overlong NPN/ALPN protocol: " << *i;
970 continue;
972 wire_length += i->size();
973 wire_length++;
975 scoped_ptr<uint8[]> wire_protos(new uint8[wire_length]);
976 uint8* dst = wire_protos.get();
977 for (std::vector<std::string>::const_iterator
978 i = ssl_config_.next_protos.begin();
979 i != ssl_config_.next_protos.end(); i++) {
980 if (i->size() > 255)
981 continue;
982 *dst++ = i->size();
983 memcpy(dst, i->data(), i->size());
984 dst += i->size();
986 DCHECK_EQ(dst, wire_protos.get() + wire_length);
987 rv = SSL_SetNextProtoNego(nss_fd_, wire_protos.get(), wire_length);
988 if (rv != SECSuccess)
989 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", "");
992 rv = SSL_AuthCertificateHook(
993 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
994 if (rv != SECSuccess) {
995 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
996 return false;
999 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1000 rv = SSL_GetPlatformClientAuthDataHook(
1001 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
1002 this);
1003 #else
1004 rv = SSL_GetClientAuthDataHook(
1005 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
1006 #endif
1007 if (rv != SECSuccess) {
1008 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
1009 return false;
1012 if (IsChannelIDEnabled(ssl_config_, server_bound_cert_service_)) {
1013 rv = SSL_SetClientChannelIDCallback(
1014 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
1015 if (rv != SECSuccess) {
1016 LogFailedNSSFunction(
1017 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
1021 rv = SSL_HandshakeCallback(
1022 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
1023 if (rv != SECSuccess) {
1024 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
1025 return false;
1028 return true;
1031 void SSLClientSocketNSS::Core::SetPredictedCertificates(
1032 const std::vector<std::string>& predicted_certs) {
1033 if (predicted_certs.empty())
1034 return;
1036 if (!OnNSSTaskRunner()) {
1037 DCHECK(!detached_);
1038 nss_task_runner_->PostTask(
1039 FROM_HERE,
1040 base::Bind(&Core::SetPredictedCertificates, this, predicted_certs));
1041 return;
1044 DCHECK(nss_fd_);
1046 predicted_certs_ = predicted_certs;
1048 scoped_ptr<CERTCertificate*[]> certs(
1049 new CERTCertificate*[predicted_certs.size()]);
1051 for (size_t i = 0; i < predicted_certs.size(); i++) {
1052 SECItem derCert;
1053 derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>(
1054 predicted_certs[i].data()));
1055 derCert.len = predicted_certs[i].size();
1056 certs[i] = CERT_NewTempCertificate(
1057 CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */,
1058 PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */);
1059 if (!certs[i]) {
1060 DestroyCertificates(&certs[0], i);
1061 NOTREACHED();
1062 return;
1066 SECStatus rv;
1067 #ifdef SSL_ENABLE_CACHED_INFO
1068 rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(),
1069 predicted_certs.size());
1070 DCHECK_EQ(SECSuccess, rv);
1071 #else
1072 rv = SECFailure; // Not implemented.
1073 #endif
1074 DestroyCertificates(&certs[0], predicted_certs.size());
1076 if (rv != SECSuccess) {
1077 LOG(WARNING) << "SetPredictedCertificates failed: "
1078 << host_and_port_.ToString();
1082 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1083 if (!OnNSSTaskRunner()) {
1084 DCHECK(!detached_);
1085 bool posted = nss_task_runner_->PostTask(
1086 FROM_HERE,
1087 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1088 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1091 DCHECK(OnNSSTaskRunner());
1092 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1093 DCHECK(user_read_callback_.is_null());
1094 DCHECK(user_write_callback_.is_null());
1095 DCHECK(user_connect_callback_.is_null());
1096 DCHECK(!user_read_buf_.get());
1097 DCHECK(!user_write_buf_.get());
1099 next_handshake_state_ = STATE_HANDSHAKE;
1100 int rv = DoHandshakeLoop(OK);
1101 if (rv == ERR_IO_PENDING) {
1102 user_connect_callback_ = callback;
1103 } else if (rv > OK) {
1104 rv = OK;
1106 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1107 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1108 return ERR_IO_PENDING;
1111 return rv;
1114 void SSLClientSocketNSS::Core::Detach() {
1115 DCHECK(OnNetworkTaskRunner());
1117 detached_ = true;
1118 transport_ = NULL;
1119 weak_net_log_factory_.InvalidateWeakPtrs();
1121 network_handshake_state_.Reset();
1123 domain_bound_cert_request_handle_.Cancel();
1126 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1127 const CompletionCallback& callback) {
1128 if (!OnNSSTaskRunner()) {
1129 DCHECK(OnNetworkTaskRunner());
1130 DCHECK(!detached_);
1131 DCHECK(transport_);
1132 DCHECK(!nss_waiting_read_);
1134 nss_waiting_read_ = true;
1135 bool posted = nss_task_runner_->PostTask(
1136 FROM_HERE,
1137 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1138 buf_len, callback));
1139 if (!posted) {
1140 nss_is_closed_ = true;
1141 nss_waiting_read_ = false;
1143 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1146 DCHECK(OnNSSTaskRunner());
1147 DCHECK(handshake_callback_called_);
1148 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1149 DCHECK(user_read_callback_.is_null());
1150 DCHECK(user_connect_callback_.is_null());
1151 DCHECK(!user_read_buf_.get());
1152 DCHECK(nss_bufs_);
1154 user_read_buf_ = buf;
1155 user_read_buf_len_ = buf_len;
1157 int rv = DoReadLoop(OK);
1158 if (rv == ERR_IO_PENDING) {
1159 if (OnNetworkTaskRunner())
1160 nss_waiting_read_ = true;
1161 user_read_callback_ = callback;
1162 } else {
1163 user_read_buf_ = NULL;
1164 user_read_buf_len_ = 0;
1166 if (!OnNetworkTaskRunner()) {
1167 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1168 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1169 return ERR_IO_PENDING;
1170 } else {
1171 DCHECK(!nss_waiting_read_);
1172 if (rv <= 0)
1173 nss_is_closed_ = true;
1177 return rv;
1180 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1181 const CompletionCallback& callback) {
1182 if (!OnNSSTaskRunner()) {
1183 DCHECK(OnNetworkTaskRunner());
1184 DCHECK(!detached_);
1185 DCHECK(transport_);
1186 DCHECK(!nss_waiting_write_);
1188 nss_waiting_write_ = true;
1189 bool posted = nss_task_runner_->PostTask(
1190 FROM_HERE,
1191 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1192 buf_len, callback));
1193 if (!posted) {
1194 nss_is_closed_ = true;
1195 nss_waiting_write_ = false;
1197 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1200 DCHECK(OnNSSTaskRunner());
1201 DCHECK(handshake_callback_called_);
1202 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1203 DCHECK(user_write_callback_.is_null());
1204 DCHECK(user_connect_callback_.is_null());
1205 DCHECK(!user_write_buf_.get());
1206 DCHECK(nss_bufs_);
1208 user_write_buf_ = buf;
1209 user_write_buf_len_ = buf_len;
1211 int rv = DoWriteLoop(OK);
1212 if (rv == ERR_IO_PENDING) {
1213 if (OnNetworkTaskRunner())
1214 nss_waiting_write_ = true;
1215 user_write_callback_ = callback;
1216 } else {
1217 user_write_buf_ = NULL;
1218 user_write_buf_len_ = 0;
1220 if (!OnNetworkTaskRunner()) {
1221 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1222 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1223 return ERR_IO_PENDING;
1224 } else {
1225 DCHECK(!nss_waiting_write_);
1226 if (rv < 0)
1227 nss_is_closed_ = true;
1231 return rv;
1234 bool SSLClientSocketNSS::Core::IsConnected() {
1235 DCHECK(OnNetworkTaskRunner());
1236 return !nss_is_closed_;
1239 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
1240 DCHECK(OnNetworkTaskRunner());
1241 return nss_waiting_read_ || nss_waiting_write_;
1244 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
1245 DCHECK(OnNetworkTaskRunner());
1246 return unhandled_buffer_size_ != 0;
1249 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1250 return nss_task_runner_->RunsTasksOnCurrentThread();
1253 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1254 return network_task_runner_->RunsTasksOnCurrentThread();
1257 // static
1258 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1259 void* arg,
1260 PRFileDesc* socket,
1261 PRBool checksig,
1262 PRBool is_server) {
1263 Core* core = reinterpret_cast<Core*>(arg);
1264 if (!core->handshake_callback_called_) {
1265 // Only need to turn off False Start in the initial handshake. Also, it is
1266 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1267 // handshake" lock isn't already held, which will result in an assertion
1268 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1269 PRBool negotiated_extension;
1270 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1271 ssl_app_layer_protocol_xtn,
1272 &negotiated_extension);
1273 if (rv != SECSuccess || !negotiated_extension) {
1274 rv = SSL_HandshakeNegotiatedExtension(socket,
1275 ssl_next_proto_nego_xtn,
1276 &negotiated_extension);
1278 if (rv != SECSuccess || !negotiated_extension) {
1279 // If the server doesn't support NPN or ALPN, then we don't do False
1280 // Start with it.
1281 SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE);
1283 } else {
1284 // Disallow the server certificate to change in a renegotiation.
1285 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1286 CERTCertificate* new_cert = SSL_PeerCertificate(socket);
1287 if (new_cert->derCert.len != old_cert->derCert.len ||
1288 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1289 new_cert->derCert.len) != 0) {
1290 // NSS doesn't have an error code that indicates the server certificate
1291 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1292 // for this purpose.
1293 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1294 return SECFailure;
1298 // Tell NSS to not verify the certificate.
1299 return SECSuccess;
1302 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1303 // static
1304 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1305 void* arg,
1306 PRFileDesc* socket,
1307 CERTDistNames* ca_names,
1308 CERTCertList** result_certs,
1309 void** result_private_key,
1310 CERTCertificate** result_nss_certificate,
1311 SECKEYPrivateKey** result_nss_private_key) {
1312 Core* core = reinterpret_cast<Core*>(arg);
1313 DCHECK(core->OnNSSTaskRunner());
1315 core->PostOrRunCallback(
1316 FROM_HERE,
1317 base::Bind(&AddLogEvent, core->weak_net_log_,
1318 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1320 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1321 #if defined(OS_WIN)
1322 if (core->ssl_config_.send_client_cert) {
1323 if (core->ssl_config_.client_cert) {
1324 PCCERT_CONTEXT cert_context =
1325 core->ssl_config_.client_cert->os_cert_handle();
1327 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1328 DWORD key_spec = 0;
1329 BOOL must_free = FALSE;
1330 DWORD flags = 0;
1331 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
1332 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
1334 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1335 cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
1337 if (acquired_key) {
1338 // Should never get a cached handle back - ownership must always be
1339 // transferred.
1340 CHECK_EQ(must_free, TRUE);
1342 SECItem der_cert;
1343 der_cert.type = siDERCertBuffer;
1344 der_cert.data = cert_context->pbCertEncoded;
1345 der_cert.len = cert_context->cbCertEncoded;
1347 // TODO(rsleevi): Error checking for NSS allocation errors.
1348 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1349 CERTCertificate* user_cert = CERT_NewTempCertificate(
1350 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1351 if (!user_cert) {
1352 // Importing the certificate can fail for reasons including a serial
1353 // number collision. See crbug.com/97355.
1354 core->AddCertProvidedEvent(0);
1355 return SECFailure;
1357 CERTCertList* cert_chain = CERT_NewCertList();
1358 CERT_AddCertToListTail(cert_chain, user_cert);
1360 // Add the intermediates.
1361 X509Certificate::OSCertHandles intermediates =
1362 core->ssl_config_.client_cert->GetIntermediateCertificates();
1363 for (X509Certificate::OSCertHandles::const_iterator it =
1364 intermediates.begin(); it != intermediates.end(); ++it) {
1365 der_cert.data = (*it)->pbCertEncoded;
1366 der_cert.len = (*it)->cbCertEncoded;
1368 CERTCertificate* intermediate = CERT_NewTempCertificate(
1369 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1370 if (!intermediate) {
1371 CERT_DestroyCertList(cert_chain);
1372 core->AddCertProvidedEvent(0);
1373 return SECFailure;
1375 CERT_AddCertToListTail(cert_chain, intermediate);
1377 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1378 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1379 key_context->cbSize = sizeof(*key_context);
1380 // NSS will free this context when no longer in use.
1381 key_context->hCryptProv = crypt_prov;
1382 key_context->dwKeySpec = key_spec;
1383 *result_private_key = key_context;
1384 *result_certs = cert_chain;
1386 int cert_count = 1 + intermediates.size();
1387 core->AddCertProvidedEvent(cert_count);
1388 return SECSuccess;
1390 LOG(WARNING) << "Client cert found without private key";
1393 // Send no client certificate.
1394 core->AddCertProvidedEvent(0);
1395 return SECFailure;
1398 core->nss_handshake_state_.cert_authorities.clear();
1400 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1401 for (int i = 0; i < ca_names->nnames; ++i) {
1402 issuer_list[i].cbData = ca_names->names[i].len;
1403 issuer_list[i].pbData = ca_names->names[i].data;
1404 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1405 reinterpret_cast<const char*>(ca_names->names[i].data),
1406 static_cast<size_t>(ca_names->names[i].len)));
1409 // Update the network task runner's view of the handshake state now that
1410 // server certificate request has been recorded.
1411 core->PostOrRunCallback(
1412 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1413 core->nss_handshake_state_));
1415 // Tell NSS to suspend the client authentication. We will then abort the
1416 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1417 return SECWouldBlock;
1418 #elif defined(OS_MACOSX)
1419 if (core->ssl_config_.send_client_cert) {
1420 if (core->ssl_config_.client_cert.get()) {
1421 OSStatus os_error = noErr;
1422 SecIdentityRef identity = NULL;
1423 SecKeyRef private_key = NULL;
1424 X509Certificate::OSCertHandles chain;
1426 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
1427 os_error = SecIdentityCreateWithCertificate(
1428 NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
1430 if (os_error == noErr) {
1431 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1432 CFRelease(identity);
1435 if (os_error == noErr) {
1436 // TODO(rsleevi): Error checking for NSS allocation errors.
1437 *result_certs = CERT_NewCertList();
1438 *result_private_key = private_key;
1440 chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
1441 const X509Certificate::OSCertHandles& intermediates =
1442 core->ssl_config_.client_cert->GetIntermediateCertificates();
1443 if (!intermediates.empty())
1444 chain.insert(chain.end(), intermediates.begin(), intermediates.end());
1446 for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
1447 CSSM_DATA cert_data;
1448 SecCertificateRef cert_ref = chain[i];
1449 os_error = SecCertificateGetData(cert_ref, &cert_data);
1450 if (os_error != noErr)
1451 break;
1453 SECItem der_cert;
1454 der_cert.type = siDERCertBuffer;
1455 der_cert.data = cert_data.Data;
1456 der_cert.len = cert_data.Length;
1457 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1458 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1459 if (!nss_cert) {
1460 // In the event of an NSS error, make up an OS error and reuse
1461 // the error handling below.
1462 os_error = errSecCreateChainFailed;
1463 break;
1465 CERT_AddCertToListTail(*result_certs, nss_cert);
1469 if (os_error == noErr) {
1470 core->AddCertProvidedEvent(chain.size());
1471 return SECSuccess;
1474 OSSTATUS_LOG(WARNING, os_error)
1475 << "Client cert found, but could not be used";
1476 if (*result_certs) {
1477 CERT_DestroyCertList(*result_certs);
1478 *result_certs = NULL;
1480 if (*result_private_key)
1481 *result_private_key = NULL;
1482 if (private_key)
1483 CFRelease(private_key);
1486 // Send no client certificate.
1487 core->AddCertProvidedEvent(0);
1488 return SECFailure;
1491 core->nss_handshake_state_.cert_authorities.clear();
1493 // Retrieve the cert issuers accepted by the server.
1494 std::vector<CertPrincipal> valid_issuers;
1495 int n = ca_names->nnames;
1496 for (int i = 0; i < n; i++) {
1497 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1498 reinterpret_cast<const char*>(ca_names->names[i].data),
1499 static_cast<size_t>(ca_names->names[i].len)));
1502 // Update the network task runner's view of the handshake state now that
1503 // server certificate request has been recorded.
1504 core->PostOrRunCallback(
1505 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1506 core->nss_handshake_state_));
1508 // Tell NSS to suspend the client authentication. We will then abort the
1509 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1510 return SECWouldBlock;
1511 #else
1512 return SECFailure;
1513 #endif
1516 #elif defined(OS_IOS)
1518 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1519 void* arg,
1520 PRFileDesc* socket,
1521 CERTDistNames* ca_names,
1522 CERTCertificate** result_certificate,
1523 SECKEYPrivateKey** result_private_key) {
1524 Core* core = reinterpret_cast<Core*>(arg);
1525 DCHECK(core->OnNSSTaskRunner());
1527 core->PostOrRunCallback(
1528 FROM_HERE,
1529 base::Bind(&AddLogEvent, core->weak_net_log_,
1530 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1532 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1533 LOG(WARNING) << "Client auth is not supported";
1535 // Never send a certificate.
1536 core->AddCertProvidedEvent(0);
1537 return SECFailure;
1540 #else // NSS_PLATFORM_CLIENT_AUTH
1542 // static
1543 // Based on Mozilla's NSS_GetClientAuthData.
1544 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1545 void* arg,
1546 PRFileDesc* socket,
1547 CERTDistNames* ca_names,
1548 CERTCertificate** result_certificate,
1549 SECKEYPrivateKey** result_private_key) {
1550 Core* core = reinterpret_cast<Core*>(arg);
1551 DCHECK(core->OnNSSTaskRunner());
1553 core->PostOrRunCallback(
1554 FROM_HERE,
1555 base::Bind(&AddLogEvent, core->weak_net_log_,
1556 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1558 // Regular client certificate requested.
1559 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1560 void* wincx = SSL_RevealPinArg(socket);
1562 if (core->ssl_config_.send_client_cert) {
1563 // Second pass: a client certificate should have been selected.
1564 if (core->ssl_config_.client_cert.get()) {
1565 CERTCertificate* cert =
1566 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1567 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1568 if (privkey) {
1569 // TODO(jsorianopastor): We should wait for server certificate
1570 // verification before sending our credentials. See
1571 // http://crbug.com/13934.
1572 *result_certificate = cert;
1573 *result_private_key = privkey;
1574 // A cert_count of -1 means the number of certificates is unknown.
1575 // NSS will construct the certificate chain.
1576 core->AddCertProvidedEvent(-1);
1578 return SECSuccess;
1580 LOG(WARNING) << "Client cert found without private key";
1582 // Send no client certificate.
1583 core->AddCertProvidedEvent(0);
1584 return SECFailure;
1587 // First pass: client certificate is needed.
1588 core->nss_handshake_state_.cert_authorities.clear();
1590 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1591 // the server and save them in |cert_authorities|.
1592 for (int i = 0; i < ca_names->nnames; i++) {
1593 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1594 reinterpret_cast<const char*>(ca_names->names[i].data),
1595 static_cast<size_t>(ca_names->names[i].len)));
1598 // Update the network task runner's view of the handshake state now that
1599 // server certificate request has been recorded.
1600 core->PostOrRunCallback(
1601 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1602 core->nss_handshake_state_));
1604 // Tell NSS to suspend the client authentication. We will then abort the
1605 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1606 return SECWouldBlock;
1608 #endif // NSS_PLATFORM_CLIENT_AUTH
1610 // static
1611 void SSLClientSocketNSS::Core::HandshakeCallback(
1612 PRFileDesc* socket,
1613 void* arg) {
1614 Core* core = reinterpret_cast<Core*>(arg);
1615 DCHECK(core->OnNSSTaskRunner());
1617 core->handshake_callback_called_ = true;
1619 HandshakeState* nss_state = &core->nss_handshake_state_;
1621 PRBool last_handshake_resumed;
1622 SECStatus rv = SSL_HandshakeResumedSession(socket, &last_handshake_resumed);
1623 if (rv == SECSuccess && last_handshake_resumed) {
1624 nss_state->resumed_handshake = true;
1625 } else {
1626 nss_state->resumed_handshake = false;
1629 core->RecordChannelIDSupportOnNSSTaskRunner();
1630 core->UpdateServerCert();
1631 core->UpdateConnectionStatus();
1632 core->UpdateNextProto();
1634 // Update the network task runners view of the handshake state whenever
1635 // a handshake has completed.
1636 core->PostOrRunCallback(
1637 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1638 *nss_state));
1641 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error,
1642 bool handshake_error) {
1643 DCHECK(OnNSSTaskRunner());
1645 int net_error = handshake_error ? MapNSSClientHandshakeError(nss_error) :
1646 MapNSSClientError(nss_error);
1648 #if defined(OS_WIN)
1649 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1650 // os_cert_handle() as an optimization. However, if the certificate
1651 // private key is stored on a smart card, and the smart card is removed,
1652 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1653 // preventing client certificate authentication. Because the
1654 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1655 // caching in X509Certificate, this failure ends up preventing client
1656 // certificate authentication with the same certificate for all future
1657 // attempts, even after the smart card has been re-inserted. By setting
1658 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1659 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1660 // the certificate on the next attempt, which should succeed if the smart
1661 // card has been re-inserted, or will typically prompt the user to
1662 // re-insert the smart card if not.
1663 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1664 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1665 ssl_config_.send_client_cert && ssl_config_.client_cert) {
1666 CertSetCertificateContextProperty(
1667 ssl_config_.client_cert->os_cert_handle(),
1668 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1670 #endif
1672 return net_error;
1675 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1676 DCHECK(OnNSSTaskRunner());
1678 int rv = last_io_result;
1679 do {
1680 // Default to STATE_NONE for next state.
1681 State state = next_handshake_state_;
1682 GotoState(STATE_NONE);
1684 switch (state) {
1685 case STATE_HANDSHAKE:
1686 rv = DoHandshake();
1687 break;
1688 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1689 rv = DoGetDBCertComplete(rv);
1690 break;
1691 case STATE_NONE:
1692 default:
1693 rv = ERR_UNEXPECTED;
1694 LOG(DFATAL) << "unexpected state " << state;
1695 break;
1698 // Do the actual network I/O
1699 bool network_moved = DoTransportIO();
1700 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1701 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1702 // special case we keep looping even if rv is ERR_IO_PENDING because
1703 // the transport IO may allow DoHandshake to make progress.
1704 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1705 rv = OK; // This causes us to stay in the loop.
1707 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1708 return rv;
1711 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1712 DCHECK(OnNSSTaskRunner());
1713 DCHECK(handshake_callback_called_);
1714 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1716 if (result < 0)
1717 return result;
1719 if (!nss_bufs_) {
1720 LOG(DFATAL) << "!nss_bufs_";
1721 int rv = ERR_UNEXPECTED;
1722 PostOrRunCallback(
1723 FROM_HERE,
1724 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1725 NetLog::TYPE_SSL_READ_ERROR,
1726 CreateNetLogSSLErrorCallback(rv, 0)));
1727 return rv;
1730 bool network_moved;
1731 int rv;
1732 do {
1733 rv = DoPayloadRead();
1734 network_moved = DoTransportIO();
1735 } while (rv == ERR_IO_PENDING && network_moved);
1737 return rv;
1740 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1741 DCHECK(OnNSSTaskRunner());
1742 DCHECK(handshake_callback_called_);
1743 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1745 if (result < 0)
1746 return result;
1748 if (!nss_bufs_) {
1749 LOG(DFATAL) << "!nss_bufs_";
1750 int rv = ERR_UNEXPECTED;
1751 PostOrRunCallback(
1752 FROM_HERE,
1753 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1754 NetLog::TYPE_SSL_READ_ERROR,
1755 CreateNetLogSSLErrorCallback(rv, 0)));
1756 return rv;
1759 bool network_moved;
1760 int rv;
1761 do {
1762 rv = DoPayloadWrite();
1763 network_moved = DoTransportIO();
1764 } while (rv == ERR_IO_PENDING && network_moved);
1766 LeaveFunction(rv);
1767 return rv;
1770 int SSLClientSocketNSS::Core::DoHandshake() {
1771 DCHECK(OnNSSTaskRunner());
1773 int net_error = net::OK;
1774 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1776 // Note: this function may be called multiple times during the handshake, so
1777 // even though channel id and client auth are separate else cases, they can
1778 // both be used during a single SSL handshake.
1779 if (channel_id_needed_) {
1780 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1781 net_error = ERR_IO_PENDING;
1782 } else if (client_auth_cert_needed_) {
1783 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1784 PostOrRunCallback(
1785 FROM_HERE,
1786 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1787 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1788 CreateNetLogSSLErrorCallback(net_error, 0)));
1790 // If the handshake already succeeded (because the server requests but
1791 // doesn't require a client cert), we need to invalidate the SSL session
1792 // so that we won't try to resume the non-client-authenticated session in
1793 // the next handshake. This will cause the server to ask for a client
1794 // cert again.
1795 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
1796 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
1797 } else if (rv == SECSuccess) {
1798 if (!handshake_callback_called_) {
1799 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1800 // SSL_ForceHandshake returned SECSuccess prematurely.
1801 rv = SECFailure;
1802 net_error = ERR_SSL_PROTOCOL_ERROR;
1803 PostOrRunCallback(
1804 FROM_HERE,
1805 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1806 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1807 CreateNetLogSSLErrorCallback(net_error, 0)));
1808 } else {
1809 #if defined(SSL_ENABLE_OCSP_STAPLING)
1810 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1811 // system library and update IsOCSPStaplingSupported for Mac.
1812 if (IsOCSPStaplingSupported()) {
1813 const SECItemArray* ocsp_responses =
1814 SSL_PeerStapledOCSPResponses(nss_fd_);
1815 if (ocsp_responses->len) {
1816 #if defined(OS_WIN)
1817 if (nss_handshake_state_.server_cert) {
1818 CRYPT_DATA_BLOB ocsp_response_blob;
1819 ocsp_response_blob.cbData = ocsp_responses->items[0].len;
1820 ocsp_response_blob.pbData = ocsp_responses->items[0].data;
1821 BOOL ok = CertSetCertificateContextProperty(
1822 nss_handshake_state_.server_cert->os_cert_handle(),
1823 CERT_OCSP_RESPONSE_PROP_ID,
1824 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1825 &ocsp_response_blob);
1826 if (!ok) {
1827 VLOG(1) << "Failed to set OCSP response property: "
1828 << GetLastError();
1831 #elif defined(USE_NSS)
1832 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
1833 GetCacheOCSPResponseFromSideChannelFunction();
1835 cache_ocsp_response(
1836 CERT_GetDefaultCertDB(),
1837 nss_handshake_state_.server_cert_chain[0], PR_Now(),
1838 &ocsp_responses->items[0], NULL);
1839 #endif
1842 #endif
1844 // Done!
1845 } else {
1846 PRErrorCode prerr = PR_GetError();
1847 net_error = HandleNSSError(prerr, true);
1849 // Some network devices that inspect application-layer packets seem to
1850 // inject TCP reset packets to break the connections when they see
1851 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1853 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1854 // 1.2. We don't lose much in this fallback because the explicit IV for CBC
1855 // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
1856 // fallback will be more painful for TLS 1.2 when we have GCM support.
1858 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1859 // to trigger a version fallback in general, especially the TLS 1.0 ->
1860 // SSL 3.0 fallback, which would drop TLS extensions.
1861 if (prerr == PR_CONNECT_RESET_ERROR &&
1862 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1) {
1863 net_error = ERR_SSL_PROTOCOL_ERROR;
1866 // If not done, stay in this state
1867 if (net_error == ERR_IO_PENDING) {
1868 GotoState(STATE_HANDSHAKE);
1869 } else {
1870 PostOrRunCallback(
1871 FROM_HERE,
1872 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1873 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1874 CreateNetLogSSLErrorCallback(net_error, prerr)));
1878 return net_error;
1881 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1882 SECStatus rv;
1883 PostOrRunCallback(
1884 FROM_HERE,
1885 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1886 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1888 channel_id_needed_ = false;
1890 if (result != OK)
1891 return result;
1893 SECKEYPublicKey* public_key;
1894 SECKEYPrivateKey* private_key;
1895 int error = ImportChannelIDKeys(&public_key, &private_key);
1896 if (error != OK)
1897 return error;
1899 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1900 if (rv != SECSuccess)
1901 return MapNSSError(PORT_GetError());
1903 SetChannelIDProvided();
1904 GotoState(STATE_HANDSHAKE);
1905 return OK;
1908 int SSLClientSocketNSS::Core::DoPayloadRead() {
1909 DCHECK(OnNSSTaskRunner());
1910 DCHECK(user_read_buf_.get());
1911 DCHECK_GT(user_read_buf_len_, 0);
1913 int rv;
1914 // If a previous greedy read resulted in an error that was not consumed (eg:
1915 // due to the caller having read some data successfully), then return that
1916 // pending error now.
1917 if (pending_read_result_ != kNoPendingReadResult) {
1918 rv = pending_read_result_;
1919 PRErrorCode prerr = pending_read_nss_error_;
1920 pending_read_result_ = kNoPendingReadResult;
1921 pending_read_nss_error_ = 0;
1923 if (rv == 0) {
1924 PostOrRunCallback(
1925 FROM_HERE,
1926 base::Bind(&LogByteTransferEvent, weak_net_log_,
1927 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1928 scoped_refptr<IOBuffer>(user_read_buf_)));
1929 } else {
1930 PostOrRunCallback(
1931 FROM_HERE,
1932 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1933 NetLog::TYPE_SSL_READ_ERROR,
1934 CreateNetLogSSLErrorCallback(rv, prerr)));
1936 return rv;
1939 // Perform a greedy read, attempting to read as much as the caller has
1940 // requested. In the current NSS implementation, PR_Read will return
1941 // exactly one SSL application data record's worth of data per invocation.
1942 // The record size is dictated by the server, and may be noticeably smaller
1943 // than the caller's buffer. This may be as little as a single byte, if the
1944 // server is performing 1/n-1 record splitting.
1946 // However, this greedy read may result in renegotiations/re-handshakes
1947 // happening or may lead to some data being read, followed by an EOF (such as
1948 // a TLS close-notify). If at least some data was read, then that result
1949 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1950 // data was read, it's safe to return the error or EOF immediately.
1951 int total_bytes_read = 0;
1952 do {
1953 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1954 user_read_buf_len_ - total_bytes_read);
1955 if (rv > 0)
1956 total_bytes_read += rv;
1957 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1958 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1959 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1960 amount_in_read_buffer));
1962 if (total_bytes_read == user_read_buf_len_) {
1963 // The caller's entire request was satisfied without error. No further
1964 // processing needed.
1965 rv = total_bytes_read;
1966 } else {
1967 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1968 // immediately, while the NSPR/NSS errors are still available in
1969 // thread-local storage. However, the handled/remapped error code should
1970 // only be returned if no application data was already read; if it was, the
1971 // error code should be deferred until the next call of DoPayloadRead.
1973 // If no data was read, |*next_result| will point to the return value of
1974 // this function. If at least some data was read, |*next_result| will point
1975 // to |pending_read_error_|, to be returned in a future call to
1976 // DoPayloadRead() (e.g.: after the current data is handled).
1977 int* next_result = &rv;
1978 if (total_bytes_read > 0) {
1979 pending_read_result_ = rv;
1980 rv = total_bytes_read;
1981 next_result = &pending_read_result_;
1984 if (client_auth_cert_needed_) {
1985 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1986 pending_read_nss_error_ = 0;
1987 } else if (*next_result < 0) {
1988 // If *next_result == 0, then that indicates EOF, and no special error
1989 // handling is needed.
1990 pending_read_nss_error_ = PR_GetError();
1991 *next_result = HandleNSSError(pending_read_nss_error_, false);
1992 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1993 // If at least some data was read from PR_Read(), do not treat
1994 // insufficient data as an error to return in the next call to
1995 // DoPayloadRead() - instead, let the call fall through to check
1996 // PR_Read() again. This is because DoTransportIO() may complete
1997 // in between the next call to DoPayloadRead(), and thus it is
1998 // important to check PR_Read() on subsequent invocations to see
1999 // if a complete record may now be read.
2000 pending_read_nss_error_ = 0;
2001 pending_read_result_ = kNoPendingReadResult;
2006 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
2008 if (rv >= 0) {
2009 PostOrRunCallback(
2010 FROM_HERE,
2011 base::Bind(&LogByteTransferEvent, weak_net_log_,
2012 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
2013 scoped_refptr<IOBuffer>(user_read_buf_)));
2014 } else if (rv != ERR_IO_PENDING) {
2015 PostOrRunCallback(
2016 FROM_HERE,
2017 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2018 NetLog::TYPE_SSL_READ_ERROR,
2019 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
2020 pending_read_nss_error_ = 0;
2022 return rv;
2025 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2026 DCHECK(OnNSSTaskRunner());
2028 DCHECK(user_write_buf_.get());
2030 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2031 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2032 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2033 // PR_Write could potentially consume the unhandled data in the memio read
2034 // buffer if a renegotiation is in progress. If the buffer is consumed,
2035 // notify the latest buffer size to NetworkRunner.
2036 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
2037 PostOrRunCallback(
2038 FROM_HERE,
2039 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
2041 if (rv >= 0) {
2042 PostOrRunCallback(
2043 FROM_HERE,
2044 base::Bind(&LogByteTransferEvent, weak_net_log_,
2045 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2046 scoped_refptr<IOBuffer>(user_write_buf_)));
2047 return rv;
2049 PRErrorCode prerr = PR_GetError();
2050 if (prerr == PR_WOULD_BLOCK_ERROR)
2051 return ERR_IO_PENDING;
2053 rv = HandleNSSError(prerr, false);
2054 PostOrRunCallback(
2055 FROM_HERE,
2056 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2057 NetLog::TYPE_SSL_WRITE_ERROR,
2058 CreateNetLogSSLErrorCallback(rv, prerr)));
2059 return rv;
2062 // Do as much network I/O as possible between the buffer and the
2063 // transport socket. Return true if some I/O performed, false
2064 // otherwise (error or ERR_IO_PENDING).
2065 bool SSLClientSocketNSS::Core::DoTransportIO() {
2066 DCHECK(OnNSSTaskRunner());
2068 bool network_moved = false;
2069 if (nss_bufs_ != NULL) {
2070 int rv;
2071 // Read and write as much data as we can. The loop is neccessary
2072 // because Write() may return synchronously.
2073 do {
2074 rv = BufferSend();
2075 if (rv != ERR_IO_PENDING && rv != 0)
2076 network_moved = true;
2077 } while (rv > 0);
2078 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
2079 network_moved = true;
2081 return network_moved;
2084 int SSLClientSocketNSS::Core::BufferRecv() {
2085 DCHECK(OnNSSTaskRunner());
2087 if (transport_recv_busy_)
2088 return ERR_IO_PENDING;
2090 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2091 // determine how much data NSS wants to read. If NSS was not blocked,
2092 // this will return 0.
2093 int requested = memio_GetReadRequest(nss_bufs_);
2094 if (requested == 0) {
2095 // This is not a perfect match of error codes, as no operation is
2096 // actually pending. However, returning 0 would be interpreted as a
2097 // possible sign of EOF, which is also an inappropriate match.
2098 return ERR_IO_PENDING;
2101 char* buf;
2102 int nb = memio_GetReadParams(nss_bufs_, &buf);
2103 int rv;
2104 if (!nb) {
2105 // buffer too full to read into, so no I/O possible at moment
2106 rv = ERR_IO_PENDING;
2107 } else {
2108 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2109 if (OnNetworkTaskRunner()) {
2110 rv = DoBufferRecv(read_buffer.get(), nb);
2111 } else {
2112 bool posted = network_task_runner_->PostTask(
2113 FROM_HERE,
2114 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2115 nb));
2116 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2119 if (rv == ERR_IO_PENDING) {
2120 transport_recv_busy_ = true;
2121 } else {
2122 if (rv > 0) {
2123 memcpy(buf, read_buffer->data(), rv);
2124 } else if (rv == 0) {
2125 transport_recv_eof_ = true;
2127 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2130 return rv;
2133 // Return 0 if nss_bufs_ was empty,
2134 // > 0 for bytes transferred immediately,
2135 // < 0 for error (or the non-error ERR_IO_PENDING).
2136 int SSLClientSocketNSS::Core::BufferSend() {
2137 DCHECK(OnNSSTaskRunner());
2139 if (transport_send_busy_)
2140 return ERR_IO_PENDING;
2142 const char* buf1;
2143 const char* buf2;
2144 unsigned int len1, len2;
2145 memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2);
2146 const unsigned int len = len1 + len2;
2148 int rv = 0;
2149 if (len) {
2150 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2151 memcpy(send_buffer->data(), buf1, len1);
2152 memcpy(send_buffer->data() + len1, buf2, len2);
2154 if (OnNetworkTaskRunner()) {
2155 rv = DoBufferSend(send_buffer.get(), len);
2156 } else {
2157 bool posted = network_task_runner_->PostTask(
2158 FROM_HERE,
2159 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2160 len));
2161 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2164 if (rv == ERR_IO_PENDING) {
2165 transport_send_busy_ = true;
2166 } else {
2167 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2171 return rv;
2174 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2175 DCHECK(OnNSSTaskRunner());
2177 if (next_handshake_state_ == STATE_HANDSHAKE) {
2178 OnHandshakeIOComplete(result);
2179 return;
2182 // Network layer received some data, check if client requested to read
2183 // decrypted data.
2184 if (!user_read_buf_.get())
2185 return;
2187 int rv = DoReadLoop(result);
2188 if (rv != ERR_IO_PENDING)
2189 DoReadCallback(rv);
2192 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2193 DCHECK(OnNSSTaskRunner());
2195 if (next_handshake_state_ == STATE_HANDSHAKE) {
2196 OnHandshakeIOComplete(result);
2197 return;
2200 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2201 // handshake is in progress.
2202 int rv_read = ERR_IO_PENDING;
2203 int rv_write = ERR_IO_PENDING;
2204 bool network_moved;
2205 do {
2206 if (user_read_buf_.get())
2207 rv_read = DoPayloadRead();
2208 if (user_write_buf_.get())
2209 rv_write = DoPayloadWrite();
2210 network_moved = DoTransportIO();
2211 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
2212 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
2214 // If the parent SSLClientSocketNSS is deleted during the processing of the
2215 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2216 // will be detached (and possibly deleted). Guard against deletion by taking
2217 // an extra reference, then check if the Core was detached before invoking the
2218 // next callback.
2219 scoped_refptr<Core> guard(this);
2220 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
2221 DoReadCallback(rv_read);
2223 if (OnNetworkTaskRunner() && detached_)
2224 return;
2226 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
2227 DoWriteCallback(rv_write);
2230 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2231 // handshake. This requires network IO, which in turn calls
2232 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2233 // winds its way through the state machine and ends up being passed to the
2234 // callback. For Read() and Write(), that's what we want. But for Connect(),
2235 // the caller expects OK (i.e. 0) for success.
2236 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2237 DCHECK(OnNSSTaskRunner());
2238 DCHECK_NE(rv, ERR_IO_PENDING);
2239 DCHECK(!user_connect_callback_.is_null());
2241 base::Closure c = base::Bind(
2242 base::ResetAndReturn(&user_connect_callback_),
2243 rv > OK ? OK : rv);
2244 PostOrRunCallback(FROM_HERE, c);
2247 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2248 DCHECK(OnNSSTaskRunner());
2249 DCHECK_NE(ERR_IO_PENDING, rv);
2250 DCHECK(!user_read_callback_.is_null());
2252 user_read_buf_ = NULL;
2253 user_read_buf_len_ = 0;
2254 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2255 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2256 // the network task runner.
2257 PostOrRunCallback(
2258 FROM_HERE,
2259 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2260 PostOrRunCallback(
2261 FROM_HERE,
2262 base::Bind(&Core::DidNSSRead, this, rv));
2263 PostOrRunCallback(
2264 FROM_HERE,
2265 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
2268 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2269 DCHECK(OnNSSTaskRunner());
2270 DCHECK_NE(ERR_IO_PENDING, rv);
2271 DCHECK(!user_write_callback_.is_null());
2273 // Since Run may result in Write being called, clear |user_write_callback_|
2274 // up front.
2275 user_write_buf_ = NULL;
2276 user_write_buf_len_ = 0;
2277 // Update buffer status because DoWriteLoop called DoTransportIO which may
2278 // perform read operations.
2279 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2280 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2281 // the network task runner.
2282 PostOrRunCallback(
2283 FROM_HERE,
2284 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2285 PostOrRunCallback(
2286 FROM_HERE,
2287 base::Bind(&Core::DidNSSWrite, this, rv));
2288 PostOrRunCallback(
2289 FROM_HERE,
2290 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
2293 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
2294 void* arg,
2295 PRFileDesc* socket,
2296 SECKEYPublicKey **out_public_key,
2297 SECKEYPrivateKey **out_private_key) {
2298 Core* core = reinterpret_cast<Core*>(arg);
2299 DCHECK(core->OnNSSTaskRunner());
2301 core->PostOrRunCallback(
2302 FROM_HERE,
2303 base::Bind(&AddLogEvent, core->weak_net_log_,
2304 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
2306 // We have negotiated the TLS channel ID extension.
2307 core->channel_id_xtn_negotiated_ = true;
2308 std::string host = core->host_and_port_.host();
2309 int error = ERR_UNEXPECTED;
2310 if (core->OnNetworkTaskRunner()) {
2311 error = core->DoGetDomainBoundCert(host);
2312 } else {
2313 bool posted = core->network_task_runner_->PostTask(
2314 FROM_HERE,
2315 base::Bind(
2316 IgnoreResult(&Core::DoGetDomainBoundCert),
2317 core, host));
2318 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2321 if (error == ERR_IO_PENDING) {
2322 // Asynchronous case.
2323 core->channel_id_needed_ = true;
2324 return SECWouldBlock;
2327 core->PostOrRunCallback(
2328 FROM_HERE,
2329 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2330 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2331 SECStatus rv = SECSuccess;
2332 if (error == OK) {
2333 // Synchronous success.
2334 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2335 if (result == OK)
2336 core->SetChannelIDProvided();
2337 else
2338 rv = SECFailure;
2339 } else {
2340 rv = SECFailure;
2343 return rv;
2346 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2347 SECKEYPrivateKey** key) {
2348 // Set the certificate.
2349 SECItem cert_item;
2350 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2351 cert_item.len = domain_bound_cert_.size();
2352 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2353 &cert_item,
2354 NULL,
2355 PR_FALSE,
2356 PR_TRUE));
2357 if (cert == NULL)
2358 return MapNSSError(PORT_GetError());
2360 // Set the private key.
2361 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2362 ServerBoundCertService::kEPKIPassword,
2363 reinterpret_cast<const unsigned char*>(
2364 domain_bound_private_key_.data()),
2365 domain_bound_private_key_.size(),
2366 &cert->subjectPublicKeyInfo,
2367 false,
2368 false,
2369 key,
2370 public_key)) {
2371 int error = MapNSSError(PORT_GetError());
2372 return error;
2375 return OK;
2378 void SSLClientSocketNSS::Core::UpdateServerCert() {
2379 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2380 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2381 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2382 if (nss_handshake_state_.server_cert.get()) {
2383 // Since this will be called asynchronously on another thread, it needs to
2384 // own a reference to the certificate.
2385 NetLog::ParametersCallback net_log_callback =
2386 base::Bind(&NetLogX509CertificateCallback,
2387 nss_handshake_state_.server_cert);
2388 PostOrRunCallback(
2389 FROM_HERE,
2390 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2391 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2392 net_log_callback));
2396 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2397 SSLChannelInfo channel_info;
2398 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2399 &channel_info, sizeof(channel_info));
2400 if (ok == SECSuccess &&
2401 channel_info.length == sizeof(channel_info) &&
2402 channel_info.cipherSuite) {
2403 nss_handshake_state_.ssl_connection_status |=
2404 (static_cast<int>(channel_info.cipherSuite) &
2405 SSL_CONNECTION_CIPHERSUITE_MASK) <<
2406 SSL_CONNECTION_CIPHERSUITE_SHIFT;
2408 nss_handshake_state_.ssl_connection_status |=
2409 (static_cast<int>(channel_info.compressionMethod) &
2410 SSL_CONNECTION_COMPRESSION_MASK) <<
2411 SSL_CONNECTION_COMPRESSION_SHIFT;
2413 // NSS 3.14.x doesn't have a version macro for TLS 1.2 (because NSS didn't
2414 // support it yet), so use 0x0303 directly.
2415 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2416 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2417 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2418 // version 2.
2419 version = SSL_CONNECTION_VERSION_SSL2;
2420 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2421 version = SSL_CONNECTION_VERSION_SSL3;
2422 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) {
2423 version = SSL_CONNECTION_VERSION_TLS1;
2424 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2425 version = SSL_CONNECTION_VERSION_TLS1_1;
2426 } else if (channel_info.protocolVersion == 0x0303) {
2427 version = SSL_CONNECTION_VERSION_TLS1_2;
2429 nss_handshake_state_.ssl_connection_status |=
2430 (version & SSL_CONNECTION_VERSION_MASK) <<
2431 SSL_CONNECTION_VERSION_SHIFT;
2434 PRBool peer_supports_renego_ext;
2435 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2436 &peer_supports_renego_ext);
2437 if (ok == SECSuccess) {
2438 if (!peer_supports_renego_ext) {
2439 nss_handshake_state_.ssl_connection_status |=
2440 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2441 // Log an informational message if the server does not support secure
2442 // renegotiation (RFC 5746).
2443 VLOG(1) << "The server " << host_and_port_.ToString()
2444 << " does not support the TLS renegotiation_info extension.";
2446 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2447 peer_supports_renego_ext, 2);
2449 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2450 // because of security concerns. For example, Google offers forward
2451 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2452 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2453 // secrecy.
2455 // Yngve from Opera has suggested using the renegotiation extension as an
2456 // indicator that SSLv3 fallback was mistaken:
2457 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2459 // As a first step, measure how often clients perform version fallback
2460 // while the server advertises support secure renegotiation.
2461 if (ssl_config_.version_fallback &&
2462 channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2463 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2464 peer_supports_renego_ext == PR_TRUE);
2468 if (ssl_config_.version_fallback) {
2469 nss_handshake_state_.ssl_connection_status |=
2470 SSL_CONNECTION_VERSION_FALLBACK;
2474 void SSLClientSocketNSS::Core::UpdateNextProto() {
2475 uint8 buf[256];
2476 SSLNextProtoState state;
2477 unsigned buf_len;
2479 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2480 if (rv != SECSuccess)
2481 return;
2483 nss_handshake_state_.next_proto =
2484 std::string(reinterpret_cast<char*>(buf), buf_len);
2485 switch (state) {
2486 case SSL_NEXT_PROTO_NEGOTIATED:
2487 case SSL_NEXT_PROTO_SELECTED:
2488 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2489 break;
2490 case SSL_NEXT_PROTO_NO_OVERLAP:
2491 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2492 break;
2493 case SSL_NEXT_PROTO_NO_SUPPORT:
2494 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2495 break;
2496 default:
2497 NOTREACHED();
2498 break;
2502 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2503 DCHECK(OnNSSTaskRunner());
2504 if (nss_handshake_state_.resumed_handshake)
2505 return;
2507 // Copy the NSS task runner-only state to the network task runner and
2508 // log histograms from there, since the histograms also need access to the
2509 // network task runner state.
2510 PostOrRunCallback(
2511 FROM_HERE,
2512 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2513 this,
2514 channel_id_xtn_negotiated_,
2515 ssl_config_.channel_id_enabled,
2516 crypto::ECPrivateKey::IsSupported()));
2519 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2520 bool negotiated_channel_id,
2521 bool channel_id_enabled,
2522 bool supports_ecc) const {
2523 DCHECK(OnNetworkTaskRunner());
2525 RecordChannelIDSupport(server_bound_cert_service_,
2526 negotiated_channel_id,
2527 channel_id_enabled,
2528 supports_ecc);
2531 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2532 DCHECK(OnNetworkTaskRunner());
2533 DCHECK_GT(len, 0);
2535 if (detached_)
2536 return ERR_ABORTED;
2538 int rv = transport_->socket()->Read(
2539 read_buffer, len,
2540 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2541 scoped_refptr<IOBuffer>(read_buffer)));
2543 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2544 nss_task_runner_->PostTask(
2545 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2546 scoped_refptr<IOBuffer>(read_buffer), rv));
2547 return rv;
2550 return rv;
2553 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2554 DCHECK(OnNetworkTaskRunner());
2555 DCHECK_GT(len, 0);
2557 if (detached_)
2558 return ERR_ABORTED;
2560 int rv = transport_->socket()->Write(
2561 send_buffer, len,
2562 base::Bind(&Core::BufferSendComplete,
2563 base::Unretained(this)));
2565 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2566 nss_task_runner_->PostTask(
2567 FROM_HERE,
2568 base::Bind(&Core::BufferSendComplete, this, rv));
2569 return rv;
2572 return rv;
2575 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(const std::string& host) {
2576 DCHECK(OnNetworkTaskRunner());
2578 if (detached_)
2579 return ERR_FAILED;
2581 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2583 int rv = server_bound_cert_service_->GetOrCreateDomainBoundCert(
2584 host,
2585 &domain_bound_private_key_,
2586 &domain_bound_cert_,
2587 base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)),
2588 &domain_bound_cert_request_handle_);
2590 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2591 nss_task_runner_->PostTask(
2592 FROM_HERE,
2593 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2594 return ERR_IO_PENDING;
2597 return rv;
2600 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2601 const HandshakeState& state) {
2602 DCHECK(OnNetworkTaskRunner());
2603 network_handshake_state_ = state;
2606 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2607 DCHECK(OnNetworkTaskRunner());
2608 unhandled_buffer_size_ = amount_in_read_buffer;
2611 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2612 DCHECK(OnNetworkTaskRunner());
2613 DCHECK(nss_waiting_read_);
2614 nss_waiting_read_ = false;
2615 if (result <= 0)
2616 nss_is_closed_ = true;
2619 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2620 DCHECK(OnNetworkTaskRunner());
2621 DCHECK(nss_waiting_write_);
2622 nss_waiting_write_ = false;
2623 if (result < 0)
2624 nss_is_closed_ = true;
2627 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2628 if (!OnNSSTaskRunner()) {
2629 if (detached_)
2630 return;
2632 nss_task_runner_->PostTask(
2633 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2634 return;
2637 DCHECK(OnNSSTaskRunner());
2639 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2640 transport_send_busy_ = false;
2641 OnSendComplete(result);
2644 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2645 if (!OnNSSTaskRunner()) {
2646 if (detached_)
2647 return;
2649 nss_task_runner_->PostTask(
2650 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2651 return;
2654 DCHECK(OnNSSTaskRunner());
2656 int rv = DoHandshakeLoop(result);
2657 if (rv != ERR_IO_PENDING)
2658 DoConnectCallback(rv);
2661 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) {
2662 DVLOG(1) << __FUNCTION__ << " " << result;
2663 DCHECK(OnNetworkTaskRunner());
2665 OnHandshakeIOComplete(result);
2668 void SSLClientSocketNSS::Core::BufferRecvComplete(
2669 IOBuffer* read_buffer,
2670 int result) {
2671 DCHECK(read_buffer);
2673 if (!OnNSSTaskRunner()) {
2674 if (detached_)
2675 return;
2677 nss_task_runner_->PostTask(
2678 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2679 scoped_refptr<IOBuffer>(read_buffer), result));
2680 return;
2683 DCHECK(OnNSSTaskRunner());
2685 if (result > 0) {
2686 char* buf;
2687 int nb = memio_GetReadParams(nss_bufs_, &buf);
2688 CHECK_GE(nb, result);
2689 memcpy(buf, read_buffer->data(), result);
2690 } else if (result == 0) {
2691 transport_recv_eof_ = true;
2694 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2695 transport_recv_busy_ = false;
2696 OnRecvComplete(result);
2699 void SSLClientSocketNSS::Core::PostOrRunCallback(
2700 const tracked_objects::Location& location,
2701 const base::Closure& task) {
2702 if (!OnNetworkTaskRunner()) {
2703 network_task_runner_->PostTask(
2704 FROM_HERE,
2705 base::Bind(&Core::PostOrRunCallback, this, location, task));
2706 return;
2709 if (detached_ || task.is_null())
2710 return;
2711 task.Run();
2714 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2715 PostOrRunCallback(
2716 FROM_HERE,
2717 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2718 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2719 NetLog::IntegerCallback("cert_count", cert_count)));
2722 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2723 PostOrRunCallback(
2724 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2725 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2726 nss_handshake_state_.channel_id_sent = true;
2727 // Update the network task runner's view of the handshake state now that
2728 // channel id has been sent.
2729 PostOrRunCallback(
2730 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2731 nss_handshake_state_));
2734 SSLClientSocketNSS::SSLClientSocketNSS(
2735 base::SequencedTaskRunner* nss_task_runner,
2736 scoped_ptr<ClientSocketHandle> transport_socket,
2737 const HostPortPair& host_and_port,
2738 const SSLConfig& ssl_config,
2739 const SSLClientSocketContext& context)
2740 : nss_task_runner_(nss_task_runner),
2741 transport_(transport_socket.Pass()),
2742 host_and_port_(host_and_port),
2743 ssl_config_(ssl_config),
2744 cert_verifier_(context.cert_verifier),
2745 server_bound_cert_service_(context.server_bound_cert_service),
2746 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2747 completed_handshake_(false),
2748 next_handshake_state_(STATE_NONE),
2749 nss_fd_(NULL),
2750 net_log_(transport_->socket()->NetLog()),
2751 transport_security_state_(context.transport_security_state),
2752 valid_thread_id_(base::kInvalidThreadId) {
2753 EnterFunction("");
2754 InitCore();
2755 LeaveFunction("");
2758 SSLClientSocketNSS::~SSLClientSocketNSS() {
2759 EnterFunction("");
2760 Disconnect();
2761 LeaveFunction("");
2764 // static
2765 void SSLClientSocket::ClearSessionCache() {
2766 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2767 // bother initializing NSS just to clear an empty SSL session cache.
2768 if (!NSS_IsInitialized())
2769 return;
2771 SSL_ClearSessionCache();
2774 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2775 EnterFunction("");
2776 ssl_info->Reset();
2777 if (core_->state().server_cert_chain.empty() ||
2778 !core_->state().server_cert_chain[0]) {
2779 return false;
2782 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2783 ssl_info->cert = server_cert_verify_result_.verified_cert;
2784 ssl_info->connection_status =
2785 core_->state().ssl_connection_status;
2786 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2787 for (HashValueVector::const_iterator i = side_pinned_public_keys_.begin();
2788 i != side_pinned_public_keys_.end(); ++i) {
2789 ssl_info->public_key_hashes.push_back(*i);
2791 ssl_info->is_issued_by_known_root =
2792 server_cert_verify_result_.is_issued_by_known_root;
2793 ssl_info->client_cert_sent =
2794 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2795 ssl_info->channel_id_sent = WasChannelIDSent();
2797 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2798 core_->state().ssl_connection_status);
2799 SSLCipherSuiteInfo cipher_info;
2800 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2801 &cipher_info, sizeof(cipher_info));
2802 if (ok == SECSuccess) {
2803 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2804 } else {
2805 ssl_info->security_bits = -1;
2806 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2807 << " for cipherSuite " << cipher_suite;
2810 ssl_info->handshake_type = core_->state().resumed_handshake ?
2811 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2813 LeaveFunction("");
2814 return true;
2817 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2818 SSLCertRequestInfo* cert_request_info) {
2819 EnterFunction("");
2820 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2821 cert_request_info->host_and_port = host_and_port_.ToString();
2822 cert_request_info->cert_authorities = core_->state().cert_authorities;
2823 LeaveFunction("");
2826 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2827 bool has_context,
2828 const base::StringPiece& context,
2829 unsigned char* out,
2830 unsigned int outlen) {
2831 if (!IsConnected())
2832 return ERR_SOCKET_NOT_CONNECTED;
2834 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2835 // the midst of a handshake.
2836 SECStatus result = SSL_ExportKeyingMaterial(
2837 nss_fd_, label.data(), label.size(), has_context,
2838 reinterpret_cast<const unsigned char*>(context.data()),
2839 context.length(), out, outlen);
2840 if (result != SECSuccess) {
2841 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2842 return MapNSSError(PORT_GetError());
2844 return OK;
2847 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2848 if (!IsConnected())
2849 return ERR_SOCKET_NOT_CONNECTED;
2850 unsigned char buf[64];
2851 unsigned int len;
2852 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2853 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2854 buf, &len, arraysize(buf));
2855 if (result != SECSuccess) {
2856 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2857 return MapNSSError(PORT_GetError());
2859 out->assign(reinterpret_cast<char*>(buf), len);
2860 return OK;
2863 SSLClientSocket::NextProtoStatus
2864 SSLClientSocketNSS::GetNextProto(std::string* proto,
2865 std::string* server_protos) {
2866 *proto = core_->state().next_proto;
2867 *server_protos = core_->state().server_protos;
2868 return core_->state().next_proto_status;
2871 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2872 EnterFunction("");
2873 DCHECK(transport_.get());
2874 // It is an error to create an SSLClientSocket whose context has no
2875 // TransportSecurityState.
2876 DCHECK(transport_security_state_);
2877 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2878 DCHECK(user_connect_callback_.is_null());
2879 DCHECK(!callback.is_null());
2881 EnsureThreadIdAssigned();
2883 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2885 int rv = Init();
2886 if (rv != OK) {
2887 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2888 return rv;
2891 rv = InitializeSSLOptions();
2892 if (rv != OK) {
2893 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2894 return rv;
2897 rv = InitializeSSLPeerName();
2898 if (rv != OK) {
2899 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2900 return rv;
2903 GotoState(STATE_HANDSHAKE);
2905 rv = DoHandshakeLoop(OK);
2906 if (rv == ERR_IO_PENDING) {
2907 user_connect_callback_ = callback;
2908 } else {
2909 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2912 LeaveFunction("");
2913 return rv > OK ? OK : rv;
2916 void SSLClientSocketNSS::Disconnect() {
2917 EnterFunction("");
2919 CHECK(CalledOnValidThread());
2921 // Shut down anything that may call us back.
2922 core_->Detach();
2923 verifier_.reset();
2924 transport_->socket()->Disconnect();
2926 // Reset object state.
2927 user_connect_callback_.Reset();
2928 server_cert_verify_result_.Reset();
2929 completed_handshake_ = false;
2930 start_cert_verification_time_ = base::TimeTicks();
2931 InitCore();
2933 LeaveFunction("");
2936 bool SSLClientSocketNSS::IsConnected() const {
2937 EnterFunction("");
2938 bool ret = completed_handshake_ &&
2939 (core_->HasPendingAsyncOperation() ||
2940 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2941 transport_->socket()->IsConnected());
2942 LeaveFunction("");
2943 return ret;
2946 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2947 EnterFunction("");
2948 bool ret = completed_handshake_ &&
2949 !core_->HasPendingAsyncOperation() &&
2950 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
2951 transport_->socket()->IsConnectedAndIdle();
2952 LeaveFunction("");
2953 return ret;
2956 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
2957 return transport_->socket()->GetPeerAddress(address);
2960 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
2961 return transport_->socket()->GetLocalAddress(address);
2964 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
2965 return net_log_;
2968 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2969 if (transport_.get() && transport_->socket()) {
2970 transport_->socket()->SetSubresourceSpeculation();
2971 } else {
2972 NOTREACHED();
2976 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2977 if (transport_.get() && transport_->socket()) {
2978 transport_->socket()->SetOmniboxSpeculation();
2979 } else {
2980 NOTREACHED();
2984 bool SSLClientSocketNSS::WasEverUsed() const {
2985 if (transport_.get() && transport_->socket()) {
2986 return transport_->socket()->WasEverUsed();
2988 NOTREACHED();
2989 return false;
2992 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2993 if (transport_.get() && transport_->socket()) {
2994 return transport_->socket()->UsingTCPFastOpen();
2996 NOTREACHED();
2997 return false;
3000 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
3001 const CompletionCallback& callback) {
3002 DCHECK(core_.get());
3003 DCHECK(!callback.is_null());
3005 EnterFunction(buf_len);
3006 int rv = core_->Read(buf, buf_len, callback);
3007 LeaveFunction(rv);
3009 return rv;
3012 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
3013 const CompletionCallback& callback) {
3014 DCHECK(core_.get());
3015 DCHECK(!callback.is_null());
3017 EnterFunction(buf_len);
3018 int rv = core_->Write(buf, buf_len, callback);
3019 LeaveFunction(rv);
3021 return rv;
3024 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
3025 return transport_->socket()->SetReceiveBufferSize(size);
3028 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
3029 return transport_->socket()->SetSendBufferSize(size);
3032 int SSLClientSocketNSS::Init() {
3033 EnterFunction("");
3034 // Initialize the NSS SSL library in a threadsafe way. This also
3035 // initializes the NSS base library.
3036 EnsureNSSSSLInit();
3037 if (!NSS_IsInitialized())
3038 return ERR_UNEXPECTED;
3039 #if defined(USE_NSS) || defined(OS_IOS)
3040 if (ssl_config_.cert_io_enabled) {
3041 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3042 // loop by MessageLoopForIO::current().
3043 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3044 EnsureNSSHttpIOInit();
3046 #endif
3048 LeaveFunction("");
3049 return OK;
3052 void SSLClientSocketNSS::InitCore() {
3053 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
3054 nss_task_runner_.get(),
3055 transport_.get(),
3056 host_and_port_,
3057 ssl_config_,
3058 &net_log_,
3059 server_bound_cert_service_);
3062 int SSLClientSocketNSS::InitializeSSLOptions() {
3063 // Transport connected, now hook it up to nss
3064 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3065 if (nss_fd_ == NULL) {
3066 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3069 // Grab pointer to buffers
3070 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3072 /* Create SSL state machine */
3073 /* Push SSL onto our fake I/O socket */
3074 nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
3075 if (nss_fd_ == NULL) {
3076 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3077 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3079 // TODO(port): set more ssl options! Check errors!
3081 int rv;
3083 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3084 if (rv != SECSuccess) {
3085 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3086 return ERR_UNEXPECTED;
3089 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3090 if (rv != SECSuccess) {
3091 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3092 return ERR_UNEXPECTED;
3095 // Don't do V2 compatible hellos because they don't support TLS extensions.
3096 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3097 if (rv != SECSuccess) {
3098 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3099 return ERR_UNEXPECTED;
3102 SSLVersionRange version_range;
3103 version_range.min = ssl_config_.version_min;
3104 version_range.max = ssl_config_.version_max;
3105 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3106 if (rv != SECSuccess) {
3107 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3108 return ERR_NO_SSL_VERSIONS_ENABLED;
3111 for (std::vector<uint16>::const_iterator it =
3112 ssl_config_.disabled_cipher_suites.begin();
3113 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3114 // This will fail if the specified cipher is not implemented by NSS, but
3115 // the failure is harmless.
3116 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3119 // Support RFC 5077
3120 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3121 if (rv != SECSuccess) {
3122 LogFailedNSSFunction(
3123 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3126 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3127 ssl_config_.false_start_enabled);
3128 if (rv != SECSuccess)
3129 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3131 // We allow servers to request renegotiation. Since we're a client,
3132 // prohibiting this is rather a waste of time. Only servers are in a
3133 // position to prevent renegotiation attacks.
3134 // http://extendedsubset.com/?p=8
3136 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3137 SSL_RENEGOTIATE_TRANSITIONAL);
3138 if (rv != SECSuccess) {
3139 LogFailedNSSFunction(
3140 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3143 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
3144 if (rv != SECSuccess)
3145 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3147 // Added in NSS 3.15
3148 #ifdef SSL_ENABLE_OCSP_STAPLING
3149 if (IsOCSPStaplingSupported()) {
3150 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE);
3151 if (rv != SECSuccess) {
3152 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3153 "SSL_ENABLE_OCSP_STAPLING");
3156 #endif
3158 // Chromium patch to libssl
3159 #ifdef SSL_ENABLE_CACHED_INFO
3160 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO,
3161 ssl_config_.cached_info_enabled);
3162 if (rv != SECSuccess)
3163 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3164 #endif
3166 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3167 if (rv != SECSuccess) {
3168 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3169 return ERR_UNEXPECTED;
3172 if (!core_->Init(nss_fd_, nss_bufs))
3173 return ERR_UNEXPECTED;
3175 // Tell SSL the hostname we're trying to connect to.
3176 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3178 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3179 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3181 return OK;
3184 int SSLClientSocketNSS::InitializeSSLPeerName() {
3185 // Tell NSS who we're connected to
3186 IPEndPoint peer_address;
3187 int err = transport_->socket()->GetPeerAddress(&peer_address);
3188 if (err != OK)
3189 return err;
3191 SockaddrStorage storage;
3192 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3193 return ERR_UNEXPECTED;
3195 PRNetAddr peername;
3196 memset(&peername, 0, sizeof(peername));
3197 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3198 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3199 sizeof(peername));
3200 memcpy(&peername, storage.addr, len);
3202 // Adjust the address family field for BSD, whose sockaddr
3203 // structure has a one-byte length and one-byte address family
3204 // field at the beginning. PRNetAddr has a two-byte address
3205 // family field at the beginning.
3206 peername.raw.family = storage.addr->sa_family;
3208 memio_SetPeerName(nss_fd_, &peername);
3210 // Set the peer ID for session reuse. This is necessary when we create an
3211 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3212 // rather than the destination server's address in that case.
3213 std::string peer_id = host_and_port_.ToString();
3214 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3215 // This will cause session cache misses between sockets with different values
3216 // of ssl_session_cache_shard_ and this is used to partition the session cache
3217 // for incognito mode.
3218 if (!ssl_session_cache_shard_.empty()) {
3219 peer_id += "/" + ssl_session_cache_shard_;
3221 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3222 if (rv != SECSuccess)
3223 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3225 return OK;
3228 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3229 EnterFunction(rv);
3230 DCHECK_NE(ERR_IO_PENDING, rv);
3231 DCHECK(!user_connect_callback_.is_null());
3233 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3234 LeaveFunction("");
3237 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3238 EnterFunction(result);
3239 int rv = DoHandshakeLoop(result);
3240 if (rv != ERR_IO_PENDING) {
3241 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3242 DoConnectCallback(rv);
3244 LeaveFunction("");
3247 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3248 EnterFunction(last_io_result);
3249 int rv = last_io_result;
3250 do {
3251 // Default to STATE_NONE for next state.
3252 // (This is a quirk carried over from the windows
3253 // implementation. It makes reading the logs a bit harder.)
3254 // State handlers can and often do call GotoState just
3255 // to stay in the current state.
3256 State state = next_handshake_state_;
3257 GotoState(STATE_NONE);
3258 switch (state) {
3259 case STATE_HANDSHAKE:
3260 rv = DoHandshake();
3261 break;
3262 case STATE_HANDSHAKE_COMPLETE:
3263 rv = DoHandshakeComplete(rv);
3264 break;
3265 case STATE_VERIFY_CERT:
3266 DCHECK(rv == OK);
3267 rv = DoVerifyCert(rv);
3268 break;
3269 case STATE_VERIFY_CERT_COMPLETE:
3270 rv = DoVerifyCertComplete(rv);
3271 break;
3272 case STATE_NONE:
3273 default:
3274 rv = ERR_UNEXPECTED;
3275 LOG(DFATAL) << "unexpected state " << state;
3276 break;
3278 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3279 LeaveFunction("");
3280 return rv;
3283 int SSLClientSocketNSS::DoHandshake() {
3284 EnterFunction("");
3285 int rv = core_->Connect(
3286 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3287 base::Unretained(this)));
3288 GotoState(STATE_HANDSHAKE_COMPLETE);
3290 LeaveFunction(rv);
3291 return rv;
3294 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3295 EnterFunction(result);
3297 if (result == OK) {
3298 // SSL handshake is completed. Let's verify the certificate.
3299 GotoState(STATE_VERIFY_CERT);
3300 // Done!
3302 set_channel_id_sent(core_->state().channel_id_sent);
3304 LeaveFunction(result);
3305 return result;
3309 int SSLClientSocketNSS::DoVerifyCert(int result) {
3310 DCHECK(!core_->state().server_cert_chain.empty());
3311 DCHECK(core_->state().server_cert_chain[0]);
3313 GotoState(STATE_VERIFY_CERT_COMPLETE);
3315 // If the certificate is expected to be bad we can use the expectation as
3316 // the cert status.
3317 base::StringPiece der_cert(
3318 reinterpret_cast<char*>(
3319 core_->state().server_cert_chain[0]->derCert.data),
3320 core_->state().server_cert_chain[0]->derCert.len);
3321 CertStatus cert_status;
3322 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3323 DCHECK(start_cert_verification_time_.is_null());
3324 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3325 server_cert_verify_result_.Reset();
3326 server_cert_verify_result_.cert_status = cert_status;
3327 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3328 return OK;
3331 // We may have failed to create X509Certificate object if we are
3332 // running inside sandbox.
3333 if (!core_->state().server_cert.get()) {
3334 server_cert_verify_result_.Reset();
3335 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3336 return ERR_CERT_INVALID;
3339 start_cert_verification_time_ = base::TimeTicks::Now();
3341 int flags = 0;
3342 if (ssl_config_.rev_checking_enabled)
3343 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3344 if (ssl_config_.verify_ev_cert)
3345 flags |= CertVerifier::VERIFY_EV_CERT;
3346 if (ssl_config_.cert_io_enabled)
3347 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3348 if (ssl_config_.rev_checking_required_local_anchors)
3349 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3350 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3351 return verifier_->Verify(
3352 core_->state().server_cert.get(),
3353 host_and_port_.host(),
3354 flags,
3355 SSLConfigService::GetCRLSet().get(),
3356 &server_cert_verify_result_,
3357 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3358 base::Unretained(this)),
3359 net_log_);
3362 // Derived from AuthCertificateCallback() in
3363 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3364 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3365 verifier_.reset();
3367 if (!start_cert_verification_time_.is_null()) {
3368 base::TimeDelta verify_time =
3369 base::TimeTicks::Now() - start_cert_verification_time_;
3370 if (result == OK)
3371 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3372 else
3373 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3376 // We used to remember the intermediate CA certs in the NSS database
3377 // persistently. However, NSS opens a connection to the SQLite database
3378 // during NSS initialization and doesn't close the connection until NSS
3379 // shuts down. If the file system where the database resides is gone,
3380 // the database connection goes bad. What's worse, the connection won't
3381 // recover when the file system comes back. Until this NSS or SQLite bug
3382 // is fixed, we need to avoid using the NSS database for non-essential
3383 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3384 // http://crbug.com/15630 for more info.
3386 // TODO(hclam): Skip logging if server cert was expected to be bad because
3387 // |server_cert_verify_result_| doesn't contain all the information about
3388 // the cert.
3389 if (result == OK)
3390 LogConnectionTypeMetrics();
3392 completed_handshake_ = true;
3394 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3395 // Take care of any mandates for public key pinning.
3397 // Pinning is only enabled for official builds to make sure that others don't
3398 // end up with pins that cannot be easily updated.
3400 // TODO(agl): We might have an issue here where a request for foo.example.com
3401 // merges into a SPDY connection to www.example.com, and gets a different
3402 // certificate.
3404 // Perform pin validation if, and only if, all these conditions obtain:
3406 // * a TransportSecurityState object is available;
3407 // * the server's certificate chain is valid (or suffers from only a minor
3408 // error);
3409 // * the server's certificate chain chains up to a known root (i.e. not a
3410 // user-installed trust anchor); and
3411 // * the build is recent (very old builds should fail open so that users
3412 // have some chance to recover).
3414 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3415 if (transport_security_state_ &&
3416 (result == OK ||
3417 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3418 server_cert_verify_result_.is_issued_by_known_root &&
3419 TransportSecurityState::IsBuildTimely()) {
3420 bool sni_available =
3421 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
3422 ssl_config_.version_fallback;
3423 const std::string& host = host_and_port_.host();
3425 TransportSecurityState::DomainState domain_state;
3426 if (transport_security_state_->GetDomainState(host, sni_available,
3427 &domain_state) &&
3428 domain_state.HasPublicKeyPins()) {
3429 if (!domain_state.CheckPublicKeyPins(
3430 server_cert_verify_result_.public_key_hashes)) {
3431 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3432 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3433 TransportSecurityState::ReportUMAOnPinFailure(host);
3434 } else {
3435 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3439 #endif
3441 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3442 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3443 return result;
3446 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3447 UpdateConnectionTypeHistograms(CONNECTION_SSL);
3448 int ssl_version = SSLConnectionStatusToVersion(
3449 core_->state().ssl_connection_status);
3450 switch (ssl_version) {
3451 case SSL_CONNECTION_VERSION_SSL2:
3452 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2);
3453 break;
3454 case SSL_CONNECTION_VERSION_SSL3:
3455 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3);
3456 break;
3457 case SSL_CONNECTION_VERSION_TLS1:
3458 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1);
3459 break;
3460 case SSL_CONNECTION_VERSION_TLS1_1:
3461 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1);
3462 break;
3463 case SSL_CONNECTION_VERSION_TLS1_2:
3464 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2);
3465 break;
3469 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3470 base::AutoLock auto_lock(lock_);
3471 if (valid_thread_id_ != base::kInvalidThreadId)
3472 return;
3473 valid_thread_id_ = base::PlatformThread::CurrentId();
3476 bool SSLClientSocketNSS::CalledOnValidThread() const {
3477 EnsureThreadIdAssigned();
3478 base::AutoLock auto_lock(lock_);
3479 return valid_thread_id_ == base::PlatformThread::CurrentId();
3482 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const {
3483 return server_bound_cert_service_;
3486 } // namespace net