[content shell] implement testRunner.overridePreference
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blobf75b5f81d44a23a669d1cc27a7d8f80274dedc68
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/string_number_conversions.h"
77 #include "base/string_util.h"
78 #include "base/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/asn1_util.h"
89 #include "net/base/cert_status_flags.h"
90 #include "net/base/cert_verifier.h"
91 #include "net/base/connection_type_histograms.h"
92 #include "net/base/dns_util.h"
93 #include "net/base/transport_security_state.h"
94 #include "net/base/io_buffer.h"
95 #include "net/base/net_errors.h"
96 #include "net/base/net_log.h"
97 #include "net/base/single_request_cert_verifier.h"
98 #include "net/base/ssl_cert_request_info.h"
99 #include "net/base/ssl_connection_status_flags.h"
100 #include "net/base/ssl_info.h"
101 #include "net/base/x509_certificate_net_log_param.h"
102 #include "net/base/x509_util.h"
103 #include "net/ocsp/nss_ocsp.h"
104 #include "net/socket/client_socket_handle.h"
105 #include "net/socket/nss_ssl_util.h"
106 #include "net/socket/ssl_error_params.h"
108 #if defined(OS_WIN)
109 #include <windows.h>
110 #include <wincrypt.h>
111 #elif defined(OS_MACOSX)
112 #include <Security/SecBase.h>
113 #include <Security/SecCertificate.h>
114 #include <Security/SecIdentity.h>
115 #include "base/mac/mac_logging.h"
116 #elif defined(USE_NSS)
117 #include <dlfcn.h>
118 #endif
120 // SSL plaintext fragments are shorter than 16KB. Although the record layer
121 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
122 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
123 // entire SSL record.
124 static const int kRecvBufferSize = 17 * 1024;
125 static const int kSendBufferSize = 17 * 1024;
127 #if defined(OS_WIN)
128 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
129 // set on Windows XP without error. There is some overhead from the server
130 // sending the OCSP response if it supports the extension, for the subset of
131 // XP clients who will request it but be unable to use it, but this is an
132 // acceptable trade-off for simplicity of implementation.
133 static bool IsOCSPStaplingSupported() {
134 return true;
136 #elif defined(USE_NSS)
137 typedef SECStatus
138 (*CacheOCSPResponseFromSideChannelFunction)(
139 CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
140 SECItem *encodedResponse, void *pwArg);
142 // On Linux, we dynamically link against the system version of libnss3.so. In
143 // order to continue working on systems without up-to-date versions of NSS we
144 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
146 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
147 // runtime symbol resolution that we need.
148 class RuntimeLibNSSFunctionPointers {
149 public:
150 CacheOCSPResponseFromSideChannelFunction
151 GetCacheOCSPResponseFromSideChannelFunction() {
152 return cache_ocsp_response_from_side_channel_;
155 static RuntimeLibNSSFunctionPointers* GetInstance() {
156 return Singleton<RuntimeLibNSSFunctionPointers>::get();
159 private:
160 friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
162 RuntimeLibNSSFunctionPointers() {
163 cache_ocsp_response_from_side_channel_ =
164 (CacheOCSPResponseFromSideChannelFunction)
165 dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
168 CacheOCSPResponseFromSideChannelFunction
169 cache_ocsp_response_from_side_channel_;
172 static CacheOCSPResponseFromSideChannelFunction
173 GetCacheOCSPResponseFromSideChannelFunction() {
174 return RuntimeLibNSSFunctionPointers::GetInstance()
175 ->GetCacheOCSPResponseFromSideChannelFunction();
178 static bool IsOCSPStaplingSupported() {
179 return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
181 #else
182 // TODO(agl): Figure out if we can plumb the OCSP response into Mac's system
183 // certificate validation functions.
184 static bool IsOCSPStaplingSupported() {
185 return false;
187 #endif
189 namespace net {
191 // State machines are easier to debug if you log state transitions.
192 // Enable these if you want to see what's going on.
193 #if 1
194 #define EnterFunction(x)
195 #define LeaveFunction(x)
196 #define GotoState(s) next_handshake_state_ = s
197 #else
198 #define EnterFunction(x)\
199 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
200 << "; next_handshake_state " << next_handshake_state_
201 #define LeaveFunction(x)\
202 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
203 << "; next_handshake_state " << next_handshake_state_
204 #define GotoState(s)\
205 do {\
206 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
207 next_handshake_state_ = s;\
208 } while (0)
209 #endif
211 namespace {
213 class FreeCERTCertificate {
214 public:
215 inline void operator()(CERTCertificate* x) const {
216 CERT_DestroyCertificate(x);
219 typedef scoped_ptr_malloc<CERTCertificate, FreeCERTCertificate>
220 ScopedCERTCertificate;
222 #if defined(OS_WIN)
224 // This callback is intended to be used with CertFindChainInStore. In addition
225 // to filtering by extended/enhanced key usage, we do not show expired
226 // certificates and require digital signature usage in the key usage
227 // extension.
229 // This matches our behavior on Mac OS X and that of NSS. It also matches the
230 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
231 // 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
232 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
233 void* find_arg) {
234 VLOG(1) << "Calling ClientCertFindCallback from _nss";
235 // Verify the certificate's KU is good.
236 BYTE key_usage;
237 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
238 &key_usage, 1)) {
239 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
240 return FALSE;
241 } else {
242 DWORD err = GetLastError();
243 // If |err| is non-zero, it's an actual error. Otherwise the extension
244 // just isn't present, and we treat it as if everything was allowed.
245 if (err) {
246 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
247 return FALSE;
251 // Verify the current time is within the certificate's validity period.
252 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
253 return FALSE;
255 // Verify private key metadata is associated with this certificate.
256 DWORD size = 0;
257 if (!CertGetCertificateContextProperty(
258 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
259 return FALSE;
262 return TRUE;
265 #endif
267 void DestroyCertificates(CERTCertificate** certs, size_t len) {
268 for (size_t i = 0; i < len; i++)
269 CERT_DestroyCertificate(certs[i]);
272 // Helper functions to make it possible to log events from within the
273 // SSLClientSocketNSS::Core.
274 void AddLogEvent(BoundNetLog* net_log, NetLog::EventType event_type) {
275 if (!net_log)
276 return;
277 net_log->AddEvent(event_type);
280 // Helper function to make it possible to log events from within the
281 // SSLClientSocketNSS::Core.
282 void AddLogEventWithCallback(BoundNetLog* net_log,
283 NetLog::EventType event_type,
284 const NetLog::ParametersCallback& callback) {
285 if (!net_log)
286 return;
287 net_log->AddEvent(event_type, callback);
290 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
291 // from within the SSLClientSocketNSS::Core.
292 // AddByteTransferEvent expects to receive a const char*, which within the
293 // Core is backed by an IOBuffer. If the "const char*" is bound via
294 // base::Bind and posted to another thread, and the IOBuffer that backs that
295 // pointer then goes out of scope on the origin thread, this would result in
296 // an invalid read of a stale pointer.
297 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
298 // to the owning IOBuffer can be bound to the Callback. This ensures that the
299 // IOBuffer will stay alive long enough to cross threads if needed.
300 void LogByteTransferEvent(BoundNetLog* net_log, NetLog::EventType event_type,
301 int len, IOBuffer* buffer) {
302 if (!net_log)
303 return;
304 net_log->AddByteTransferEvent(event_type, len, buffer->data());
307 // PeerCertificateChain is a helper object which extracts the certificate
308 // chain, as given by the server, from an NSS socket and performs the needed
309 // resource management. The first element of the chain is the leaf certificate
310 // and the other elements are in the order given by the server.
311 class PeerCertificateChain {
312 public:
313 PeerCertificateChain() {}
314 PeerCertificateChain(const PeerCertificateChain& other);
315 ~PeerCertificateChain();
316 PeerCertificateChain& operator=(const PeerCertificateChain& other);
318 // Resets the current chain, freeing any resources, and updates the current
319 // chain to be a copy of the chain stored in |nss_fd|.
320 // If |nss_fd| is NULL, then the current certificate chain will be freed.
321 void Reset(PRFileDesc* nss_fd);
323 // Returns the current certificate chain as a vector of DER-encoded
324 // base::StringPieces. The returned vector remains valid until Reset is
325 // called.
326 std::vector<base::StringPiece> AsStringPieceVector() const;
328 bool empty() const { return certs_.empty(); }
329 size_t size() const { return certs_.size(); }
331 CERTCertificate* operator[](size_t index) const {
332 DCHECK_LT(index, certs_.size());
333 return certs_[index];
336 private:
337 std::vector<CERTCertificate*> certs_;
340 PeerCertificateChain::PeerCertificateChain(
341 const PeerCertificateChain& other) {
342 *this = other;
345 PeerCertificateChain::~PeerCertificateChain() {
346 Reset(NULL);
349 PeerCertificateChain& PeerCertificateChain::operator=(
350 const PeerCertificateChain& other) {
351 if (this == &other)
352 return *this;
354 Reset(NULL);
355 certs_.reserve(other.certs_.size());
356 for (size_t i = 0; i < other.certs_.size(); ++i)
357 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
359 return *this;
362 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
363 for (size_t i = 0; i < certs_.size(); ++i)
364 CERT_DestroyCertificate(certs_[i]);
365 certs_.clear();
367 if (nss_fd == NULL)
368 return;
370 unsigned int num_certs = 0;
371 SECStatus rv = SSL_PeerCertificateChain(nss_fd, NULL, &num_certs, 0);
372 DCHECK_EQ(SECSuccess, rv);
374 // The handshake on |nss_fd| may not have completed.
375 if (num_certs == 0)
376 return;
378 certs_.resize(num_certs);
379 const unsigned int expected_num_certs = num_certs;
380 rv = SSL_PeerCertificateChain(nss_fd, vector_as_array(&certs_),
381 &num_certs, expected_num_certs);
382 DCHECK_EQ(SECSuccess, rv);
383 DCHECK_EQ(expected_num_certs, num_certs);
386 std::vector<base::StringPiece>
387 PeerCertificateChain::AsStringPieceVector() const {
388 std::vector<base::StringPiece> v(certs_.size());
389 for (unsigned i = 0; i < certs_.size(); i++) {
390 v[i] = base::StringPiece(
391 reinterpret_cast<const char*>(certs_[i]->derCert.data),
392 certs_[i]->derCert.len);
395 return v;
398 // HandshakeState is a helper struct used to pass handshake state between
399 // the NSS task runner and the network task runner.
401 // It contains members that may be read or written on the NSS task runner,
402 // but which also need to be read from the network task runner. The NSS task
403 // runner will notify the network task runner whenever this state changes, so
404 // that the network task runner can safely make a copy, which avoids the need
405 // for locking.
406 struct HandshakeState {
407 HandshakeState() { Reset(); }
409 void Reset() {
410 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
411 next_proto.clear();
412 server_protos.clear();
413 channel_id_sent = false;
414 client_certs.clear();
415 server_cert_chain.Reset(NULL);
416 server_cert = NULL;
417 resumed_handshake = false;
418 ssl_connection_status = 0;
421 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
422 // negotiated protocol stored in |next_proto|.
423 SSLClientSocket::NextProtoStatus next_proto_status;
424 std::string next_proto;
425 // If the server supports NPN, the protocols supported by the server.
426 std::string server_protos;
428 // True if a channel ID was sent.
429 bool channel_id_sent;
431 // If the peer requests client certificate authentication, the set of
432 // certificates that matched the peer's criteria.
433 CertificateList client_certs;
435 // Set when the handshake fully completes.
437 // The server certificate is first received from NSS as an NSS certificate
438 // chain (|server_cert_chain|) and then converted into a platform-specific
439 // X509Certificate object (|server_cert|). It's possible for some
440 // certificates to be successfully parsed by NSS, and not by the platform
441 // libraries (i.e.: when running within a sandbox, different parsing
442 // algorithms, etc), so it's not safe to assume that |server_cert| will
443 // always be non-NULL.
444 PeerCertificateChain server_cert_chain;
445 scoped_refptr<X509Certificate> server_cert;
447 // True if the current handshake was the result of TLS session resumption.
448 bool resumed_handshake;
450 // The negotiated security parameters (TLS version, cipher, extensions) of
451 // the SSL connection.
452 int ssl_connection_status;
455 // Client-side error mapping functions.
457 // Map NSS error code to network error code.
458 int MapNSSClientError(PRErrorCode err) {
459 switch (err) {
460 case SSL_ERROR_BAD_CERT_ALERT:
461 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
462 case SSL_ERROR_REVOKED_CERT_ALERT:
463 case SSL_ERROR_EXPIRED_CERT_ALERT:
464 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
465 case SSL_ERROR_UNKNOWN_CA_ALERT:
466 case SSL_ERROR_ACCESS_DENIED_ALERT:
467 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
468 default:
469 return MapNSSError(err);
473 // Map NSS error code from the first SSL handshake to network error code.
474 int MapNSSClientHandshakeError(PRErrorCode err) {
475 switch (err) {
476 // If the server closed on us, it is a protocol error.
477 // Some TLS-intolerant servers do this when we request TLS.
478 case PR_END_OF_FILE_ERROR:
479 return ERR_SSL_PROTOCOL_ERROR;
480 default:
481 return MapNSSClientError(err);
485 } // namespace
487 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
488 // able to marshal data between NSS functions and an underlying transport
489 // socket.
491 // All public functions are meant to be called from the network task runner,
492 // and any callbacks supplied will be invoked there as well, provided that
493 // Detach() has not been called yet.
495 /////////////////////////////////////////////////////////////////////////////
497 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
499 // Because NSS may block on either hardware or user input during operations
500 // such as signing, creating certificates, or locating private keys, the Core
501 // handles all of the interactions with the underlying NSS SSL socket, so
502 // that these blocking calls can be executed on a dedicated task runner.
504 // Note that the network task runner and the NSS task runner may be executing
505 // on the same thread. If that happens, then it's more performant to try to
506 // complete as much work as possible synchronously, even if it might block,
507 // rather than continually PostTask-ing to the same thread.
509 // Because NSS functions should only be called on the NSS task runner, while
510 // I/O resources should only be accessed on the network task runner, most
511 // public functions are implemented via three methods, each with different
512 // task runner affinities.
514 // In the single-threaded mode (where the network and NSS task runners run on
515 // the same thread), these are all attempted synchronously, while in the
516 // multi-threaded mode, message passing is used.
518 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
519 // DoHandshake)
520 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
521 // (BufferRecv, BufferSend)
522 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
523 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete)
524 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
525 // data from the network task runner back to NSS (BufferRecvComplete,
526 // BufferSendComplete, OnHandshakeIOComplete)
528 /////////////////////////////////////////////////////////////////////////////
529 // Single-threaded example
531 // |--------------------------Network Task Runner--------------------------|
532 // SSLClientSocketNSS Core (Transport Socket)
533 // Read()
534 // |-------------------------V
535 // Read()
536 // |
537 // DoPayloadRead()
538 // |
539 // BufferRecv()
540 // |
541 // DoBufferRecv()
542 // |-------------------------V
543 // Read()
544 // V-------------------------|
545 // BufferRecvComplete()
546 // |
547 // PostOrRunCallback()
548 // V-------------------------|
549 // (Read Callback)
551 /////////////////////////////////////////////////////////////////////////////
552 // Multi-threaded example:
554 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
555 // SSLClientSocketNSS Core Socket Core
556 // Read()
557 // |---------------------V
558 // Read()
559 // |-------------------------------V
560 // Read()
561 // |
562 // DoPayloadRead()
563 // |
564 // BufferRecv
565 // V-------------------------------|
566 // DoBufferRecv
567 // |----------------V
568 // Read()
569 // V----------------|
570 // BufferRecvComplete()
571 // |-------------------------------V
572 // BufferRecvComplete()
573 // |
574 // PostOrRunCallback()
575 // V-------------------------------|
576 // PostOrRunCallback()
577 // V---------------------|
578 // (Read Callback)
580 /////////////////////////////////////////////////////////////////////////////
581 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
582 public:
583 // Creates a new Core.
585 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
586 // that need to operate on the underlying transport, net log, or server
587 // bound certificate fetching will happen on the |network_task_runner|, so
588 // that their lifetimes match that of the owning SSLClientSocketNSS.
590 // The caller retains ownership of |transport|, |net_log|, and
591 // |server_bound_cert_service|, and they will not be accessed once Detach()
592 // has been called.
593 Core(base::SequencedTaskRunner* network_task_runner,
594 base::SequencedTaskRunner* nss_task_runner,
595 ClientSocketHandle* transport,
596 const HostPortPair& host_and_port,
597 const SSLConfig& ssl_config,
598 BoundNetLog* net_log,
599 ServerBoundCertService* server_bound_cert_service);
601 // Called on the network task runner.
602 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
603 // underlying memio implementation, to the Core. Returns true if the Core
604 // was successfully registered with the socket.
605 bool Init(PRFileDesc* socket, memio_Private* buffers);
607 // Called on the network task runner.
608 // Sets the predicted certificate chain that the peer will send, for use
609 // with the TLS CachedInfo extension. If called, it must not be called
610 // before Init() or after Connect().
611 void SetPredictedCertificates(
612 const std::vector<std::string>& predicted_certificates);
614 // Called on the network task runner.
616 // Attempts to perform an SSL handshake. If the handshake cannot be
617 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
618 // the network task runner once the handshake has completed. Otherwise,
619 // returns OK on success or a network error code on failure.
620 int Connect(const CompletionCallback& callback);
622 // Called on the network task runner.
623 // Signals that the resources owned by the network task runner are going
624 // away. No further callbacks will be invoked on the network task runner.
625 // May be called at any time.
626 void Detach();
628 // Called on the network task runner.
629 // Returns the current state of the underlying SSL socket. May be called at
630 // any time.
631 const HandshakeState& state() const { return network_handshake_state_; }
633 // Called on the network task runner.
634 // Read() and Write() mirror the net::Socket functions of the same name.
635 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
636 // task runner at a later point, unless the caller calls Detach().
637 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
638 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
640 private:
641 friend class base::RefCountedThreadSafe<Core>;
642 ~Core();
644 enum State {
645 STATE_NONE,
646 STATE_HANDSHAKE,
647 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
650 bool OnNSSTaskRunner() const;
651 bool OnNetworkTaskRunner() const;
653 ////////////////////////////////////////////////////////////////////////////
654 // Methods that are ONLY called on the NSS task runner:
655 ////////////////////////////////////////////////////////////////////////////
657 // Called by NSS during full handshakes to allow the application to
658 // verify the certificate. Instead of verifying the certificate in the midst
659 // of the handshake, SECSuccess is always returned and the peer's certificate
660 // is verified afterwards.
661 // This behaviour is an artifact of the original SSLClientSocketWin
662 // implementation, which could not verify the peer's certificate until after
663 // the handshake had completed, as well as bugs in NSS that prevent
664 // SSL_RestartHandshakeAfterCertReq from working.
665 static SECStatus OwnAuthCertHandler(void* arg,
666 PRFileDesc* socket,
667 PRBool checksig,
668 PRBool is_server);
670 // Callbacks called by NSS when the peer requests client certificate
671 // authentication.
672 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
673 // the arguments.
674 #if defined(NSS_PLATFORM_CLIENT_AUTH)
675 // When NSS has been integrated with awareness of the underlying system
676 // cryptographic libraries, this callback allows the caller to supply a
677 // native platform certificate and key for use by NSS. At most, one of
678 // either (result_certs, result_private_key) or (result_nss_certificate,
679 // result_nss_private_key) should be set.
680 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
681 static SECStatus PlatformClientAuthHandler(
682 void* arg,
683 PRFileDesc* socket,
684 CERTDistNames* ca_names,
685 CERTCertList** result_certs,
686 void** result_private_key,
687 CERTCertificate** result_nss_certificate,
688 SECKEYPrivateKey** result_nss_private_key);
689 #else
690 static SECStatus ClientAuthHandler(void* arg,
691 PRFileDesc* socket,
692 CERTDistNames* ca_names,
693 CERTCertificate** result_certificate,
694 SECKEYPrivateKey** result_private_key);
695 #endif
697 // Called by NSS once the handshake has completed.
698 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
699 static void HandshakeCallback(PRFileDesc* socket, void* arg);
701 // Called by NSS if the peer supports the NPN handshake extension, to allow
702 // the application to select the protocol to use.
703 // See the documentation for SSLNextProtocolCallback in
704 // third_party/nss/ssl/ssl.h for the meanings of the arguments.
705 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
706 static SECStatus NextProtoCallback(void* arg,
707 PRFileDesc* fd,
708 const unsigned char* protos,
709 unsigned int protos_len,
710 unsigned char* proto_out,
711 unsigned int* proto_out_len,
712 unsigned int proto_max_len);
714 // Handles an NSS error generated while handshaking or performing IO.
715 // Returns a network error code mapped from the original NSS error.
716 int HandleNSSError(PRErrorCode error, bool handshake_error);
718 int DoHandshakeLoop(int last_io_result);
719 int DoReadLoop(int result);
720 int DoWriteLoop(int result);
722 int DoHandshake();
723 int DoGetDBCertComplete(int result);
725 int DoPayloadRead();
726 int DoPayloadWrite();
728 bool DoTransportIO();
729 int BufferRecv();
730 int BufferSend();
732 void OnRecvComplete(int result);
733 void OnSendComplete(int result);
735 void DoConnectCallback(int result);
736 void DoReadCallback(int result);
737 void DoWriteCallback(int result);
739 // Client channel ID handler.
740 static SECStatus ClientChannelIDHandler(
741 void* arg,
742 PRFileDesc* socket,
743 SECKEYPublicKey **out_public_key,
744 SECKEYPrivateKey **out_private_key);
746 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
747 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
748 // and an error code otherwise.
749 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
750 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller
751 // takes ownership of the |*cert| and |*key|.
752 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
754 // Updates the NSS and platform specific certificates.
755 void UpdateServerCert();
756 // Updates the nss_handshake_state_ with the negotiated security parameters.
757 void UpdateConnectionStatus();
758 // Record histograms for channel id support during full handshakes - resumed
759 // handshakes are ignored.
760 void RecordChannelIDSupport() const;
762 ////////////////////////////////////////////////////////////////////////////
763 // Methods that are ONLY called on the network task runner:
764 ////////////////////////////////////////////////////////////////////////////
765 int DoBufferRecv(IOBuffer* buffer, int len);
766 int DoBufferSend(IOBuffer* buffer, int len);
767 int DoGetDomainBoundCert(const std::string& origin,
768 const std::vector<uint8>& requested_cert_types);
770 void OnGetDomainBoundCertComplete(int result);
771 void OnHandshakeStateUpdated(const HandshakeState& state);
773 ////////////////////////////////////////////////////////////////////////////
774 // Methods that are called on both the network task runner and the NSS
775 // task runner.
776 ////////////////////////////////////////////////////////////////////////////
777 void OnHandshakeIOComplete(int result);
778 void BufferRecvComplete(IOBuffer* buffer, int result);
779 void BufferSendComplete(int result);
781 // PostOrRunCallback is a helper function to ensure that |callback| is
782 // invoked on the network task runner, but only if Detach() has not yet
783 // been called.
784 void PostOrRunCallback(const tracked_objects::Location& location,
785 const base::Closure& callback);
787 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
788 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
789 void AddCertProvidedEvent(int cert_count);
791 // Sets the handshake state |channel_id_sent| flag and logs the
792 // SSL_CHANNEL_ID_PROVIDED event.
793 void SetChannelIDProvided();
795 ////////////////////////////////////////////////////////////////////////////
796 // Members that are ONLY accessed on the network task runner:
797 ////////////////////////////////////////////////////////////////////////////
799 // True if the owning SSLClientSocketNSS has called Detach(). No further
800 // callbacks will be invoked nor access to members owned by the network
801 // task runner.
802 bool detached_;
804 // The underlying transport to use for network IO.
805 ClientSocketHandle* transport_;
806 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
808 // The current handshake state. Mirrors |nss_handshake_state_|.
809 HandshakeState network_handshake_state_;
811 // The service for retrieving Channel ID keys. May be NULL.
812 ServerBoundCertService* server_bound_cert_service_;
813 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_;
815 ////////////////////////////////////////////////////////////////////////////
816 // Members that are ONLY accessed on the NSS task runner:
817 ////////////////////////////////////////////////////////////////////////////
818 HostPortPair host_and_port_;
819 SSLConfig ssl_config_;
821 // NSS SSL socket.
822 PRFileDesc* nss_fd_;
824 // Buffers for the network end of the SSL state machine
825 memio_Private* nss_bufs_;
827 // The certificate chain, in DER form, that is expected to be received from
828 // the server.
829 std::vector<std::string> predicted_certs_;
831 State next_handshake_state_;
833 // True if channel ID extension was negotiated.
834 bool channel_id_xtn_negotiated_;
835 // True if the handshake state machine was interrupted for channel ID.
836 bool channel_id_needed_;
837 // True if the handshake state machine was interrupted for client auth.
838 bool client_auth_cert_needed_;
839 // True if NSS has called HandshakeCallback.
840 bool handshake_callback_called_;
842 HandshakeState nss_handshake_state_;
844 bool transport_recv_busy_;
845 bool transport_recv_eof_;
846 bool transport_send_busy_;
848 // Used by Read function.
849 scoped_refptr<IOBuffer> user_read_buf_;
850 int user_read_buf_len_;
852 // Used by Write function.
853 scoped_refptr<IOBuffer> user_write_buf_;
854 int user_write_buf_len_;
856 CompletionCallback user_connect_callback_;
857 CompletionCallback user_read_callback_;
858 CompletionCallback user_write_callback_;
860 ////////////////////////////////////////////////////////////////////////////
861 // Members that are accessed on both the network task runner and the NSS
862 // task runner.
863 ////////////////////////////////////////////////////////////////////////////
864 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
865 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
867 // Dereferenced only on the network task runner, but bound to tasks destined
868 // for the network task runner from the NSS task runner.
869 base::WeakPtr<BoundNetLog> weak_net_log_;
871 // Written on the network task runner by the |server_bound_cert_service_|,
872 // prior to invoking OnHandshakeIOComplete.
873 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
874 // on the NSS task runner.
875 SSLClientCertType domain_bound_cert_type_;
876 std::string domain_bound_private_key_;
877 std::string domain_bound_cert_;
879 DISALLOW_COPY_AND_ASSIGN(Core);
882 SSLClientSocketNSS::Core::Core(
883 base::SequencedTaskRunner* network_task_runner,
884 base::SequencedTaskRunner* nss_task_runner,
885 ClientSocketHandle* transport,
886 const HostPortPair& host_and_port,
887 const SSLConfig& ssl_config,
888 BoundNetLog* net_log,
889 ServerBoundCertService* server_bound_cert_service)
890 : detached_(false),
891 transport_(transport),
892 weak_net_log_factory_(net_log),
893 server_bound_cert_service_(server_bound_cert_service),
894 domain_bound_cert_request_handle_(NULL),
895 host_and_port_(host_and_port),
896 ssl_config_(ssl_config),
897 nss_fd_(NULL),
898 nss_bufs_(NULL),
899 next_handshake_state_(STATE_NONE),
900 channel_id_xtn_negotiated_(false),
901 channel_id_needed_(false),
902 client_auth_cert_needed_(false),
903 handshake_callback_called_(false),
904 transport_recv_busy_(false),
905 transport_recv_eof_(false),
906 transport_send_busy_(false),
907 user_read_buf_len_(0),
908 user_write_buf_len_(0),
909 network_task_runner_(network_task_runner),
910 nss_task_runner_(nss_task_runner),
911 weak_net_log_(weak_net_log_factory_.GetWeakPtr()),
912 domain_bound_cert_type_(CLIENT_CERT_INVALID_TYPE) {
915 SSLClientSocketNSS::Core::~Core() {
916 // TODO(wtc): Send SSL close_notify alert.
917 if (nss_fd_ != NULL) {
918 PR_Close(nss_fd_);
919 nss_fd_ = NULL;
923 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
924 memio_Private* buffers) {
925 DCHECK(OnNetworkTaskRunner());
926 DCHECK(!nss_fd_);
927 DCHECK(!nss_bufs_);
929 nss_fd_ = socket;
930 nss_bufs_ = buffers;
932 SECStatus rv = SECSuccess;
934 if (!ssl_config_.next_protos.empty()) {
935 rv = SSL_SetNextProtoCallback(
936 nss_fd_, SSLClientSocketNSS::Core::NextProtoCallback, this);
937 if (rv != SECSuccess)
938 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", "");
941 rv = SSL_AuthCertificateHook(
942 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
943 if (rv != SECSuccess) {
944 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
945 return false;
948 #if defined(NSS_PLATFORM_CLIENT_AUTH)
949 rv = SSL_GetPlatformClientAuthDataHook(
950 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
951 this);
952 #else
953 rv = SSL_GetClientAuthDataHook(
954 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
955 #endif
956 if (rv != SECSuccess) {
957 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
958 return false;
961 if (ssl_config_.channel_id_enabled) {
962 if (!server_bound_cert_service_) {
963 DVLOG(1) << "NULL server_bound_cert_service_, not enabling channel ID.";
964 } else if (!crypto::ECPrivateKey::IsSupported()) {
965 DVLOG(1) << "Elliptic Curve not supported, not enabling channel ID.";
966 } else if (!server_bound_cert_service_->IsSystemTimeValid()) {
967 DVLOG(1) << "System time is weird, not enabling channel ID.";
968 } else {
969 rv = SSL_SetClientChannelIDCallback(
970 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
971 if (rv != SECSuccess)
972 LogFailedNSSFunction(*weak_net_log_, "SSL_SetClientChannelIDCallback",
973 "");
977 rv = SSL_HandshakeCallback(
978 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
979 if (rv != SECSuccess) {
980 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
981 return false;
984 return true;
987 void SSLClientSocketNSS::Core::SetPredictedCertificates(
988 const std::vector<std::string>& predicted_certs) {
989 if (predicted_certs.empty())
990 return;
992 if (!OnNSSTaskRunner()) {
993 DCHECK(!detached_);
994 nss_task_runner_->PostTask(
995 FROM_HERE,
996 base::Bind(&Core::SetPredictedCertificates, this, predicted_certs));
997 return;
1000 DCHECK(nss_fd_);
1002 predicted_certs_ = predicted_certs;
1004 scoped_array<CERTCertificate*> certs(
1005 new CERTCertificate*[predicted_certs.size()]);
1007 for (size_t i = 0; i < predicted_certs.size(); i++) {
1008 SECItem derCert;
1009 derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>(
1010 predicted_certs[i].data()));
1011 derCert.len = predicted_certs[i].size();
1012 certs[i] = CERT_NewTempCertificate(
1013 CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */,
1014 PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */);
1015 if (!certs[i]) {
1016 DestroyCertificates(&certs[0], i);
1017 NOTREACHED();
1018 return;
1022 SECStatus rv;
1023 #ifdef SSL_ENABLE_CACHED_INFO
1024 rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(),
1025 predicted_certs.size());
1026 DCHECK_EQ(SECSuccess, rv);
1027 #else
1028 rv = SECFailure; // Not implemented.
1029 #endif
1030 DestroyCertificates(&certs[0], predicted_certs.size());
1032 if (rv != SECSuccess) {
1033 LOG(WARNING) << "SetPredictedCertificates failed: "
1034 << host_and_port_.ToString();
1038 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1039 if (!OnNSSTaskRunner()) {
1040 DCHECK(!detached_);
1041 bool posted = nss_task_runner_->PostTask(
1042 FROM_HERE,
1043 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1044 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1047 DCHECK(OnNSSTaskRunner());
1048 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1049 DCHECK(user_read_callback_.is_null());
1050 DCHECK(user_write_callback_.is_null());
1051 DCHECK(user_connect_callback_.is_null());
1052 DCHECK(!user_read_buf_);
1053 DCHECK(!user_write_buf_);
1055 next_handshake_state_ = STATE_HANDSHAKE;
1056 int rv = DoHandshakeLoop(OK);
1057 if (rv == ERR_IO_PENDING) {
1058 user_connect_callback_ = callback;
1059 } else if (rv > OK) {
1060 rv = OK;
1062 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1063 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1064 return ERR_IO_PENDING;
1067 return rv;
1070 void SSLClientSocketNSS::Core::Detach() {
1071 DCHECK(OnNetworkTaskRunner());
1073 detached_ = true;
1074 transport_ = NULL;
1075 weak_net_log_factory_.InvalidateWeakPtrs();
1077 network_handshake_state_.Reset();
1079 if (domain_bound_cert_request_handle_ != NULL) {
1080 server_bound_cert_service_->CancelRequest(
1081 domain_bound_cert_request_handle_);
1082 domain_bound_cert_request_handle_ = NULL;
1086 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1087 const CompletionCallback& callback) {
1088 if (!OnNSSTaskRunner()) {
1089 DCHECK(OnNetworkTaskRunner());
1090 DCHECK(!detached_);
1091 DCHECK(transport_);
1093 bool posted = nss_task_runner_->PostTask(
1094 FROM_HERE,
1095 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1096 buf_len, callback));
1097 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1100 DCHECK(OnNSSTaskRunner());
1101 DCHECK(handshake_callback_called_);
1102 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1103 DCHECK(user_read_callback_.is_null());
1104 DCHECK(user_connect_callback_.is_null());
1105 DCHECK(!user_read_buf_);
1106 DCHECK(nss_bufs_);
1108 user_read_buf_ = buf;
1109 user_read_buf_len_ = buf_len;
1111 int rv = DoReadLoop(OK);
1112 if (rv == ERR_IO_PENDING) {
1113 user_read_callback_ = callback;
1114 } else {
1115 user_read_buf_ = NULL;
1116 user_read_buf_len_ = 0;
1118 if (!OnNetworkTaskRunner()) {
1119 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1120 return ERR_IO_PENDING;
1124 return rv;
1127 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1128 const CompletionCallback& callback) {
1129 if (!OnNSSTaskRunner()) {
1130 DCHECK(OnNetworkTaskRunner());
1131 DCHECK(!detached_);
1132 DCHECK(transport_);
1134 bool posted = nss_task_runner_->PostTask(
1135 FROM_HERE,
1136 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1137 buf_len, callback));
1138 int rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1139 return rv;
1142 DCHECK(OnNSSTaskRunner());
1143 DCHECK(handshake_callback_called_);
1144 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1145 DCHECK(user_write_callback_.is_null());
1146 DCHECK(user_connect_callback_.is_null());
1147 DCHECK(!user_write_buf_);
1148 DCHECK(nss_bufs_);
1150 user_write_buf_ = buf;
1151 user_write_buf_len_ = buf_len;
1153 int rv = DoWriteLoop(OK);
1154 if (rv == ERR_IO_PENDING) {
1155 user_write_callback_ = callback;
1156 } else {
1157 user_write_buf_ = NULL;
1158 user_write_buf_len_ = 0;
1160 if (!OnNetworkTaskRunner()) {
1161 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1162 return ERR_IO_PENDING;
1166 return rv;
1169 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1170 return nss_task_runner_->RunsTasksOnCurrentThread();
1173 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1174 return network_task_runner_->RunsTasksOnCurrentThread();
1177 // static
1178 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1179 void* arg,
1180 PRFileDesc* socket,
1181 PRBool checksig,
1182 PRBool is_server) {
1183 #ifdef SSL_ENABLE_FALSE_START
1184 Core* core = reinterpret_cast<Core*>(arg);
1185 if (!core->handshake_callback_called_) {
1186 // Only need to turn off False Start in the initial handshake. Also, it is
1187 // unsafe to call SSL_OptionSet in a renegotiation because the "first
1188 // handshake" lock isn't already held, which will result in an assertion
1189 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet.
1190 PRBool npn;
1191 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1192 ssl_next_proto_nego_xtn,
1193 &npn);
1194 if (rv != SECSuccess || !npn) {
1195 // If the server doesn't support NPN, then we don't do False Start with
1196 // it.
1197 SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE);
1200 #endif
1202 // Tell NSS to not verify the certificate.
1203 return SECSuccess;
1206 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1207 // static
1208 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1209 void* arg,
1210 PRFileDesc* socket,
1211 CERTDistNames* ca_names,
1212 CERTCertList** result_certs,
1213 void** result_private_key,
1214 CERTCertificate** result_nss_certificate,
1215 SECKEYPrivateKey** result_nss_private_key) {
1216 Core* core = reinterpret_cast<Core*>(arg);
1217 DCHECK(core->OnNSSTaskRunner());
1219 core->PostOrRunCallback(
1220 FROM_HERE,
1221 base::Bind(&AddLogEvent, core->weak_net_log_,
1222 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1224 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1225 #if defined(OS_WIN)
1226 if (core->ssl_config_.send_client_cert) {
1227 if (core->ssl_config_.client_cert) {
1228 PCCERT_CONTEXT cert_context =
1229 core->ssl_config_.client_cert->os_cert_handle();
1231 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1232 DWORD key_spec = 0;
1233 BOOL must_free = FALSE;
1234 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1235 cert_context, CRYPT_ACQUIRE_CACHE_FLAG, NULL,
1236 &crypt_prov, &key_spec, &must_free);
1238 if (acquired_key) {
1239 // Since we passed CRYPT_ACQUIRE_CACHE_FLAG, |must_free| must be false
1240 // according to the MSDN documentation.
1241 CHECK_EQ(must_free, FALSE);
1242 DCHECK_NE(key_spec, CERT_NCRYPT_KEY_SPEC);
1244 SECItem der_cert;
1245 der_cert.type = siDERCertBuffer;
1246 der_cert.data = cert_context->pbCertEncoded;
1247 der_cert.len = cert_context->cbCertEncoded;
1249 // TODO(rsleevi): Error checking for NSS allocation errors.
1250 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1251 CERTCertificate* user_cert = CERT_NewTempCertificate(
1252 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1253 if (!user_cert) {
1254 // Importing the certificate can fail for reasons including a serial
1255 // number collision. See crbug.com/97355.
1256 core->AddCertProvidedEvent(0);
1257 return SECFailure;
1259 CERTCertList* cert_chain = CERT_NewCertList();
1260 CERT_AddCertToListTail(cert_chain, user_cert);
1262 // Add the intermediates.
1263 X509Certificate::OSCertHandles intermediates =
1264 core->ssl_config_.client_cert->GetIntermediateCertificates();
1265 for (X509Certificate::OSCertHandles::const_iterator it =
1266 intermediates.begin(); it != intermediates.end(); ++it) {
1267 der_cert.data = (*it)->pbCertEncoded;
1268 der_cert.len = (*it)->cbCertEncoded;
1270 CERTCertificate* intermediate = CERT_NewTempCertificate(
1271 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1272 if (!intermediate) {
1273 CERT_DestroyCertList(cert_chain);
1274 core->AddCertProvidedEvent(0);
1275 return SECFailure;
1277 CERT_AddCertToListTail(cert_chain, intermediate);
1279 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1280 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1281 key_context->cbSize = sizeof(*key_context);
1282 // NSS will free this context when no longer in use, but the
1283 // |must_free| result from CryptAcquireCertificatePrivateKey was false
1284 // so we increment the refcount to negate NSS's future decrement.
1285 CryptContextAddRef(crypt_prov, NULL, 0);
1286 key_context->hCryptProv = crypt_prov;
1287 key_context->dwKeySpec = key_spec;
1288 *result_private_key = key_context;
1289 *result_certs = cert_chain;
1291 int cert_count = 1 + intermediates.size();
1292 core->AddCertProvidedEvent(cert_count);
1293 return SECSuccess;
1295 LOG(WARNING) << "Client cert found without private key";
1298 // Send no client certificate.
1299 core->AddCertProvidedEvent(0);
1300 return SECFailure;
1303 core->nss_handshake_state_.client_certs.clear();
1305 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1306 for (int i = 0; i < ca_names->nnames; ++i) {
1307 issuer_list[i].cbData = ca_names->names[i].len;
1308 issuer_list[i].pbData = ca_names->names[i].data;
1311 // Client certificates of the user are in the "MY" system certificate store.
1312 HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY");
1313 if (!my_cert_store) {
1314 PLOG(ERROR) << "Could not open the \"MY\" system certificate store";
1316 core->AddCertProvidedEvent(0);
1317 return SECFailure;
1320 // Enumerate the client certificates.
1321 CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para;
1322 memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para));
1323 find_by_issuer_para.cbSize = sizeof(find_by_issuer_para);
1324 find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH;
1325 find_by_issuer_para.cIssuer = ca_names->nnames;
1326 find_by_issuer_para.rgIssuer = ca_names->nnames ? &issuer_list[0] : NULL;
1327 find_by_issuer_para.pfnFindCallback = ClientCertFindCallback;
1329 PCCERT_CHAIN_CONTEXT chain_context = NULL;
1330 DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG |
1331 CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG;
1333 for (;;) {
1334 // Find a certificate chain.
1335 chain_context = CertFindChainInStore(my_cert_store,
1336 X509_ASN_ENCODING,
1337 find_flags,
1338 CERT_CHAIN_FIND_BY_ISSUER,
1339 &find_by_issuer_para,
1340 chain_context);
1341 if (!chain_context) {
1342 DWORD err = GetLastError();
1343 if (err != CRYPT_E_NOT_FOUND)
1344 DLOG(ERROR) << "CertFindChainInStore failed: " << err;
1345 break;
1348 // Get the leaf certificate.
1349 PCCERT_CONTEXT cert_context =
1350 chain_context->rgpChain[0]->rgpElement[0]->pCertContext;
1351 // Create a copy the handle, so that we can close the "MY" certificate store
1352 // before returning from this function.
1353 PCCERT_CONTEXT cert_context2;
1354 BOOL ok = CertAddCertificateContextToStore(NULL, cert_context,
1355 CERT_STORE_ADD_USE_EXISTING,
1356 &cert_context2);
1357 if (!ok) {
1358 NOTREACHED();
1359 continue;
1362 // Copy the rest of the chain. Copying the chain stops gracefully if an
1363 // error is encountered, with the partial chain being used as the
1364 // intermediates, as opposed to failing to consider the client certificate
1365 // at all.
1366 net::X509Certificate::OSCertHandles intermediates;
1367 for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; i++) {
1368 PCCERT_CONTEXT intermediate_copy;
1369 ok = CertAddCertificateContextToStore(
1370 NULL, chain_context->rgpChain[0]->rgpElement[i]->pCertContext,
1371 CERT_STORE_ADD_USE_EXISTING, &intermediate_copy);
1372 if (!ok) {
1373 NOTREACHED();
1374 break;
1376 intermediates.push_back(intermediate_copy);
1379 scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle(
1380 cert_context2, intermediates);
1381 core->nss_handshake_state_.client_certs.push_back(cert);
1383 X509Certificate::FreeOSCertHandle(cert_context2);
1384 for (net::X509Certificate::OSCertHandles::iterator it =
1385 intermediates.begin(); it != intermediates.end(); ++it) {
1386 net::X509Certificate::FreeOSCertHandle(*it);
1390 std::sort(core->nss_handshake_state_.client_certs.begin(),
1391 core->nss_handshake_state_.client_certs.end(),
1392 x509_util::ClientCertSorter());
1394 BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG);
1395 DCHECK(ok);
1397 // Update the network task runner's view of the handshake state now that
1398 // client certs have been detected.
1399 core->PostOrRunCallback(
1400 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1401 core->nss_handshake_state_));
1403 // Tell NSS to suspend the client authentication. We will then abort the
1404 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1405 return SECWouldBlock;
1406 #elif defined(OS_MACOSX)
1407 if (core->ssl_config_.send_client_cert) {
1408 if (core->ssl_config_.client_cert) {
1409 OSStatus os_error = noErr;
1410 SecIdentityRef identity = NULL;
1411 SecKeyRef private_key = NULL;
1412 CFArrayRef chain =
1413 core->ssl_config_.client_cert->CreateClientCertificateChain();
1414 if (chain) {
1415 identity = reinterpret_cast<SecIdentityRef>(
1416 const_cast<void*>(CFArrayGetValueAtIndex(chain, 0)));
1418 if (identity)
1419 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1421 if (chain && identity && os_error == noErr) {
1422 // TODO(rsleevi): Error checking for NSS allocation errors.
1423 *result_certs = CERT_NewCertList();
1424 *result_private_key = private_key;
1426 for (CFIndex i = 0; i < CFArrayGetCount(chain); ++i) {
1427 CSSM_DATA cert_data;
1428 SecCertificateRef cert_ref;
1429 if (i == 0) {
1430 cert_ref = core->ssl_config_.client_cert->os_cert_handle();
1431 } else {
1432 cert_ref = reinterpret_cast<SecCertificateRef>(
1433 const_cast<void*>(CFArrayGetValueAtIndex(chain, i)));
1435 os_error = SecCertificateGetData(cert_ref, &cert_data);
1436 if (os_error != noErr)
1437 break;
1439 SECItem der_cert;
1440 der_cert.type = siDERCertBuffer;
1441 der_cert.data = cert_data.Data;
1442 der_cert.len = cert_data.Length;
1443 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1444 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1445 if (!nss_cert) {
1446 // In the event of an NSS error we make up an OS error and reuse
1447 // the error handling, below.
1448 os_error = errSecCreateChainFailed;
1449 break;
1451 CERT_AddCertToListTail(*result_certs, nss_cert);
1454 if (os_error == noErr) {
1455 int cert_count = 0;
1456 if (chain) {
1457 cert_count = CFArrayGetCount(chain);
1458 CFRelease(chain);
1460 core->AddCertProvidedEvent(cert_count);
1461 return SECSuccess;
1463 OSSTATUS_LOG(WARNING, os_error)
1464 << "Client cert found, but could not be used";
1465 if (*result_certs) {
1466 CERT_DestroyCertList(*result_certs);
1467 *result_certs = NULL;
1469 if (*result_private_key)
1470 *result_private_key = NULL;
1471 if (private_key)
1472 CFRelease(private_key);
1473 if (chain)
1474 CFRelease(chain);
1477 // Send no client certificate.
1478 core->AddCertProvidedEvent(0);
1479 return SECFailure;
1482 core->nss_handshake_state_.client_certs.clear();
1484 // First, get the cert issuer names allowed by the server.
1485 std::vector<CertPrincipal> valid_issuers;
1486 int n = ca_names->nnames;
1487 for (int i = 0; i < n; i++) {
1488 // Parse each name into a CertPrincipal object.
1489 CertPrincipal p;
1490 if (p.ParseDistinguishedName(ca_names->names[i].data,
1491 ca_names->names[i].len)) {
1492 valid_issuers.push_back(p);
1496 // Now get the available client certs whose issuers are allowed by the server.
1497 X509Certificate::GetSSLClientCertificates(
1498 core->host_and_port_.host(), valid_issuers,
1499 &core->nss_handshake_state_.client_certs);
1501 std::sort(core->nss_handshake_state_.client_certs.begin(),
1502 core->nss_handshake_state_.client_certs.end(),
1503 x509_util::ClientCertSorter());
1505 // Update the network task runner's view of the handshake state now that
1506 // client certs have been detected.
1507 core->PostOrRunCallback(
1508 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1509 core->nss_handshake_state_));
1511 // Tell NSS to suspend the client authentication. We will then abort the
1512 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1513 return SECWouldBlock;
1514 #else
1515 return SECFailure;
1516 #endif
1519 #elif defined(OS_IOS)
1521 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1522 void* arg,
1523 PRFileDesc* socket,
1524 CERTDistNames* ca_names,
1525 CERTCertificate** result_certificate,
1526 SECKEYPrivateKey** result_private_key) {
1527 Core* core = reinterpret_cast<Core*>(arg);
1528 DCHECK(core->OnNSSTaskRunner());
1530 core->PostOrRunCallback(
1531 FROM_HERE,
1532 base::Bind(&AddLogEvent, core->weak_net_log_,
1533 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1535 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1536 LOG(WARNING) << "Client auth is not supported";
1538 // Never send a certificate.
1539 core->AddCertProvidedEvent(0);
1540 return SECFailure;
1543 #else // NSS_PLATFORM_CLIENT_AUTH
1545 // static
1546 // Based on Mozilla's NSS_GetClientAuthData.
1547 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1548 void* arg,
1549 PRFileDesc* socket,
1550 CERTDistNames* ca_names,
1551 CERTCertificate** result_certificate,
1552 SECKEYPrivateKey** result_private_key) {
1553 Core* core = reinterpret_cast<Core*>(arg);
1554 DCHECK(core->OnNSSTaskRunner());
1556 core->PostOrRunCallback(
1557 FROM_HERE,
1558 base::Bind(&AddLogEvent, core->weak_net_log_,
1559 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1561 // Regular client certificate requested.
1562 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1563 void* wincx = SSL_RevealPinArg(socket);
1565 // Second pass: a client certificate should have been selected.
1566 if (core->ssl_config_.send_client_cert) {
1567 if (core->ssl_config_.client_cert) {
1568 CERTCertificate* cert = CERT_DupCertificate(
1569 core->ssl_config_.client_cert->os_cert_handle());
1570 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1571 if (privkey) {
1572 // TODO(jsorianopastor): We should wait for server certificate
1573 // verification before sending our credentials. See
1574 // http://crbug.com/13934.
1575 *result_certificate = cert;
1576 *result_private_key = privkey;
1577 // A cert_count of -1 means the number of certificates is unknown.
1578 // NSS will construct the certificate chain.
1579 core->AddCertProvidedEvent(-1);
1581 return SECSuccess;
1583 LOG(WARNING) << "Client cert found without private key";
1585 // Send no client certificate.
1586 core->AddCertProvidedEvent(0);
1587 return SECFailure;
1590 core->nss_handshake_state_.client_certs.clear();
1592 // Iterate over all client certificates.
1593 CERTCertList* client_certs = CERT_FindUserCertsByUsage(
1594 CERT_GetDefaultCertDB(), certUsageSSLClient,
1595 PR_FALSE, PR_FALSE, wincx);
1596 if (client_certs) {
1597 for (CERTCertListNode* node = CERT_LIST_HEAD(client_certs);
1598 !CERT_LIST_END(node, client_certs);
1599 node = CERT_LIST_NEXT(node)) {
1600 // Only offer unexpired certificates.
1601 if (CERT_CheckCertValidTimes(node->cert, PR_Now(), PR_TRUE) !=
1602 secCertTimeValid) {
1603 continue;
1605 // Filter by issuer.
1607 // TODO(davidben): This does a binary comparison of the DER-encoded
1608 // issuers. We should match according to RFC 5280 sec. 7.1. We should find
1609 // an appropriate NSS function or add one if needbe.
1610 if (ca_names->nnames &&
1611 NSS_CmpCertChainWCANames(node->cert, ca_names) != SECSuccess) {
1612 continue;
1615 X509Certificate* x509_cert = X509Certificate::CreateFromHandle(
1616 node->cert, net::X509Certificate::OSCertHandles());
1617 core->nss_handshake_state_.client_certs.push_back(x509_cert);
1619 CERT_DestroyCertList(client_certs);
1622 std::sort(core->nss_handshake_state_.client_certs.begin(),
1623 core->nss_handshake_state_.client_certs.end(),
1624 x509_util::ClientCertSorter());
1626 // Update the network task runner's view of the handshake state now that
1627 // client certs have been detected.
1628 core->PostOrRunCallback(
1629 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1630 core->nss_handshake_state_));
1632 // Tell NSS to suspend the client authentication. We will then abort the
1633 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1634 return SECWouldBlock;
1636 #endif // NSS_PLATFORM_CLIENT_AUTH
1638 // static
1639 void SSLClientSocketNSS::Core::HandshakeCallback(
1640 PRFileDesc* socket,
1641 void* arg) {
1642 Core* core = reinterpret_cast<Core*>(arg);
1643 DCHECK(core->OnNSSTaskRunner());
1645 core->handshake_callback_called_ = true;
1647 HandshakeState* nss_state = &core->nss_handshake_state_;
1649 PRBool last_handshake_resumed;
1650 SECStatus rv = SSL_HandshakeResumedSession(socket, &last_handshake_resumed);
1651 if (rv == SECSuccess && last_handshake_resumed) {
1652 nss_state->resumed_handshake = true;
1653 } else {
1654 nss_state->resumed_handshake = false;
1657 core->RecordChannelIDSupport();
1658 core->UpdateServerCert();
1659 core->UpdateConnectionStatus();
1661 // Update the network task runners view of the handshake state whenever
1662 // a handshake has completed.
1663 core->PostOrRunCallback(
1664 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1665 *nss_state));
1668 // static
1669 SECStatus SSLClientSocketNSS::Core::NextProtoCallback(
1670 void* arg,
1671 PRFileDesc* nss_fd,
1672 const unsigned char* protos,
1673 unsigned int protos_len,
1674 unsigned char* proto_out,
1675 unsigned int* proto_out_len,
1676 unsigned int proto_max_len) {
1677 Core* core = reinterpret_cast<Core*>(arg);
1678 DCHECK(core->OnNSSTaskRunner());
1680 HandshakeState* nss_state = &core->nss_handshake_state_;
1682 // For each protocol in server preference, see if we support it.
1683 for (unsigned int i = 0; i < protos_len; ) {
1684 const size_t len = protos[i];
1685 for (std::vector<std::string>::const_iterator
1686 j = core->ssl_config_.next_protos.begin();
1687 j != core->ssl_config_.next_protos.end(); j++) {
1688 // Having very long elements in the |next_protos| vector isn't a disaster
1689 // because they'll never be selected, but it does indicate an error
1690 // somewhere.
1691 DCHECK_LT(j->size(), 256u);
1693 if (j->size() == len &&
1694 memcmp(&protos[i + 1], j->data(), len) == 0) {
1695 nss_state->next_proto_status = kNextProtoNegotiated;
1696 nss_state->next_proto = *j;
1697 break;
1701 if (nss_state->next_proto_status == kNextProtoNegotiated)
1702 break;
1704 // NSS ensures that the data in |protos| is well formed, so this will not
1705 // cause a jump past the end of the buffer.
1706 i += len + 1;
1709 nss_state->server_protos.assign(
1710 reinterpret_cast<const char*>(protos), protos_len);
1712 // If we didn't find a protocol, we select the first one from our list.
1713 if (nss_state->next_proto_status != kNextProtoNegotiated) {
1714 nss_state->next_proto_status = kNextProtoNoOverlap;
1715 nss_state->next_proto = core->ssl_config_.next_protos[0];
1718 if (nss_state->next_proto.size() > proto_max_len) {
1719 PORT_SetError(SEC_ERROR_OUTPUT_LEN);
1720 return SECFailure;
1722 memcpy(proto_out, nss_state->next_proto.data(),
1723 nss_state->next_proto.size());
1724 *proto_out_len = nss_state->next_proto.size();
1726 // Update the network task runner's view of the handshake state now that
1727 // NPN negotiation has occurred.
1728 core->PostOrRunCallback(
1729 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1730 *nss_state));
1732 return SECSuccess;
1735 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error,
1736 bool handshake_error) {
1737 DCHECK(OnNSSTaskRunner());
1739 int net_error = handshake_error ? MapNSSClientHandshakeError(nss_error) :
1740 MapNSSClientError(nss_error);
1742 #if defined(OS_WIN)
1743 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1744 // os_cert_handle() as an optimization. However, if the certificate
1745 // private key is stored on a smart card, and the smart card is removed,
1746 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1747 // preventing client certificate authentication. Because the
1748 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1749 // caching in X509Certificate, this failure ends up preventing client
1750 // certificate authentication with the same certificate for all future
1751 // attempts, even after the smart card has been re-inserted. By setting
1752 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1753 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1754 // the certificate on the next attempt, which should succeed if the smart
1755 // card has been re-inserted, or will typically prompt the user to
1756 // re-insert the smart card if not.
1757 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1758 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1759 ssl_config_.send_client_cert && ssl_config_.client_cert) {
1760 CertSetCertificateContextProperty(
1761 ssl_config_.client_cert->os_cert_handle(),
1762 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1764 #endif
1766 return net_error;
1769 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1770 DCHECK(OnNSSTaskRunner());
1772 int rv = last_io_result;
1773 do {
1774 // Default to STATE_NONE for next state.
1775 State state = next_handshake_state_;
1776 GotoState(STATE_NONE);
1778 switch (state) {
1779 case STATE_HANDSHAKE:
1780 rv = DoHandshake();
1781 break;
1782 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1783 rv = DoGetDBCertComplete(rv);
1784 break;
1785 case STATE_NONE:
1786 default:
1787 rv = ERR_UNEXPECTED;
1788 LOG(DFATAL) << "unexpected state " << state;
1789 break;
1792 // Do the actual network I/O
1793 bool network_moved = DoTransportIO();
1794 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1795 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1796 // special case we keep looping even if rv is ERR_IO_PENDING because
1797 // the transport IO may allow DoHandshake to make progress.
1798 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1799 rv = OK; // This causes us to stay in the loop.
1801 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1802 return rv;
1805 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1806 DCHECK(OnNSSTaskRunner());
1807 DCHECK(handshake_callback_called_);
1808 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1810 if (result < 0)
1811 return result;
1813 if (!nss_bufs_) {
1814 LOG(DFATAL) << "!nss_bufs_";
1815 int rv = ERR_UNEXPECTED;
1816 PostOrRunCallback(
1817 FROM_HERE,
1818 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1819 NetLog::TYPE_SSL_READ_ERROR,
1820 CreateNetLogSSLErrorCallback(rv, 0)));
1821 return rv;
1824 bool network_moved;
1825 int rv;
1826 do {
1827 rv = DoPayloadRead();
1828 network_moved = DoTransportIO();
1829 } while (rv == ERR_IO_PENDING && network_moved);
1831 return rv;
1834 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1835 DCHECK(OnNSSTaskRunner());
1836 DCHECK(handshake_callback_called_);
1837 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1839 if (result < 0)
1840 return result;
1842 if (!nss_bufs_) {
1843 LOG(DFATAL) << "!nss_bufs_";
1844 int rv = ERR_UNEXPECTED;
1845 PostOrRunCallback(
1846 FROM_HERE,
1847 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1848 NetLog::TYPE_SSL_READ_ERROR,
1849 CreateNetLogSSLErrorCallback(rv, 0)));
1850 return rv;
1853 bool network_moved;
1854 int rv;
1855 do {
1856 rv = DoPayloadWrite();
1857 network_moved = DoTransportIO();
1858 } while (rv == ERR_IO_PENDING && network_moved);
1860 LeaveFunction(rv);
1861 return rv;
1864 int SSLClientSocketNSS::Core::DoHandshake() {
1865 DCHECK(OnNSSTaskRunner());
1867 int net_error = net::OK;
1868 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1870 // Note: this function may be called multiple times during the handshake, so
1871 // even though channel id and client auth are separate else cases, they can
1872 // both be used during a single SSL handshake.
1873 if (channel_id_needed_) {
1874 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1875 net_error = ERR_IO_PENDING;
1876 } else if (client_auth_cert_needed_) {
1877 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1878 PostOrRunCallback(
1879 FROM_HERE,
1880 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1881 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1882 CreateNetLogSSLErrorCallback(net_error, 0)));
1884 // If the handshake already succeeded (because the server requests but
1885 // doesn't require a client cert), we need to invalidate the SSL session
1886 // so that we won't try to resume the non-client-authenticated session in
1887 // the next handshake. This will cause the server to ask for a client
1888 // cert again.
1889 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess)
1890 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError();
1891 } else if (rv == SECSuccess) {
1892 if (!handshake_callback_called_) {
1893 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 -
1894 // SSL_ForceHandshake returned SECSuccess prematurely.
1895 rv = SECFailure;
1896 net_error = ERR_SSL_PROTOCOL_ERROR;
1897 PostOrRunCallback(
1898 FROM_HERE,
1899 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1900 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1901 CreateNetLogSSLErrorCallback(net_error, 0)));
1902 } else {
1903 #if defined(SSL_ENABLE_OCSP_STAPLING)
1904 // TODO(agl): figure out how to plumb an OCSP response into the Mac
1905 // system library and update IsOCSPStaplingSupported for Mac.
1906 if (IsOCSPStaplingSupported()) {
1907 unsigned int len = 0;
1908 SSL_GetStapledOCSPResponse(nss_fd_, NULL, &len);
1909 if (len) {
1910 const unsigned int orig_len = len;
1911 scoped_array<uint8> ocsp_response(new uint8[orig_len]);
1912 SSL_GetStapledOCSPResponse(nss_fd_, ocsp_response.get(), &len);
1913 DCHECK_EQ(orig_len, len);
1915 #if defined(OS_WIN)
1916 if (nss_handshake_state_.server_cert) {
1917 CRYPT_DATA_BLOB ocsp_response_blob;
1918 ocsp_response_blob.cbData = len;
1919 ocsp_response_blob.pbData = ocsp_response.get();
1920 BOOL ok = CertSetCertificateContextProperty(
1921 nss_handshake_state_.server_cert->os_cert_handle(),
1922 CERT_OCSP_RESPONSE_PROP_ID,
1923 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
1924 &ocsp_response_blob);
1925 if (!ok) {
1926 VLOG(1) << "Failed to set OCSP response property: "
1927 << GetLastError();
1930 #elif defined(USE_NSS)
1931 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
1932 GetCacheOCSPResponseFromSideChannelFunction();
1933 SECItem ocsp_response_item;
1934 ocsp_response_item.type = siBuffer;
1935 ocsp_response_item.data = ocsp_response.get();
1936 ocsp_response_item.len = len;
1938 cache_ocsp_response(
1939 CERT_GetDefaultCertDB(),
1940 nss_handshake_state_.server_cert_chain[0], PR_Now(),
1941 &ocsp_response_item, NULL);
1942 #endif
1945 #endif
1947 // Done!
1948 } else {
1949 PRErrorCode prerr = PR_GetError();
1950 net_error = HandleNSSError(prerr, true);
1952 // Some network devices that inspect application-layer packets seem to
1953 // inject TCP reset packets to break the connections when they see
1954 // TLS 1.1 in ClientHello or ServerHello. See http://crbug.com/130293.
1956 // Only allow ERR_CONNECTION_RESET to trigger a TLS 1.1 -> TLS 1.0
1957 // fallback. We don't lose much in this fallback because the explicit
1958 // IV for CBC mode in TLS 1.1 is approximated by record splitting in
1959 // TLS 1.0.
1961 // ERR_CONNECTION_RESET is a common network error, so we don't want it
1962 // to trigger a version fallback in general, especially the TLS 1.0 ->
1963 // SSL 3.0 fallback, which would drop TLS extensions.
1964 if (prerr == PR_CONNECT_RESET_ERROR &&
1965 ssl_config_.version_max == SSL_PROTOCOL_VERSION_TLS1_1) {
1966 net_error = ERR_SSL_PROTOCOL_ERROR;
1969 // If not done, stay in this state
1970 if (net_error == ERR_IO_PENDING) {
1971 GotoState(STATE_HANDSHAKE);
1972 } else {
1973 PostOrRunCallback(
1974 FROM_HERE,
1975 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1976 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1977 CreateNetLogSSLErrorCallback(net_error, prerr)));
1981 return net_error;
1984 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1985 SECStatus rv;
1986 PostOrRunCallback(
1987 FROM_HERE,
1988 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1989 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1991 channel_id_needed_ = false;
1993 if (result != OK)
1994 return result;
1996 SECKEYPublicKey* public_key;
1997 SECKEYPrivateKey* private_key;
1998 int error = ImportChannelIDKeys(&public_key, &private_key);
1999 if (error != OK)
2000 return error;
2002 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
2003 if (rv != SECSuccess)
2004 return MapNSSError(PORT_GetError());
2006 SetChannelIDProvided();
2007 GotoState(STATE_HANDSHAKE);
2008 return OK;
2011 int SSLClientSocketNSS::Core::DoPayloadRead() {
2012 DCHECK(OnNSSTaskRunner());
2013 DCHECK(user_read_buf_);
2014 DCHECK_GT(user_read_buf_len_, 0);
2016 int rv = PR_Read(nss_fd_, user_read_buf_->data(), user_read_buf_len_);
2017 if (client_auth_cert_needed_) {
2018 // We don't need to invalidate the non-client-authenticated SSL session
2019 // because the server will renegotiate anyway.
2020 rv = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
2021 PostOrRunCallback(
2022 FROM_HERE,
2023 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2024 NetLog::TYPE_SSL_READ_ERROR,
2025 CreateNetLogSSLErrorCallback(rv, 0)));
2026 return rv;
2028 if (rv >= 0) {
2029 PostOrRunCallback(
2030 FROM_HERE,
2031 base::Bind(&LogByteTransferEvent, weak_net_log_,
2032 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
2033 scoped_refptr<IOBuffer>(user_read_buf_)));
2034 return rv;
2036 PRErrorCode prerr = PR_GetError();
2037 if (prerr == PR_WOULD_BLOCK_ERROR)
2038 return ERR_IO_PENDING;
2040 rv = HandleNSSError(prerr, false);
2041 PostOrRunCallback(
2042 FROM_HERE,
2043 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2044 NetLog::TYPE_SSL_READ_ERROR,
2045 CreateNetLogSSLErrorCallback(rv, prerr)));
2046 return rv;
2049 int SSLClientSocketNSS::Core::DoPayloadWrite() {
2050 DCHECK(OnNSSTaskRunner());
2052 DCHECK(user_write_buf_);
2054 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2055 if (rv >= 0) {
2056 PostOrRunCallback(
2057 FROM_HERE,
2058 base::Bind(&LogByteTransferEvent, weak_net_log_,
2059 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2060 scoped_refptr<IOBuffer>(user_write_buf_)));
2061 return rv;
2063 PRErrorCode prerr = PR_GetError();
2064 if (prerr == PR_WOULD_BLOCK_ERROR)
2065 return ERR_IO_PENDING;
2067 rv = HandleNSSError(prerr, false);
2068 PostOrRunCallback(
2069 FROM_HERE,
2070 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2071 NetLog::TYPE_SSL_WRITE_ERROR,
2072 CreateNetLogSSLErrorCallback(rv, prerr)));
2073 return rv;
2076 // Do as much network I/O as possible between the buffer and the
2077 // transport socket. Return true if some I/O performed, false
2078 // otherwise (error or ERR_IO_PENDING).
2079 bool SSLClientSocketNSS::Core::DoTransportIO() {
2080 DCHECK(OnNSSTaskRunner());
2082 bool network_moved = false;
2083 if (nss_bufs_ != NULL) {
2084 int rv;
2085 // Read and write as much data as we can. The loop is neccessary
2086 // because Write() may return synchronously.
2087 do {
2088 rv = BufferSend();
2089 if (rv > 0)
2090 network_moved = true;
2091 } while (rv > 0);
2092 if (!transport_recv_eof_ && BufferRecv() >= 0)
2093 network_moved = true;
2095 return network_moved;
2098 int SSLClientSocketNSS::Core::BufferRecv() {
2099 DCHECK(OnNSSTaskRunner());
2101 if (transport_recv_busy_)
2102 return ERR_IO_PENDING;
2104 char* buf;
2105 int nb = memio_GetReadParams(nss_bufs_, &buf);
2106 int rv;
2107 if (!nb) {
2108 // buffer too full to read into, so no I/O possible at moment
2109 rv = ERR_IO_PENDING;
2110 } else {
2111 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2112 if (OnNetworkTaskRunner()) {
2113 rv = DoBufferRecv(read_buffer, nb);
2114 } else {
2115 bool posted = network_task_runner_->PostTask(
2116 FROM_HERE,
2117 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2118 nb));
2119 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2122 if (rv == ERR_IO_PENDING) {
2123 transport_recv_busy_ = true;
2124 } else {
2125 if (rv > 0) {
2126 memcpy(buf, read_buffer->data(), rv);
2127 } else if (rv == 0) {
2128 transport_recv_eof_ = true;
2130 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2133 return rv;
2136 // Return 0 for EOF,
2137 // > 0 for bytes transferred immediately,
2138 // < 0 for error (or the non-error ERR_IO_PENDING).
2139 int SSLClientSocketNSS::Core::BufferSend() {
2140 DCHECK(OnNSSTaskRunner());
2142 if (transport_send_busy_)
2143 return ERR_IO_PENDING;
2145 const char* buf1;
2146 const char* buf2;
2147 unsigned int len1, len2;
2148 memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2);
2149 const unsigned int len = len1 + len2;
2151 int rv = 0;
2152 if (len) {
2153 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2154 memcpy(send_buffer->data(), buf1, len1);
2155 memcpy(send_buffer->data() + len1, buf2, len2);
2157 if (OnNetworkTaskRunner()) {
2158 rv = DoBufferSend(send_buffer, len);
2159 } else {
2160 bool posted = network_task_runner_->PostTask(
2161 FROM_HERE,
2162 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2163 len));
2164 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2167 if (rv == ERR_IO_PENDING) {
2168 transport_send_busy_ = true;
2169 } else {
2170 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2174 return rv;
2177 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2178 DCHECK(OnNSSTaskRunner());
2180 if (next_handshake_state_ == STATE_HANDSHAKE) {
2181 OnHandshakeIOComplete(result);
2182 return;
2185 // Network layer received some data, check if client requested to read
2186 // decrypted data.
2187 if (!user_read_buf_)
2188 return;
2190 int rv = DoReadLoop(result);
2191 if (rv != ERR_IO_PENDING)
2192 DoReadCallback(rv);
2195 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2196 DCHECK(OnNSSTaskRunner());
2198 if (next_handshake_state_ == STATE_HANDSHAKE) {
2199 OnHandshakeIOComplete(result);
2200 return;
2203 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2204 // handshake is in progress.
2205 int rv_read = ERR_IO_PENDING;
2206 int rv_write = ERR_IO_PENDING;
2207 bool network_moved;
2208 do {
2209 if (user_read_buf_)
2210 rv_read = DoPayloadRead();
2211 if (user_write_buf_)
2212 rv_write = DoPayloadWrite();
2213 network_moved = DoTransportIO();
2214 } while (rv_read == ERR_IO_PENDING &&
2215 rv_write == ERR_IO_PENDING &&
2216 (user_read_buf_ || user_write_buf_) &&
2217 network_moved);
2219 if (user_read_buf_ && rv_read != ERR_IO_PENDING)
2220 DoReadCallback(rv_read);
2221 if (user_write_buf_ && rv_write != ERR_IO_PENDING)
2222 DoWriteCallback(rv_write);
2225 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2226 // handshake. This requires network IO, which in turn calls
2227 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2228 // winds its way through the state machine and ends up being passed to the
2229 // callback. For Read() and Write(), that's what we want. But for Connect(),
2230 // the caller expects OK (i.e. 0) for success.
2231 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2232 DCHECK(OnNSSTaskRunner());
2233 DCHECK_NE(rv, ERR_IO_PENDING);
2234 DCHECK(!user_connect_callback_.is_null());
2236 base::Closure c = base::Bind(
2237 base::ResetAndReturn(&user_connect_callback_),
2238 rv > OK ? OK : rv);
2239 PostOrRunCallback(FROM_HERE, c);
2242 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2243 DCHECK(OnNSSTaskRunner());
2244 DCHECK_NE(ERR_IO_PENDING, rv);
2245 DCHECK(!user_read_callback_.is_null());
2247 user_read_buf_ = NULL;
2248 user_read_buf_len_ = 0;
2249 base::Closure c = base::Bind(
2250 base::ResetAndReturn(&user_read_callback_),
2251 rv);
2252 PostOrRunCallback(FROM_HERE, c);
2255 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2256 DCHECK(OnNSSTaskRunner());
2257 DCHECK_NE(ERR_IO_PENDING, rv);
2258 DCHECK(!user_write_callback_.is_null());
2260 // Since Run may result in Write being called, clear |user_write_callback_|
2261 // up front.
2262 user_write_buf_ = NULL;
2263 user_write_buf_len_ = 0;
2264 base::Closure c = base::Bind(
2265 base::ResetAndReturn(&user_write_callback_),
2266 rv);
2267 PostOrRunCallback(FROM_HERE, c);
2270 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
2271 void* arg,
2272 PRFileDesc* socket,
2273 SECKEYPublicKey **out_public_key,
2274 SECKEYPrivateKey **out_private_key) {
2275 Core* core = reinterpret_cast<Core*>(arg);
2276 DCHECK(core->OnNSSTaskRunner());
2278 core->PostOrRunCallback(
2279 FROM_HERE,
2280 base::Bind(&AddLogEvent, core->weak_net_log_,
2281 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
2283 // We have negotiated the TLS channel ID extension.
2284 core->channel_id_xtn_negotiated_ = true;
2285 std::string origin = "https://" + core->host_and_port_.ToString();
2286 std::vector<uint8> requested_cert_types;
2287 requested_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2288 int error = ERR_UNEXPECTED;
2289 if (core->OnNetworkTaskRunner()) {
2290 error = core->DoGetDomainBoundCert(origin, requested_cert_types);
2291 } else {
2292 bool posted = core->network_task_runner_->PostTask(
2293 FROM_HERE,
2294 base::Bind(
2295 IgnoreResult(&Core::DoGetDomainBoundCert),
2296 core, origin, requested_cert_types));
2297 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2300 if (error == ERR_IO_PENDING) {
2301 // Asynchronous case.
2302 core->channel_id_needed_ = true;
2303 return SECWouldBlock;
2306 core->PostOrRunCallback(
2307 FROM_HERE,
2308 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2309 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2310 SECStatus rv = SECSuccess;
2311 if (error == OK) {
2312 // Synchronous success.
2313 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2314 if (result == OK)
2315 core->SetChannelIDProvided();
2316 else
2317 rv = SECFailure;
2318 } else {
2319 rv = SECFailure;
2322 return rv;
2325 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2326 SECKEYPrivateKey** key) {
2327 // Set the certificate.
2328 SECItem cert_item;
2329 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2330 cert_item.len = domain_bound_cert_.size();
2331 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2332 &cert_item,
2333 NULL,
2334 PR_FALSE,
2335 PR_TRUE));
2336 if (cert == NULL)
2337 return MapNSSError(PORT_GetError());
2339 // Set the private key.
2340 switch (domain_bound_cert_type_) {
2341 case CLIENT_CERT_ECDSA_SIGN: {
2342 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2343 ServerBoundCertService::kEPKIPassword,
2344 reinterpret_cast<const unsigned char*>(
2345 domain_bound_private_key_.data()),
2346 domain_bound_private_key_.size(),
2347 &cert->subjectPublicKeyInfo,
2348 false,
2349 false,
2350 key,
2351 public_key)) {
2352 int error = MapNSSError(PORT_GetError());
2353 return error;
2355 break;
2358 default:
2359 NOTREACHED();
2360 return ERR_INVALID_ARGUMENT;
2363 return OK;
2366 void SSLClientSocketNSS::Core::UpdateServerCert() {
2367 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2368 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2369 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2370 if (nss_handshake_state_.server_cert) {
2371 // Since this will be called asynchronously on another thread, it needs to
2372 // own a reference to the certificate.
2373 NetLog::ParametersCallback net_log_callback =
2374 base::Bind(&NetLogX509CertificateCallback,
2375 nss_handshake_state_.server_cert);
2376 PostOrRunCallback(
2377 FROM_HERE,
2378 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2379 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2380 net_log_callback));
2384 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2385 SSLChannelInfo channel_info;
2386 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2387 &channel_info, sizeof(channel_info));
2388 if (ok == SECSuccess &&
2389 channel_info.length == sizeof(channel_info) &&
2390 channel_info.cipherSuite) {
2391 nss_handshake_state_.ssl_connection_status |=
2392 (static_cast<int>(channel_info.cipherSuite) &
2393 SSL_CONNECTION_CIPHERSUITE_MASK) <<
2394 SSL_CONNECTION_CIPHERSUITE_SHIFT;
2396 nss_handshake_state_.ssl_connection_status |=
2397 (static_cast<int>(channel_info.compressionMethod) &
2398 SSL_CONNECTION_COMPRESSION_MASK) <<
2399 SSL_CONNECTION_COMPRESSION_SHIFT;
2401 // NSS 3.12.x doesn't have version macros for TLS 1.1 and 1.2 (because NSS
2402 // doesn't support them yet), so we use 0x0302 and 0x0303 directly.
2403 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2404 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2405 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2406 // version 2.
2407 version = SSL_CONNECTION_VERSION_SSL2;
2408 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2409 version = SSL_CONNECTION_VERSION_SSL3;
2410 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) {
2411 version = SSL_CONNECTION_VERSION_TLS1;
2412 } else if (channel_info.protocolVersion == 0x0302) {
2413 version = SSL_CONNECTION_VERSION_TLS1_1;
2414 } else if (channel_info.protocolVersion == 0x0303) {
2415 version = SSL_CONNECTION_VERSION_TLS1_2;
2417 nss_handshake_state_.ssl_connection_status |=
2418 (version & SSL_CONNECTION_VERSION_MASK) <<
2419 SSL_CONNECTION_VERSION_SHIFT;
2422 // SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6.
2423 // Since SSL_MAX_EXTENSIONS was added at the same time, we can test
2424 // SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension.
2425 #if defined(SSL_MAX_EXTENSIONS)
2426 PRBool peer_supports_renego_ext;
2427 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2428 &peer_supports_renego_ext);
2429 if (ok == SECSuccess) {
2430 if (!peer_supports_renego_ext) {
2431 nss_handshake_state_.ssl_connection_status |=
2432 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2433 // Log an informational message if the server does not support secure
2434 // renegotiation (RFC 5746).
2435 VLOG(1) << "The server " << host_and_port_.ToString()
2436 << " does not support the TLS renegotiation_info extension.";
2438 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported",
2439 peer_supports_renego_ext, 2);
2441 // We would like to eliminate fallback to SSLv3 for non-buggy servers
2442 // because of security concerns. For example, Google offers forward
2443 // secrecy with ECDHE but that requires TLS 1.0. An attacker can block
2444 // TLSv1 connections and force us to downgrade to SSLv3 and remove forward
2445 // secrecy.
2447 // Yngve from Opera has suggested using the renegotiation extension as an
2448 // indicator that SSLv3 fallback was mistaken:
2449 // tools.ietf.org/html/draft-pettersen-tls-version-rollback-removal-00 .
2451 // As a first step, measure how often clients perform version fallback
2452 // while the server advertises support secure renegotiation.
2453 if (ssl_config_.version_fallback &&
2454 channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2455 UMA_HISTOGRAM_BOOLEAN("Net.SSLv3FallbackToRenegoPatchedServer",
2456 peer_supports_renego_ext == PR_TRUE);
2459 #endif
2461 if (ssl_config_.version_fallback) {
2462 nss_handshake_state_.ssl_connection_status |=
2463 SSL_CONNECTION_VERSION_FALLBACK;
2467 void SSLClientSocketNSS::Core::RecordChannelIDSupport() const {
2468 if (nss_handshake_state_.resumed_handshake)
2469 return;
2471 // Since this enum is used for a histogram, do not change or re-use values.
2472 enum {
2473 DISABLED = 0,
2474 CLIENT_ONLY = 1,
2475 CLIENT_AND_SERVER = 2,
2476 CLIENT_NO_ECC = 3,
2477 CLIENT_BAD_SYSTEM_TIME = 4,
2478 CLIENT_NO_SERVER_BOUND_CERT_SERVICE = 5,
2479 DOMAIN_BOUND_CERT_USAGE_MAX
2480 } supported = DISABLED;
2481 if (channel_id_xtn_negotiated_) {
2482 supported = CLIENT_AND_SERVER;
2483 } else if (ssl_config_.channel_id_enabled) {
2484 if (!server_bound_cert_service_)
2485 supported = CLIENT_NO_SERVER_BOUND_CERT_SERVICE;
2486 else if (!crypto::ECPrivateKey::IsSupported())
2487 supported = CLIENT_NO_ECC;
2488 else if (!server_bound_cert_service_->IsSystemTimeValid())
2489 supported = CLIENT_BAD_SYSTEM_TIME;
2490 else
2491 supported = CLIENT_ONLY;
2493 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported,
2494 DOMAIN_BOUND_CERT_USAGE_MAX);
2497 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2498 DCHECK(OnNetworkTaskRunner());
2499 DCHECK_GT(len, 0);
2501 if (detached_)
2502 return ERR_ABORTED;
2504 int rv = transport_->socket()->Read(
2505 read_buffer, len,
2506 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2507 scoped_refptr<IOBuffer>(read_buffer)));
2509 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2510 nss_task_runner_->PostTask(
2511 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2512 scoped_refptr<IOBuffer>(read_buffer), rv));
2513 return rv;
2516 return rv;
2519 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2520 DCHECK(OnNetworkTaskRunner());
2521 DCHECK_GT(len, 0);
2523 if (detached_)
2524 return ERR_ABORTED;
2526 int rv = transport_->socket()->Write(
2527 send_buffer, len,
2528 base::Bind(&Core::BufferSendComplete,
2529 base::Unretained(this)));
2531 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2532 nss_task_runner_->PostTask(
2533 FROM_HERE,
2534 base::Bind(&Core::BufferSendComplete, this, rv));
2535 return rv;
2538 return rv;
2541 int SSLClientSocketNSS::Core::DoGetDomainBoundCert(
2542 const std::string& origin,
2543 const std::vector<uint8>& requested_cert_types) {
2544 DCHECK(OnNetworkTaskRunner());
2546 if (detached_)
2547 return ERR_FAILED;
2549 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2551 int rv = server_bound_cert_service_->GetDomainBoundCert(
2552 origin,
2553 requested_cert_types,
2554 &domain_bound_cert_type_,
2555 &domain_bound_private_key_,
2556 &domain_bound_cert_,
2557 base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)),
2558 &domain_bound_cert_request_handle_);
2560 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2561 nss_task_runner_->PostTask(
2562 FROM_HERE,
2563 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2564 return ERR_IO_PENDING;
2567 return rv;
2570 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2571 const HandshakeState& state) {
2572 network_handshake_state_ = state;
2575 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2576 if (!OnNSSTaskRunner()) {
2577 if (detached_)
2578 return;
2580 nss_task_runner_->PostTask(
2581 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2582 return;
2585 DCHECK(OnNSSTaskRunner());
2587 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2588 transport_send_busy_ = false;
2589 OnSendComplete(result);
2592 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2593 if (!OnNSSTaskRunner()) {
2594 if (detached_)
2595 return;
2597 nss_task_runner_->PostTask(
2598 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2599 return;
2602 DCHECK(OnNSSTaskRunner());
2604 int rv = DoHandshakeLoop(result);
2605 if (rv != ERR_IO_PENDING)
2606 DoConnectCallback(rv);
2609 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) {
2610 DVLOG(1) << __FUNCTION__ << " " << result;
2611 DCHECK(OnNetworkTaskRunner());
2613 domain_bound_cert_request_handle_ = NULL;
2614 OnHandshakeIOComplete(result);
2617 void SSLClientSocketNSS::Core::BufferRecvComplete(
2618 IOBuffer* read_buffer,
2619 int result) {
2620 DCHECK(read_buffer);
2622 if (!OnNSSTaskRunner()) {
2623 if (detached_)
2624 return;
2626 nss_task_runner_->PostTask(
2627 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2628 scoped_refptr<IOBuffer>(read_buffer), result));
2629 return;
2632 DCHECK(OnNSSTaskRunner());
2634 if (result > 0) {
2635 char* buf;
2636 int nb = memio_GetReadParams(nss_bufs_, &buf);
2637 CHECK_GE(nb, result);
2638 memcpy(buf, read_buffer->data(), result);
2639 } else if (result == 0) {
2640 transport_recv_eof_ = true;
2643 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2644 transport_recv_busy_ = false;
2645 OnRecvComplete(result);
2648 void SSLClientSocketNSS::Core::PostOrRunCallback(
2649 const tracked_objects::Location& location,
2650 const base::Closure& task) {
2651 if (!OnNetworkTaskRunner()) {
2652 network_task_runner_->PostTask(
2653 FROM_HERE,
2654 base::Bind(&Core::PostOrRunCallback, this, location, task));
2655 return;
2658 if (detached_ || task.is_null())
2659 return;
2660 task.Run();
2663 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2664 PostOrRunCallback(
2665 FROM_HERE,
2666 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2667 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2668 NetLog::IntegerCallback("cert_count", cert_count)));
2671 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2672 PostOrRunCallback(
2673 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2674 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2675 nss_handshake_state_.channel_id_sent = true;
2676 // Update the network task runner's view of the handshake state now that
2677 // channel id has been sent.
2678 PostOrRunCallback(
2679 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2680 nss_handshake_state_));
2683 SSLClientSocketNSS::SSLClientSocketNSS(
2684 base::SequencedTaskRunner* nss_task_runner,
2685 ClientSocketHandle* transport_socket,
2686 const HostPortPair& host_and_port,
2687 const SSLConfig& ssl_config,
2688 const SSLClientSocketContext& context)
2689 : nss_task_runner_(nss_task_runner),
2690 transport_(transport_socket),
2691 host_and_port_(host_and_port),
2692 ssl_config_(ssl_config),
2693 cert_verifier_(context.cert_verifier),
2694 server_bound_cert_service_(context.server_bound_cert_service),
2695 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2696 completed_handshake_(false),
2697 next_handshake_state_(STATE_NONE),
2698 nss_fd_(NULL),
2699 net_log_(transport_socket->socket()->NetLog()),
2700 transport_security_state_(context.transport_security_state),
2701 valid_thread_id_(base::kInvalidThreadId) {
2702 EnterFunction("");
2703 InitCore();
2704 LeaveFunction("");
2707 SSLClientSocketNSS::~SSLClientSocketNSS() {
2708 EnterFunction("");
2709 Disconnect();
2710 LeaveFunction("");
2713 // static
2714 void SSLClientSocket::ClearSessionCache() {
2715 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2716 // bother initializing NSS just to clear an empty SSL session cache.
2717 if (!NSS_IsInitialized())
2718 return;
2720 SSL_ClearSessionCache();
2723 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2724 EnterFunction("");
2725 ssl_info->Reset();
2726 if (core_->state().server_cert_chain.empty() ||
2727 !core_->state().server_cert_chain[0]) {
2728 return false;
2731 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2732 ssl_info->cert = server_cert_verify_result_.verified_cert;
2733 ssl_info->connection_status =
2734 core_->state().ssl_connection_status;
2735 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2736 for (HashValueVector::const_iterator i = side_pinned_public_keys_.begin();
2737 i != side_pinned_public_keys_.end(); ++i) {
2738 ssl_info->public_key_hashes.push_back(*i);
2740 ssl_info->is_issued_by_known_root =
2741 server_cert_verify_result_.is_issued_by_known_root;
2742 ssl_info->client_cert_sent =
2743 ssl_config_.send_client_cert && ssl_config_.client_cert;
2744 ssl_info->channel_id_sent = WasChannelIDSent();
2746 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2747 core_->state().ssl_connection_status);
2748 SSLCipherSuiteInfo cipher_info;
2749 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2750 &cipher_info, sizeof(cipher_info));
2751 if (ok == SECSuccess) {
2752 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2753 } else {
2754 ssl_info->security_bits = -1;
2755 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2756 << " for cipherSuite " << cipher_suite;
2759 ssl_info->handshake_type = core_->state().resumed_handshake ?
2760 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2762 LeaveFunction("");
2763 return true;
2766 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2767 SSLCertRequestInfo* cert_request_info) {
2768 EnterFunction("");
2769 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair
2770 cert_request_info->host_and_port = host_and_port_.ToString();
2771 cert_request_info->client_certs = core_->state().client_certs;
2772 LeaveFunction(cert_request_info->client_certs.size());
2775 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2776 bool has_context,
2777 const base::StringPiece& context,
2778 unsigned char* out,
2779 unsigned int outlen) {
2780 if (!IsConnected())
2781 return ERR_SOCKET_NOT_CONNECTED;
2783 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2784 // the midst of a handshake.
2785 SECStatus result = SSL_ExportKeyingMaterial(
2786 nss_fd_, label.data(), label.size(), has_context,
2787 reinterpret_cast<const unsigned char*>(context.data()),
2788 context.length(), out, outlen);
2789 if (result != SECSuccess) {
2790 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2791 return MapNSSError(PORT_GetError());
2793 return OK;
2796 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2797 if (!IsConnected())
2798 return ERR_SOCKET_NOT_CONNECTED;
2799 unsigned char buf[64];
2800 unsigned int len;
2801 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2802 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2803 buf, &len, arraysize(buf));
2804 if (result != SECSuccess) {
2805 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2806 return MapNSSError(PORT_GetError());
2808 out->assign(reinterpret_cast<char*>(buf), len);
2809 return OK;
2812 SSLClientSocket::NextProtoStatus
2813 SSLClientSocketNSS::GetNextProto(std::string* proto,
2814 std::string* server_protos) {
2815 *proto = core_->state().next_proto;
2816 *server_protos = core_->state().server_protos;
2817 return core_->state().next_proto_status;
2820 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2821 EnterFunction("");
2822 DCHECK(transport_.get());
2823 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2824 DCHECK(user_connect_callback_.is_null());
2825 DCHECK(!callback.is_null());
2827 EnsureThreadIdAssigned();
2829 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2831 int rv = Init();
2832 if (rv != OK) {
2833 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2834 return rv;
2837 rv = InitializeSSLOptions();
2838 if (rv != OK) {
2839 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2840 return rv;
2843 rv = InitializeSSLPeerName();
2844 if (rv != OK) {
2845 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2846 return rv;
2849 GotoState(STATE_HANDSHAKE);
2851 rv = DoHandshakeLoop(OK);
2852 if (rv == ERR_IO_PENDING) {
2853 user_connect_callback_ = callback;
2854 } else {
2855 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2858 LeaveFunction("");
2859 return rv > OK ? OK : rv;
2862 void SSLClientSocketNSS::Disconnect() {
2863 EnterFunction("");
2865 CHECK(CalledOnValidThread());
2867 // Shut down anything that may call us back.
2868 core_->Detach();
2869 verifier_.reset();
2870 transport_->socket()->Disconnect();
2872 // Reset object state.
2873 user_connect_callback_.Reset();
2874 server_cert_verify_result_.Reset();
2875 completed_handshake_ = false;
2876 start_cert_verification_time_ = base::TimeTicks();
2877 InitCore();
2879 LeaveFunction("");
2882 bool SSLClientSocketNSS::IsConnected() const {
2883 // Ideally, we should also check if we have received the close_notify alert
2884 // message from the server, and return false in that case. We're not doing
2885 // that, so this function may return a false positive. Since the upper
2886 // layer (HttpNetworkTransaction) needs to handle a persistent connection
2887 // closed by the server when we send a request anyway, a false positive in
2888 // exchange for simpler code is a good trade-off.
2889 EnterFunction("");
2890 bool ret = completed_handshake_ && transport_->socket()->IsConnected();
2891 LeaveFunction("");
2892 return ret;
2895 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2896 // Unlike IsConnected, this method doesn't return a false positive.
2898 // Strictly speaking, we should check if we have received the close_notify
2899 // alert message from the server, and return false in that case. Although
2900 // the close_notify alert message means EOF in the SSL layer, it is just
2901 // bytes to the transport layer below, so
2902 // transport_->socket()->IsConnectedAndIdle() returns the desired false
2903 // when we receive close_notify.
2904 EnterFunction("");
2905 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle();
2906 LeaveFunction("");
2907 return ret;
2910 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
2911 return transport_->socket()->GetPeerAddress(address);
2914 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
2915 return transport_->socket()->GetLocalAddress(address);
2918 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
2919 return net_log_;
2922 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2923 if (transport_.get() && transport_->socket()) {
2924 transport_->socket()->SetSubresourceSpeculation();
2925 } else {
2926 NOTREACHED();
2930 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2931 if (transport_.get() && transport_->socket()) {
2932 transport_->socket()->SetOmniboxSpeculation();
2933 } else {
2934 NOTREACHED();
2938 bool SSLClientSocketNSS::WasEverUsed() const {
2939 if (transport_.get() && transport_->socket()) {
2940 return transport_->socket()->WasEverUsed();
2942 NOTREACHED();
2943 return false;
2946 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2947 if (transport_.get() && transport_->socket()) {
2948 return transport_->socket()->UsingTCPFastOpen();
2950 NOTREACHED();
2951 return false;
2954 int64 SSLClientSocketNSS::NumBytesRead() const {
2955 if (transport_.get() && transport_->socket()) {
2956 return transport_->socket()->NumBytesRead();
2958 NOTREACHED();
2959 return -1;
2962 base::TimeDelta SSLClientSocketNSS::GetConnectTimeMicros() const {
2963 if (transport_.get() && transport_->socket()) {
2964 return transport_->socket()->GetConnectTimeMicros();
2966 NOTREACHED();
2967 return base::TimeDelta::FromMicroseconds(-1);
2970 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
2971 const CompletionCallback& callback) {
2972 DCHECK(core_);
2973 DCHECK(!callback.is_null());
2975 EnterFunction(buf_len);
2976 int rv = core_->Read(buf, buf_len, callback);
2977 LeaveFunction(rv);
2979 return rv;
2982 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
2983 const CompletionCallback& callback) {
2984 DCHECK(core_);
2985 DCHECK(!callback.is_null());
2987 EnterFunction(buf_len);
2988 int rv = core_->Write(buf, buf_len, callback);
2989 LeaveFunction(rv);
2991 return rv;
2994 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
2995 return transport_->socket()->SetReceiveBufferSize(size);
2998 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) {
2999 return transport_->socket()->SetSendBufferSize(size);
3002 int SSLClientSocketNSS::Init() {
3003 EnterFunction("");
3004 // Initialize the NSS SSL library in a threadsafe way. This also
3005 // initializes the NSS base library.
3006 EnsureNSSSSLInit();
3007 if (!NSS_IsInitialized())
3008 return ERR_UNEXPECTED;
3009 #if defined(USE_NSS) || defined(OS_IOS)
3010 if (ssl_config_.cert_io_enabled) {
3011 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3012 // loop by MessageLoopForIO::current().
3013 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3014 EnsureNSSHttpIOInit();
3016 #endif
3018 LeaveFunction("");
3019 return OK;
3022 void SSLClientSocketNSS::InitCore() {
3023 core_ = new Core(base::ThreadTaskRunnerHandle::Get(), nss_task_runner_,
3024 transport_.get(), host_and_port_, ssl_config_, &net_log_,
3025 server_bound_cert_service_);
3028 int SSLClientSocketNSS::InitializeSSLOptions() {
3029 // Transport connected, now hook it up to nss
3030 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3031 if (nss_fd_ == NULL) {
3032 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3035 // Grab pointer to buffers
3036 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3038 /* Create SSL state machine */
3039 /* Push SSL onto our fake I/O socket */
3040 nss_fd_ = SSL_ImportFD(NULL, nss_fd_);
3041 if (nss_fd_ == NULL) {
3042 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3043 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3045 // TODO(port): set more ssl options! Check errors!
3047 int rv;
3049 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3050 if (rv != SECSuccess) {
3051 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3052 return ERR_UNEXPECTED;
3055 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3056 if (rv != SECSuccess) {
3057 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3058 return ERR_UNEXPECTED;
3061 // Don't do V2 compatible hellos because they don't support TLS extensions.
3062 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3063 if (rv != SECSuccess) {
3064 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3065 return ERR_UNEXPECTED;
3068 SSLVersionRange version_range;
3069 version_range.min = ssl_config_.version_min;
3070 version_range.max = ssl_config_.version_max;
3071 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3072 if (rv != SECSuccess) {
3073 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3074 return ERR_NO_SSL_VERSIONS_ENABLED;
3077 for (std::vector<uint16>::const_iterator it =
3078 ssl_config_.disabled_cipher_suites.begin();
3079 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3080 // This will fail if the specified cipher is not implemented by NSS, but
3081 // the failure is harmless.
3082 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3085 #ifdef SSL_ENABLE_SESSION_TICKETS
3086 // Support RFC 5077
3087 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3088 if (rv != SECSuccess) {
3089 LogFailedNSSFunction(
3090 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3092 #else
3093 #error "You need to install NSS-3.12 or later to build chromium"
3094 #endif
3096 #ifdef SSL_ENABLE_FALSE_START
3097 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3098 ssl_config_.false_start_enabled);
3099 if (rv != SECSuccess)
3100 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3101 #endif
3103 #ifdef SSL_ENABLE_RENEGOTIATION
3104 // We allow servers to request renegotiation. Since we're a client,
3105 // prohibiting this is rather a waste of time. Only servers are in a
3106 // position to prevent renegotiation attacks.
3107 // http://extendedsubset.com/?p=8
3109 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3110 SSL_RENEGOTIATE_TRANSITIONAL);
3111 if (rv != SECSuccess) {
3112 LogFailedNSSFunction(
3113 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3115 #endif // SSL_ENABLE_RENEGOTIATION
3117 #ifdef SSL_CBC_RANDOM_IV
3118 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV,
3119 ssl_config_.false_start_enabled);
3120 if (rv != SECSuccess)
3121 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3122 #endif
3124 #ifdef SSL_ENABLE_OCSP_STAPLING
3125 if (IsOCSPStaplingSupported()) {
3126 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE);
3127 if (rv != SECSuccess) {
3128 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3129 "SSL_ENABLE_OCSP_STAPLING");
3132 #endif
3134 #ifdef SSL_ENABLE_CACHED_INFO
3135 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO,
3136 ssl_config_.cached_info_enabled);
3137 if (rv != SECSuccess)
3138 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO");
3139 #endif
3141 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3142 if (rv != SECSuccess) {
3143 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3144 return ERR_UNEXPECTED;
3147 if (!core_->Init(nss_fd_, nss_bufs))
3148 return ERR_UNEXPECTED;
3150 // Tell SSL the hostname we're trying to connect to.
3151 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3153 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3154 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3156 return OK;
3159 int SSLClientSocketNSS::InitializeSSLPeerName() {
3160 // Tell NSS who we're connected to
3161 IPEndPoint peer_address;
3162 int err = transport_->socket()->GetPeerAddress(&peer_address);
3163 if (err != OK)
3164 return err;
3166 SockaddrStorage storage;
3167 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3168 return ERR_UNEXPECTED;
3170 PRNetAddr peername;
3171 memset(&peername, 0, sizeof(peername));
3172 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3173 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3174 sizeof(peername));
3175 memcpy(&peername, storage.addr, len);
3177 // Adjust the address family field for BSD, whose sockaddr
3178 // structure has a one-byte length and one-byte address family
3179 // field at the beginning. PRNetAddr has a two-byte address
3180 // family field at the beginning.
3181 peername.raw.family = storage.addr->sa_family;
3183 memio_SetPeerName(nss_fd_, &peername);
3185 // Set the peer ID for session reuse. This is necessary when we create an
3186 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3187 // rather than the destination server's address in that case.
3188 std::string peer_id = host_and_port_.ToString();
3189 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id.
3190 // This will cause session cache misses between sockets with different values
3191 // of ssl_session_cache_shard_ and this is used to partition the session cache
3192 // for incognito mode.
3193 if (!ssl_session_cache_shard_.empty()) {
3194 peer_id += "/" + ssl_session_cache_shard_;
3196 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3197 if (rv != SECSuccess)
3198 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3200 return OK;
3203 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3204 EnterFunction(rv);
3205 DCHECK_NE(ERR_IO_PENDING, rv);
3206 DCHECK(!user_connect_callback_.is_null());
3208 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3209 LeaveFunction("");
3212 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3213 EnterFunction(result);
3214 int rv = DoHandshakeLoop(result);
3215 if (rv != ERR_IO_PENDING) {
3216 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3217 DoConnectCallback(rv);
3219 LeaveFunction("");
3222 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3223 EnterFunction(last_io_result);
3224 int rv = last_io_result;
3225 do {
3226 // Default to STATE_NONE for next state.
3227 // (This is a quirk carried over from the windows
3228 // implementation. It makes reading the logs a bit harder.)
3229 // State handlers can and often do call GotoState just
3230 // to stay in the current state.
3231 State state = next_handshake_state_;
3232 GotoState(STATE_NONE);
3233 switch (state) {
3234 case STATE_HANDSHAKE:
3235 rv = DoHandshake();
3236 break;
3237 case STATE_HANDSHAKE_COMPLETE:
3238 rv = DoHandshakeComplete(rv);
3239 break;
3240 case STATE_VERIFY_CERT:
3241 DCHECK(rv == OK);
3242 rv = DoVerifyCert(rv);
3243 break;
3244 case STATE_VERIFY_CERT_COMPLETE:
3245 rv = DoVerifyCertComplete(rv);
3246 break;
3247 case STATE_NONE:
3248 default:
3249 rv = ERR_UNEXPECTED;
3250 LOG(DFATAL) << "unexpected state " << state;
3251 break;
3253 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3254 LeaveFunction("");
3255 return rv;
3258 int SSLClientSocketNSS::DoHandshake() {
3259 EnterFunction("");
3260 int rv = core_->Connect(
3261 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3262 base::Unretained(this)));
3263 GotoState(STATE_HANDSHAKE_COMPLETE);
3265 LeaveFunction(rv);
3266 return rv;
3269 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3270 EnterFunction(result);
3272 if (result == OK) {
3273 // SSL handshake is completed. Let's verify the certificate.
3274 GotoState(STATE_VERIFY_CERT);
3275 // Done!
3277 set_channel_id_sent(core_->state().channel_id_sent);
3279 LeaveFunction(result);
3280 return result;
3284 int SSLClientSocketNSS::DoVerifyCert(int result) {
3285 DCHECK(!core_->state().server_cert_chain.empty());
3286 DCHECK(core_->state().server_cert_chain[0]);
3288 GotoState(STATE_VERIFY_CERT_COMPLETE);
3290 // If the certificate is expected to be bad we can use the expectation as
3291 // the cert status.
3292 base::StringPiece der_cert(
3293 reinterpret_cast<char*>(
3294 core_->state().server_cert_chain[0]->derCert.data),
3295 core_->state().server_cert_chain[0]->derCert.len);
3296 CertStatus cert_status;
3297 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3298 DCHECK(start_cert_verification_time_.is_null());
3299 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3300 server_cert_verify_result_.Reset();
3301 server_cert_verify_result_.cert_status = cert_status;
3302 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3303 return OK;
3306 // We may have failed to create X509Certificate object if we are
3307 // running inside sandbox.
3308 if (!core_->state().server_cert) {
3309 server_cert_verify_result_.Reset();
3310 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3311 return ERR_CERT_INVALID;
3314 start_cert_verification_time_ = base::TimeTicks::Now();
3316 int flags = 0;
3317 if (ssl_config_.rev_checking_enabled)
3318 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3319 if (ssl_config_.verify_ev_cert)
3320 flags |= CertVerifier::VERIFY_EV_CERT;
3321 if (ssl_config_.cert_io_enabled)
3322 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3323 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3324 return verifier_->Verify(
3325 core_->state().server_cert, host_and_port_.host(), flags,
3326 SSLConfigService::GetCRLSet(), &server_cert_verify_result_,
3327 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3328 base::Unretained(this)),
3329 net_log_);
3332 // Derived from AuthCertificateCallback() in
3333 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3334 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3335 verifier_.reset();
3337 if (!start_cert_verification_time_.is_null()) {
3338 base::TimeDelta verify_time =
3339 base::TimeTicks::Now() - start_cert_verification_time_;
3340 if (result == OK)
3341 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3342 else
3343 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3346 // We used to remember the intermediate CA certs in the NSS database
3347 // persistently. However, NSS opens a connection to the SQLite database
3348 // during NSS initialization and doesn't close the connection until NSS
3349 // shuts down. If the file system where the database resides is gone,
3350 // the database connection goes bad. What's worse, the connection won't
3351 // recover when the file system comes back. Until this NSS or SQLite bug
3352 // is fixed, we need to avoid using the NSS database for non-essential
3353 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3354 // http://crbug.com/15630 for more info.
3356 // TODO(hclam): Skip logging if server cert was expected to be bad because
3357 // |server_cert_verify_result_| doesn't contain all the information about
3358 // the cert.
3359 if (result == OK)
3360 LogConnectionTypeMetrics();
3362 completed_handshake_ = true;
3364 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID)
3365 // Take care of any mandates for public key pinning.
3367 // Pinning is only enabled for official builds to make sure that others don't
3368 // end up with pins that cannot be easily updated.
3370 // TODO(agl): we might have an issue here where a request for foo.example.com
3371 // merges into a SPDY connection to www.example.com, and gets a different
3372 // certificate.
3374 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3375 if ((result == OK || (IsCertificateError(result) &&
3376 IsCertStatusMinorError(cert_status))) &&
3377 server_cert_verify_result_.is_issued_by_known_root &&
3378 transport_security_state_) {
3379 bool sni_available =
3380 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1 ||
3381 ssl_config_.version_fallback;
3382 const std::string& host = host_and_port_.host();
3384 TransportSecurityState::DomainState domain_state;
3385 if (transport_security_state_->GetDomainState(host, sni_available,
3386 &domain_state) &&
3387 domain_state.HasPins()) {
3388 if (!domain_state.IsChainOfPublicKeysPermitted(
3389 server_cert_verify_result_.public_key_hashes)) {
3390 // Pins are not enforced if the build is too old.
3391 if (TransportSecurityState::IsBuildTimely()) {
3392 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3393 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", false);
3394 TransportSecurityState::ReportUMAOnPinFailure(host);
3396 } else {
3397 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true);
3401 #endif
3403 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3404 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3405 return result;
3408 void SSLClientSocketNSS::LogConnectionTypeMetrics() const {
3409 UpdateConnectionTypeHistograms(CONNECTION_SSL);
3410 if (server_cert_verify_result_.has_md5)
3411 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5);
3412 if (server_cert_verify_result_.has_md2)
3413 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2);
3414 if (server_cert_verify_result_.has_md4)
3415 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4);
3416 if (server_cert_verify_result_.has_md5_ca)
3417 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA);
3418 if (server_cert_verify_result_.has_md2_ca)
3419 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA);
3420 int ssl_version = SSLConnectionStatusToVersion(
3421 core_->state().ssl_connection_status);
3422 switch (ssl_version) {
3423 case SSL_CONNECTION_VERSION_SSL2:
3424 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2);
3425 break;
3426 case SSL_CONNECTION_VERSION_SSL3:
3427 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3);
3428 break;
3429 case SSL_CONNECTION_VERSION_TLS1:
3430 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1);
3431 break;
3432 case SSL_CONNECTION_VERSION_TLS1_1:
3433 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_1);
3434 break;
3435 case SSL_CONNECTION_VERSION_TLS1_2:
3436 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1_2);
3437 break;
3441 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3442 base::AutoLock auto_lock(lock_);
3443 if (valid_thread_id_ != base::kInvalidThreadId)
3444 return;
3445 valid_thread_id_ = base::PlatformThread::CurrentId();
3448 bool SSLClientSocketNSS::CalledOnValidThread() const {
3449 EnsureThreadIdAssigned();
3450 base::AutoLock auto_lock(lock_);
3451 return valid_thread_id_ == base::PlatformThread::CurrentId();
3454 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const {
3455 return server_bound_cert_service_;
3458 } // namespace net