Fix Telemetry media seek action flakiness.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blobc3e5a9d13798bebec44a783ba6f31cc3b4403ba6
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 unsigned int num_certs = 0;
384 SECStatus rv = SSL_PeerCertificateChain(nss_fd, NULL, &num_certs, 0);
385 DCHECK_EQ(SECSuccess, rv);
387 // The handshake on |nss_fd| may not have completed.
388 if (num_certs == 0)
389 return;
391 certs_.resize(num_certs);
392 const unsigned int expected_num_certs = num_certs;
393 rv = SSL_PeerCertificateChain(nss_fd, vector_as_array(&certs_),
394 &num_certs, expected_num_certs);
395 DCHECK_EQ(SECSuccess, rv);
396 DCHECK_EQ(expected_num_certs, num_certs);
399 std::vector<base::StringPiece>
400 PeerCertificateChain::AsStringPieceVector() const {
401 std::vector<base::StringPiece> v(certs_.size());
402 for (unsigned i = 0; i < certs_.size(); i++) {
403 v[i] = base::StringPiece(
404 reinterpret_cast<const char*>(certs_[i]->derCert.data),
405 certs_[i]->derCert.len);
408 return v;
411 // HandshakeState is a helper struct used to pass handshake state between
412 // the NSS task runner and the network task runner.
414 // It contains members that may be read or written on the NSS task runner,
415 // but which also need to be read from the network task runner. The NSS task
416 // runner will notify the network task runner whenever this state changes, so
417 // that the network task runner can safely make a copy, which avoids the need
418 // for locking.
419 struct HandshakeState {
420 HandshakeState() { Reset(); }
422 void Reset() {
423 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
424 next_proto.clear();
425 server_protos.clear();
426 channel_id_sent = false;
427 server_cert_chain.Reset(NULL);
428 server_cert = NULL;
429 resumed_handshake = false;
430 ssl_connection_status = 0;
433 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
434 // negotiated protocol stored in |next_proto|.
435 SSLClientSocket::NextProtoStatus next_proto_status;
436 std::string next_proto;
437 // If the server supports NPN, the protocols supported by the server.
438 std::string server_protos;
440 // True if a channel ID was sent.
441 bool channel_id_sent;
443 // List of DER-encoded X.509 DistinguishedName of certificate authorities
444 // allowed by the server.
445 std::vector<std::string> cert_authorities;
447 // Set when the handshake fully completes.
449 // The server certificate is first received from NSS as an NSS certificate
450 // chain (|server_cert_chain|) and then converted into a platform-specific
451 // X509Certificate object (|server_cert|). It's possible for some
452 // certificates to be successfully parsed by NSS, and not by the platform
453 // libraries (i.e.: when running within a sandbox, different parsing
454 // algorithms, etc), so it's not safe to assume that |server_cert| will
455 // always be non-NULL.
456 PeerCertificateChain server_cert_chain;
457 scoped_refptr<X509Certificate> server_cert;
459 // True if the current handshake was the result of TLS session resumption.
460 bool resumed_handshake;
462 // The negotiated security parameters (TLS version, cipher, extensions) of
463 // the SSL connection.
464 int ssl_connection_status;
467 // Client-side error mapping functions.
469 // Map NSS error code to network error code.
470 int MapNSSClientError(PRErrorCode err) {
471 switch (err) {
472 case SSL_ERROR_BAD_CERT_ALERT:
473 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
474 case SSL_ERROR_REVOKED_CERT_ALERT:
475 case SSL_ERROR_EXPIRED_CERT_ALERT:
476 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
477 case SSL_ERROR_UNKNOWN_CA_ALERT:
478 case SSL_ERROR_ACCESS_DENIED_ALERT:
479 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
480 default:
481 return MapNSSError(err);
485 // Map NSS error code from the first SSL handshake to network error code.
486 int MapNSSClientHandshakeError(PRErrorCode err) {
487 switch (err) {
488 // If the server closed on us, it is a protocol error.
489 // Some TLS-intolerant servers do this when we request TLS.
490 case PR_END_OF_FILE_ERROR:
491 return ERR_SSL_PROTOCOL_ERROR;
492 default:
493 return MapNSSClientError(err);
497 } // namespace
499 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
500 // able to marshal data between NSS functions and an underlying transport
501 // socket.
503 // All public functions are meant to be called from the network task runner,
504 // and any callbacks supplied will be invoked there as well, provided that
505 // Detach() has not been called yet.
507 /////////////////////////////////////////////////////////////////////////////
509 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
511 // Because NSS may block on either hardware or user input during operations
512 // such as signing, creating certificates, or locating private keys, the Core
513 // handles all of the interactions with the underlying NSS SSL socket, so
514 // that these blocking calls can be executed on a dedicated task runner.
516 // Note that the network task runner and the NSS task runner may be executing
517 // on the same thread. If that happens, then it's more performant to try to
518 // complete as much work as possible synchronously, even if it might block,
519 // rather than continually PostTask-ing to the same thread.
521 // Because NSS functions should only be called on the NSS task runner, while
522 // I/O resources should only be accessed on the network task runner, most
523 // public functions are implemented via three methods, each with different
524 // task runner affinities.
526 // In the single-threaded mode (where the network and NSS task runners run on
527 // the same thread), these are all attempted synchronously, while in the
528 // multi-threaded mode, message passing is used.
530 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
531 // DoHandshake)
532 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
533 // (BufferRecv, BufferSend)
534 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
535 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
536 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
537 // data from the network task runner back to NSS (BufferRecvComplete,
538 // BufferSendComplete, OnHandshakeIOComplete)
540 /////////////////////////////////////////////////////////////////////////////
541 // Single-threaded example
543 // |--------------------------Network Task Runner--------------------------|
544 // SSLClientSocketNSS Core (Transport Socket)
545 // Read()
546 // |-------------------------V
547 // Read()
548 // |
549 // DoPayloadRead()
550 // |
551 // BufferRecv()
552 // |
553 // DoBufferRecv()
554 // |-------------------------V
555 // Read()
556 // V-------------------------|
557 // BufferRecvComplete()
558 // |
559 // PostOrRunCallback()
560 // V-------------------------|
561 // (Read Callback)
563 /////////////////////////////////////////////////////////////////////////////
564 // Multi-threaded example:
566 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
567 // SSLClientSocketNSS Core Socket Core
568 // Read()
569 // |---------------------V
570 // Read()
571 // |-------------------------------V
572 // Read()
573 // |
574 // DoPayloadRead()
575 // |
576 // BufferRecv
577 // V-------------------------------|
578 // DoBufferRecv
579 // |----------------V
580 // Read()
581 // V----------------|
582 // BufferRecvComplete()
583 // |-------------------------------V
584 // BufferRecvComplete()
585 // |
586 // PostOrRunCallback()
587 // V-------------------------------|
588 // PostOrRunCallback()
589 // V---------------------|
590 // (Read Callback)
592 /////////////////////////////////////////////////////////////////////////////
593 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
594 public:
595 // Creates a new Core.
597 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
598 // that need to operate on the underlying transport, net log, or server
599 // bound certificate fetching will happen on the |network_task_runner|, so
600 // that their lifetimes match that of the owning SSLClientSocketNSS.
602 // The caller retains ownership of |transport|, |net_log|, and
603 // |server_bound_cert_service|, and they will not be accessed once Detach()
604 // has been called.
605 Core(base::SequencedTaskRunner* network_task_runner,
606 base::SequencedTaskRunner* nss_task_runner,
607 ClientSocketHandle* transport,
608 const HostPortPair& host_and_port,
609 const SSLConfig& ssl_config,
610 BoundNetLog* net_log,
611 ServerBoundCertService* server_bound_cert_service);
613 // Called on the network task runner.
614 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
615 // underlying memio implementation, to the Core. Returns true if the Core
616 // was successfully registered with the socket.
617 bool Init(PRFileDesc* socket, memio_Private* buffers);
619 // Called on the network task runner.
620 // Sets the predicted certificate chain that the peer will send, for use
621 // with the TLS CachedInfo extension. If called, it must not be called
622 // before Init() or after Connect().
623 void SetPredictedCertificates(
624 const std::vector<std::string>& predicted_certificates);
626 // Called on the network task runner.
628 // Attempts to perform an SSL handshake. If the handshake cannot be
629 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
630 // the network task runner once the handshake has completed. Otherwise,
631 // returns OK on success or a network error code on failure.
632 int Connect(const CompletionCallback& callback);
634 // Called on the network task runner.
635 // Signals that the resources owned by the network task runner are going
636 // away. No further callbacks will be invoked on the network task runner.
637 // May be called at any time.
638 void Detach();
640 // Called on the network task runner.
641 // Returns the current state of the underlying SSL socket. May be called at
642 // any time.
643 const HandshakeState& state() const { return network_handshake_state_; }
645 // Called on the network task runner.
646 // Read() and Write() mirror the net::Socket functions of the same name.
647 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
648 // task runner at a later point, unless the caller calls Detach().
649 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
650 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
652 // Called on the network task runner.
653 bool IsConnected();
654 bool HasPendingAsyncOperation();
655 bool HasUnhandledReceivedData();
657 private:
658 friend class base::RefCountedThreadSafe<Core>;
659 ~Core();
661 enum State {
662 STATE_NONE,
663 STATE_HANDSHAKE,
664 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
667 bool OnNSSTaskRunner() const;
668 bool OnNetworkTaskRunner() const;
670 ////////////////////////////////////////////////////////////////////////////
671 // Methods that are ONLY called on the NSS task runner:
672 ////////////////////////////////////////////////////////////////////////////
674 // Called by NSS during full handshakes to allow the application to
675 // verify the certificate. Instead of verifying the certificate in the midst
676 // of the handshake, SECSuccess is always returned and the peer's certificate
677 // is verified afterwards.
678 // This behaviour is an artifact of the original SSLClientSocketWin
679 // implementation, which could not verify the peer's certificate until after
680 // the handshake had completed, as well as bugs in NSS that prevent
681 // SSL_RestartHandshakeAfterCertReq from working.
682 static SECStatus OwnAuthCertHandler(void* arg,
683 PRFileDesc* socket,
684 PRBool checksig,
685 PRBool is_server);
687 // Callbacks called by NSS when the peer requests client certificate
688 // authentication.
689 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
690 // the arguments.
691 #if defined(NSS_PLATFORM_CLIENT_AUTH)
692 // When NSS has been integrated with awareness of the underlying system
693 // cryptographic libraries, this callback allows the caller to supply a
694 // native platform certificate and key for use by NSS. At most, one of
695 // either (result_certs, result_private_key) or (result_nss_certificate,
696 // result_nss_private_key) should be set.
697 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
698 static SECStatus PlatformClientAuthHandler(
699 void* arg,
700 PRFileDesc* socket,
701 CERTDistNames* ca_names,
702 CERTCertList** result_certs,
703 void** result_private_key,
704 CERTCertificate** result_nss_certificate,
705 SECKEYPrivateKey** result_nss_private_key);
706 #else
707 static SECStatus ClientAuthHandler(void* arg,
708 PRFileDesc* socket,
709 CERTDistNames* ca_names,
710 CERTCertificate** result_certificate,
711 SECKEYPrivateKey** result_private_key);
712 #endif
714 // Called by NSS once the handshake has completed.
715 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
716 static void HandshakeCallback(PRFileDesc* socket, void* arg);
718 // Handles an NSS error generated while handshaking or performing IO.
719 // Returns a network error code mapped from the original NSS error.
720 int HandleNSSError(PRErrorCode error, bool handshake_error);
722 int DoHandshakeLoop(int last_io_result);
723 int DoReadLoop(int result);
724 int DoWriteLoop(int result);
726 int DoHandshake();
727 int DoGetDBCertComplete(int result);
729 int DoPayloadRead();
730 int DoPayloadWrite();
732 bool DoTransportIO();
733 int BufferRecv();
734 int BufferSend();
736 void OnRecvComplete(int result);
737 void OnSendComplete(int result);
739 void DoConnectCallback(int result);
740 void DoReadCallback(int result);
741 void DoWriteCallback(int result);
743 // Client channel ID handler.
744 static SECStatus ClientChannelIDHandler(
745 void* arg,
746 PRFileDesc* socket,
747 SECKEYPublicKey **out_public_key,
748 SECKEYPrivateKey **out_private_key);
750 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
751 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
752 // and an error code otherwise.
753 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
754 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
755 // takes ownership of the |*cert| and |*key|.
756 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
758 // Updates the NSS and platform specific certificates.
759 void UpdateServerCert();
760 // Updates the nss_handshake_state_ with the negotiated security parameters.
761 void UpdateConnectionStatus();
762 // Record histograms for channel id support during full handshakes - resumed
763 // handshakes are ignored.
764 void RecordChannelIDSupport();
765 // UpdateNextProto gets any application-layer protocol that may have been
766 // negotiated by the TLS connection.
767 void UpdateNextProto();
769 ////////////////////////////////////////////////////////////////////////////
770 // Methods that are ONLY called on the network task runner:
771 ////////////////////////////////////////////////////////////////////////////
772 int DoBufferRecv(IOBuffer* buffer, int len);
773 int DoBufferSend(IOBuffer* buffer, int len);
774 int DoGetDomainBoundCert(const std::string& host,
775 const std::vector<uint8>& requested_cert_types);
777 void OnGetDomainBoundCertComplete(int result);
778 void OnHandshakeStateUpdated(const HandshakeState& state);
779 void OnNSSBufferUpdated(int amount_in_read_buffer);
780 void DidNSSRead(int result);
781 void DidNSSWrite(int result);
782 void RecordChannelIDSupportOnNetworkTaskRunner(
783 bool negotiated_channel_id,
784 bool channel_id_enabled,
785 bool supports_ecc) const;
787 ////////////////////////////////////////////////////////////////////////////
788 // Methods that are called on both the network task runner and the NSS
789 // task runner.
790 ////////////////////////////////////////////////////////////////////////////
791 void OnHandshakeIOComplete(int result);
792 void BufferRecvComplete(IOBuffer* buffer, int result);
793 void BufferSendComplete(int result);
795 // PostOrRunCallback is a helper function to ensure that |callback| is
796 // invoked on the network task runner, but only if Detach() has not yet
797 // been called.
798 void PostOrRunCallback(const tracked_objects::Location& location,
799 const base::Closure& callback);
801 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
802 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
803 void AddCertProvidedEvent(int cert_count);
805 // Sets the handshake state |channel_id_sent| flag and logs the
806 // SSL_CHANNEL_ID_PROVIDED event.
807 void SetChannelIDProvided();
809 ////////////////////////////////////////////////////////////////////////////
810 // Members that are ONLY accessed on the network task runner:
811 ////////////////////////////////////////////////////////////////////////////
813 // True if the owning SSLClientSocketNSS has called Detach(). No further
814 // callbacks will be invoked nor access to members owned by the network
815 // task runner.
816 bool detached_;
818 // The underlying transport to use for network IO.
819 ClientSocketHandle* transport_;
820 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
822 // The current handshake state. Mirrors |nss_handshake_state_|.
823 HandshakeState network_handshake_state_;
825 // The service for retrieving Channel ID keys. May be NULL.
826 ServerBoundCertService* server_bound_cert_service_;
827 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_;
829 // The information about NSS task runner.
830 int unhandled_buffer_size_;
831 bool nss_waiting_read_;
832 bool nss_waiting_write_;
833 bool nss_is_closed_;
835 ////////////////////////////////////////////////////////////////////////////
836 // Members that are ONLY accessed on the NSS task runner:
837 ////////////////////////////////////////////////////////////////////////////
838 HostPortPair host_and_port_;
839 SSLConfig ssl_config_;
841 // NSS SSL socket.
842 PRFileDesc* nss_fd_;
844 // Buffers for the network end of the SSL state machine
845 memio_Private* nss_bufs_;
847 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
848 // as much data as possible, without blocking.
849 // If DoPayloadRead() encounters an error after having read some data, stores
850 // the results to return on the *next* call to DoPayloadRead(). A value of
851 // kNoPendingReadResult indicates there is no pending result, otherwise 0
852 // indicates EOF and < 0 indicates an error.
853 int pending_read_result_;
854 // Contains the previously observed NSS error. Only valid when
855 // pending_read_result_ != kNoPendingReadResult.
856 PRErrorCode pending_read_nss_error_;
858 // The certificate chain, in DER form, that is expected to be received from
859 // the server.
860 std::vector<std::string> predicted_certs_;
862 State next_handshake_state_;
864 // True if channel ID extension was negotiated.
865 bool channel_id_xtn_negotiated_;
866 // True if the handshake state machine was interrupted for channel ID.
867 bool channel_id_needed_;
868 // True if the handshake state machine was interrupted for client auth.
869 bool client_auth_cert_needed_;
870 // True if NSS has called HandshakeCallback.
871 bool handshake_callback_called_;
873 HandshakeState nss_handshake_state_;
875 bool transport_recv_busy_;
876 bool transport_recv_eof_;
877 bool transport_send_busy_;
879 // Used by Read function.
880 scoped_refptr<IOBuffer> user_read_buf_;
881 int user_read_buf_len_;
883 // Used by Write function.
884 scoped_refptr<IOBuffer> user_write_buf_;
885 int user_write_buf_len_;
887 CompletionCallback user_connect_callback_;
888 CompletionCallback user_read_callback_;
889 CompletionCallback user_write_callback_;
891 ////////////////////////////////////////////////////////////////////////////
892 // Members that are accessed on both the network task runner and the NSS
893 // task runner.
894 ////////////////////////////////////////////////////////////////////////////
895 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
896 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
898 // Dereferenced only on the network task runner, but bound to tasks destined
899 // for the network task runner from the NSS task runner.
900 base::WeakPtr<BoundNetLog> weak_net_log_;
902 // Written on the network task runner by the |server_bound_cert_service_|,
903 // prior to invoking OnHandshakeIOComplete.
904 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
905 // on the NSS task runner.
906 SSLClientCertType domain_bound_cert_type_;
907 std::string domain_bound_private_key_;
908 std::string domain_bound_cert_;
910 DISALLOW_COPY_AND_ASSIGN(Core);
913 SSLClientSocketNSS::Core::Core(
914 base::SequencedTaskRunner* network_task_runner,
915 base::SequencedTaskRunner* nss_task_runner,
916 ClientSocketHandle* transport,
917 const HostPortPair& host_and_port,
918 const SSLConfig& ssl_config,
919 BoundNetLog* net_log,
920 ServerBoundCertService* server_bound_cert_service)
921 : detached_(false),
922 transport_(transport),
923 weak_net_log_factory_(net_log),
924 server_bound_cert_service_(server_bound_cert_service),
925 unhandled_buffer_size_(0),
926 nss_waiting_read_(false),
927 nss_waiting_write_(false),
928 nss_is_closed_(false),
929 host_and_port_(host_and_port),
930 ssl_config_(ssl_config),
931 nss_fd_(NULL),
932 nss_bufs_(NULL),
933 pending_read_result_(kNoPendingReadResult),
934 pending_read_nss_error_(0),
935 next_handshake_state_(STATE_NONE),
936 channel_id_xtn_negotiated_(false),
937 channel_id_needed_(false),
938 client_auth_cert_needed_(false),
939 handshake_callback_called_(false),
940 transport_recv_busy_(false),
941 transport_recv_eof_(false),
942 transport_send_busy_(false),
943 user_read_buf_len_(0),
944 user_write_buf_len_(0),
945 network_task_runner_(network_task_runner),
946 nss_task_runner_(nss_task_runner),
947 weak_net_log_(weak_net_log_factory_.GetWeakPtr()),
948 domain_bound_cert_type_(CLIENT_CERT_INVALID_TYPE) {
951 SSLClientSocketNSS::Core::~Core() {
952 // TODO(wtc): Send SSL close_notify alert.
953 if (nss_fd_ != NULL) {
954 PR_Close(nss_fd_);
955 nss_fd_ = NULL;
959 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
960 memio_Private* buffers) {
961 DCHECK(OnNetworkTaskRunner());
962 DCHECK(!nss_fd_);
963 DCHECK(!nss_bufs_);
965 nss_fd_ = socket;
966 nss_bufs_ = buffers;
968 SECStatus rv = SECSuccess;
970 if (!ssl_config_.next_protos.empty()) {
971 size_t wire_length = 0;
972 for (std::vector<std::string>::const_iterator
973 i = ssl_config_.next_protos.begin();
974 i != ssl_config_.next_protos.end(); ++i) {
975 if (i->size() > 255) {
976 LOG(WARNING) << "Ignoring overlong NPN/ALPN protocol: " << *i;
977 continue;
979 wire_length += i->size();
980 wire_length++;
982 scoped_ptr<uint8[]> wire_protos(new uint8[wire_length]);
983 uint8* dst = wire_protos.get();
984 for (std::vector<std::string>::const_iterator
985 i = ssl_config_.next_protos.begin();
986 i != ssl_config_.next_protos.end(); i++) {
987 if (i->size() > 255)
988 continue;
989 *dst++ = i->size();
990 memcpy(dst, i->data(), i->size());
991 dst += i->size();
993 DCHECK_EQ(dst, wire_protos.get() + wire_length);
994 rv = SSL_SetNextProtoNego(nss_fd_, wire_protos.get(), wire_length);
995 if (rv != SECSuccess)
996 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", "");
999 rv = SSL_AuthCertificateHook(
1000 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
1001 if (rv != SECSuccess) {
1002 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
1003 return false;
1006 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1007 rv = SSL_GetPlatformClientAuthDataHook(
1008 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
1009 this);
1010 #else
1011 rv = SSL_GetClientAuthDataHook(
1012 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
1013 #endif
1014 if (rv != SECSuccess) {
1015 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
1016 return false;
1019 if (ssl_config_.channel_id_enabled) {
1020 if (!server_bound_cert_service_) {
1021 DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
1022 } else if (!crypto::ECPrivateKey::IsSupported()) {
1023 DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
1024 } else if (!server_bound_cert_service_->IsSystemTimeValid()) {
1025 DVLOG(1) << "System time is weird, not enabling channel ID.";
1026 } else {
1027 rv = SSL_SetClientChannelIDCallback(
1028 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
1029 if (rv != SECSuccess)
1030 LogFailedNSSFunction(*weak_net_log_, "SSL_SetClientChannelIDCallback",
1031 "");
1035 rv = SSL_HandshakeCallback(
1036 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
1037 if (rv != SECSuccess) {
1038 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
1039 return false;
1042 return true;
1045 void SSLClientSocketNSS::Core::SetPredictedCertificates(
1046 const std::vector<std::string>& predicted_certs) {
1047 if (predicted_certs.empty())
1048 return;
1050 if (!OnNSSTaskRunner()) {
1051 DCHECK(!detached_);
1052 nss_task_runner_->PostTask(
1053 FROM_HERE,
1054 base::Bind(&Core::SetPredictedCertificates, this, predicted_certs));
1055 return;
1058 DCHECK(nss_fd_);
1060 predicted_certs_ = predicted_certs;
1062 scoped_ptr<CERTCertificate*[]> certs(
1063 new CERTCertificate*[predicted_certs.size()]);
1065 for (size_t i = 0; i < predicted_certs.size(); i++) {
1066 SECItem derCert;
1067 derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>(
1068 predicted_certs[i].data()));
1069 derCert.len = predicted_certs[i].size();
1070 certs[i] = CERT_NewTempCertificate(
1071 CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */,
1072 PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */);
1073 if (!certs[i]) {
1074 DestroyCertificates(&certs[0], i);
1075 NOTREACHED();
1076 return;
1080 SECStatus rv;
1081 #ifdef SSL_ENABLE_CACHED_INFO
1082 rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(),
1083 predicted_certs.size());
1084 DCHECK_EQ(SECSuccess, rv);
1085 #else
1086 rv = SECFailure; // Not implemented.
1087 #endif
1088 DestroyCertificates(&certs[0], predicted_certs.size());
1090 if (rv != SECSuccess) {
1091 LOG(WARNING) << "SetPredictedCertificates failed: "
1092 << host_and_port_.ToString();
1096 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1097 if (!OnNSSTaskRunner()) {
1098 DCHECK(!detached_);
1099 bool posted = nss_task_runner_->PostTask(
1100 FROM_HERE,
1101 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1102 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1105 DCHECK(OnNSSTaskRunner());
1106 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1107 DCHECK(user_read_callback_.is_null());
1108 DCHECK(user_write_callback_.is_null());
1109 DCHECK(user_connect_callback_.is_null());
1110 DCHECK(!user_read_buf_.get());
1111 DCHECK(!user_write_buf_.get());
1113 next_handshake_state_ = STATE_HANDSHAKE;
1114 int rv = DoHandshakeLoop(OK);
1115 if (rv == ERR_IO_PENDING) {
1116 user_connect_callback_ = callback;
1117 } else if (rv > OK) {
1118 rv = OK;
1120 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1121 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1122 return ERR_IO_PENDING;
1125 return rv;
1128 void SSLClientSocketNSS::Core::Detach() {
1129 DCHECK(OnNetworkTaskRunner());
1131 detached_ = true;
1132 transport_ = NULL;
1133 weak_net_log_factory_.InvalidateWeakPtrs();
1135 network_handshake_state_.Reset();
1137 domain_bound_cert_request_handle_.Cancel();
1140 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1141 const CompletionCallback& callback) {
1142 if (!OnNSSTaskRunner()) {
1143 DCHECK(OnNetworkTaskRunner());
1144 DCHECK(!detached_);
1145 DCHECK(transport_);
1146 DCHECK(!nss_waiting_read_);
1148 nss_waiting_read_ = true;
1149 bool posted = nss_task_runner_->PostTask(
1150 FROM_HERE,
1151 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1152 buf_len, callback));
1153 if (!posted) {
1154 nss_is_closed_ = true;
1155 nss_waiting_read_ = false;
1157 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1160 DCHECK(OnNSSTaskRunner());
1161 DCHECK(handshake_callback_called_);
1162 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1163 DCHECK(user_read_callback_.is_null());
1164 DCHECK(user_connect_callback_.is_null());
1165 DCHECK(!user_read_buf_.get());
1166 DCHECK(nss_bufs_);
1168 user_read_buf_ = buf;
1169 user_read_buf_len_ = buf_len;
1171 int rv = DoReadLoop(OK);
1172 if (rv == ERR_IO_PENDING) {
1173 if (OnNetworkTaskRunner())
1174 nss_waiting_read_ = true;
1175 user_read_callback_ = callback;
1176 } else {
1177 user_read_buf_ = NULL;
1178 user_read_buf_len_ = 0;
1180 if (!OnNetworkTaskRunner()) {
1181 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1182 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1183 return ERR_IO_PENDING;
1184 } else {
1185 DCHECK(!nss_waiting_read_);
1186 if (rv <= 0)
1187 nss_is_closed_ = true;
1191 return rv;
1194 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1195 const CompletionCallback& callback) {
1196 if (!OnNSSTaskRunner()) {
1197 DCHECK(OnNetworkTaskRunner());
1198 DCHECK(!detached_);
1199 DCHECK(transport_);
1200 DCHECK(!nss_waiting_write_);
1202 nss_waiting_write_ = true;
1203 bool posted = nss_task_runner_->PostTask(
1204 FROM_HERE,
1205 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1206 buf_len, callback));
1207 if (!posted) {
1208 nss_is_closed_ = true;
1209 nss_waiting_write_ = false;
1211 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1214 DCHECK(OnNSSTaskRunner());
1215 DCHECK(handshake_callback_called_);
1216 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1217 DCHECK(user_write_callback_.is_null());
1218 DCHECK(user_connect_callback_.is_null());
1219 DCHECK(!user_write_buf_.get());
1220 DCHECK(nss_bufs_);
1222 user_write_buf_ = buf;
1223 user_write_buf_len_ = buf_len;
1225 int rv = DoWriteLoop(OK);
1226 if (rv == ERR_IO_PENDING) {
1227 if (OnNetworkTaskRunner())
1228 nss_waiting_write_ = true;
1229 user_write_callback_ = callback;
1230 } else {
1231 user_write_buf_ = NULL;
1232 user_write_buf_len_ = 0;
1234 if (!OnNetworkTaskRunner()) {
1235 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1236 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1237 return ERR_IO_PENDING;
1238 } else {
1239 DCHECK(!nss_waiting_write_);
1240 if (rv < 0)
1241 nss_is_closed_ = true;
1245 return rv;
1248 bool SSLClientSocketNSS::Core::IsConnected() {
1249 DCHECK(OnNetworkTaskRunner());
1250 return !nss_is_closed_;
1253 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() {
1254 DCHECK(OnNetworkTaskRunner());
1255 return nss_waiting_read_ || nss_waiting_write_;
1258 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() {
1259 DCHECK(OnNetworkTaskRunner());
1260 return unhandled_buffer_size_ != 0;
1263 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1264 return nss_task_runner_->RunsTasksOnCurrentThread();
1267 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1268 return network_task_runner_->RunsTasksOnCurrentThread();
1271 // static
1272 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1273 void* arg,
1274 PRFileDesc* socket,
1275 PRBool checksig,
1276 PRBool is_server) {
1277 #ifdef SSL_ENABLE_FALSE_START
1278 Core* core = reinterpret_cast<Core*>(arg);
1279 if (!core->handshake_callback_called_) {
1280 // Only need to turn off False Start in the initial handshake. Also, it is
1281 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1282 // handshake" lock isn't already held, which will result in an assertion
1283 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1284 PRBool npn;
1285 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1286 ssl_next_proto_nego_xtn,
1287 &npn);
1288 if (rv != SECSuccess || !npn) {
1289 // If the server doesn't support NPN, then we don't do False Start with
1290 // it.
1291 SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE);
1294 #endif
1296 // Tell NSS to not verify the certificate.
1297 return SECSuccess;
1300 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1301 // static
1302 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1303 void* arg,
1304 PRFileDesc* socket,
1305 CERTDistNames* ca_names,
1306 CERTCertList** result_certs,
1307 void** result_private_key,
1308 CERTCertificate** result_nss_certificate,
1309 SECKEYPrivateKey** result_nss_private_key) {
1310 Core* core = reinterpret_cast<Core*>(arg);
1311 DCHECK(core->OnNSSTaskRunner());
1313 core->PostOrRunCallback(
1314 FROM_HERE,
1315 base::Bind(&AddLogEvent, core->weak_net_log_,
1316 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1318 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1319 #if defined(OS_WIN)
1320 if (core->ssl_config_.send_client_cert) {
1321 if (core->ssl_config_.client_cert) {
1322 PCCERT_CONTEXT cert_context =
1323 core->ssl_config_.client_cert->os_cert_handle();
1325 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1326 DWORD key_spec = 0;
1327 BOOL must_free = FALSE;
1328 DWORD flags = 0;
1329 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
1330 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
1332 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1333 cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
1335 if (acquired_key) {
1336 // Should never get a cached handle back - ownership must always be
1337 // transferred.
1338 CHECK_EQ(must_free, TRUE);
1340 SECItem der_cert;
1341 der_cert.type = siDERCertBuffer;
1342 der_cert.data = cert_context->pbCertEncoded;
1343 der_cert.len = cert_context->cbCertEncoded;
1345 // TODO(rsleevi): Error checking for NSS allocation errors.
1346 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1347 CERTCertificate* user_cert = CERT_NewTempCertificate(
1348 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1349 if (!user_cert) {
1350 // Importing the certificate can fail for reasons including a serial
1351 // number collision. See crbug.com/97355.
1352 core->AddCertProvidedEvent(0);
1353 return SECFailure;
1355 CERTCertList* cert_chain = CERT_NewCertList();
1356 CERT_AddCertToListTail(cert_chain, user_cert);
1358 // Add the intermediates.
1359 X509Certificate::OSCertHandles intermediates =
1360 core->ssl_config_.client_cert->GetIntermediateCertificates();
1361 for (X509Certificate::OSCertHandles::const_iterator it =
1362 intermediates.begin(); it != intermediates.end(); ++it) {
1363 der_cert.data = (*it)->pbCertEncoded;
1364 der_cert.len = (*it)->cbCertEncoded;
1366 CERTCertificate* intermediate = CERT_NewTempCertificate(
1367 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1368 if (!intermediate) {
1369 CERT_DestroyCertList(cert_chain);
1370 core->AddCertProvidedEvent(0);
1371 return SECFailure;
1373 CERT_AddCertToListTail(cert_chain, intermediate);
1375 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1376 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1377 key_context->cbSize = sizeof(*key_context);
1378 // NSS will free this context when no longer in use.
1379 key_context->hCryptProv = crypt_prov;
1380 key_context->dwKeySpec = key_spec;
1381 *result_private_key = key_context;
1382 *result_certs = cert_chain;
1384 int cert_count = 1 + intermediates.size();
1385 core->AddCertProvidedEvent(cert_count);
1386 return SECSuccess;
1388 LOG(WARNING) << "Client cert found without private key";
1391 // Send no client certificate.
1392 core->AddCertProvidedEvent(0);
1393 return SECFailure;
1396 core->nss_handshake_state_.cert_authorities.clear();
1398 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1399 for (int i = 0; i < ca_names->nnames; ++i) {
1400 issuer_list[i].cbData = ca_names->names[i].len;
1401 issuer_list[i].pbData = ca_names->names[i].data;
1402 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1403 reinterpret_cast<const char*>(ca_names->names[i].data),
1404 static_cast<size_t>(ca_names->names[i].len)));
1407 // Update the network task runner's view of the handshake state now that
1408 // server certificate request has been recorded.
1409 core->PostOrRunCallback(
1410 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1411 core->nss_handshake_state_));
1413 // Tell NSS to suspend the client authentication. We will then abort the
1414 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1415 return SECWouldBlock;
1416 #elif defined(OS_MACOSX)
1417 if (core->ssl_config_.send_client_cert) {
1418 if (core->ssl_config_.client_cert.get()) {
1419 OSStatus os_error = noErr;
1420 SecIdentityRef identity = NULL;
1421 SecKeyRef private_key = NULL;
1422 X509Certificate::OSCertHandles chain;
1424 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
1425 os_error = SecIdentityCreateWithCertificate(
1426 NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
1428 if (os_error == noErr) {
1429 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1430 CFRelease(identity);
1433 if (os_error == noErr) {
1434 // TODO(rsleevi): Error checking for NSS allocation errors.
1435 *result_certs = CERT_NewCertList();
1436 *result_private_key = private_key;
1438 chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
1439 const X509Certificate::OSCertHandles& intermediates =
1440 core->ssl_config_.client_cert->GetIntermediateCertificates();
1441 if (!intermediates.empty())
1442 chain.insert(chain.end(), intermediates.begin(), intermediates.end());
1444 for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
1445 CSSM_DATA cert_data;
1446 SecCertificateRef cert_ref = chain[i];
1447 os_error = SecCertificateGetData(cert_ref, &cert_data);
1448 if (os_error != noErr)
1449 break;
1451 SECItem der_cert;
1452 der_cert.type = siDERCertBuffer;
1453 der_cert.data = cert_data.Data;
1454 der_cert.len = cert_data.Length;
1455 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1456 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1457 if (!nss_cert) {
1458 // In the event of an NSS error, make up an OS error and reuse
1459 // the error handling below.
1460 os_error = errSecCreateChainFailed;
1461 break;
1463 CERT_AddCertToListTail(*result_certs, nss_cert);
1467 if (os_error == noErr) {
1468 core->AddCertProvidedEvent(chain.size());
1469 return SECSuccess;
1472 OSSTATUS_LOG(WARNING, os_error)
1473 << "Client cert found, but could not be used";
1474 if (*result_certs) {
1475 CERT_DestroyCertList(*result_certs);
1476 *result_certs = NULL;
1478 if (*result_private_key)
1479 *result_private_key = NULL;
1480 if (private_key)
1481 CFRelease(private_key);
1484 // Send no client certificate.
1485 core->AddCertProvidedEvent(0);
1486 return SECFailure;
1489 core->nss_handshake_state_.cert_authorities.clear();
1491 // Retrieve the cert issuers accepted by the server.
1492 std::vector<CertPrincipal> valid_issuers;
1493 int n = ca_names->nnames;
1494 for (int i = 0; i < n; i++) {
1495 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1496 reinterpret_cast<const char*>(ca_names->names[i].data),
1497 static_cast<size_t>(ca_names->names[i].len)));
1500 // Update the network task runner's view of the handshake state now that
1501 // server certificate request has been recorded.
1502 core->PostOrRunCallback(
1503 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1504 core->nss_handshake_state_));
1506 // Tell NSS to suspend the client authentication. We will then abort the
1507 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1508 return SECWouldBlock;
1509 #else
1510 return SECFailure;
1511 #endif
1514 #elif defined(OS_IOS)
1516 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1517 void* arg,
1518 PRFileDesc* socket,
1519 CERTDistNames* ca_names,
1520 CERTCertificate** result_certificate,
1521 SECKEYPrivateKey** result_private_key) {
1522 Core* core = reinterpret_cast<Core*>(arg);
1523 DCHECK(core->OnNSSTaskRunner());
1525 core->PostOrRunCallback(
1526 FROM_HERE,
1527 base::Bind(&AddLogEvent, core->weak_net_log_,
1528 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1530 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1531 LOG(WARNING) << "Client auth is not supported";
1533 // Never send a certificate.
1534 core->AddCertProvidedEvent(0);
1535 return SECFailure;
1538 #else // NSS_PLATFORM_CLIENT_AUTH
1540 // static
1541 // Based on Mozilla's NSS_GetClientAuthData.
1542 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1543 void* arg,
1544 PRFileDesc* socket,
1545 CERTDistNames* ca_names,
1546 CERTCertificate** result_certificate,
1547 SECKEYPrivateKey** result_private_key) {
1548 Core* core = reinterpret_cast<Core*>(arg);
1549 DCHECK(core->OnNSSTaskRunner());
1551 core->PostOrRunCallback(
1552 FROM_HERE,
1553 base::Bind(&AddLogEvent, core->weak_net_log_,
1554 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1556 // Regular client certificate requested.
1557 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1558 void* wincx = SSL_RevealPinArg(socket);
1560 if (core->ssl_config_.send_client_cert) {
1561 // Second pass: a client certificate should have been selected.
1562 if (core->ssl_config_.client_cert.get()) {
1563 CERTCertificate* cert =
1564 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1565 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1566 if (privkey) {
1567 // TODO(jsorianopastor): We should wait for server certificate
1568 // verification before sending our credentials. See
1569 // http://crbug.com/13934.
1570 *result_certificate = cert;
1571 *result_private_key = privkey;
1572 // A cert_count of -1 means the number of certificates is unknown.
1573 // NSS will construct the certificate chain.
1574 core->AddCertProvidedEvent(-1);
1576 return SECSuccess;
1578 LOG(WARNING) << "Client cert found without private key";
1580 // Send no client certificate.
1581 core->AddCertProvidedEvent(0);
1582 return SECFailure;
1585 // First pass: client certificate is needed.
1586 core->nss_handshake_state_.cert_authorities.clear();
1588 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1589 // the server and save them in |cert_authorities|.
1590 for (int i = 0; i < ca_names->nnames; i++) {
1591 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1592 reinterpret_cast<const char*>(ca_names->names[i].data),
1593 static_cast<size_t>(ca_names->names[i].len)));
1596 // Update the network task runner's view of the handshake state now that
1597 // server certificate request has been recorded.
1598 core->PostOrRunCallback(
1599 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1600 core->nss_handshake_state_));
1602 // Tell NSS to suspend the client authentication. We will then abort the
1603 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1604 return SECWouldBlock;
1606 #endif // NSS_PLATFORM_CLIENT_AUTH
1608 // static
1609 void SSLClientSocketNSS::Core::HandshakeCallback(
1610 PRFileDesc* socket,
1611 void* arg) {
1612 Core* core = reinterpret_cast<Core*>(arg);
1613 DCHECK(core->OnNSSTaskRunner());
1615 core->handshake_callback_called_ = true;
1617 HandshakeState* nss_state = &core->nss_handshake_state_;
1619 PRBool last_handshake_resumed;
1620 SECStatus rv = SSL_HandshakeResumedSession(socket, &last_handshake_resumed);
1621 if (rv == SECSuccess && last_handshake_resumed) {
1622 nss_state->resumed_handshake = true;
1623 } else {
1624 nss_state->resumed_handshake = false;
1627 core->RecordChannelIDSupport();
1628 core->UpdateServerCert();
1629 core->UpdateConnectionStatus();
1630 core->UpdateNextProto();
1632 // Update the network task runners view of the handshake state whenever
1633 // a handshake has completed.
1634 core->PostOrRunCallback(
1635 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1636 *nss_state));
1639 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error,
1640 bool handshake_error) {
1641 DCHECK(OnNSSTaskRunner());
1643 int net_error = handshake_error ? MapNSSClientHandshakeError(nss_error) :
1644 MapNSSClientError(nss_error);
1646 #if defined(OS_WIN)
1647 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1648 // os_cert_handle() as an optimization. However, if the certificate
1649 // private key is stored on a smart card, and the smart card is removed,
1650 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1651 // preventing client certificate authentication. Because the
1652 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1653 // caching in X509Certificate, this failure ends up preventing client
1654 // certificate authentication with the same certificate for all future
1655 // attempts, even after the smart card has been re-inserted. By setting
1656 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1657 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1658 // the certificate on the next attempt, which should succeed if the smart
1659 // card has been re-inserted, or will typically prompt the user to
1660 // re-insert the smart card if not.
1661 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1662 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1663 ssl_config_.send_client_cert && ssl_config_.client_cert) {
1664 CertSetCertificateContextProperty(
1665 ssl_config_.client_cert->os_cert_handle(),
1666 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1668 #endif
1670 return net_error;
1673 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1674 DCHECK(OnNSSTaskRunner());
1676 int rv = last_io_result;
1677 do {
1678 // Default to STATE_NONE for next state.
1679 State state = next_handshake_state_;
1680 GotoState(STATE_NONE);
1682 switch (state) {
1683 case STATE_HANDSHAKE:
1684 rv = DoHandshake();
1685 break;
1686 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1687 rv = DoGetDBCertComplete(rv);
1688 break;
1689 case STATE_NONE:
1690 default:
1691 rv = ERR_UNEXPECTED;
1692 LOG(DFATAL) << "unexpected state " << state;
1693 break;
1696 // Do the actual network I/O
1697 bool network_moved = DoTransportIO();
1698 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1699 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1700 // special case we keep looping even if rv is ERR_IO_PENDING because
1701 // the transport IO may allow DoHandshake to make progress.
1702 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1703 rv = OK; // This causes us to stay in the loop.
1705 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1706 return rv;
1709 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1710 DCHECK(OnNSSTaskRunner());
1711 DCHECK(handshake_callback_called_);
1712 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1714 if (result < 0)
1715 return result;
1717 if (!nss_bufs_) {
1718 LOG(DFATAL) << "!nss_bufs_";
1719 int rv = ERR_UNEXPECTED;
1720 PostOrRunCallback(
1721 FROM_HERE,
1722 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1723 NetLog::TYPE_SSL_READ_ERROR,
1724 CreateNetLogSSLErrorCallback(rv, 0)));
1725 return rv;
1728 bool network_moved;
1729 int rv;
1730 do {
1731 rv = DoPayloadRead();
1732 network_moved = DoTransportIO();
1733 } while (rv == ERR_IO_PENDING && network_moved);
1735 return rv;
1738 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1739 DCHECK(OnNSSTaskRunner());
1740 DCHECK(handshake_callback_called_);
1741 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1743 if (result < 0)
1744 return result;
1746 if (!nss_bufs_) {
1747 LOG(DFATAL) << "!nss_bufs_";
1748 int rv = ERR_UNEXPECTED;
1749 PostOrRunCallback(
1750 FROM_HERE,
1751 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1752 NetLog::TYPE_SSL_READ_ERROR,
1753 CreateNetLogSSLErrorCallback(rv, 0)));
1754 return rv;
1757 bool network_moved;
1758 int rv;
1759 do {
1760 rv = DoPayloadWrite();
1761 network_moved = DoTransportIO();
1762 } while (rv == ERR_IO_PENDING && network_moved);
1764 LeaveFunction(rv);
1765 return rv;
1768 int SSLClientSocketNSS::Core::DoHandshake() {
1769 DCHECK(OnNSSTaskRunner());
1771 int net_error = net::OK;
1772 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1774 // Note: this function may be called multiple times during the handshake, so
1775 // even though channel id and client auth are separate else cases, they can
1776 // both be used during a single SSL handshake.
1777 if (channel_id_needed_) {
1778 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1779 net_error = ERR_IO_PENDING;
1780 } else if (client_auth_cert_needed_) {
1781 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1782 PostOrRunCallback(
1783 FROM_HERE,
1784 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1785 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1786 CreateNetLogSSLErrorCallback(net_error, 0)));
1788 // If the handshake already succeeded (because the server requests but
1789 // doesn't require a client cert), we need to invalidate the SSL session
1790 // so that we won't try to resume the non-client-authenticated session in
1791 // the next handshake. This will cause the server to ask for a client
1792 // cert again.
1793 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
1794 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
1795 } else if (rv == SECSuccess) {
1796 if (!handshake_callback_called_) {
1797 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1798 // SSL_ForceHandshake returned SECSuccess prematurely.
1799 rv = SECFailure;
1800 net_error = ERR_SSL_PROTOCOL_ERROR;
1801 PostOrRunCallback(
1802 FROM_HERE,
1803 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1804 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1805 CreateNetLogSSLErrorCallback(net_error, 0)));
1806 } else {
1807 #if defined(SSL_ENABLE_OCSP_STAPLING)
1808 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1809 // system library and update IsOCSPStaplingSupported for Mac.
1810 if (IsOCSPStaplingSupported()) {
1811 const SECItemArray* ocsp_responses =
1812 SSL_PeerStapledOCSPResponses(nss_fd_);
1813 if (ocsp_responses->len) {
1814 #if defined(OS_WIN)
1815 if (nss_handshake_state_.server_cert) {
1816 CRYPT_DATA_BLOB ocsp_response_blob;
1817 ocsp_response_blob.cbData = ocsp_responses->items[0].len;
1818 ocsp_response_blob.pbData = ocsp_responses->items[0].data;
1819 BOOL ok = CertSetCertificateContextProperty(
1820 nss_handshake_state_.server_cert->os_cert_handle(),
1821 CERT_OCSP_RESPONSE_PROP_ID,
1822 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1823 &ocsp_response_blob);
1824 if (!ok) {
1825 VLOG(1) << "Failed to set OCSP response property: "
1826 << GetLastError();
1829 #elif defined(USE_NSS)
1830 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
1831 GetCacheOCSPResponseFromSideChannelFunction();
1833 cache_ocsp_response(
1834 CERT_GetDefaultCertDB(),
1835 nss_handshake_state_.server_cert_chain[0], PR_Now(),
1836 &ocsp_responses->items[0], NULL);
1837 #endif
1840 #endif
1842 // Done!
1843 } else {
1844 PRErrorCode prerr = PR_GetError();
1845 net_error = HandleNSSError(prerr, true);
1847 // Some network devices that inspect application-layer packets seem to
1848 // inject TCP reset packets to break the connections when they see
1849 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1851 // Only allow ERR_CONNECTION_RESET to trigger a fallback from TLS 1.1 or
1852 // 1.2. We don't lose much in this fallback because the explicit IV for CBC
1853 // mode in TLS 1.1 is approximated by record splitting in TLS 1.0. The
1854 // fallback will be more painful for TLS 1.2 when we have GCM support.
1856 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1857 // to trigger a version fallback in general, especially the TLS 1.0 ->
1858 // SSL 3.0 fallback, which would drop TLS extensions.
1859 if (prerr == PR_CONNECT_RESET_ERROR &&
1860 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1) {
1861 net_error = ERR_SSL_PROTOCOL_ERROR;
1864 // Some broken SSL devices negotiate TLS 1.0 when sent a TLS 1.1 or 1.2
1865 // ClientHello, but then return a bad-record-MAC alert. See
1866 // crbug.com/260358. In order to make the fallback as minimal as possible,
1867 // this fallback is only triggered for >= TLS 1.1.
1868 if (net_error == ERR_SSL_BAD_RECORD_MAC_ALERT &&
1869 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1_1) {
1870 net_error = ERR_SSL_PROTOCOL_ERROR;
1873 // If not done, stay in this state
1874 if (net_error == ERR_IO_PENDING) {
1875 GotoState(STATE_HANDSHAKE);
1876 } else {
1877 PostOrRunCallback(
1878 FROM_HERE,
1879 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1880 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1881 CreateNetLogSSLErrorCallback(net_error, prerr)));
1885 return net_error;
1888 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1889 SECStatus rv;
1890 PostOrRunCallback(
1891 FROM_HERE,
1892 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1893 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1895 channel_id_needed_ = false;
1897 if (result != OK)
1898 return result;
1900 SECKEYPublicKey* public_key;
1901 SECKEYPrivateKey* private_key;
1902 int error = ImportChannelIDKeys(&public_key, &private_key);
1903 if (error != OK)
1904 return error;
1906 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1907 if (rv != SECSuccess)
1908 return MapNSSError(PORT_GetError());
1910 SetChannelIDProvided();
1911 GotoState(STATE_HANDSHAKE);
1912 return OK;
1915 int SSLClientSocketNSS::Core::DoPayloadRead() {
1916 DCHECK(OnNSSTaskRunner());
1917 DCHECK(user_read_buf_.get());
1918 DCHECK_GT(user_read_buf_len_, 0);
1920 int rv;
1921 // If a previous greedy read resulted in an error that was not consumed (eg:
1922 // due to the caller having read some data successfully), then return that
1923 // pending error now.
1924 if (pending_read_result_ != kNoPendingReadResult) {
1925 rv = pending_read_result_;
1926 PRErrorCode prerr = pending_read_nss_error_;
1927 pending_read_result_ = kNoPendingReadResult;
1928 pending_read_nss_error_ = 0;
1930 if (rv == 0) {
1931 PostOrRunCallback(
1932 FROM_HERE,
1933 base::Bind(&LogByteTransferEvent, weak_net_log_,
1934 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1935 scoped_refptr<IOBuffer>(user_read_buf_)));
1936 } else {
1937 PostOrRunCallback(
1938 FROM_HERE,
1939 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1940 NetLog::TYPE_SSL_READ_ERROR,
1941 CreateNetLogSSLErrorCallback(rv, prerr)));
1943 return rv;
1946 // Perform a greedy read, attempting to read as much as the caller has
1947 // requested. In the current NSS implementation, PR_Read will return
1948 // exactly one SSL application data record's worth of data per invocation.
1949 // The record size is dictated by the server, and may be noticeably smaller
1950 // than the caller's buffer. This may be as little as a single byte, if the
1951 // server is performing 1/n-1 record splitting.
1953 // However, this greedy read may result in renegotiations/re-handshakes
1954 // happening or may lead to some data being read, followed by an EOF (such as
1955 // a TLS close-notify). If at least some data was read, then that result
1956 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1957 // data was read, it's safe to return the error or EOF immediately.
1958 int total_bytes_read = 0;
1959 do {
1960 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1961 user_read_buf_len_ - total_bytes_read);
1962 if (rv > 0)
1963 total_bytes_read += rv;
1964 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1965 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1966 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1967 amount_in_read_buffer));
1969 if (total_bytes_read == user_read_buf_len_) {
1970 // The caller's entire request was satisfied without error. No further
1971 // processing needed.
1972 rv = total_bytes_read;
1973 } else {
1974 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1975 // immediately, while the NSPR/NSS errors are still available in
1976 // thread-local storage. However, the handled/remapped error code should
1977 // only be returned if no application data was already read; if it was, the
1978 // error code should be deferred until the next call of DoPayloadRead.
1980 // If no data was read, |*next_result| will point to the return value of
1981 // this function. If at least some data was read, |*next_result| will point
1982 // to |pending_read_error_|, to be returned in a future call to
1983 // DoPayloadRead() (e.g.: after the current data is handled).
1984 int* next_result = &rv;
1985 if (total_bytes_read > 0) {
1986 pending_read_result_ = rv;
1987 rv = total_bytes_read;
1988 next_result = &pending_read_result_;
1991 if (client_auth_cert_needed_) {
1992 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1993 pending_read_nss_error_ = 0;
1994 } else if (*next_result < 0) {
1995 // If *next_result == 0, then that indicates EOF, and no special error
1996 // handling is needed.
1997 pending_read_nss_error_ = PR_GetError();
1998 *next_result = HandleNSSError(pending_read_nss_error_, false);
1999 if (rv > 0 && *next_result == ERR_IO_PENDING) {
2000 // If at least some data was read from PR_Read(), do not treat
2001 // insufficient data as an error to return in the next call to
2002 // DoPayloadRead() - instead, let the call fall through to check
2003 // PR_Read() again. This is because DoTransportIO() may complete
2004 // in between the next call to DoPayloadRead(), and thus it is
2005 // important to check PR_Read() on subsequent invocations to see
2006 // if a complete record may now be read.
2007 pending_read_nss_error_ = 0;
2008 pending_read_result_ = kNoPendingReadResult;
2013 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
2015 if (rv >= 0) {
2016 PostOrRunCallback(
2017 FROM_HERE,
2018 base::Bind(&LogByteTransferEvent, weak_net_log_,
2019 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
2020 scoped_refptr<IOBuffer>(user_read_buf_)));
2021 } else if (rv != ERR_IO_PENDING) {
2022 PostOrRunCallback(
2023 FROM_HERE,
2024 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2025 NetLog::TYPE_SSL_READ_ERROR,
2026 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
2027 pending_read_nss_error_ = 0;
2029 return rv;
2032 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2033 DCHECK(OnNSSTaskRunner());
2035 DCHECK(user_write_buf_.get());
2037 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2038 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2039 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2040 // PR_Write could potentially consume the unhandled data in the memio read
2041 // buffer if a renegotiation is in progress. If the buffer is consumed,
2042 // notify the latest buffer size to NetworkRunner.
2043 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
2044 PostOrRunCallback(
2045 FROM_HERE,
2046 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
2048 if (rv >= 0) {
2049 PostOrRunCallback(
2050 FROM_HERE,
2051 base::Bind(&LogByteTransferEvent, weak_net_log_,
2052 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2053 scoped_refptr<IOBuffer>(user_write_buf_)));
2054 return rv;
2056 PRErrorCode prerr = PR_GetError();
2057 if (prerr == PR_WOULD_BLOCK_ERROR)
2058 return ERR_IO_PENDING;
2060 rv = HandleNSSError(prerr, false);
2061 PostOrRunCallback(
2062 FROM_HERE,
2063 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2064 NetLog::TYPE_SSL_WRITE_ERROR,
2065 CreateNetLogSSLErrorCallback(rv, prerr)));
2066 return rv;
2069 // Do as much network I/O as possible between the buffer and the
2070 // transport socket. Return true if some I/O performed, false
2071 // otherwise (error or ERR_IO_PENDING).
2072 bool SSLClientSocketNSS::Core::DoTransportIO() {
2073 DCHECK(OnNSSTaskRunner());
2075 bool network_moved = false;
2076 if (nss_bufs_ != NULL) {
2077 int rv;
2078 // Read and write as much data as we can. The loop is neccessary
2079 // because Write() may return synchronously.
2080 do {
2081 rv = BufferSend();
2082 if (rv != ERR_IO_PENDING && rv != 0)
2083 network_moved = true;
2084 } while (rv > 0);
2085 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
2086 network_moved = true;
2088 return network_moved;
2091 int SSLClientSocketNSS::Core::BufferRecv() {
2092 DCHECK(OnNSSTaskRunner());
2094 if (transport_recv_busy_)
2095 return ERR_IO_PENDING;
2097 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2098 // determine how much data NSS wants to read. If NSS was not blocked,
2099 // this will return 0.
2100 int requested = memio_GetReadRequest(nss_bufs_);
2101 if (requested == 0) {
2102 // This is not a perfect match of error codes, as no operation is
2103 // actually pending. However, returning 0 would be interpreted as a
2104 // possible sign of EOF, which is also an inappropriate match.
2105 return ERR_IO_PENDING;
2108 char* buf;
2109 int nb = memio_GetReadParams(nss_bufs_, &buf);
2110 int rv;
2111 if (!nb) {
2112 // buffer too full to read into, so no I/O possible at moment
2113 rv = ERR_IO_PENDING;
2114 } else {
2115 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2116 if (OnNetworkTaskRunner()) {
2117 rv = DoBufferRecv(read_buffer.get(), nb);
2118 } else {
2119 bool posted = network_task_runner_->PostTask(
2120 FROM_HERE,
2121 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2122 nb));
2123 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2126 if (rv == ERR_IO_PENDING) {
2127 transport_recv_busy_ = true;
2128 } else {
2129 if (rv > 0) {
2130 memcpy(buf, read_buffer->data(), rv);
2131 } else if (rv == 0) {
2132 transport_recv_eof_ = true;
2134 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2137 return rv;
2140 // Return 0 if nss_bufs_ was empty,
2141 // > 0 for bytes transferred immediately,
2142 // < 0 for error (or the non-error ERR_IO_PENDING).
2143 int SSLClientSocketNSS::Core::BufferSend() {
2144 DCHECK(OnNSSTaskRunner());
2146 if (transport_send_busy_)
2147 return ERR_IO_PENDING;
2149 const char* buf1;
2150 const char* buf2;
2151 unsigned int len1, len2;
2152 memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2);
2153 const unsigned int len = len1 + len2;
2155 int rv = 0;
2156 if (len) {
2157 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2158 memcpy(send_buffer->data(), buf1, len1);
2159 memcpy(send_buffer->data() + len1, buf2, len2);
2161 if (OnNetworkTaskRunner()) {
2162 rv = DoBufferSend(send_buffer.get(), len);
2163 } else {
2164 bool posted = network_task_runner_->PostTask(
2165 FROM_HERE,
2166 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2167 len));
2168 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2171 if (rv == ERR_IO_PENDING) {
2172 transport_send_busy_ = true;
2173 } else {
2174 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2178 return rv;
2181 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2182 DCHECK(OnNSSTaskRunner());
2184 if (next_handshake_state_ == STATE_HANDSHAKE) {
2185 OnHandshakeIOComplete(result);
2186 return;
2189 // Network layer received some data, check if client requested to read
2190 // decrypted data.
2191 if (!user_read_buf_.get())
2192 return;
2194 int rv = DoReadLoop(result);
2195 if (rv != ERR_IO_PENDING)
2196 DoReadCallback(rv);
2199 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2200 DCHECK(OnNSSTaskRunner());
2202 if (next_handshake_state_ == STATE_HANDSHAKE) {
2203 OnHandshakeIOComplete(result);
2204 return;
2207 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2208 // handshake is in progress.
2209 int rv_read = ERR_IO_PENDING;
2210 int rv_write = ERR_IO_PENDING;
2211 bool network_moved;
2212 do {
2213 if (user_read_buf_.get())
2214 rv_read = DoPayloadRead();
2215 if (user_write_buf_.get())
2216 rv_write = DoPayloadWrite();
2217 network_moved = DoTransportIO();
2218 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
2219 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
2221 // If the parent SSLClientSocketNSS is deleted during the processing of the
2222 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2223 // will be detached (and possibly deleted). Guard against deletion by taking
2224 // an extra reference, then check if the Core was detached before invoking the
2225 // next callback.
2226 scoped_refptr<Core> guard(this);
2227 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
2228 DoReadCallback(rv_read);
2230 if (OnNetworkTaskRunner() && detached_)
2231 return;
2233 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
2234 DoWriteCallback(rv_write);
2237 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2238 // handshake. This requires network IO, which in turn calls
2239 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2240 // winds its way through the state machine and ends up being passed to the
2241 // callback. For Read() and Write(), that's what we want. But for Connect(),
2242 // the caller expects OK (i.e. 0) for success.
2243 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2244 DCHECK(OnNSSTaskRunner());
2245 DCHECK_NE(rv, ERR_IO_PENDING);
2246 DCHECK(!user_connect_callback_.is_null());
2248 base::Closure c = base::Bind(
2249 base::ResetAndReturn(&user_connect_callback_),
2250 rv > OK ? OK : rv);
2251 PostOrRunCallback(FROM_HERE, c);
2254 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2255 DCHECK(OnNSSTaskRunner());
2256 DCHECK_NE(ERR_IO_PENDING, rv);
2257 DCHECK(!user_read_callback_.is_null());
2259 user_read_buf_ = NULL;
2260 user_read_buf_len_ = 0;
2261 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2262 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2263 // the network task runner.
2264 PostOrRunCallback(
2265 FROM_HERE,
2266 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2267 PostOrRunCallback(
2268 FROM_HERE,
2269 base::Bind(&Core::DidNSSRead, this, rv));
2270 PostOrRunCallback(
2271 FROM_HERE,
2272 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
2275 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2276 DCHECK(OnNSSTaskRunner());
2277 DCHECK_NE(ERR_IO_PENDING, rv);
2278 DCHECK(!user_write_callback_.is_null());
2280 // Since Run may result in Write being called, clear |user_write_callback_|
2281 // up front.
2282 user_write_buf_ = NULL;
2283 user_write_buf_len_ = 0;
2284 // Update buffer status because DoWriteLoop called DoTransportIO which may
2285 // perform read operations.
2286 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2287 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2288 // the network task runner.
2289 PostOrRunCallback(
2290 FROM_HERE,
2291 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2292 PostOrRunCallback(
2293 FROM_HERE,
2294 base::Bind(&Core::DidNSSWrite, this, rv));
2295 PostOrRunCallback(
2296 FROM_HERE,
2297 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
2300 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
2301 void* arg,
2302 PRFileDesc* socket,
2303 SECKEYPublicKey **out_public_key,
2304 SECKEYPrivateKey **out_private_key) {
2305 Core* core = reinterpret_cast<Core*>(arg);
2306 DCHECK(core->OnNSSTaskRunner());
2308 core->PostOrRunCallback(
2309 FROM_HERE,
2310 base::Bind(&AddLogEvent, core->weak_net_log_,
2311 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
2313 // We have negotiated the TLS channel ID extension.
2314 core->channel_id_xtn_negotiated_ = true;
2315 std::string host = core->host_and_port_.host();
2316 std::vector<uint8> requested_cert_types;
2317 requested_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2318 int error = ERR_UNEXPECTED;
2319 if (core->OnNetworkTaskRunner()) {
2320 error = core->DoGetDomainBoundCert(host, requested_cert_types);
2321 } else {
2322 bool posted = core->network_task_runner_->PostTask(
2323 FROM_HERE,
2324 base::Bind(
2325 IgnoreResult(&Core::DoGetDomainBoundCert),
2326 core, host, requested_cert_types));
2327 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2330 if (error == ERR_IO_PENDING) {
2331 // Asynchronous case.
2332 core->channel_id_needed_ = true;
2333 return SECWouldBlock;
2336 core->PostOrRunCallback(
2337 FROM_HERE,
2338 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2339 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2340 SECStatus rv = SECSuccess;
2341 if (error == OK) {
2342 // Synchronous success.
2343 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2344 if (result == OK)
2345 core->SetChannelIDProvided();
2346 else
2347 rv = SECFailure;
2348 } else {
2349 rv = SECFailure;
2352 return rv;
2355 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2356 SECKEYPrivateKey** key) {
2357 // Set the certificate.
2358 SECItem cert_item;
2359 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2360 cert_item.len = domain_bound_cert_.size();
2361 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2362 &cert_item,
2363 NULL,
2364 PR_FALSE,
2365 PR_TRUE));
2366 if (cert == NULL)
2367 return MapNSSError(PORT_GetError());
2369 // Set the private key.
2370 switch (domain_bound_cert_type_) {
2371 case CLIENT_CERT_ECDSA_SIGN: {
2372 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2373 ServerBoundCertService::kEPKIPassword,
2374 reinterpret_cast<const unsigned char*>(
2375 domain_bound_private_key_.data()),
2376 domain_bound_private_key_.size(),
2377 &cert->subjectPublicKeyInfo,
2378 false,
2379 false,
2380 key,
2381 public_key)) {
2382 int error = MapNSSError(PORT_GetError());
2383 return error;
2385 break;
2388 default:
2389 NOTREACHED();
2390 return ERR_INVALID_ARGUMENT;
2393 return OK;
2396 void SSLClientSocketNSS::Core::UpdateServerCert() {
2397 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2398 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2399 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2400 if (nss_handshake_state_.server_cert.get()) {
2401 // Since this will be called asynchronously on another thread, it needs to
2402 // own a reference to the certificate.
2403 NetLog::ParametersCallback net_log_callback =
2404 base::Bind(&NetLogX509CertificateCallback,
2405 nss_handshake_state_.server_cert);
2406 PostOrRunCallback(
2407 FROM_HERE,
2408 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2409 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2410 net_log_callback));
2414 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2415 SSLChannelInfo channel_info;
2416 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2417 &channel_info, sizeof(channel_info));
2418 if (ok == SECSuccess &&
2419 channel_info.length == sizeof(channel_info) &&
2420 channel_info.cipherSuite) {
2421 nss_handshake_state_.ssl_connection_status |=
2422 (static_cast<int>(channel_info.cipherSuite) &
2423 SSL_CONNECTION_CIPHERSUITE_MASK) <<
2424 SSL_CONNECTION_CIPHERSUITE_SHIFT;
2426 nss_handshake_state_.ssl_connection_status |=
2427 (static_cast<int>(channel_info.compressionMethod) &
2428 SSL_CONNECTION_COMPRESSION_MASK) <<
2429 SSL_CONNECTION_COMPRESSION_SHIFT;
2431 // NSS 3.12.x doesn't have version macros for TLS 1.1 and 1.2 (because NSS
2432 // doesn't support them yet), so we use 0x0302 and 0x0303 directly.
2433 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2434 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2435 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2436 // version 2.
2437 version = SSL_CONNECTION_VERSION_SSL2;
2438 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2439 version = SSL_CONNECTION_VERSION_SSL3;
2440 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) {
2441 version = SSL_CONNECTION_VERSION_TLS1;
2442 } else if (channel_info.protocolVersion == 0x0302) {
2443 version = SSL_CONNECTION_VERSION_TLS1_1;
2444 } else if (channel_info.protocolVersion == 0x0303) {
2445 version = SSL_CONNECTION_VERSION_TLS1_2;
2447 nss_handshake_state_.ssl_connection_status |=
2448 (version & SSL_CONNECTION_VERSION_MASK) <<
2449 SSL_CONNECTION_VERSION_SHIFT;
2452 // SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6.
2453 // Since SSL_MAX_EXTENSIONS was added at the same time, we can test
2454 // SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension.
2455 #if defined(SSL_MAX_EXTENSIONS)
2456 PRBool peer_supports_renego_ext;
2457 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2458 &peer_supports_renego_ext);
2459 if (ok == SECSuccess) {
2460 if (!peer_supports_renego_ext) {
2461 nss_handshake_state_.ssl_connection_status |=
2462 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2463 // Log an informational message if the server does not support secure
2464 // renegotiation (RFC 5746).
2465 VLOG(1) << "The server " << host_and_port_.ToString()
2466 << " does not support the TLS renegotiation_info extension.";
2468 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2469 peer_supports_renego_ext, 2);
2471 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2472 // because of security concerns. For example, Google offers forward
2473 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2474 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2475 // secrecy.
2477 // Yngve from Opera has suggested using the renegotiation extension as an
2478 // indicator that SSLv3 fallback was mistaken:
2479 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2481 // As a first step, measure how often clients perform version fallback
2482 // while the server advertises support secure renegotiation.
2483 if (ssl_config_.version_fallback &&
2484 channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2485 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2486 peer_supports_renego_ext == PR_TRUE);
2489 #endif
2491 if (ssl_config_.version_fallback) {
2492 nss_handshake_state_.ssl_connection_status |=
2493 SSL_CONNECTION_VERSION_FALLBACK;
2497 void SSLClientSocketNSS::Core::UpdateNextProto() {
2498 uint8 buf[256];
2499 SSLNextProtoState state;
2500 unsigned buf_len;
2502 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2503 if (rv != SECSuccess)
2504 return;
2506 nss_handshake_state_.next_proto =
2507 std::string(reinterpret_cast<char*>(buf), buf_len);
2508 switch (state) {
2509 case SSL_NEXT_PROTO_NEGOTIATED:
2510 case SSL_NEXT_PROTO_SELECTED:
2511 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2512 break;
2513 case SSL_NEXT_PROTO_NO_OVERLAP:
2514 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2515 break;
2516 case SSL_NEXT_PROTO_NO_SUPPORT:
2517 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2518 break;
2519 default:
2520 NOTREACHED();
2521 break;
2525 void SSLClientSocketNSS::Core::RecordChannelIDSupport() {
2526 DCHECK(OnNSSTaskRunner());
2527 if (nss_handshake_state_.resumed_handshake)
2528 return;
2530 // Copy the NSS task runner-only state to the network task runner and
2531 // log histograms from there, since the histograms also need access to the
2532 // network task runner state.
2533 PostOrRunCallback(
2534 FROM_HERE,
2535 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2536 this,
2537 channel_id_xtn_negotiated_,
2538 ssl_config_.channel_id_enabled,
2539 crypto::ECPrivateKey::IsSupported()));
2542 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2543 bool negotiated_channel_id,
2544 bool channel_id_enabled,
2545 bool supports_ecc) const {
2546 DCHECK(OnNetworkTaskRunner());
2548 // Since this enum is used for a histogram, do not change or re-use values.
2549 enum {
2550 DISABLED = 0,
2551 CLIENT_ONLY = 1,
2552 CLIENT_AND_SERVER = 2,
2553 CLIENT_NO_ECC = 3,
2554 CLIENT_BAD_SYSTEM_TIME = 4,
2555 CLIENT_NO_SERVER_BOUND_CERT_SERVICE = 5,
2556 DOMAIN_BOUND_CERT_USAGE_MAX
2557 } supported = DISABLED;
2558 if (negotiated_channel_id) {
2559 supported = CLIENT_AND_SERVER;
2560 } else if (channel_id_enabled) {
2561 if (!server_bound_cert_service_)
2562 supported = CLIENT_NO_SERVER_BOUND_CERT_SERVICE;
2563 else if (!supports_ecc)
2564 supported = CLIENT_NO_ECC;
2565 else if (!server_bound_cert_service_->IsSystemTimeValid())
2566 supported = CLIENT_BAD_SYSTEM_TIME;
2567 else
2568 supported = CLIENT_ONLY;
2570 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported,
2571 DOMAIN_BOUND_CERT_USAGE_MAX);
2574 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2575 DCHECK(OnNetworkTaskRunner());
2576 DCHECK_GT(len, 0);
2578 if (detached_)
2579 return ERR_ABORTED;
2581 int rv = transport_->socket()->Read(
2582 read_buffer, len,
2583 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2584 scoped_refptr<IOBuffer>(read_buffer)));
2586 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2587 nss_task_runner_->PostTask(
2588 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2589 scoped_refptr<IOBuffer>(read_buffer), rv));
2590 return rv;
2593 return rv;
2596 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2597 DCHECK(OnNetworkTaskRunner());
2598 DCHECK_GT(len, 0);
2600 if (detached_)
2601 return ERR_ABORTED;
2603 int rv = transport_->socket()->Write(
2604 send_buffer, len,
2605 base::Bind(&Core::BufferSendComplete,
2606 base::Unretained(this)));
2608 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2609 nss_task_runner_->PostTask(
2610 FROM_HERE,
2611 base::Bind(&Core::BufferSendComplete, this, rv));
2612 return rv;
2615 return rv;
2618 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(
2619 const std::string& host,
2620 const std::vector<uint8>& requested_cert_types) {
2621 DCHECK(OnNetworkTaskRunner());
2623 if (detached_)
2624 return ERR_FAILED;
2626 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2628 int rv = server_bound_cert_service_->GetDomainBoundCert(
2629 host,
2630 requested_cert_types,
2631 &domain_bound_cert_type_,
2632 &domain_bound_private_key_,
2633 &domain_bound_cert_,
2634 base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)),
2635 &domain_bound_cert_request_handle_);
2637 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2638 nss_task_runner_->PostTask(
2639 FROM_HERE,
2640 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2641 return ERR_IO_PENDING;
2644 return rv;
2647 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2648 const HandshakeState& state) {
2649 DCHECK(OnNetworkTaskRunner());
2650 network_handshake_state_ = state;
2653 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2654 DCHECK(OnNetworkTaskRunner());
2655 unhandled_buffer_size_ = amount_in_read_buffer;
2658 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2659 DCHECK(OnNetworkTaskRunner());
2660 DCHECK(nss_waiting_read_);
2661 nss_waiting_read_ = false;
2662 if (result <= 0)
2663 nss_is_closed_ = true;
2666 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2667 DCHECK(OnNetworkTaskRunner());
2668 DCHECK(nss_waiting_write_);
2669 nss_waiting_write_ = false;
2670 if (result < 0)
2671 nss_is_closed_ = true;
2674 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2675 if (!OnNSSTaskRunner()) {
2676 if (detached_)
2677 return;
2679 nss_task_runner_->PostTask(
2680 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2681 return;
2684 DCHECK(OnNSSTaskRunner());
2686 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2687 transport_send_busy_ = false;
2688 OnSendComplete(result);
2691 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2692 if (!OnNSSTaskRunner()) {
2693 if (detached_)
2694 return;
2696 nss_task_runner_->PostTask(
2697 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2698 return;
2701 DCHECK(OnNSSTaskRunner());
2703 int rv = DoHandshakeLoop(result);
2704 if (rv != ERR_IO_PENDING)
2705 DoConnectCallback(rv);
2708 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) {
2709 DVLOG(1) << __FUNCTION__ << " " << result;
2710 DCHECK(OnNetworkTaskRunner());
2712 OnHandshakeIOComplete(result);
2715 void SSLClientSocketNSS::Core::BufferRecvComplete(
2716 IOBuffer* read_buffer,
2717 int result) {
2718 DCHECK(read_buffer);
2720 if (!OnNSSTaskRunner()) {
2721 if (detached_)
2722 return;
2724 nss_task_runner_->PostTask(
2725 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2726 scoped_refptr<IOBuffer>(read_buffer), result));
2727 return;
2730 DCHECK(OnNSSTaskRunner());
2732 if (result > 0) {
2733 char* buf;
2734 int nb = memio_GetReadParams(nss_bufs_, &buf);
2735 CHECK_GE(nb, result);
2736 memcpy(buf, read_buffer->data(), result);
2737 } else if (result == 0) {
2738 transport_recv_eof_ = true;
2741 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2742 transport_recv_busy_ = false;
2743 OnRecvComplete(result);
2746 void SSLClientSocketNSS::Core::PostOrRunCallback(
2747 const tracked_objects::Location& location,
2748 const base::Closure& task) {
2749 if (!OnNetworkTaskRunner()) {
2750 network_task_runner_->PostTask(
2751 FROM_HERE,
2752 base::Bind(&Core::PostOrRunCallback, this, location, task));
2753 return;
2756 if (detached_ || task.is_null())
2757 return;
2758 task.Run();
2761 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2762 PostOrRunCallback(
2763 FROM_HERE,
2764 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2765 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2766 NetLog::IntegerCallback("cert_count", cert_count)));
2769 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2770 PostOrRunCallback(
2771 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2772 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2773 nss_handshake_state_.channel_id_sent = true;
2774 // Update the network task runner's view of the handshake state now that
2775 // channel id has been sent.
2776 PostOrRunCallback(
2777 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2778 nss_handshake_state_));
2781 SSLClientSocketNSS::SSLClientSocketNSS(
2782 base::SequencedTaskRunner* nss_task_runner,
2783 ClientSocketHandle* transport_socket,
2784 const HostPortPair& host_and_port,
2785 const SSLConfig& ssl_config,
2786 const SSLClientSocketContext& context)
2787 : nss_task_runner_(nss_task_runner),
2788 transport_(transport_socket),
2789 host_and_port_(host_and_port),
2790 ssl_config_(ssl_config),
2791 cert_verifier_(context.cert_verifier),
2792 server_bound_cert_service_(context.server_bound_cert_service),
2793 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2794 completed_handshake_(false),
2795 next_handshake_state_(STATE_NONE),
2796 nss_fd_(NULL),
2797 net_log_(transport_socket->socket()->NetLog()),
2798 transport_security_state_(context.transport_security_state),
2799 valid_thread_id_(base::kInvalidThreadId) {
2800 EnterFunction("");
2801 InitCore();
2802 LeaveFunction("");
2805 SSLClientSocketNSS::~SSLClientSocketNSS() {
2806 EnterFunction("");
2807 Disconnect();
2808 LeaveFunction("");
2811 // static
2812 void SSLClientSocket::ClearSessionCache() {
2813 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2814 // bother initializing NSS just to clear an empty SSL session cache.
2815 if (!NSS_IsInitialized())
2816 return;
2818 SSL_ClearSessionCache();
2821 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2822 EnterFunction("");
2823 ssl_info->Reset();
2824 if (core_->state().server_cert_chain.empty() ||
2825 !core_->state().server_cert_chain[0]) {
2826 return false;
2829 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2830 ssl_info->cert = server_cert_verify_result_.verified_cert;
2831 ssl_info->connection_status =
2832 core_->state().ssl_connection_status;
2833 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2834 for (HashValueVector::const_iterator i = side_pinned_public_keys_.begin();
2835 i != side_pinned_public_keys_.end(); ++i) {
2836 ssl_info->public_key_hashes.push_back(*i);
2838 ssl_info->is_issued_by_known_root =
2839 server_cert_verify_result_.is_issued_by_known_root;
2840 ssl_info->client_cert_sent =
2841 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2842 ssl_info->channel_id_sent = WasChannelIDSent();
2844 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2845 core_->state().ssl_connection_status);
2846 SSLCipherSuiteInfo cipher_info;
2847 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2848 &cipher_info, sizeof(cipher_info));
2849 if (ok == SECSuccess) {
2850 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2851 } else {
2852 ssl_info->security_bits = -1;
2853 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2854 << " for cipherSuite " << cipher_suite;
2857 ssl_info->handshake_type = core_->state().resumed_handshake ?
2858 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2860 LeaveFunction("");
2861 return true;
2864 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2865 SSLCertRequestInfo* cert_request_info) {
2866 EnterFunction("");
2867 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2868 cert_request_info->host_and_port = host_and_port_.ToString();
2869 cert_request_info->cert_authorities = core_->state().cert_authorities;
2870 LeaveFunction("");
2873 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2874 bool has_context,
2875 const base::StringPiece& context,
2876 unsigned char* out,
2877 unsigned int outlen) {
2878 if (!IsConnected())
2879 return ERR_SOCKET_NOT_CONNECTED;
2881 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2882 // the midst of a handshake.
2883 SECStatus result = SSL_ExportKeyingMaterial(
2884 nss_fd_, label.data(), label.size(), has_context,
2885 reinterpret_cast<const unsigned char*>(context.data()),
2886 context.length(), out, outlen);
2887 if (result != SECSuccess) {
2888 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2889 return MapNSSError(PORT_GetError());
2891 return OK;
2894 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2895 if (!IsConnected())
2896 return ERR_SOCKET_NOT_CONNECTED;
2897 unsigned char buf[64];
2898 unsigned int len;
2899 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2900 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2901 buf, &len, arraysize(buf));
2902 if (result != SECSuccess) {
2903 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2904 return MapNSSError(PORT_GetError());
2906 out->assign(reinterpret_cast<char*>(buf), len);
2907 return OK;
2910 SSLClientSocket::NextProtoStatus
2911 SSLClientSocketNSS::GetNextProto(std::string* proto,
2912 std::string* server_protos) {
2913 *proto = core_->state().next_proto;
2914 *server_protos = core_->state().server_protos;
2915 return core_->state().next_proto_status;
2918 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2919 EnterFunction("");
2920 DCHECK(transport_.get());
2921 // It is an error to create an SSLClientSocket whose context has no
2922 // TransportSecurityState.
2923 DCHECK(transport_security_state_);
2924 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2925 DCHECK(user_connect_callback_.is_null());
2926 DCHECK(!callback.is_null());
2928 EnsureThreadIdAssigned();
2930 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2932 int rv = Init();
2933 if (rv != OK) {
2934 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2935 return rv;
2938 rv = InitializeSSLOptions();
2939 if (rv != OK) {
2940 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2941 return rv;
2944 rv = InitializeSSLPeerName();
2945 if (rv != OK) {
2946 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2947 return rv;
2950 GotoState(STATE_HANDSHAKE);
2952 rv = DoHandshakeLoop(OK);
2953 if (rv == ERR_IO_PENDING) {
2954 user_connect_callback_ = callback;
2955 } else {
2956 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2959 LeaveFunction("");
2960 return rv > OK ? OK : rv;
2963 void SSLClientSocketNSS::Disconnect() {
2964 EnterFunction("");
2966 CHECK(CalledOnValidThread());
2968 // Shut down anything that may call us back.
2969 core_->Detach();
2970 verifier_.reset();
2971 transport_->socket()->Disconnect();
2973 // Reset object state.
2974 user_connect_callback_.Reset();
2975 server_cert_verify_result_.Reset();
2976 completed_handshake_ = false;
2977 start_cert_verification_time_ = base::TimeTicks();
2978 InitCore();
2980 LeaveFunction("");
2983 bool SSLClientSocketNSS::IsConnected() const {
2984 EnterFunction("");
2985 bool ret = completed_handshake_ &&
2986 (core_->HasPendingAsyncOperation() ||
2987 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2988 transport_->socket()->IsConnected());
2989 LeaveFunction("");
2990 return ret;
2993 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2994 EnterFunction("");
2995 bool ret = completed_handshake_ &&
2996 !core_->HasPendingAsyncOperation() &&
2997 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
2998 transport_->socket()->IsConnectedAndIdle();
2999 LeaveFunction("");
3000 return ret;
3003 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
3004 return transport_->socket()->GetPeerAddress(address);
3007 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
3008 return transport_->socket()->GetLocalAddress(address);
3011 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
3012 return net_log_;
3015 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3016 if (transport_.get() && transport_->socket()) {
3017 transport_->socket()->SetSubresourceSpeculation();
3018 } else {
3019 NOTREACHED();
3023 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3024 if (transport_.get() && transport_->socket()) {
3025 transport_->socket()->SetOmniboxSpeculation();
3026 } else {
3027 NOTREACHED();
3031 bool SSLClientSocketNSS::WasEverUsed() const {
3032 if (transport_.get() && transport_->socket()) {
3033 return transport_->socket()->WasEverUsed();
3035 NOTREACHED();
3036 return false;
3039 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3040 if (transport_.get() && transport_->socket()) {
3041 return transport_->socket()->UsingTCPFastOpen();
3043 NOTREACHED();
3044 return false;
3047 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
3048 const CompletionCallback& callback) {
3049 DCHECK(core_.get());
3050 DCHECK(!callback.is_null());
3052 EnterFunction(buf_len);
3053 int rv = core_->Read(buf, buf_len, callback);
3054 LeaveFunction(rv);
3056 return rv;
3059 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
3060 const CompletionCallback& callback) {
3061 DCHECK(core_.get());
3062 DCHECK(!callback.is_null());
3064 EnterFunction(buf_len);
3065 int rv = core_->Write(buf, buf_len, callback);
3066 LeaveFunction(rv);
3068 return rv;
3071 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
3072 return transport_->socket()->SetReceiveBufferSize(size);
3075 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
3076 return transport_->socket()->SetSendBufferSize(size);
3079 int SSLClientSocketNSS::Init() {
3080 EnterFunction("");
3081 // Initialize the NSS SSL library in a threadsafe way. This also
3082 // initializes the NSS base library.
3083 EnsureNSSSSLInit();
3084 if (!NSS_IsInitialized())
3085 return ERR_UNEXPECTED;
3086 #if defined(USE_NSS) || defined(OS_IOS)
3087 if (ssl_config_.cert_io_enabled) {
3088 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3089 // loop by MessageLoopForIO::current().
3090 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3091 EnsureNSSHttpIOInit();
3093 #endif
3095 LeaveFunction("");
3096 return OK;
3099 void SSLClientSocketNSS::InitCore() {
3100 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
3101 nss_task_runner_.get(),
3102 transport_.get(),
3103 host_and_port_,
3104 ssl_config_,
3105 &net_log_,
3106 server_bound_cert_service_);
3109 int SSLClientSocketNSS::InitializeSSLOptions() {
3110 // Transport connected, now hook it up to nss
3111 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3112 if (nss_fd_ == NULL) {
3113 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3116 // Grab pointer to buffers
3117 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3119 /* Create SSL state machine */
3120 /* Push SSL onto our fake I/O socket */
3121 nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
3122 if (nss_fd_ == NULL) {
3123 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3124 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3126 // TODO(port): set more ssl options! Check errors!
3128 int rv;
3130 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3131 if (rv != SECSuccess) {
3132 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3133 return ERR_UNEXPECTED;
3136 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3137 if (rv != SECSuccess) {
3138 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3139 return ERR_UNEXPECTED;
3142 // Don't do V2 compatible hellos because they don't support TLS extensions.
3143 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3144 if (rv != SECSuccess) {
3145 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3146 return ERR_UNEXPECTED;
3149 SSLVersionRange version_range;
3150 version_range.min = ssl_config_.version_min;
3151 version_range.max = ssl_config_.version_max;
3152 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3153 if (rv != SECSuccess) {
3154 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3155 return ERR_NO_SSL_VERSIONS_ENABLED;
3158 for (std::vector<uint16>::const_iterator it =
3159 ssl_config_.disabled_cipher_suites.begin();
3160 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3161 // This will fail if the specified cipher is not implemented by NSS, but
3162 // the failure is harmless.
3163 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3166 #ifdef SSL_ENABLE_SESSION_TICKETS
3167 // Support RFC 5077
3168 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3169 if (rv != SECSuccess) {
3170 LogFailedNSSFunction(
3171 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3173 #else
3174 #error "You need to install NSS-3.12 or later to build chromium"
3175 #endif
3177 #ifdef SSL_ENABLE_FALSE_START
3178 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3179 ssl_config_.false_start_enabled);
3180 if (rv != SECSuccess)
3181 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3182 #endif
3184 #ifdef SSL_ENABLE_RENEGOTIATION
3185 // We allow servers to request renegotiation. Since we're a client,
3186 // prohibiting this is rather a waste of time. Only servers are in a
3187 // position to prevent renegotiation attacks.
3188 // http://extendedsubset.com/?p=8
3190 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3191 SSL_RENEGOTIATE_TRANSITIONAL);
3192 if (rv != SECSuccess) {
3193 LogFailedNSSFunction(
3194 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3196 #endif // SSL_ENABLE_RENEGOTIATION
3198 #ifdef SSL_CBC_RANDOM_IV
3199 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
3200 if (rv != SECSuccess)
3201 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3202 #endif
3204 #ifdef SSL_ENABLE_OCSP_STAPLING
3205 if (IsOCSPStaplingSupported()) {
3206 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE);
3207 if (rv != SECSuccess) {
3208 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3209 "SSL_ENABLE_OCSP_STAPLING");
3212 #endif
3214 #ifdef SSL_ENABLE_CACHED_INFO
3215 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO,
3216 ssl_config_.cached_info_enabled);
3217 if (rv != SECSuccess)
3218 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3219 #endif
3221 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3222 if (rv != SECSuccess) {
3223 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3224 return ERR_UNEXPECTED;
3227 if (!core_->Init(nss_fd_, nss_bufs))
3228 return ERR_UNEXPECTED;
3230 // Tell SSL the hostname we're trying to connect to.
3231 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3233 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3234 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3236 return OK;
3239 int SSLClientSocketNSS::InitializeSSLPeerName() {
3240 // Tell NSS who we're connected to
3241 IPEndPoint peer_address;
3242 int err = transport_->socket()->GetPeerAddress(&peer_address);
3243 if (err != OK)
3244 return err;
3246 SockaddrStorage storage;
3247 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3248 return ERR_UNEXPECTED;
3250 PRNetAddr peername;
3251 memset(&peername, 0, sizeof(peername));
3252 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3253 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3254 sizeof(peername));
3255 memcpy(&peername, storage.addr, len);
3257 // Adjust the address family field for BSD, whose sockaddr
3258 // structure has a one-byte length and one-byte address family
3259 // field at the beginning. PRNetAddr has a two-byte address
3260 // family field at the beginning.
3261 peername.raw.family = storage.addr->sa_family;
3263 memio_SetPeerName(nss_fd_, &peername);
3265 // Set the peer ID for session reuse. This is necessary when we create an
3266 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3267 // rather than the destination server's address in that case.
3268 std::string peer_id = host_and_port_.ToString();
3269 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3270 // This will cause session cache misses between sockets with different values
3271 // of ssl_session_cache_shard_ and this is used to partition the session cache
3272 // for incognito mode.
3273 if (!ssl_session_cache_shard_.empty()) {
3274 peer_id += "/" + ssl_session_cache_shard_;
3276 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3277 if (rv != SECSuccess)
3278 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3280 return OK;
3283 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3284 EnterFunction(rv);
3285 DCHECK_NE(ERR_IO_PENDING, rv);
3286 DCHECK(!user_connect_callback_.is_null());
3288 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3289 LeaveFunction("");
3292 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3293 EnterFunction(result);
3294 int rv = DoHandshakeLoop(result);
3295 if (rv != ERR_IO_PENDING) {
3296 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3297 DoConnectCallback(rv);
3299 LeaveFunction("");
3302 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3303 EnterFunction(last_io_result);
3304 int rv = last_io_result;
3305 do {
3306 // Default to STATE_NONE for next state.
3307 // (This is a quirk carried over from the windows
3308 // implementation. It makes reading the logs a bit harder.)
3309 // State handlers can and often do call GotoState just
3310 // to stay in the current state.
3311 State state = next_handshake_state_;
3312 GotoState(STATE_NONE);
3313 switch (state) {
3314 case STATE_HANDSHAKE:
3315 rv = DoHandshake();
3316 break;
3317 case STATE_HANDSHAKE_COMPLETE:
3318 rv = DoHandshakeComplete(rv);
3319 break;
3320 case STATE_VERIFY_CERT:
3321 DCHECK(rv == OK);
3322 rv = DoVerifyCert(rv);
3323 break;
3324 case STATE_VERIFY_CERT_COMPLETE:
3325 rv = DoVerifyCertComplete(rv);
3326 break;
3327 case STATE_NONE:
3328 default:
3329 rv = ERR_UNEXPECTED;
3330 LOG(DFATAL) << "unexpected state " << state;
3331 break;
3333 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3334 LeaveFunction("");
3335 return rv;
3338 int SSLClientSocketNSS::DoHandshake() {
3339 EnterFunction("");
3340 int rv = core_->Connect(
3341 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3342 base::Unretained(this)));
3343 GotoState(STATE_HANDSHAKE_COMPLETE);
3345 LeaveFunction(rv);
3346 return rv;
3349 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3350 EnterFunction(result);
3352 if (result == OK) {
3353 // SSL handshake is completed. Let's verify the certificate.
3354 GotoState(STATE_VERIFY_CERT);
3355 // Done!
3357 set_channel_id_sent(core_->state().channel_id_sent);
3359 LeaveFunction(result);
3360 return result;
3364 int SSLClientSocketNSS::DoVerifyCert(int result) {
3365 DCHECK(!core_->state().server_cert_chain.empty());
3366 DCHECK(core_->state().server_cert_chain[0]);
3368 GotoState(STATE_VERIFY_CERT_COMPLETE);
3370 // If the certificate is expected to be bad we can use the expectation as
3371 // the cert status.
3372 base::StringPiece der_cert(
3373 reinterpret_cast<char*>(
3374 core_->state().server_cert_chain[0]->derCert.data),
3375 core_->state().server_cert_chain[0]->derCert.len);
3376 CertStatus cert_status;
3377 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3378 DCHECK(start_cert_verification_time_.is_null());
3379 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3380 server_cert_verify_result_.Reset();
3381 server_cert_verify_result_.cert_status = cert_status;
3382 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3383 return OK;
3386 // We may have failed to create X509Certificate object if we are
3387 // running inside sandbox.
3388 if (!core_->state().server_cert.get()) {
3389 server_cert_verify_result_.Reset();
3390 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3391 return ERR_CERT_INVALID;
3394 start_cert_verification_time_ = base::TimeTicks::Now();
3396 int flags = 0;
3397 if (ssl_config_.rev_checking_enabled)
3398 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3399 if (ssl_config_.verify_ev_cert)
3400 flags |= CertVerifier::VERIFY_EV_CERT;
3401 if (ssl_config_.cert_io_enabled)
3402 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3403 if (ssl_config_.rev_checking_required_local_anchors)
3404 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3405 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3406 return verifier_->Verify(
3407 core_->state().server_cert.get(),
3408 host_and_port_.host(),
3409 flags,
3410 SSLConfigService::GetCRLSet().get(),
3411 &server_cert_verify_result_,
3412 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3413 base::Unretained(this)),
3414 net_log_);
3417 // Derived from AuthCertificateCallback() in
3418 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3419 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3420 verifier_.reset();
3422 if (!start_cert_verification_time_.is_null()) {
3423 base::TimeDelta verify_time =
3424 base::TimeTicks::Now() - start_cert_verification_time_;
3425 if (result == OK)
3426 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3427 else
3428 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3431 // We used to remember the intermediate CA certs in the NSS database
3432 // persistently. However, NSS opens a connection to the SQLite database
3433 // during NSS initialization and doesn't close the connection until NSS
3434 // shuts down. If the file system where the database resides is gone,
3435 // the database connection goes bad. What's worse, the connection won't
3436 // recover when the file system comes back. Until this NSS or SQLite bug
3437 // is fixed, we need to avoid using the NSS database for non-essential
3438 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3439 // http://crbug.com/15630 for more info.
3441 // TODO(hclam): Skip logging if server cert was expected to be bad because
3442 // |server_cert_verify_result_| doesn't contain all the information about
3443 // the cert.
3444 if (result == OK)
3445 LogConnectionTypeMetrics();
3447 completed_handshake_ = true;
3449 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) && !defined(OS_IOS)
3450 // Take care of any mandates for public key pinning.
3452 // Pinning is only enabled for official builds to make sure that others don't
3453 // end up with pins that cannot be easily updated.
3455 // TODO(agl): We might have an issue here where a request for foo.example.com
3456 // merges into a SPDY connection to www.example.com, and gets a different
3457 // certificate.
3459 // Perform pin validation if, and only if, all these conditions obtain:
3461 // * a TransportSecurityState object is available;
3462 // * the server's certificate chain is valid (or suffers from only a minor
3463 // error);
3464 // * the server's certificate chain chains up to a known root (i.e. not a
3465 // user-installed trust anchor); and
3466 // * the build is recent (very old builds should fail open so that users
3467 // have some chance to recover).
3469 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3470 if (transport_security_state_ &&
3471 (result == OK ||
3472 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3473 server_cert_verify_result_.is_issued_by_known_root &&
3474 TransportSecurityState::IsBuildTimely()) {
3475 bool sni_available =
3476 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
3477 ssl_config_.version_fallback;
3478 const std::string& host = host_and_port_.host();
3480 TransportSecurityState::DomainState domain_state;
3481 if (transport_security_state_->GetDomainState(host, sni_available,
3482 &domain_state) &&
3483 domain_state.HasPublicKeyPins()) {
3484 if (!domain_state.CheckPublicKeyPins(
3485 server_cert_verify_result_.public_key_hashes)) {
3486 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3487 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3488 TransportSecurityState::ReportUMAOnPinFailure(host);
3489 } else {
3490 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3494 #endif
3496 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3497 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3498 return result;
3501 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3502 UpdateConnectionTypeHistograms(CONNECTION_SSL);
3503 int ssl_version = SSLConnectionStatusToVersion(
3504 core_->state().ssl_connection_status);
3505 switch (ssl_version) {
3506 case SSL_CONNECTION_VERSION_SSL2:
3507 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2);
3508 break;
3509 case SSL_CONNECTION_VERSION_SSL3:
3510 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3);
3511 break;
3512 case SSL_CONNECTION_VERSION_TLS1:
3513 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1);
3514 break;
3515 case SSL_CONNECTION_VERSION_TLS1_1:
3516 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1);
3517 break;
3518 case SSL_CONNECTION_VERSION_TLS1_2:
3519 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2);
3520 break;
3524 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3525 base::AutoLock auto_lock(lock_);
3526 if (valid_thread_id_ != base::kInvalidThreadId)
3527 return;
3528 valid_thread_id_ = base::PlatformThread::CurrentId();
3531 bool SSLClientSocketNSS::CalledOnValidThread() const {
3532 EnsureThreadIdAssigned();
3533 base::AutoLock auto_lock(lock_);
3534 return valid_thread_id_ == base::PlatformThread::CurrentId();
3537 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const {
3538 return server_bound_cert_service_;
3541 } // namespace net