Disable draw_properties benchmark on Android.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blobb7beae151160aae4dde489c8d47d7a43d7b17c00
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
6 // from AuthCertificateCallback() in
7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
9 /* ***** BEGIN LICENSE BLOCK *****
10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
12 * The contents of this file are subject to the Mozilla Public License Version
13 * 1.1 (the "License"); you may not use this file except in compliance with
14 * the License. You may obtain a copy of the License at
15 * http://www.mozilla.org/MPL/
17 * Software distributed under the License is distributed on an "AS IS" basis,
18 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
19 * for the specific language governing rights and limitations under the
20 * License.
22 * The Original Code is the Netscape security libraries.
24 * The Initial Developer of the Original Code is
25 * Netscape Communications Corporation.
26 * Portions created by the Initial Developer are Copyright (C) 2000
27 * the Initial Developer. All Rights Reserved.
29 * Contributor(s):
30 * Ian McGreer <mcgreer@netscape.com>
31 * Javier Delgadillo <javi@netscape.com>
32 * Kai Engert <kengert@redhat.com>
34 * Alternatively, the contents of this file may be used under the terms of
35 * either the GNU General Public License Version 2 or later (the "GPL"), or
36 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
37 * in which case the provisions of the GPL or the LGPL are applicable instead
38 * of those above. If you wish to allow use of your version of this file only
39 * under the terms of either the GPL or the LGPL, and not to allow others to
40 * use your version of this file under the terms of the MPL, indicate your
41 * decision by deleting the provisions above and replace them with the notice
42 * and other provisions required by the GPL or the LGPL. If you do not delete
43 * the provisions above, a recipient may use your version of this file under
44 * the terms of any one of the MPL, the GPL or the LGPL.
46 * ***** END LICENSE BLOCK ***** */
48 #include "net/socket/ssl_client_socket_nss.h"
50 #include <certdb.h>
51 #include <hasht.h>
52 #include <keyhi.h>
53 #include <nspr.h>
54 #include <nss.h>
55 #include <ocsp.h>
56 #include <pk11pub.h>
57 #include <secerr.h>
58 #include <sechash.h>
59 #include <ssl.h>
60 #include <sslerr.h>
61 #include <sslproto.h>
63 #include <algorithm>
64 #include <limits>
65 #include <map>
67 #include "base/bind.h"
68 #include "base/bind_helpers.h"
69 #include "base/callback_helpers.h"
70 #include "base/compiler_specific.h"
71 #include "base/logging.h"
72 #include "base/memory/singleton.h"
73 #include "base/metrics/histogram.h"
74 #include "base/single_thread_task_runner.h"
75 #include "base/stl_util.h"
76 #include "base/strings/string_number_conversions.h"
77 #include "base/strings/string_util.h"
78 #include "base/strings/stringprintf.h"
79 #include "base/thread_task_runner_handle.h"
80 #include "base/threading/thread_restrictions.h"
81 #include "base/values.h"
82 #include "crypto/ec_private_key.h"
83 #include "crypto/nss_util.h"
84 #include "crypto/nss_util_internal.h"
85 #include "crypto/rsa_private_key.h"
86 #include "crypto/scoped_nss_types.h"
87 #include "net/base/address_list.h"
88 #include "net/base/dns_util.h"
89 #include "net/base/io_buffer.h"
90 #include "net/base/net_errors.h"
91 #include "net/cert/asn1_util.h"
92 #include "net/cert/cert_policy_enforcer.h"
93 #include "net/cert/cert_status_flags.h"
94 #include "net/cert/cert_verifier.h"
95 #include "net/cert/ct_ev_whitelist.h"
96 #include "net/cert/ct_verifier.h"
97 #include "net/cert/ct_verify_result.h"
98 #include "net/cert/scoped_nss_types.h"
99 #include "net/cert/sct_status_flags.h"
100 #include "net/cert/single_request_cert_verifier.h"
101 #include "net/cert/x509_certificate_net_log_param.h"
102 #include "net/cert/x509_util.h"
103 #include "net/http/transport_security_state.h"
104 #include "net/log/net_log.h"
105 #include "net/ocsp/nss_ocsp.h"
106 #include "net/socket/client_socket_handle.h"
107 #include "net/socket/nss_ssl_util.h"
108 #include "net/ssl/ssl_cert_request_info.h"
109 #include "net/ssl/ssl_cipher_suite_names.h"
110 #include "net/ssl/ssl_connection_status_flags.h"
111 #include "net/ssl/ssl_info.h"
113 #if defined(OS_WIN)
114 #include <windows.h>
115 #include <wincrypt.h>
117 #include "base/win/windows_version.h"
118 #elif defined(OS_MACOSX)
119 #include <Security/SecBase.h>
120 #include <Security/SecCertificate.h>
121 #include <Security/SecIdentity.h>
123 #include "base/mac/mac_logging.h"
124 #include "base/synchronization/lock.h"
125 #include "crypto/mac_security_services_lock.h"
126 #elif defined(USE_NSS)
127 #include <dlfcn.h>
128 #endif
130 namespace net {
132 // State machines are easier to debug if you log state transitions.
133 // Enable these if you want to see what's going on.
134 #if 1
135 #define EnterFunction(x)
136 #define LeaveFunction(x)
137 #define GotoState(s) next_handshake_state_ = s
138 #else
139 #define EnterFunction(x)\
140 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
141 << "; next_handshake_state " << next_handshake_state_
142 #define LeaveFunction(x)\
143 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
144 << "; next_handshake_state " << next_handshake_state_
145 #define GotoState(s)\
146 do {\
147 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
148 next_handshake_state_ = s;\
149 } while (0)
150 #endif
152 #if !defined(CKM_AES_GCM)
153 #define CKM_AES_GCM 0x00001087
154 #endif
156 #if !defined(CKM_NSS_CHACHA20_POLY1305)
157 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
158 #endif
160 namespace {
162 // SSL plaintext fragments are shorter than 16KB. Although the record layer
163 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
164 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
165 // entire SSL record.
166 const int kRecvBufferSize = 17 * 1024;
167 const int kSendBufferSize = 17 * 1024;
169 // Used by SSLClientSocketNSS::Core to indicate there is no read result
170 // obtained by a previous operation waiting to be returned to the caller.
171 // This constant can be any non-negative/non-zero value (eg: it does not
172 // overlap with any value of the net::Error range, including net::OK).
173 const int kNoPendingReadResult = 1;
175 #if defined(OS_WIN)
176 // CERT_OCSP_RESPONSE_PROP_ID is only implemented on Vista+, but it can be
177 // set on Windows XP without error. There is some overhead from the server
178 // sending the OCSP response if it supports the extension, for the subset of
179 // XP clients who will request it but be unable to use it, but this is an
180 // acceptable trade-off for simplicity of implementation.
181 bool IsOCSPStaplingSupported() {
182 return true;
184 #elif defined(USE_NSS)
185 typedef SECStatus
186 (*CacheOCSPResponseFromSideChannelFunction)(
187 CERTCertDBHandle *handle, CERTCertificate *cert, PRTime time,
188 SECItem *encodedResponse, void *pwArg);
190 // On Linux, we dynamically link against the system version of libnss3.so. In
191 // order to continue working on systems without up-to-date versions of NSS we
192 // lookup CERT_CacheOCSPResponseFromSideChannel with dlsym.
194 // RuntimeLibNSSFunctionPointers is a singleton which caches the results of any
195 // runtime symbol resolution that we need.
196 class RuntimeLibNSSFunctionPointers {
197 public:
198 CacheOCSPResponseFromSideChannelFunction
199 GetCacheOCSPResponseFromSideChannelFunction() {
200 return cache_ocsp_response_from_side_channel_;
203 static RuntimeLibNSSFunctionPointers* GetInstance() {
204 return Singleton<RuntimeLibNSSFunctionPointers>::get();
207 private:
208 friend struct DefaultSingletonTraits<RuntimeLibNSSFunctionPointers>;
210 RuntimeLibNSSFunctionPointers() {
211 cache_ocsp_response_from_side_channel_ =
212 (CacheOCSPResponseFromSideChannelFunction)
213 dlsym(RTLD_DEFAULT, "CERT_CacheOCSPResponseFromSideChannel");
216 CacheOCSPResponseFromSideChannelFunction
217 cache_ocsp_response_from_side_channel_;
220 CacheOCSPResponseFromSideChannelFunction
221 GetCacheOCSPResponseFromSideChannelFunction() {
222 return RuntimeLibNSSFunctionPointers::GetInstance()
223 ->GetCacheOCSPResponseFromSideChannelFunction();
226 bool IsOCSPStaplingSupported() {
227 return GetCacheOCSPResponseFromSideChannelFunction() != NULL;
229 #else
230 bool IsOCSPStaplingSupported() {
231 return false;
233 #endif
235 #if defined(OS_WIN)
237 // This callback is intended to be used with CertFindChainInStore. In addition
238 // to filtering by extended/enhanced key usage, we do not show expired
239 // certificates and require digital signature usage in the key usage
240 // extension.
242 // This matches our behavior on Mac OS X and that of NSS. It also matches the
243 // default behavior of IE8. See http://support.microsoft.com/kb/890326 and
244 // 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
245 BOOL WINAPI ClientCertFindCallback(PCCERT_CONTEXT cert_context,
246 void* find_arg) {
247 VLOG(1) << "Calling ClientCertFindCallback from _nss";
248 // Verify the certificate's KU is good.
249 BYTE key_usage;
250 if (CertGetIntendedKeyUsage(X509_ASN_ENCODING, cert_context->pCertInfo,
251 &key_usage, 1)) {
252 if (!(key_usage & CERT_DIGITAL_SIGNATURE_KEY_USAGE))
253 return FALSE;
254 } else {
255 DWORD err = GetLastError();
256 // If |err| is non-zero, it's an actual error. Otherwise the extension
257 // just isn't present, and we treat it as if everything was allowed.
258 if (err) {
259 DLOG(ERROR) << "CertGetIntendedKeyUsage failed: " << err;
260 return FALSE;
264 // Verify the current time is within the certificate's validity period.
265 if (CertVerifyTimeValidity(NULL, cert_context->pCertInfo) != 0)
266 return FALSE;
268 // Verify private key metadata is associated with this certificate.
269 DWORD size = 0;
270 if (!CertGetCertificateContextProperty(
271 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) {
272 return FALSE;
275 return TRUE;
278 #endif
280 // Helper functions to make it possible to log events from within the
281 // SSLClientSocketNSS::Core.
282 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
283 NetLog::EventType event_type) {
284 if (!net_log)
285 return;
286 net_log->AddEvent(event_type);
289 // Helper function to make it possible to log events from within the
290 // SSLClientSocketNSS::Core.
291 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
292 NetLog::EventType event_type,
293 const NetLog::ParametersCallback& callback) {
294 if (!net_log)
295 return;
296 net_log->AddEvent(event_type, callback);
299 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
300 // from within the SSLClientSocketNSS::Core.
301 // AddByteTransferEvent expects to receive a const char*, which within the
302 // Core is backed by an IOBuffer. If the "const char*" is bound via
303 // base::Bind and posted to another thread, and the IOBuffer that backs that
304 // pointer then goes out of scope on the origin thread, this would result in
305 // an invalid read of a stale pointer.
306 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
307 // to the owning IOBuffer can be bound to the Callback. This ensures that the
308 // IOBuffer will stay alive long enough to cross threads if needed.
309 void LogByteTransferEvent(
310 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
311 int len, IOBuffer* buffer) {
312 if (!net_log)
313 return;
314 net_log->AddByteTransferEvent(event_type, len, buffer->data());
317 // PeerCertificateChain is a helper object which extracts the certificate
318 // chain, as given by the server, from an NSS socket and performs the needed
319 // resource management. The first element of the chain is the leaf certificate
320 // and the other elements are in the order given by the server.
321 class PeerCertificateChain {
322 public:
323 PeerCertificateChain() {}
324 PeerCertificateChain(const PeerCertificateChain& other);
325 ~PeerCertificateChain();
326 PeerCertificateChain& operator=(const PeerCertificateChain& other);
328 // Resets the current chain, freeing any resources, and updates the current
329 // chain to be a copy of the chain stored in |nss_fd|.
330 // If |nss_fd| is NULL, then the current certificate chain will be freed.
331 void Reset(PRFileDesc* nss_fd);
333 // Returns the current certificate chain as a vector of DER-encoded
334 // base::StringPieces. The returned vector remains valid until Reset is
335 // called.
336 std::vector<base::StringPiece> AsStringPieceVector() const;
338 bool empty() const { return certs_.empty(); }
340 CERTCertificate* operator[](size_t index) const {
341 DCHECK_LT(index, certs_.size());
342 return certs_[index];
345 private:
346 std::vector<CERTCertificate*> certs_;
349 PeerCertificateChain::PeerCertificateChain(
350 const PeerCertificateChain& other) {
351 *this = other;
354 PeerCertificateChain::~PeerCertificateChain() {
355 Reset(NULL);
358 PeerCertificateChain& PeerCertificateChain::operator=(
359 const PeerCertificateChain& other) {
360 if (this == &other)
361 return *this;
363 Reset(NULL);
364 certs_.reserve(other.certs_.size());
365 for (size_t i = 0; i < other.certs_.size(); ++i)
366 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
368 return *this;
371 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
372 for (size_t i = 0; i < certs_.size(); ++i)
373 CERT_DestroyCertificate(certs_[i]);
374 certs_.clear();
376 if (nss_fd == NULL)
377 return;
379 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
380 // The handshake on |nss_fd| may not have completed.
381 if (list == NULL)
382 return;
384 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
385 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
386 certs_.push_back(CERT_DupCertificate(node->cert));
388 CERT_DestroyCertList(list);
391 std::vector<base::StringPiece>
392 PeerCertificateChain::AsStringPieceVector() const {
393 std::vector<base::StringPiece> v(certs_.size());
394 for (unsigned i = 0; i < certs_.size(); i++) {
395 v[i] = base::StringPiece(
396 reinterpret_cast<const char*>(certs_[i]->derCert.data),
397 certs_[i]->derCert.len);
400 return v;
403 // HandshakeState is a helper struct used to pass handshake state between
404 // the NSS task runner and the network task runner.
406 // It contains members that may be read or written on the NSS task runner,
407 // but which also need to be read from the network task runner. The NSS task
408 // runner will notify the network task runner whenever this state changes, so
409 // that the network task runner can safely make a copy, which avoids the need
410 // for locking.
411 struct HandshakeState {
412 HandshakeState() { Reset(); }
414 void Reset() {
415 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
416 next_proto.clear();
417 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
418 channel_id_sent = false;
419 server_cert_chain.Reset(NULL);
420 server_cert = NULL;
421 sct_list_from_tls_extension.clear();
422 stapled_ocsp_response.clear();
423 resumed_handshake = false;
424 ssl_connection_status = 0;
427 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
428 // negotiated protocol stored in |next_proto|.
429 SSLClientSocket::NextProtoStatus next_proto_status;
430 std::string next_proto;
432 // TLS extension used for protocol negotiation.
433 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
435 // True if a channel ID was sent.
436 bool channel_id_sent;
438 // List of DER-encoded X.509 DistinguishedName of certificate authorities
439 // allowed by the server.
440 std::vector<std::string> cert_authorities;
442 // Set when the handshake fully completes.
444 // The server certificate is first received from NSS as an NSS certificate
445 // chain (|server_cert_chain|) and then converted into a platform-specific
446 // X509Certificate object (|server_cert|). It's possible for some
447 // certificates to be successfully parsed by NSS, and not by the platform
448 // libraries (i.e.: when running within a sandbox, different parsing
449 // algorithms, etc), so it's not safe to assume that |server_cert| will
450 // always be non-NULL.
451 PeerCertificateChain server_cert_chain;
452 scoped_refptr<X509Certificate> server_cert;
453 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
454 std::string sct_list_from_tls_extension;
455 // Stapled OCSP response received.
456 std::string stapled_ocsp_response;
458 // True if the current handshake was the result of TLS session resumption.
459 bool resumed_handshake;
461 // The negotiated security parameters (TLS version, cipher, extensions) of
462 // the SSL connection.
463 int ssl_connection_status;
466 // Client-side error mapping functions.
468 // Map NSS error code to network error code.
469 int MapNSSClientError(PRErrorCode err) {
470 switch (err) {
471 case SSL_ERROR_BAD_CERT_ALERT:
472 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
473 case SSL_ERROR_REVOKED_CERT_ALERT:
474 case SSL_ERROR_EXPIRED_CERT_ALERT:
475 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
476 case SSL_ERROR_UNKNOWN_CA_ALERT:
477 case SSL_ERROR_ACCESS_DENIED_ALERT:
478 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
479 default:
480 return MapNSSError(err);
484 } // namespace
486 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
487 // able to marshal data between NSS functions and an underlying transport
488 // socket.
490 // All public functions are meant to be called from the network task runner,
491 // and any callbacks supplied will be invoked there as well, provided that
492 // Detach() has not been called yet.
494 /////////////////////////////////////////////////////////////////////////////
496 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
498 // Because NSS may block on either hardware or user input during operations
499 // such as signing, creating certificates, or locating private keys, the Core
500 // handles all of the interactions with the underlying NSS SSL socket, so
501 // that these blocking calls can be executed on a dedicated task runner.
503 // Note that the network task runner and the NSS task runner may be executing
504 // on the same thread. If that happens, then it's more performant to try to
505 // complete as much work as possible synchronously, even if it might block,
506 // rather than continually PostTask-ing to the same thread.
508 // Because NSS functions should only be called on the NSS task runner, while
509 // I/O resources should only be accessed on the network task runner, most
510 // public functions are implemented via three methods, each with different
511 // task runner affinities.
513 // In the single-threaded mode (where the network and NSS task runners run on
514 // the same thread), these are all attempted synchronously, while in the
515 // multi-threaded mode, message passing is used.
517 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
518 // DoHandshake)
519 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
520 // (BufferRecv, BufferSend)
521 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
522 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
523 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
524 // data from the network task runner back to NSS (BufferRecvComplete,
525 // BufferSendComplete, OnHandshakeIOComplete)
527 /////////////////////////////////////////////////////////////////////////////
528 // Single-threaded example
530 // |--------------------------Network Task Runner--------------------------|
531 // SSLClientSocketNSS Core (Transport Socket)
532 // Read()
533 // |-------------------------V
534 // Read()
535 // |
536 // DoPayloadRead()
537 // |
538 // BufferRecv()
539 // |
540 // DoBufferRecv()
541 // |-------------------------V
542 // Read()
543 // V-------------------------|
544 // BufferRecvComplete()
545 // |
546 // PostOrRunCallback()
547 // V-------------------------|
548 // (Read Callback)
550 /////////////////////////////////////////////////////////////////////////////
551 // Multi-threaded example:
553 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
554 // SSLClientSocketNSS Core Socket Core
555 // Read()
556 // |---------------------V
557 // Read()
558 // |-------------------------------V
559 // Read()
560 // |
561 // DoPayloadRead()
562 // |
563 // BufferRecv
564 // V-------------------------------|
565 // DoBufferRecv
566 // |----------------V
567 // Read()
568 // V----------------|
569 // BufferRecvComplete()
570 // |-------------------------------V
571 // BufferRecvComplete()
572 // |
573 // PostOrRunCallback()
574 // V-------------------------------|
575 // PostOrRunCallback()
576 // V---------------------|
577 // (Read Callback)
579 /////////////////////////////////////////////////////////////////////////////
580 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
581 public:
582 // Creates a new Core.
584 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
585 // that need to operate on the underlying transport, net log, or server
586 // bound certificate fetching will happen on the |network_task_runner|, so
587 // that their lifetimes match that of the owning SSLClientSocketNSS.
589 // The caller retains ownership of |transport|, |net_log|, and
590 // |channel_id_service|, and they will not be accessed once Detach()
591 // has been called.
592 Core(base::SequencedTaskRunner* network_task_runner,
593 base::SequencedTaskRunner* nss_task_runner,
594 ClientSocketHandle* transport,
595 const HostPortPair& host_and_port,
596 const SSLConfig& ssl_config,
597 BoundNetLog* net_log,
598 ChannelIDService* channel_id_service);
600 // Called on the network task runner.
601 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
602 // underlying memio implementation, to the Core. Returns true if the Core
603 // was successfully registered with the socket.
604 bool Init(PRFileDesc* socket, memio_Private* buffers);
606 // Called on the network task runner.
608 // Attempts to perform an SSL handshake. If the handshake cannot be
609 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
610 // the network task runner once the handshake has completed. Otherwise,
611 // returns OK on success or a network error code on failure.
612 int Connect(const CompletionCallback& callback);
614 // Called on the network task runner.
615 // Signals that the resources owned by the network task runner are going
616 // away. No further callbacks will be invoked on the network task runner.
617 // May be called at any time.
618 void Detach();
620 // Called on the network task runner.
621 // Returns the current state of the underlying SSL socket. May be called at
622 // any time.
623 const HandshakeState& state() const { return network_handshake_state_; }
625 // Called on the network task runner.
626 // Read() and Write() mirror the net::Socket functions of the same name.
627 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
628 // task runner at a later point, unless the caller calls Detach().
629 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
630 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
632 // Called on the network task runner.
633 bool IsConnected() const;
634 bool HasPendingAsyncOperation() const;
635 bool HasUnhandledReceivedData() const;
636 bool WasEverUsed() const;
638 // Called on the network task runner.
639 // Causes the associated SSL/TLS session ID to be added to NSS's session
640 // cache, but only if the connection has not been False Started.
642 // This should only be called after the server's certificate has been
643 // verified, and may not be called within an NSS callback.
644 void CacheSessionIfNecessary();
646 private:
647 friend class base::RefCountedThreadSafe<Core>;
648 ~Core();
650 enum State {
651 STATE_NONE,
652 STATE_HANDSHAKE,
653 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
656 bool OnNSSTaskRunner() const;
657 bool OnNetworkTaskRunner() const;
659 ////////////////////////////////////////////////////////////////////////////
660 // Methods that are ONLY called on the NSS task runner:
661 ////////////////////////////////////////////////////////////////////////////
663 // Called by NSS during full handshakes to allow the application to
664 // verify the certificate. Instead of verifying the certificate in the midst
665 // of the handshake, SECSuccess is always returned and the peer's certificate
666 // is verified afterwards.
667 // This behaviour is an artifact of the original SSLClientSocketWin
668 // implementation, which could not verify the peer's certificate until after
669 // the handshake had completed, as well as bugs in NSS that prevent
670 // SSL_RestartHandshakeAfterCertReq from working.
671 static SECStatus OwnAuthCertHandler(void* arg,
672 PRFileDesc* socket,
673 PRBool checksig,
674 PRBool is_server);
676 // Callbacks called by NSS when the peer requests client certificate
677 // authentication.
678 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
679 // the arguments.
680 #if defined(NSS_PLATFORM_CLIENT_AUTH)
681 // When NSS has been integrated with awareness of the underlying system
682 // cryptographic libraries, this callback allows the caller to supply a
683 // native platform certificate and key for use by NSS. At most, one of
684 // either (result_certs, result_private_key) or (result_nss_certificate,
685 // result_nss_private_key) should be set.
686 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
687 static SECStatus PlatformClientAuthHandler(
688 void* arg,
689 PRFileDesc* socket,
690 CERTDistNames* ca_names,
691 CERTCertList** result_certs,
692 void** result_private_key,
693 CERTCertificate** result_nss_certificate,
694 SECKEYPrivateKey** result_nss_private_key);
695 #else
696 static SECStatus ClientAuthHandler(void* arg,
697 PRFileDesc* socket,
698 CERTDistNames* ca_names,
699 CERTCertificate** result_certificate,
700 SECKEYPrivateKey** result_private_key);
701 #endif
703 // Called by NSS to determine if we can False Start.
704 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
705 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
706 void* arg,
707 PRBool* can_false_start);
709 // Called by NSS once the handshake has completed.
710 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
711 static void HandshakeCallback(PRFileDesc* socket, void* arg);
713 // Called once the handshake has succeeded.
714 void HandshakeSucceeded();
716 // Handles an NSS error generated while handshaking or performing IO.
717 // Returns a network error code mapped from the original NSS error.
718 int HandleNSSError(PRErrorCode error);
720 int DoHandshakeLoop(int last_io_result);
721 int DoReadLoop(int result);
722 int DoWriteLoop(int result);
724 int DoHandshake();
725 int DoGetDBCertComplete(int result);
727 int DoPayloadRead();
728 int DoPayloadWrite();
730 bool DoTransportIO();
731 int BufferRecv();
732 int BufferSend();
734 void OnRecvComplete(int result);
735 void OnSendComplete(int result);
737 void DoConnectCallback(int result);
738 void DoReadCallback(int result);
739 void DoWriteCallback(int result);
741 // Client channel ID handler.
742 static SECStatus ClientChannelIDHandler(
743 void* arg,
744 PRFileDesc* socket,
745 SECKEYPublicKey **out_public_key,
746 SECKEYPrivateKey **out_private_key);
748 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
749 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
750 // and an error code otherwise.
751 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
752 // set by a call to ChannelIDService->GetChannelID. The caller
753 // takes ownership of the |*cert| and |*key|.
754 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
756 // Updates the NSS and platform specific certificates.
757 void UpdateServerCert();
758 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
759 // received in the handshake via a TLS extension.
760 void UpdateSignedCertTimestamps();
761 // Update the OCSP response cache with the stapled response received in the
762 // handshake, and update nss_handshake_state_ with
763 // the SignedCertificateTimestampList received in the stapled OCSP response.
764 void UpdateStapledOCSPResponse();
765 // Updates the nss_handshake_state_ with the negotiated security parameters.
766 void UpdateConnectionStatus();
767 // Record histograms for channel id support during full handshakes - resumed
768 // handshakes are ignored.
769 void RecordChannelIDSupportOnNSSTaskRunner();
770 // UpdateNextProto gets any application-layer protocol that may have been
771 // negotiated by the TLS connection.
772 void UpdateNextProto();
773 // Record TLS extension used for protocol negotiation (NPN or ALPN).
774 void UpdateExtensionUsed();
776 ////////////////////////////////////////////////////////////////////////////
777 // Methods that are ONLY called on the network task runner:
778 ////////////////////////////////////////////////////////////////////////////
779 int DoBufferRecv(IOBuffer* buffer, int len);
780 int DoBufferSend(IOBuffer* buffer, int len);
781 int DoGetChannelID(const std::string& host);
783 void OnGetChannelIDComplete(int result);
784 void OnHandshakeStateUpdated(const HandshakeState& state);
785 void OnNSSBufferUpdated(int amount_in_read_buffer);
786 void DidNSSRead(int result);
787 void DidNSSWrite(int result);
788 void RecordChannelIDSupportOnNetworkTaskRunner(
789 bool negotiated_channel_id,
790 bool channel_id_enabled,
791 bool supports_ecc) const;
793 ////////////////////////////////////////////////////////////////////////////
794 // Methods that are called on both the network task runner and the NSS
795 // task runner.
796 ////////////////////////////////////////////////////////////////////////////
797 void OnHandshakeIOComplete(int result);
798 void BufferRecvComplete(IOBuffer* buffer, int result);
799 void BufferSendComplete(int result);
801 // PostOrRunCallback is a helper function to ensure that |callback| is
802 // invoked on the network task runner, but only if Detach() has not yet
803 // been called.
804 void PostOrRunCallback(const tracked_objects::Location& location,
805 const base::Closure& callback);
807 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
808 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
809 void AddCertProvidedEvent(int cert_count);
811 // Sets the handshake state |channel_id_sent| flag and logs the
812 // SSL_CHANNEL_ID_PROVIDED event.
813 void SetChannelIDProvided();
815 ////////////////////////////////////////////////////////////////////////////
816 // Members that are ONLY accessed on the network task runner:
817 ////////////////////////////////////////////////////////////////////////////
819 // True if the owning SSLClientSocketNSS has called Detach(). No further
820 // callbacks will be invoked nor access to members owned by the network
821 // task runner.
822 bool detached_;
824 // The underlying transport to use for network IO.
825 ClientSocketHandle* transport_;
826 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
828 // The current handshake state. Mirrors |nss_handshake_state_|.
829 HandshakeState network_handshake_state_;
831 // The service for retrieving Channel ID keys. May be NULL.
832 ChannelIDService* channel_id_service_;
833 ChannelIDService::RequestHandle domain_bound_cert_request_handle_;
835 // The information about NSS task runner.
836 int unhandled_buffer_size_;
837 bool nss_waiting_read_;
838 bool nss_waiting_write_;
839 bool nss_is_closed_;
841 // Set when Read() or Write() successfully reads or writes data to or from the
842 // network.
843 bool was_ever_used_;
845 ////////////////////////////////////////////////////////////////////////////
846 // Members that are ONLY accessed on the NSS task runner:
847 ////////////////////////////////////////////////////////////////////////////
848 HostPortPair host_and_port_;
849 SSLConfig ssl_config_;
851 // NSS SSL socket.
852 PRFileDesc* nss_fd_;
854 // Buffers for the network end of the SSL state machine
855 memio_Private* nss_bufs_;
857 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
858 // as much data as possible, without blocking.
859 // If DoPayloadRead() encounters an error after having read some data, stores
860 // the results to return on the *next* call to DoPayloadRead(). A value of
861 // kNoPendingReadResult indicates there is no pending result, otherwise 0
862 // indicates EOF and < 0 indicates an error.
863 int pending_read_result_;
864 // Contains the previously observed NSS error. Only valid when
865 // pending_read_result_ != kNoPendingReadResult.
866 PRErrorCode pending_read_nss_error_;
868 // The certificate chain, in DER form, that is expected to be received from
869 // the server.
870 std::vector<std::string> predicted_certs_;
872 State next_handshake_state_;
874 // True if channel ID extension was negotiated.
875 bool channel_id_xtn_negotiated_;
876 // True if the handshake state machine was interrupted for channel ID.
877 bool channel_id_needed_;
878 // True if the handshake state machine was interrupted for client auth.
879 bool client_auth_cert_needed_;
880 // True if NSS has False Started.
881 bool false_started_;
882 // True if NSS has called HandshakeCallback.
883 bool handshake_callback_called_;
885 HandshakeState nss_handshake_state_;
887 bool transport_recv_busy_;
888 bool transport_recv_eof_;
889 bool transport_send_busy_;
891 // Used by Read function.
892 scoped_refptr<IOBuffer> user_read_buf_;
893 int user_read_buf_len_;
895 // Used by Write function.
896 scoped_refptr<IOBuffer> user_write_buf_;
897 int user_write_buf_len_;
899 CompletionCallback user_connect_callback_;
900 CompletionCallback user_read_callback_;
901 CompletionCallback user_write_callback_;
903 ////////////////////////////////////////////////////////////////////////////
904 // Members that are accessed on both the network task runner and the NSS
905 // task runner.
906 ////////////////////////////////////////////////////////////////////////////
907 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
908 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
910 // Dereferenced only on the network task runner, but bound to tasks destined
911 // for the network task runner from the NSS task runner.
912 base::WeakPtr<BoundNetLog> weak_net_log_;
914 // Written on the network task runner by the |channel_id_service_|,
915 // prior to invoking OnHandshakeIOComplete.
916 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
917 // on the NSS task runner.
918 std::string domain_bound_private_key_;
919 std::string domain_bound_cert_;
921 DISALLOW_COPY_AND_ASSIGN(Core);
924 SSLClientSocketNSS::Core::Core(
925 base::SequencedTaskRunner* network_task_runner,
926 base::SequencedTaskRunner* nss_task_runner,
927 ClientSocketHandle* transport,
928 const HostPortPair& host_and_port,
929 const SSLConfig& ssl_config,
930 BoundNetLog* net_log,
931 ChannelIDService* channel_id_service)
932 : detached_(false),
933 transport_(transport),
934 weak_net_log_factory_(net_log),
935 channel_id_service_(channel_id_service),
936 unhandled_buffer_size_(0),
937 nss_waiting_read_(false),
938 nss_waiting_write_(false),
939 nss_is_closed_(false),
940 was_ever_used_(false),
941 host_and_port_(host_and_port),
942 ssl_config_(ssl_config),
943 nss_fd_(NULL),
944 nss_bufs_(NULL),
945 pending_read_result_(kNoPendingReadResult),
946 pending_read_nss_error_(0),
947 next_handshake_state_(STATE_NONE),
948 channel_id_xtn_negotiated_(false),
949 channel_id_needed_(false),
950 client_auth_cert_needed_(false),
951 false_started_(false),
952 handshake_callback_called_(false),
953 transport_recv_busy_(false),
954 transport_recv_eof_(false),
955 transport_send_busy_(false),
956 user_read_buf_len_(0),
957 user_write_buf_len_(0),
958 network_task_runner_(network_task_runner),
959 nss_task_runner_(nss_task_runner),
960 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
963 SSLClientSocketNSS::Core::~Core() {
964 // TODO(wtc): Send SSL close_notify alert.
965 if (nss_fd_ != NULL) {
966 PR_Close(nss_fd_);
967 nss_fd_ = NULL;
969 nss_bufs_ = NULL;
972 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
973 memio_Private* buffers) {
974 DCHECK(OnNetworkTaskRunner());
975 DCHECK(!nss_fd_);
976 DCHECK(!nss_bufs_);
978 nss_fd_ = socket;
979 nss_bufs_ = buffers;
981 SECStatus rv = SECSuccess;
983 if (!ssl_config_.next_protos.empty()) {
984 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
985 const bool adequate_encryption =
986 PK11_TokenExists(CKM_AES_GCM) ||
987 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305);
988 const bool adequate_key_agreement = PK11_TokenExists(CKM_DH_PKCS_DERIVE) ||
989 PK11_TokenExists(CKM_ECDH1_DERIVE);
990 std::vector<uint8_t> wire_protos =
991 SerializeNextProtos(ssl_config_.next_protos,
992 adequate_encryption && adequate_key_agreement &&
993 IsTLSVersionAdequateForHTTP2(ssl_config_));
994 rv = SSL_SetNextProtoNego(
995 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
996 wire_protos.size());
997 if (rv != SECSuccess)
998 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
999 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
1000 if (rv != SECSuccess)
1001 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
1002 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
1003 if (rv != SECSuccess)
1004 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
1007 rv = SSL_AuthCertificateHook(
1008 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
1009 if (rv != SECSuccess) {
1010 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
1011 return false;
1014 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1015 rv = SSL_GetPlatformClientAuthDataHook(
1016 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler,
1017 this);
1018 #else
1019 rv = SSL_GetClientAuthDataHook(
1020 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
1021 #endif
1022 if (rv != SECSuccess) {
1023 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
1024 return false;
1027 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
1028 rv = SSL_SetClientChannelIDCallback(
1029 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
1030 if (rv != SECSuccess) {
1031 LogFailedNSSFunction(
1032 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
1036 rv = SSL_SetCanFalseStartCallback(
1037 nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
1038 if (rv != SECSuccess) {
1039 LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
1040 return false;
1043 rv = SSL_HandshakeCallback(
1044 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
1045 if (rv != SECSuccess) {
1046 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
1047 return false;
1050 return true;
1053 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
1054 if (!OnNSSTaskRunner()) {
1055 DCHECK(!detached_);
1056 bool posted = nss_task_runner_->PostTask(
1057 FROM_HERE,
1058 base::Bind(IgnoreResult(&Core::Connect), this, callback));
1059 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1062 DCHECK(OnNSSTaskRunner());
1063 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1064 DCHECK(user_read_callback_.is_null());
1065 DCHECK(user_write_callback_.is_null());
1066 DCHECK(user_connect_callback_.is_null());
1067 DCHECK(!user_read_buf_.get());
1068 DCHECK(!user_write_buf_.get());
1070 next_handshake_state_ = STATE_HANDSHAKE;
1071 int rv = DoHandshakeLoop(OK);
1072 if (rv == ERR_IO_PENDING) {
1073 user_connect_callback_ = callback;
1074 } else if (rv > OK) {
1075 rv = OK;
1077 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
1078 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1079 return ERR_IO_PENDING;
1082 return rv;
1085 void SSLClientSocketNSS::Core::Detach() {
1086 DCHECK(OnNetworkTaskRunner());
1088 detached_ = true;
1089 transport_ = NULL;
1090 weak_net_log_factory_.InvalidateWeakPtrs();
1092 network_handshake_state_.Reset();
1094 domain_bound_cert_request_handle_.Cancel();
1097 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
1098 const CompletionCallback& callback) {
1099 if (!OnNSSTaskRunner()) {
1100 DCHECK(OnNetworkTaskRunner());
1101 DCHECK(!detached_);
1102 DCHECK(transport_);
1103 DCHECK(!nss_waiting_read_);
1105 nss_waiting_read_ = true;
1106 bool posted = nss_task_runner_->PostTask(
1107 FROM_HERE,
1108 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
1109 buf_len, callback));
1110 if (!posted) {
1111 nss_is_closed_ = true;
1112 nss_waiting_read_ = false;
1114 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1117 DCHECK(OnNSSTaskRunner());
1118 DCHECK(false_started_ || handshake_callback_called_);
1119 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1120 DCHECK(user_read_callback_.is_null());
1121 DCHECK(user_connect_callback_.is_null());
1122 DCHECK(!user_read_buf_.get());
1123 DCHECK(nss_bufs_);
1125 user_read_buf_ = buf;
1126 user_read_buf_len_ = buf_len;
1128 int rv = DoReadLoop(OK);
1129 if (rv == ERR_IO_PENDING) {
1130 if (OnNetworkTaskRunner())
1131 nss_waiting_read_ = true;
1132 user_read_callback_ = callback;
1133 } else {
1134 user_read_buf_ = NULL;
1135 user_read_buf_len_ = 0;
1137 if (!OnNetworkTaskRunner()) {
1138 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1139 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1140 return ERR_IO_PENDING;
1141 } else {
1142 DCHECK(!nss_waiting_read_);
1143 if (rv <= 0) {
1144 nss_is_closed_ = true;
1145 } else {
1146 was_ever_used_ = true;
1151 return rv;
1154 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1155 const CompletionCallback& callback) {
1156 if (!OnNSSTaskRunner()) {
1157 DCHECK(OnNetworkTaskRunner());
1158 DCHECK(!detached_);
1159 DCHECK(transport_);
1160 DCHECK(!nss_waiting_write_);
1162 nss_waiting_write_ = true;
1163 bool posted = nss_task_runner_->PostTask(
1164 FROM_HERE,
1165 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1166 buf_len, callback));
1167 if (!posted) {
1168 nss_is_closed_ = true;
1169 nss_waiting_write_ = false;
1171 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1174 DCHECK(OnNSSTaskRunner());
1175 DCHECK(false_started_ || handshake_callback_called_);
1176 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1177 DCHECK(user_write_callback_.is_null());
1178 DCHECK(user_connect_callback_.is_null());
1179 DCHECK(!user_write_buf_.get());
1180 DCHECK(nss_bufs_);
1182 user_write_buf_ = buf;
1183 user_write_buf_len_ = buf_len;
1185 int rv = DoWriteLoop(OK);
1186 if (rv == ERR_IO_PENDING) {
1187 if (OnNetworkTaskRunner())
1188 nss_waiting_write_ = true;
1189 user_write_callback_ = callback;
1190 } else {
1191 user_write_buf_ = NULL;
1192 user_write_buf_len_ = 0;
1194 if (!OnNetworkTaskRunner()) {
1195 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1196 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1197 return ERR_IO_PENDING;
1198 } else {
1199 DCHECK(!nss_waiting_write_);
1200 if (rv < 0) {
1201 nss_is_closed_ = true;
1202 } else if (rv > 0) {
1203 was_ever_used_ = true;
1208 return rv;
1211 bool SSLClientSocketNSS::Core::IsConnected() const {
1212 DCHECK(OnNetworkTaskRunner());
1213 return !nss_is_closed_;
1216 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1217 DCHECK(OnNetworkTaskRunner());
1218 return nss_waiting_read_ || nss_waiting_write_;
1221 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1222 DCHECK(OnNetworkTaskRunner());
1223 return unhandled_buffer_size_ != 0;
1226 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1227 DCHECK(OnNetworkTaskRunner());
1228 return was_ever_used_;
1231 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1232 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1233 // nss_fd_. However, it happens on the network task runner in order to match
1234 // the buggy behavior of ExportKeyingMaterial.
1236 // Once http://crbug.com/330360 is fixed, this should be moved to an
1237 // implementation that exclusively does this work on the NSS TaskRunner. This
1238 // is "safe" because it is only called during the certificate verification
1239 // state machine of the main socket, which is safe because no underlying
1240 // transport IO will be occuring in that state, and NSS will not be blocking
1241 // on any PKCS#11 related locks that might block the Network TaskRunner.
1242 DCHECK(OnNetworkTaskRunner());
1244 // Only cache the session if the connection was not False Started, because
1245 // sessions should only be cached *after* the peer's Finished message is
1246 // processed.
1247 // In the case of False Start, the session will be cached once the
1248 // HandshakeCallback is called, which signals the receipt and processing of
1249 // the Finished message, and which will happen during a call to
1250 // PR_Read/PR_Write.
1251 if (!false_started_)
1252 SSL_CacheSession(nss_fd_);
1255 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1256 return nss_task_runner_->RunsTasksOnCurrentThread();
1259 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1260 return network_task_runner_->RunsTasksOnCurrentThread();
1263 // static
1264 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1265 void* arg,
1266 PRFileDesc* socket,
1267 PRBool checksig,
1268 PRBool is_server) {
1269 Core* core = reinterpret_cast<Core*>(arg);
1270 if (core->handshake_callback_called_) {
1271 // Disallow the server certificate to change in a renegotiation.
1272 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1273 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1274 if (new_cert->derCert.len != old_cert->derCert.len ||
1275 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1276 new_cert->derCert.len) != 0) {
1277 // NSS doesn't have an error code that indicates the server certificate
1278 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1279 // for this purpose.
1280 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1281 return SECFailure;
1285 // Tell NSS to not verify the certificate.
1286 return SECSuccess;
1289 #if defined(NSS_PLATFORM_CLIENT_AUTH)
1290 // static
1291 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler(
1292 void* arg,
1293 PRFileDesc* socket,
1294 CERTDistNames* ca_names,
1295 CERTCertList** result_certs,
1296 void** result_private_key,
1297 CERTCertificate** result_nss_certificate,
1298 SECKEYPrivateKey** result_nss_private_key) {
1299 Core* core = reinterpret_cast<Core*>(arg);
1300 DCHECK(core->OnNSSTaskRunner());
1302 core->PostOrRunCallback(
1303 FROM_HERE,
1304 base::Bind(&AddLogEvent, core->weak_net_log_,
1305 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1307 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1308 #if defined(OS_WIN)
1309 if (core->ssl_config_.send_client_cert) {
1310 if (core->ssl_config_.client_cert.get()) {
1311 PCCERT_CONTEXT cert_context =
1312 core->ssl_config_.client_cert->os_cert_handle();
1314 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0;
1315 DWORD key_spec = 0;
1316 BOOL must_free = FALSE;
1317 DWORD flags = 0;
1318 if (base::win::GetVersion() >= base::win::VERSION_VISTA)
1319 flags |= CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG;
1321 BOOL acquired_key = CryptAcquireCertificatePrivateKey(
1322 cert_context, flags, NULL, &crypt_prov, &key_spec, &must_free);
1324 if (acquired_key) {
1325 // Should never get a cached handle back - ownership must always be
1326 // transferred.
1327 CHECK_EQ(must_free, TRUE);
1329 SECItem der_cert;
1330 der_cert.type = siDERCertBuffer;
1331 der_cert.data = cert_context->pbCertEncoded;
1332 der_cert.len = cert_context->cbCertEncoded;
1334 // TODO(rsleevi): Error checking for NSS allocation errors.
1335 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB();
1336 CERTCertificate* user_cert = CERT_NewTempCertificate(
1337 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1338 if (!user_cert) {
1339 // Importing the certificate can fail for reasons including a serial
1340 // number collision. See crbug.com/97355.
1341 core->AddCertProvidedEvent(0);
1342 return SECFailure;
1344 CERTCertList* cert_chain = CERT_NewCertList();
1345 CERT_AddCertToListTail(cert_chain, user_cert);
1347 // Add the intermediates.
1348 X509Certificate::OSCertHandles intermediates =
1349 core->ssl_config_.client_cert->GetIntermediateCertificates();
1350 for (X509Certificate::OSCertHandles::const_iterator it =
1351 intermediates.begin(); it != intermediates.end(); ++it) {
1352 der_cert.data = (*it)->pbCertEncoded;
1353 der_cert.len = (*it)->cbCertEncoded;
1355 CERTCertificate* intermediate = CERT_NewTempCertificate(
1356 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE);
1357 if (!intermediate) {
1358 CERT_DestroyCertList(cert_chain);
1359 core->AddCertProvidedEvent(0);
1360 return SECFailure;
1362 CERT_AddCertToListTail(cert_chain, intermediate);
1364 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>(
1365 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT)));
1366 key_context->cbSize = sizeof(*key_context);
1367 // NSS will free this context when no longer in use.
1368 key_context->hCryptProv = crypt_prov;
1369 key_context->dwKeySpec = key_spec;
1370 *result_private_key = key_context;
1371 *result_certs = cert_chain;
1373 int cert_count = 1 + intermediates.size();
1374 core->AddCertProvidedEvent(cert_count);
1375 return SECSuccess;
1377 LOG(WARNING) << "Client cert found without private key";
1380 // Send no client certificate.
1381 core->AddCertProvidedEvent(0);
1382 return SECFailure;
1385 core->nss_handshake_state_.cert_authorities.clear();
1387 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames);
1388 for (int i = 0; i < ca_names->nnames; ++i) {
1389 issuer_list[i].cbData = ca_names->names[i].len;
1390 issuer_list[i].pbData = ca_names->names[i].data;
1391 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1392 reinterpret_cast<const char*>(ca_names->names[i].data),
1393 static_cast<size_t>(ca_names->names[i].len)));
1396 // Update the network task runner's view of the handshake state now that
1397 // server certificate request has been recorded.
1398 core->PostOrRunCallback(
1399 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1400 core->nss_handshake_state_));
1402 // Tell NSS to suspend the client authentication. We will then abort the
1403 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1404 return SECWouldBlock;
1405 #elif defined(OS_MACOSX)
1406 if (core->ssl_config_.send_client_cert) {
1407 if (core->ssl_config_.client_cert.get()) {
1408 OSStatus os_error = noErr;
1409 SecIdentityRef identity = NULL;
1410 SecKeyRef private_key = NULL;
1411 X509Certificate::OSCertHandles chain;
1413 base::AutoLock lock(crypto::GetMacSecurityServicesLock());
1414 os_error = SecIdentityCreateWithCertificate(
1415 NULL, core->ssl_config_.client_cert->os_cert_handle(), &identity);
1417 if (os_error == noErr) {
1418 os_error = SecIdentityCopyPrivateKey(identity, &private_key);
1419 CFRelease(identity);
1422 if (os_error == noErr) {
1423 // TODO(rsleevi): Error checking for NSS allocation errors.
1424 *result_certs = CERT_NewCertList();
1425 *result_private_key = private_key;
1427 chain.push_back(core->ssl_config_.client_cert->os_cert_handle());
1428 const X509Certificate::OSCertHandles& intermediates =
1429 core->ssl_config_.client_cert->GetIntermediateCertificates();
1430 if (!intermediates.empty())
1431 chain.insert(chain.end(), intermediates.begin(), intermediates.end());
1433 for (size_t i = 0, chain_count = chain.size(); i < chain_count; ++i) {
1434 CSSM_DATA cert_data;
1435 SecCertificateRef cert_ref = chain[i];
1436 os_error = SecCertificateGetData(cert_ref, &cert_data);
1437 if (os_error != noErr)
1438 break;
1440 SECItem der_cert;
1441 der_cert.type = siDERCertBuffer;
1442 der_cert.data = cert_data.Data;
1443 der_cert.len = cert_data.Length;
1444 CERTCertificate* nss_cert = CERT_NewTempCertificate(
1445 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE);
1446 if (!nss_cert) {
1447 // In the event of an NSS error, make up an OS error and reuse
1448 // the error handling below.
1449 os_error = errSecCreateChainFailed;
1450 break;
1452 CERT_AddCertToListTail(*result_certs, nss_cert);
1456 if (os_error == noErr) {
1457 core->AddCertProvidedEvent(chain.size());
1458 return SECSuccess;
1461 OSSTATUS_LOG(WARNING, os_error)
1462 << "Client cert found, but could not be used";
1463 if (*result_certs) {
1464 CERT_DestroyCertList(*result_certs);
1465 *result_certs = NULL;
1467 if (*result_private_key)
1468 *result_private_key = NULL;
1469 if (private_key)
1470 CFRelease(private_key);
1473 // Send no client certificate.
1474 core->AddCertProvidedEvent(0);
1475 return SECFailure;
1478 core->nss_handshake_state_.cert_authorities.clear();
1480 // Retrieve the cert issuers accepted by the server.
1481 std::vector<CertPrincipal> valid_issuers;
1482 int n = ca_names->nnames;
1483 for (int i = 0; i < n; i++) {
1484 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1485 reinterpret_cast<const char*>(ca_names->names[i].data),
1486 static_cast<size_t>(ca_names->names[i].len)));
1489 // Update the network task runner's view of the handshake state now that
1490 // server certificate request has been recorded.
1491 core->PostOrRunCallback(
1492 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1493 core->nss_handshake_state_));
1495 // Tell NSS to suspend the client authentication. We will then abort the
1496 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1497 return SECWouldBlock;
1498 #else
1499 return SECFailure;
1500 #endif
1503 #elif defined(OS_IOS)
1505 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1506 void* arg,
1507 PRFileDesc* socket,
1508 CERTDistNames* ca_names,
1509 CERTCertificate** result_certificate,
1510 SECKEYPrivateKey** result_private_key) {
1511 Core* core = reinterpret_cast<Core*>(arg);
1512 DCHECK(core->OnNSSTaskRunner());
1514 core->PostOrRunCallback(
1515 FROM_HERE,
1516 base::Bind(&AddLogEvent, core->weak_net_log_,
1517 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1519 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1520 LOG(WARNING) << "Client auth is not supported";
1522 // Never send a certificate.
1523 core->AddCertProvidedEvent(0);
1524 return SECFailure;
1527 #else // NSS_PLATFORM_CLIENT_AUTH
1529 // static
1530 // Based on Mozilla's NSS_GetClientAuthData.
1531 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1532 void* arg,
1533 PRFileDesc* socket,
1534 CERTDistNames* ca_names,
1535 CERTCertificate** result_certificate,
1536 SECKEYPrivateKey** result_private_key) {
1537 Core* core = reinterpret_cast<Core*>(arg);
1538 DCHECK(core->OnNSSTaskRunner());
1540 core->PostOrRunCallback(
1541 FROM_HERE,
1542 base::Bind(&AddLogEvent, core->weak_net_log_,
1543 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1545 // Regular client certificate requested.
1546 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1547 void* wincx = SSL_RevealPinArg(socket);
1549 if (core->ssl_config_.send_client_cert) {
1550 // Second pass: a client certificate should have been selected.
1551 if (core->ssl_config_.client_cert.get()) {
1552 CERTCertificate* cert =
1553 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1554 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1555 if (privkey) {
1556 // TODO(jsorianopastor): We should wait for server certificate
1557 // verification before sending our credentials. See
1558 // http://crbug.com/13934.
1559 *result_certificate = cert;
1560 *result_private_key = privkey;
1561 // A cert_count of -1 means the number of certificates is unknown.
1562 // NSS will construct the certificate chain.
1563 core->AddCertProvidedEvent(-1);
1565 return SECSuccess;
1567 LOG(WARNING) << "Client cert found without private key";
1569 // Send no client certificate.
1570 core->AddCertProvidedEvent(0);
1571 return SECFailure;
1574 // First pass: client certificate is needed.
1575 core->nss_handshake_state_.cert_authorities.clear();
1577 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1578 // the server and save them in |cert_authorities|.
1579 for (int i = 0; i < ca_names->nnames; i++) {
1580 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1581 reinterpret_cast<const char*>(ca_names->names[i].data),
1582 static_cast<size_t>(ca_names->names[i].len)));
1585 // Update the network task runner's view of the handshake state now that
1586 // server certificate request has been recorded.
1587 core->PostOrRunCallback(
1588 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1589 core->nss_handshake_state_));
1591 // Tell NSS to suspend the client authentication. We will then abort the
1592 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1593 return SECWouldBlock;
1595 #endif // NSS_PLATFORM_CLIENT_AUTH
1597 // static
1598 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1599 PRFileDesc* socket,
1600 void* arg,
1601 PRBool* can_false_start) {
1602 // If the server doesn't support NPN or ALPN, then we don't do False
1603 // Start with it.
1604 PRBool negotiated_extension;
1605 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1606 ssl_app_layer_protocol_xtn,
1607 &negotiated_extension);
1608 if (rv != SECSuccess || !negotiated_extension) {
1609 rv = SSL_HandshakeNegotiatedExtension(socket,
1610 ssl_next_proto_nego_xtn,
1611 &negotiated_extension);
1613 if (rv != SECSuccess || !negotiated_extension) {
1614 *can_false_start = PR_FALSE;
1615 return SECSuccess;
1618 SSLChannelInfo channel_info;
1619 SECStatus ok =
1620 SSL_GetChannelInfo(socket, &channel_info, sizeof(channel_info));
1621 if (ok != SECSuccess || channel_info.length != sizeof(channel_info) ||
1622 channel_info.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_2 ||
1623 !IsFalseStartableTLSCipherSuite(channel_info.cipherSuite)) {
1624 *can_false_start = PR_FALSE;
1625 return SECSuccess;
1628 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1631 // static
1632 void SSLClientSocketNSS::Core::HandshakeCallback(
1633 PRFileDesc* socket,
1634 void* arg) {
1635 Core* core = reinterpret_cast<Core*>(arg);
1636 DCHECK(core->OnNSSTaskRunner());
1638 core->handshake_callback_called_ = true;
1639 if (core->false_started_) {
1640 core->false_started_ = false;
1641 // If the connection was False Started, then at the time of this callback,
1642 // the peer's certificate will have been verified or the caller will have
1643 // accepted the error.
1644 // This is guaranteed when using False Start because this callback will
1645 // not be invoked until processing the peer's Finished message, which
1646 // will only happen in a PR_Read/PR_Write call, which can only happen
1647 // after the peer's certificate is verified.
1648 SSL_CacheSessionUnlocked(socket);
1650 // Additionally, when False Starting, DoHandshake() will have already
1651 // called HandshakeSucceeded(), so return now.
1652 return;
1654 core->HandshakeSucceeded();
1657 void SSLClientSocketNSS::Core::HandshakeSucceeded() {
1658 DCHECK(OnNSSTaskRunner());
1660 PRBool last_handshake_resumed;
1661 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1662 if (rv == SECSuccess && last_handshake_resumed) {
1663 nss_handshake_state_.resumed_handshake = true;
1664 } else {
1665 nss_handshake_state_.resumed_handshake = false;
1668 RecordChannelIDSupportOnNSSTaskRunner();
1669 UpdateServerCert();
1670 UpdateSignedCertTimestamps();
1671 UpdateStapledOCSPResponse();
1672 UpdateConnectionStatus();
1673 UpdateNextProto();
1674 UpdateExtensionUsed();
1676 // Update the network task runners view of the handshake state whenever
1677 // a handshake has completed.
1678 PostOrRunCallback(
1679 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1680 nss_handshake_state_));
1683 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1684 DCHECK(OnNSSTaskRunner());
1686 int net_error = MapNSSClientError(nss_error);
1688 #if defined(OS_WIN)
1689 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate
1690 // os_cert_handle() as an optimization. However, if the certificate
1691 // private key is stored on a smart card, and the smart card is removed,
1692 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again,
1693 // preventing client certificate authentication. Because the
1694 // X509Certificate may outlive the individual SSLClientSocketNSS, due to
1695 // caching in X509Certificate, this failure ends up preventing client
1696 // certificate authentication with the same certificate for all future
1697 // attempts, even after the smart card has been re-inserted. By setting
1698 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will
1699 // typically be freed. This allows a new HCRYPTPROV to be obtained from
1700 // the certificate on the next attempt, which should succeed if the smart
1701 // card has been re-inserted, or will typically prompt the user to
1702 // re-insert the smart card if not.
1703 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY ||
1704 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) &&
1705 ssl_config_.send_client_cert && ssl_config_.client_cert.get()) {
1706 CertSetCertificateContextProperty(
1707 ssl_config_.client_cert->os_cert_handle(),
1708 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL);
1710 #endif
1712 return net_error;
1715 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1716 DCHECK(OnNSSTaskRunner());
1718 int rv = last_io_result;
1719 do {
1720 // Default to STATE_NONE for next state.
1721 State state = next_handshake_state_;
1722 GotoState(STATE_NONE);
1724 switch (state) {
1725 case STATE_HANDSHAKE:
1726 rv = DoHandshake();
1727 break;
1728 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1729 rv = DoGetDBCertComplete(rv);
1730 break;
1731 case STATE_NONE:
1732 default:
1733 rv = ERR_UNEXPECTED;
1734 LOG(DFATAL) << "unexpected state " << state;
1735 break;
1738 // Do the actual network I/O
1739 bool network_moved = DoTransportIO();
1740 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1741 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1742 // special case we keep looping even if rv is ERR_IO_PENDING because
1743 // the transport IO may allow DoHandshake to make progress.
1744 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1745 rv = OK; // This causes us to stay in the loop.
1747 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1748 return rv;
1751 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1752 DCHECK(OnNSSTaskRunner());
1753 DCHECK(false_started_ || handshake_callback_called_);
1754 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1756 if (result < 0)
1757 return result;
1759 if (!nss_bufs_) {
1760 LOG(DFATAL) << "!nss_bufs_";
1761 int rv = ERR_UNEXPECTED;
1762 PostOrRunCallback(
1763 FROM_HERE,
1764 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1765 NetLog::TYPE_SSL_READ_ERROR,
1766 CreateNetLogSSLErrorCallback(rv, 0)));
1767 return rv;
1770 bool network_moved;
1771 int rv;
1772 do {
1773 rv = DoPayloadRead();
1774 network_moved = DoTransportIO();
1775 } while (rv == ERR_IO_PENDING && network_moved);
1777 return rv;
1780 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1781 DCHECK(OnNSSTaskRunner());
1782 DCHECK(false_started_ || handshake_callback_called_);
1783 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1785 if (result < 0)
1786 return result;
1788 if (!nss_bufs_) {
1789 LOG(DFATAL) << "!nss_bufs_";
1790 int rv = ERR_UNEXPECTED;
1791 PostOrRunCallback(
1792 FROM_HERE,
1793 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1794 NetLog::TYPE_SSL_READ_ERROR,
1795 CreateNetLogSSLErrorCallback(rv, 0)));
1796 return rv;
1799 bool network_moved;
1800 int rv;
1801 do {
1802 rv = DoPayloadWrite();
1803 network_moved = DoTransportIO();
1804 } while (rv == ERR_IO_PENDING && network_moved);
1806 LeaveFunction(rv);
1807 return rv;
1810 int SSLClientSocketNSS::Core::DoHandshake() {
1811 DCHECK(OnNSSTaskRunner());
1813 int net_error = OK;
1814 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1816 // Note: this function may be called multiple times during the handshake, so
1817 // even though channel id and client auth are separate else cases, they can
1818 // both be used during a single SSL handshake.
1819 if (channel_id_needed_) {
1820 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1821 net_error = ERR_IO_PENDING;
1822 } else if (client_auth_cert_needed_) {
1823 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1824 PostOrRunCallback(
1825 FROM_HERE,
1826 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1827 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1828 CreateNetLogSSLErrorCallback(net_error, 0)));
1829 } else if (rv == SECSuccess) {
1830 if (!handshake_callback_called_) {
1831 false_started_ = true;
1832 HandshakeSucceeded();
1834 } else {
1835 PRErrorCode prerr = PR_GetError();
1836 net_error = HandleNSSError(prerr);
1838 // If not done, stay in this state
1839 if (net_error == ERR_IO_PENDING) {
1840 GotoState(STATE_HANDSHAKE);
1841 } else {
1842 PostOrRunCallback(
1843 FROM_HERE,
1844 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1845 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1846 CreateNetLogSSLErrorCallback(net_error, prerr)));
1850 return net_error;
1853 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1854 SECStatus rv;
1855 PostOrRunCallback(
1856 FROM_HERE,
1857 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1858 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1860 channel_id_needed_ = false;
1862 if (result != OK)
1863 return result;
1865 SECKEYPublicKey* public_key;
1866 SECKEYPrivateKey* private_key;
1867 int error = ImportChannelIDKeys(&public_key, &private_key);
1868 if (error != OK)
1869 return error;
1871 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1872 if (rv != SECSuccess)
1873 return MapNSSError(PORT_GetError());
1875 SetChannelIDProvided();
1876 GotoState(STATE_HANDSHAKE);
1877 return OK;
1880 int SSLClientSocketNSS::Core::DoPayloadRead() {
1881 DCHECK(OnNSSTaskRunner());
1882 DCHECK(user_read_buf_.get());
1883 DCHECK_GT(user_read_buf_len_, 0);
1885 int rv;
1886 // If a previous greedy read resulted in an error that was not consumed (eg:
1887 // due to the caller having read some data successfully), then return that
1888 // pending error now.
1889 if (pending_read_result_ != kNoPendingReadResult) {
1890 rv = pending_read_result_;
1891 PRErrorCode prerr = pending_read_nss_error_;
1892 pending_read_result_ = kNoPendingReadResult;
1893 pending_read_nss_error_ = 0;
1895 if (rv == 0) {
1896 PostOrRunCallback(
1897 FROM_HERE,
1898 base::Bind(&LogByteTransferEvent, weak_net_log_,
1899 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1900 scoped_refptr<IOBuffer>(user_read_buf_)));
1901 } else {
1902 PostOrRunCallback(
1903 FROM_HERE,
1904 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1905 NetLog::TYPE_SSL_READ_ERROR,
1906 CreateNetLogSSLErrorCallback(rv, prerr)));
1908 return rv;
1911 // Perform a greedy read, attempting to read as much as the caller has
1912 // requested. In the current NSS implementation, PR_Read will return
1913 // exactly one SSL application data record's worth of data per invocation.
1914 // The record size is dictated by the server, and may be noticeably smaller
1915 // than the caller's buffer. This may be as little as a single byte, if the
1916 // server is performing 1/n-1 record splitting.
1918 // However, this greedy read may result in renegotiations/re-handshakes
1919 // happening or may lead to some data being read, followed by an EOF (such as
1920 // a TLS close-notify). If at least some data was read, then that result
1921 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1922 // data was read, it's safe to return the error or EOF immediately.
1923 int total_bytes_read = 0;
1924 do {
1925 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1926 user_read_buf_len_ - total_bytes_read);
1927 if (rv > 0)
1928 total_bytes_read += rv;
1929 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1930 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1931 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1932 amount_in_read_buffer));
1934 if (total_bytes_read == user_read_buf_len_) {
1935 // The caller's entire request was satisfied without error. No further
1936 // processing needed.
1937 rv = total_bytes_read;
1938 } else {
1939 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1940 // immediately, while the NSPR/NSS errors are still available in
1941 // thread-local storage. However, the handled/remapped error code should
1942 // only be returned if no application data was already read; if it was, the
1943 // error code should be deferred until the next call of DoPayloadRead.
1945 // If no data was read, |*next_result| will point to the return value of
1946 // this function. If at least some data was read, |*next_result| will point
1947 // to |pending_read_error_|, to be returned in a future call to
1948 // DoPayloadRead() (e.g.: after the current data is handled).
1949 int* next_result = &rv;
1950 if (total_bytes_read > 0) {
1951 pending_read_result_ = rv;
1952 rv = total_bytes_read;
1953 next_result = &pending_read_result_;
1956 if (client_auth_cert_needed_) {
1957 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1958 pending_read_nss_error_ = 0;
1959 } else if (*next_result < 0) {
1960 // If *next_result == 0, then that indicates EOF, and no special error
1961 // handling is needed.
1962 pending_read_nss_error_ = PR_GetError();
1963 *next_result = HandleNSSError(pending_read_nss_error_);
1964 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1965 // If at least some data was read from PR_Read(), do not treat
1966 // insufficient data as an error to return in the next call to
1967 // DoPayloadRead() - instead, let the call fall through to check
1968 // PR_Read() again. This is because DoTransportIO() may complete
1969 // in between the next call to DoPayloadRead(), and thus it is
1970 // important to check PR_Read() on subsequent invocations to see
1971 // if a complete record may now be read.
1972 pending_read_nss_error_ = 0;
1973 pending_read_result_ = kNoPendingReadResult;
1978 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
1980 if (rv >= 0) {
1981 PostOrRunCallback(
1982 FROM_HERE,
1983 base::Bind(&LogByteTransferEvent, weak_net_log_,
1984 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1985 scoped_refptr<IOBuffer>(user_read_buf_)));
1986 } else if (rv != ERR_IO_PENDING) {
1987 PostOrRunCallback(
1988 FROM_HERE,
1989 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1990 NetLog::TYPE_SSL_READ_ERROR,
1991 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
1992 pending_read_nss_error_ = 0;
1994 return rv;
1997 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1998 DCHECK(OnNSSTaskRunner());
2000 DCHECK(user_write_buf_.get());
2002 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2003 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
2004 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2005 // PR_Write could potentially consume the unhandled data in the memio read
2006 // buffer if a renegotiation is in progress. If the buffer is consumed,
2007 // notify the latest buffer size to NetworkRunner.
2008 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
2009 PostOrRunCallback(
2010 FROM_HERE,
2011 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
2013 if (rv >= 0) {
2014 PostOrRunCallback(
2015 FROM_HERE,
2016 base::Bind(&LogByteTransferEvent, weak_net_log_,
2017 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
2018 scoped_refptr<IOBuffer>(user_write_buf_)));
2019 return rv;
2021 PRErrorCode prerr = PR_GetError();
2022 if (prerr == PR_WOULD_BLOCK_ERROR)
2023 return ERR_IO_PENDING;
2025 rv = HandleNSSError(prerr);
2026 PostOrRunCallback(
2027 FROM_HERE,
2028 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2029 NetLog::TYPE_SSL_WRITE_ERROR,
2030 CreateNetLogSSLErrorCallback(rv, prerr)));
2031 return rv;
2034 // Do as much network I/O as possible between the buffer and the
2035 // transport socket. Return true if some I/O performed, false
2036 // otherwise (error or ERR_IO_PENDING).
2037 bool SSLClientSocketNSS::Core::DoTransportIO() {
2038 DCHECK(OnNSSTaskRunner());
2040 bool network_moved = false;
2041 if (nss_bufs_ != NULL) {
2042 int rv;
2043 // Read and write as much data as we can. The loop is neccessary
2044 // because Write() may return synchronously.
2045 do {
2046 rv = BufferSend();
2047 if (rv != ERR_IO_PENDING && rv != 0)
2048 network_moved = true;
2049 } while (rv > 0);
2050 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
2051 network_moved = true;
2053 return network_moved;
2056 int SSLClientSocketNSS::Core::BufferRecv() {
2057 DCHECK(OnNSSTaskRunner());
2059 if (transport_recv_busy_)
2060 return ERR_IO_PENDING;
2062 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
2063 // determine how much data NSS wants to read. If NSS was not blocked,
2064 // this will return 0.
2065 int requested = memio_GetReadRequest(nss_bufs_);
2066 if (requested == 0) {
2067 // This is not a perfect match of error codes, as no operation is
2068 // actually pending. However, returning 0 would be interpreted as a
2069 // possible sign of EOF, which is also an inappropriate match.
2070 return ERR_IO_PENDING;
2073 char* buf;
2074 int nb = memio_GetReadParams(nss_bufs_, &buf);
2075 int rv;
2076 if (!nb) {
2077 // buffer too full to read into, so no I/O possible at moment
2078 rv = ERR_IO_PENDING;
2079 } else {
2080 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
2081 if (OnNetworkTaskRunner()) {
2082 rv = DoBufferRecv(read_buffer.get(), nb);
2083 } else {
2084 bool posted = network_task_runner_->PostTask(
2085 FROM_HERE,
2086 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
2087 nb));
2088 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2091 if (rv == ERR_IO_PENDING) {
2092 transport_recv_busy_ = true;
2093 } else {
2094 if (rv > 0) {
2095 memcpy(buf, read_buffer->data(), rv);
2096 } else if (rv == 0) {
2097 transport_recv_eof_ = true;
2099 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
2102 return rv;
2105 // Return 0 if nss_bufs_ was empty,
2106 // > 0 for bytes transferred immediately,
2107 // < 0 for error (or the non-error ERR_IO_PENDING).
2108 int SSLClientSocketNSS::Core::BufferSend() {
2109 DCHECK(OnNSSTaskRunner());
2111 if (transport_send_busy_)
2112 return ERR_IO_PENDING;
2114 const char* buf1;
2115 const char* buf2;
2116 unsigned int len1, len2;
2117 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
2118 // It is important this return synchronously to prevent spinning infinitely
2119 // in the off-thread NSS case. The error code itself is ignored, so just
2120 // return ERR_ABORTED. See https://crbug.com/381160.
2121 return ERR_ABORTED;
2123 const unsigned int len = len1 + len2;
2125 int rv = 0;
2126 if (len) {
2127 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
2128 memcpy(send_buffer->data(), buf1, len1);
2129 memcpy(send_buffer->data() + len1, buf2, len2);
2131 if (OnNetworkTaskRunner()) {
2132 rv = DoBufferSend(send_buffer.get(), len);
2133 } else {
2134 bool posted = network_task_runner_->PostTask(
2135 FROM_HERE,
2136 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
2137 len));
2138 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
2141 if (rv == ERR_IO_PENDING) {
2142 transport_send_busy_ = true;
2143 } else {
2144 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
2148 return rv;
2151 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
2152 DCHECK(OnNSSTaskRunner());
2154 if (next_handshake_state_ == STATE_HANDSHAKE) {
2155 OnHandshakeIOComplete(result);
2156 return;
2159 // Network layer received some data, check if client requested to read
2160 // decrypted data.
2161 if (!user_read_buf_.get())
2162 return;
2164 int rv = DoReadLoop(result);
2165 if (rv != ERR_IO_PENDING)
2166 DoReadCallback(rv);
2169 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
2170 DCHECK(OnNSSTaskRunner());
2172 if (next_handshake_state_ == STATE_HANDSHAKE) {
2173 OnHandshakeIOComplete(result);
2174 return;
2177 // OnSendComplete may need to call DoPayloadRead while the renegotiation
2178 // handshake is in progress.
2179 int rv_read = ERR_IO_PENDING;
2180 int rv_write = ERR_IO_PENDING;
2181 bool network_moved;
2182 do {
2183 if (user_read_buf_.get())
2184 rv_read = DoPayloadRead();
2185 if (user_write_buf_.get())
2186 rv_write = DoPayloadWrite();
2187 network_moved = DoTransportIO();
2188 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
2189 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
2191 // If the parent SSLClientSocketNSS is deleted during the processing of the
2192 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
2193 // will be detached (and possibly deleted). Guard against deletion by taking
2194 // an extra reference, then check if the Core was detached before invoking the
2195 // next callback.
2196 scoped_refptr<Core> guard(this);
2197 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
2198 DoReadCallback(rv_read);
2200 if (OnNetworkTaskRunner() && detached_)
2201 return;
2203 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
2204 DoWriteCallback(rv_write);
2207 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
2208 // handshake. This requires network IO, which in turn calls
2209 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
2210 // winds its way through the state machine and ends up being passed to the
2211 // callback. For Read() and Write(), that's what we want. But for Connect(),
2212 // the caller expects OK (i.e. 0) for success.
2213 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
2214 DCHECK(OnNSSTaskRunner());
2215 DCHECK_NE(rv, ERR_IO_PENDING);
2216 DCHECK(!user_connect_callback_.is_null());
2218 base::Closure c = base::Bind(
2219 base::ResetAndReturn(&user_connect_callback_),
2220 rv > OK ? OK : rv);
2221 PostOrRunCallback(FROM_HERE, c);
2224 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
2225 DCHECK(OnNSSTaskRunner());
2226 DCHECK_NE(ERR_IO_PENDING, rv);
2227 DCHECK(!user_read_callback_.is_null());
2229 user_read_buf_ = NULL;
2230 user_read_buf_len_ = 0;
2231 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2232 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2233 // the network task runner.
2234 PostOrRunCallback(
2235 FROM_HERE,
2236 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2237 PostOrRunCallback(
2238 FROM_HERE,
2239 base::Bind(&Core::DidNSSRead, this, rv));
2240 PostOrRunCallback(
2241 FROM_HERE,
2242 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
2245 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
2246 DCHECK(OnNSSTaskRunner());
2247 DCHECK_NE(ERR_IO_PENDING, rv);
2248 DCHECK(!user_write_callback_.is_null());
2250 // Since Run may result in Write being called, clear |user_write_callback_|
2251 // up front.
2252 user_write_buf_ = NULL;
2253 user_write_buf_len_ = 0;
2254 // Update buffer status because DoWriteLoop called DoTransportIO which may
2255 // perform read operations.
2256 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
2257 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
2258 // the network task runner.
2259 PostOrRunCallback(
2260 FROM_HERE,
2261 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
2262 PostOrRunCallback(
2263 FROM_HERE,
2264 base::Bind(&Core::DidNSSWrite, this, rv));
2265 PostOrRunCallback(
2266 FROM_HERE,
2267 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
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 host = core->host_and_port_.host();
2286 int error = ERR_UNEXPECTED;
2287 if (core->OnNetworkTaskRunner()) {
2288 error = core->DoGetChannelID(host);
2289 } else {
2290 bool posted = core->network_task_runner_->PostTask(
2291 FROM_HERE,
2292 base::Bind(
2293 IgnoreResult(&Core::DoGetChannelID),
2294 core, host));
2295 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
2298 if (error == ERR_IO_PENDING) {
2299 // Asynchronous case.
2300 core->channel_id_needed_ = true;
2301 return SECWouldBlock;
2304 core->PostOrRunCallback(
2305 FROM_HERE,
2306 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
2307 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
2308 SECStatus rv = SECSuccess;
2309 if (error == OK) {
2310 // Synchronous success.
2311 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
2312 if (result == OK)
2313 core->SetChannelIDProvided();
2314 else
2315 rv = SECFailure;
2316 } else {
2317 rv = SECFailure;
2320 return rv;
2323 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
2324 SECKEYPrivateKey** key) {
2325 // Set the certificate.
2326 SECItem cert_item;
2327 cert_item.data = (unsigned char*) domain_bound_cert_.data();
2328 cert_item.len = domain_bound_cert_.size();
2329 ScopedCERTCertificate cert(CERT_NewTempCertificate(CERT_GetDefaultCertDB(),
2330 &cert_item,
2331 NULL,
2332 PR_FALSE,
2333 PR_TRUE));
2334 if (cert == NULL)
2335 return MapNSSError(PORT_GetError());
2337 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
2338 // Set the private key.
2339 if (!crypto::ECPrivateKey::ImportFromEncryptedPrivateKeyInfo(
2340 slot.get(),
2341 ChannelIDService::kEPKIPassword,
2342 reinterpret_cast<const unsigned char*>(
2343 domain_bound_private_key_.data()),
2344 domain_bound_private_key_.size(),
2345 &cert->subjectPublicKeyInfo,
2346 false,
2347 false,
2348 key,
2349 public_key)) {
2350 int error = MapNSSError(PORT_GetError());
2351 return error;
2354 return OK;
2357 void SSLClientSocketNSS::Core::UpdateServerCert() {
2358 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
2359 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
2360 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
2361 if (nss_handshake_state_.server_cert.get()) {
2362 // Since this will be called asynchronously on another thread, it needs to
2363 // own a reference to the certificate.
2364 NetLog::ParametersCallback net_log_callback =
2365 base::Bind(&NetLogX509CertificateCallback,
2366 nss_handshake_state_.server_cert);
2367 PostOrRunCallback(
2368 FROM_HERE,
2369 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2370 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
2371 net_log_callback));
2375 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
2376 const SECItem* signed_cert_timestamps =
2377 SSL_PeerSignedCertTimestamps(nss_fd_);
2379 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
2380 return;
2382 nss_handshake_state_.sct_list_from_tls_extension = std::string(
2383 reinterpret_cast<char*>(signed_cert_timestamps->data),
2384 signed_cert_timestamps->len);
2387 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2388 PRBool ocsp_requested = PR_FALSE;
2389 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2390 const SECItemArray* ocsp_responses =
2391 SSL_PeerStapledOCSPResponses(nss_fd_);
2392 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2393 if (ocsp_requested)
2394 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2395 if (!ocsp_responses_present)
2396 return;
2398 nss_handshake_state_.stapled_ocsp_response = std::string(
2399 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2400 ocsp_responses->items[0].len);
2402 if (IsOCSPStaplingSupported()) {
2403 #if defined(OS_WIN)
2404 if (nss_handshake_state_.server_cert.get()) {
2405 CRYPT_DATA_BLOB ocsp_response_blob;
2406 ocsp_response_blob.cbData = ocsp_responses->items[0].len;
2407 ocsp_response_blob.pbData = ocsp_responses->items[0].data;
2408 BOOL ok = CertSetCertificateContextProperty(
2409 nss_handshake_state_.server_cert->os_cert_handle(),
2410 CERT_OCSP_RESPONSE_PROP_ID,
2411 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG,
2412 &ocsp_response_blob);
2413 if (!ok) {
2414 VLOG(1) << "Failed to set OCSP response property: "
2415 << GetLastError();
2418 #elif defined(USE_NSS)
2419 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response =
2420 GetCacheOCSPResponseFromSideChannelFunction();
2422 cache_ocsp_response(
2423 CERT_GetDefaultCertDB(),
2424 nss_handshake_state_.server_cert_chain[0], PR_Now(),
2425 &ocsp_responses->items[0], NULL);
2426 #endif
2427 } // IsOCSPStaplingSupported()
2430 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2431 // Note: This function may be called multiple times for a single connection
2432 // if renegotiations occur.
2433 nss_handshake_state_.ssl_connection_status = 0;
2435 SSLChannelInfo channel_info;
2436 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2437 &channel_info, sizeof(channel_info));
2438 if (ok == SECSuccess &&
2439 channel_info.length == sizeof(channel_info) &&
2440 channel_info.cipherSuite) {
2441 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2443 nss_handshake_state_.ssl_connection_status |=
2444 (static_cast<int>(channel_info.compressionMethod) &
2445 SSL_CONNECTION_COMPRESSION_MASK) <<
2446 SSL_CONNECTION_COMPRESSION_SHIFT;
2448 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2449 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) {
2450 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL
2451 // version 2.
2452 version = SSL_CONNECTION_VERSION_SSL2;
2453 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) {
2454 version = SSL_CONNECTION_VERSION_SSL3;
2455 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2456 version = SSL_CONNECTION_VERSION_TLS1;
2457 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2458 version = SSL_CONNECTION_VERSION_TLS1_1;
2459 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2460 version = SSL_CONNECTION_VERSION_TLS1_2;
2462 nss_handshake_state_.ssl_connection_status |=
2463 (version & SSL_CONNECTION_VERSION_MASK) <<
2464 SSL_CONNECTION_VERSION_SHIFT;
2467 PRBool peer_supports_renego_ext;
2468 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2469 &peer_supports_renego_ext);
2470 if (ok == SECSuccess) {
2471 if (!peer_supports_renego_ext) {
2472 nss_handshake_state_.ssl_connection_status |=
2473 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2474 // Log an informational message if the server does not support secure
2475 // renegotiation (RFC 5746).
2476 VLOG(1) << "The server " << host_and_port_.ToString()
2477 << " does not support the TLS renegotiation_info extension.";
2481 if (ssl_config_.version_fallback) {
2482 nss_handshake_state_.ssl_connection_status |=
2483 SSL_CONNECTION_VERSION_FALLBACK;
2487 void SSLClientSocketNSS::Core::UpdateNextProto() {
2488 uint8 buf[256];
2489 SSLNextProtoState state;
2490 unsigned buf_len;
2492 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2493 if (rv != SECSuccess)
2494 return;
2496 nss_handshake_state_.next_proto =
2497 std::string(reinterpret_cast<char*>(buf), buf_len);
2498 switch (state) {
2499 case SSL_NEXT_PROTO_NEGOTIATED:
2500 case SSL_NEXT_PROTO_SELECTED:
2501 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2502 break;
2503 case SSL_NEXT_PROTO_NO_OVERLAP:
2504 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2505 break;
2506 case SSL_NEXT_PROTO_NO_SUPPORT:
2507 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2508 break;
2509 default:
2510 NOTREACHED();
2511 break;
2515 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2516 PRBool negotiated_extension;
2517 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2518 ssl_app_layer_protocol_xtn,
2519 &negotiated_extension);
2520 if (rv == SECSuccess && negotiated_extension) {
2521 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2522 } else {
2523 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2524 ssl_next_proto_nego_xtn,
2525 &negotiated_extension);
2526 if (rv == SECSuccess && negotiated_extension) {
2527 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2532 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2533 DCHECK(OnNSSTaskRunner());
2534 if (nss_handshake_state_.resumed_handshake)
2535 return;
2537 // Copy the NSS task runner-only state to the network task runner and
2538 // log histograms from there, since the histograms also need access to the
2539 // network task runner state.
2540 PostOrRunCallback(
2541 FROM_HERE,
2542 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2543 this,
2544 channel_id_xtn_negotiated_,
2545 ssl_config_.channel_id_enabled,
2546 crypto::ECPrivateKey::IsSupported()));
2549 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2550 bool negotiated_channel_id,
2551 bool channel_id_enabled,
2552 bool supports_ecc) const {
2553 DCHECK(OnNetworkTaskRunner());
2555 RecordChannelIDSupport(channel_id_service_,
2556 negotiated_channel_id,
2557 channel_id_enabled,
2558 supports_ecc);
2561 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2562 DCHECK(OnNetworkTaskRunner());
2563 DCHECK_GT(len, 0);
2565 if (detached_)
2566 return ERR_ABORTED;
2568 int rv = transport_->socket()->Read(
2569 read_buffer, len,
2570 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2571 scoped_refptr<IOBuffer>(read_buffer)));
2573 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2574 nss_task_runner_->PostTask(
2575 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2576 scoped_refptr<IOBuffer>(read_buffer), rv));
2577 return rv;
2580 return rv;
2583 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2584 DCHECK(OnNetworkTaskRunner());
2585 DCHECK_GT(len, 0);
2587 if (detached_)
2588 return ERR_ABORTED;
2590 int rv = transport_->socket()->Write(
2591 send_buffer, len,
2592 base::Bind(&Core::BufferSendComplete,
2593 base::Unretained(this)));
2595 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2596 nss_task_runner_->PostTask(
2597 FROM_HERE,
2598 base::Bind(&Core::BufferSendComplete, this, rv));
2599 return rv;
2602 return rv;
2605 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2606 DCHECK(OnNetworkTaskRunner());
2608 if (detached_)
2609 return ERR_ABORTED;
2611 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2613 int rv = channel_id_service_->GetOrCreateChannelID(
2614 host,
2615 &domain_bound_private_key_,
2616 &domain_bound_cert_,
2617 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2618 &domain_bound_cert_request_handle_);
2620 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2621 nss_task_runner_->PostTask(
2622 FROM_HERE,
2623 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2624 return ERR_IO_PENDING;
2627 return rv;
2630 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2631 const HandshakeState& state) {
2632 DCHECK(OnNetworkTaskRunner());
2633 network_handshake_state_ = state;
2636 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2637 DCHECK(OnNetworkTaskRunner());
2638 unhandled_buffer_size_ = amount_in_read_buffer;
2641 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2642 DCHECK(OnNetworkTaskRunner());
2643 DCHECK(nss_waiting_read_);
2644 nss_waiting_read_ = false;
2645 if (result <= 0) {
2646 nss_is_closed_ = true;
2647 } else {
2648 was_ever_used_ = true;
2652 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2653 DCHECK(OnNetworkTaskRunner());
2654 DCHECK(nss_waiting_write_);
2655 nss_waiting_write_ = false;
2656 if (result < 0) {
2657 nss_is_closed_ = true;
2658 } else if (result > 0) {
2659 was_ever_used_ = true;
2663 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2664 if (!OnNSSTaskRunner()) {
2665 if (detached_)
2666 return;
2668 nss_task_runner_->PostTask(
2669 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2670 return;
2673 DCHECK(OnNSSTaskRunner());
2675 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2676 transport_send_busy_ = false;
2677 OnSendComplete(result);
2680 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2681 if (!OnNSSTaskRunner()) {
2682 if (detached_)
2683 return;
2685 nss_task_runner_->PostTask(
2686 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2687 return;
2690 DCHECK(OnNSSTaskRunner());
2692 int rv = DoHandshakeLoop(result);
2693 if (rv != ERR_IO_PENDING)
2694 DoConnectCallback(rv);
2697 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2698 DVLOG(1) << __FUNCTION__ << " " << result;
2699 DCHECK(OnNetworkTaskRunner());
2701 OnHandshakeIOComplete(result);
2704 void SSLClientSocketNSS::Core::BufferRecvComplete(
2705 IOBuffer* read_buffer,
2706 int result) {
2707 DCHECK(read_buffer);
2709 if (!OnNSSTaskRunner()) {
2710 if (detached_)
2711 return;
2713 nss_task_runner_->PostTask(
2714 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2715 scoped_refptr<IOBuffer>(read_buffer), result));
2716 return;
2719 DCHECK(OnNSSTaskRunner());
2721 if (result > 0) {
2722 char* buf;
2723 int nb = memio_GetReadParams(nss_bufs_, &buf);
2724 CHECK_GE(nb, result);
2725 memcpy(buf, read_buffer->data(), result);
2726 } else if (result == 0) {
2727 transport_recv_eof_ = true;
2730 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2731 transport_recv_busy_ = false;
2732 OnRecvComplete(result);
2735 void SSLClientSocketNSS::Core::PostOrRunCallback(
2736 const tracked_objects::Location& location,
2737 const base::Closure& task) {
2738 if (!OnNetworkTaskRunner()) {
2739 network_task_runner_->PostTask(
2740 FROM_HERE,
2741 base::Bind(&Core::PostOrRunCallback, this, location, task));
2742 return;
2745 if (detached_ || task.is_null())
2746 return;
2747 task.Run();
2750 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2751 PostOrRunCallback(
2752 FROM_HERE,
2753 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2754 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2755 NetLog::IntegerCallback("cert_count", cert_count)));
2758 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2759 PostOrRunCallback(
2760 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2761 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2762 nss_handshake_state_.channel_id_sent = true;
2763 // Update the network task runner's view of the handshake state now that
2764 // channel id has been sent.
2765 PostOrRunCallback(
2766 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2767 nss_handshake_state_));
2770 SSLClientSocketNSS::SSLClientSocketNSS(
2771 base::SequencedTaskRunner* nss_task_runner,
2772 scoped_ptr<ClientSocketHandle> transport_socket,
2773 const HostPortPair& host_and_port,
2774 const SSLConfig& ssl_config,
2775 const SSLClientSocketContext& context)
2776 : nss_task_runner_(nss_task_runner),
2777 transport_(transport_socket.Pass()),
2778 host_and_port_(host_and_port),
2779 ssl_config_(ssl_config),
2780 cert_verifier_(context.cert_verifier),
2781 cert_transparency_verifier_(context.cert_transparency_verifier),
2782 channel_id_service_(context.channel_id_service),
2783 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2784 completed_handshake_(false),
2785 next_handshake_state_(STATE_NONE),
2786 nss_fd_(NULL),
2787 net_log_(transport_->socket()->NetLog()),
2788 transport_security_state_(context.transport_security_state),
2789 policy_enforcer_(context.cert_policy_enforcer),
2790 valid_thread_id_(base::kInvalidThreadId) {
2791 EnterFunction("");
2792 InitCore();
2793 LeaveFunction("");
2796 SSLClientSocketNSS::~SSLClientSocketNSS() {
2797 EnterFunction("");
2798 Disconnect();
2799 LeaveFunction("");
2802 // static
2803 void SSLClientSocket::ClearSessionCache() {
2804 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2805 // bother initializing NSS just to clear an empty SSL session cache.
2806 if (!NSS_IsInitialized())
2807 return;
2809 SSL_ClearSessionCache();
2812 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2813 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2814 #endif
2816 // static
2817 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
2818 crypto::EnsureNSSInit();
2819 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) {
2820 return SSL_PROTOCOL_VERSION_TLS1_2;
2821 } else {
2822 return SSL_PROTOCOL_VERSION_TLS1_1;
2826 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2827 EnterFunction("");
2828 ssl_info->Reset();
2829 if (core_->state().server_cert_chain.empty() ||
2830 !core_->state().server_cert_chain[0]) {
2831 return false;
2834 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2835 ssl_info->cert = server_cert_verify_result_.verified_cert;
2837 AddSCTInfoToSSLInfo(ssl_info);
2839 ssl_info->connection_status =
2840 core_->state().ssl_connection_status;
2841 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2842 ssl_info->is_issued_by_known_root =
2843 server_cert_verify_result_.is_issued_by_known_root;
2844 ssl_info->client_cert_sent =
2845 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2846 ssl_info->channel_id_sent = WasChannelIDSent();
2847 ssl_info->pinning_failure_log = pinning_failure_log_;
2849 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2850 core_->state().ssl_connection_status);
2851 SSLCipherSuiteInfo cipher_info;
2852 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2853 &cipher_info, sizeof(cipher_info));
2854 if (ok == SECSuccess) {
2855 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2856 } else {
2857 ssl_info->security_bits = -1;
2858 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2859 << " for cipherSuite " << cipher_suite;
2862 ssl_info->handshake_type = core_->state().resumed_handshake ?
2863 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2865 LeaveFunction("");
2866 return true;
2869 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2870 SSLCertRequestInfo* cert_request_info) {
2871 EnterFunction("");
2872 cert_request_info->host_and_port = host_and_port_;
2873 cert_request_info->cert_authorities = core_->state().cert_authorities;
2874 LeaveFunction("");
2877 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2878 bool has_context,
2879 const base::StringPiece& context,
2880 unsigned char* out,
2881 unsigned int outlen) {
2882 if (!IsConnected())
2883 return ERR_SOCKET_NOT_CONNECTED;
2885 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2886 // the midst of a handshake.
2887 SECStatus result = SSL_ExportKeyingMaterial(
2888 nss_fd_, label.data(), label.size(), has_context,
2889 reinterpret_cast<const unsigned char*>(context.data()),
2890 context.length(), out, outlen);
2891 if (result != SECSuccess) {
2892 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2893 return MapNSSError(PORT_GetError());
2895 return OK;
2898 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2899 if (!IsConnected())
2900 return ERR_SOCKET_NOT_CONNECTED;
2901 unsigned char buf[64];
2902 unsigned int len;
2903 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2904 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2905 buf, &len, arraysize(buf));
2906 if (result != SECSuccess) {
2907 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2908 return MapNSSError(PORT_GetError());
2910 out->assign(reinterpret_cast<char*>(buf), len);
2911 return OK;
2914 SSLClientSocket::NextProtoStatus
2915 SSLClientSocketNSS::GetNextProto(std::string* proto) {
2916 *proto = core_->state().next_proto;
2917 return core_->state().next_proto_status;
2920 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2921 EnterFunction("");
2922 DCHECK(transport_.get());
2923 // It is an error to create an SSLClientSocket whose context has no
2924 // TransportSecurityState.
2925 DCHECK(transport_security_state_);
2926 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2927 DCHECK(user_connect_callback_.is_null());
2928 DCHECK(!callback.is_null());
2930 EnsureThreadIdAssigned();
2932 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2934 int rv = Init();
2935 if (rv != OK) {
2936 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2937 return rv;
2940 rv = InitializeSSLOptions();
2941 if (rv != OK) {
2942 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2943 return rv;
2946 rv = InitializeSSLPeerName();
2947 if (rv != OK) {
2948 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2949 return rv;
2952 GotoState(STATE_HANDSHAKE);
2954 rv = DoHandshakeLoop(OK);
2955 if (rv == ERR_IO_PENDING) {
2956 user_connect_callback_ = callback;
2957 } else {
2958 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2961 LeaveFunction("");
2962 return rv > OK ? OK : rv;
2965 void SSLClientSocketNSS::Disconnect() {
2966 EnterFunction("");
2968 CHECK(CalledOnValidThread());
2970 // Shut down anything that may call us back.
2971 core_->Detach();
2972 verifier_.reset();
2973 transport_->socket()->Disconnect();
2975 // Reset object state.
2976 user_connect_callback_.Reset();
2977 server_cert_verify_result_.Reset();
2978 completed_handshake_ = false;
2979 start_cert_verification_time_ = base::TimeTicks();
2980 InitCore();
2982 LeaveFunction("");
2985 bool SSLClientSocketNSS::IsConnected() const {
2986 EnterFunction("");
2987 bool ret = completed_handshake_ &&
2988 (core_->HasPendingAsyncOperation() ||
2989 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2990 transport_->socket()->IsConnected());
2991 LeaveFunction("");
2992 return ret;
2995 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2996 EnterFunction("");
2997 bool ret = completed_handshake_ &&
2998 !core_->HasPendingAsyncOperation() &&
2999 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
3000 transport_->socket()->IsConnectedAndIdle();
3001 LeaveFunction("");
3002 return ret;
3005 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
3006 return transport_->socket()->GetPeerAddress(address);
3009 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
3010 return transport_->socket()->GetLocalAddress(address);
3013 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
3014 return net_log_;
3017 void SSLClientSocketNSS::SetSubresourceSpeculation() {
3018 if (transport_.get() && transport_->socket()) {
3019 transport_->socket()->SetSubresourceSpeculation();
3020 } else {
3021 NOTREACHED();
3025 void SSLClientSocketNSS::SetOmniboxSpeculation() {
3026 if (transport_.get() && transport_->socket()) {
3027 transport_->socket()->SetOmniboxSpeculation();
3028 } else {
3029 NOTREACHED();
3033 bool SSLClientSocketNSS::WasEverUsed() const {
3034 DCHECK(core_.get());
3036 return core_->WasEverUsed();
3039 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
3040 if (transport_.get() && transport_->socket()) {
3041 return transport_->socket()->UsingTCPFastOpen();
3043 NOTREACHED();
3044 return false;
3047 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
3048 const CompletionCallback& callback) {
3049 DCHECK(core_.get());
3050 DCHECK(!callback.is_null());
3052 EnterFunction(buf_len);
3053 int rv = core_->Read(buf, buf_len, callback);
3054 LeaveFunction(rv);
3056 return rv;
3059 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
3060 const CompletionCallback& callback) {
3061 DCHECK(core_.get());
3062 DCHECK(!callback.is_null());
3064 EnterFunction(buf_len);
3065 int rv = core_->Write(buf, buf_len, callback);
3066 LeaveFunction(rv);
3068 return rv;
3071 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
3072 return transport_->socket()->SetReceiveBufferSize(size);
3075 int SSLClientSocketNSS::SetSendBufferSize(int32 size) {
3076 return transport_->socket()->SetSendBufferSize(size);
3079 int SSLClientSocketNSS::Init() {
3080 EnterFunction("");
3081 // Initialize the NSS SSL library in a threadsafe way. This also
3082 // initializes the NSS base library.
3083 EnsureNSSSSLInit();
3084 if (!NSS_IsInitialized())
3085 return ERR_UNEXPECTED;
3086 #if defined(USE_NSS) || defined(OS_IOS)
3087 if (ssl_config_.cert_io_enabled) {
3088 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
3089 // loop by MessageLoopForIO::current().
3090 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
3091 EnsureNSSHttpIOInit();
3093 #endif
3095 LeaveFunction("");
3096 return OK;
3099 void SSLClientSocketNSS::InitCore() {
3100 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
3101 nss_task_runner_.get(),
3102 transport_.get(),
3103 host_and_port_,
3104 ssl_config_,
3105 &net_log_,
3106 channel_id_service_);
3109 int SSLClientSocketNSS::InitializeSSLOptions() {
3110 // Transport connected, now hook it up to nss
3111 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
3112 if (nss_fd_ == NULL) {
3113 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
3116 // Grab pointer to buffers
3117 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
3119 /* Create SSL state machine */
3120 /* Push SSL onto our fake I/O socket */
3121 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
3122 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
3123 PR_Close(nss_fd_);
3124 nss_fd_ = NULL;
3125 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
3127 // TODO(port): set more ssl options! Check errors!
3129 int rv;
3131 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
3132 if (rv != SECSuccess) {
3133 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
3134 return ERR_UNEXPECTED;
3137 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
3138 if (rv != SECSuccess) {
3139 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
3140 return ERR_UNEXPECTED;
3143 // Don't do V2 compatible hellos because they don't support TLS extensions.
3144 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
3145 if (rv != SECSuccess) {
3146 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
3147 return ERR_UNEXPECTED;
3150 SSLVersionRange version_range;
3151 version_range.min = ssl_config_.version_min;
3152 version_range.max = ssl_config_.version_max;
3153 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
3154 if (rv != SECSuccess) {
3155 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
3156 return ERR_NO_SSL_VERSIONS_ENABLED;
3159 if (ssl_config_.version_fallback) {
3160 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
3161 if (rv != SECSuccess) {
3162 LogFailedNSSFunction(
3163 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
3167 for (std::vector<uint16>::const_iterator it =
3168 ssl_config_.disabled_cipher_suites.begin();
3169 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
3170 // This will fail if the specified cipher is not implemented by NSS, but
3171 // the failure is harmless.
3172 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
3175 if (!ssl_config_.enable_deprecated_cipher_suites) {
3176 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
3177 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
3178 for (int i = 0; i < num_ciphers; i++) {
3179 SSLCipherSuiteInfo info;
3180 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) !=
3181 SECSuccess) {
3182 continue;
3184 if (info.symCipher == ssl_calg_rc4)
3185 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
3189 // Support RFC 5077
3190 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
3191 if (rv != SECSuccess) {
3192 LogFailedNSSFunction(
3193 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
3196 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
3197 ssl_config_.false_start_enabled);
3198 if (rv != SECSuccess)
3199 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
3201 // We allow servers to request renegotiation. Since we're a client,
3202 // prohibiting this is rather a waste of time. Only servers are in a
3203 // position to prevent renegotiation attacks.
3204 // http://extendedsubset.com/?p=8
3206 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
3207 SSL_RENEGOTIATE_TRANSITIONAL);
3208 if (rv != SECSuccess) {
3209 LogFailedNSSFunction(
3210 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
3213 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
3214 if (rv != SECSuccess)
3215 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
3217 // Added in NSS 3.15
3218 #ifdef SSL_ENABLE_OCSP_STAPLING
3219 // Request OCSP stapling even on platforms that don't support it, in
3220 // order to extract Certificate Transparency information.
3221 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
3222 (IsOCSPStaplingSupported() ||
3223 ssl_config_.signed_cert_timestamps_enabled));
3224 if (rv != SECSuccess) {
3225 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3226 "SSL_ENABLE_OCSP_STAPLING");
3228 #endif
3230 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
3231 ssl_config_.signed_cert_timestamps_enabled);
3232 if (rv != SECSuccess) {
3233 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
3234 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
3237 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
3238 if (rv != SECSuccess) {
3239 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
3240 return ERR_UNEXPECTED;
3243 if (!core_->Init(nss_fd_, nss_bufs))
3244 return ERR_UNEXPECTED;
3246 // Tell SSL the hostname we're trying to connect to.
3247 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
3249 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
3250 SSL_ResetHandshake(nss_fd_, PR_FALSE);
3252 return OK;
3255 int SSLClientSocketNSS::InitializeSSLPeerName() {
3256 // Tell NSS who we're connected to
3257 IPEndPoint peer_address;
3258 int err = transport_->socket()->GetPeerAddress(&peer_address);
3259 if (err != OK)
3260 return err;
3262 SockaddrStorage storage;
3263 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
3264 return ERR_ADDRESS_INVALID;
3266 PRNetAddr peername;
3267 memset(&peername, 0, sizeof(peername));
3268 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
3269 size_t len = std::min(static_cast<size_t>(storage.addr_len),
3270 sizeof(peername));
3271 memcpy(&peername, storage.addr, len);
3273 // Adjust the address family field for BSD, whose sockaddr
3274 // structure has a one-byte length and one-byte address family
3275 // field at the beginning. PRNetAddr has a two-byte address
3276 // family field at the beginning.
3277 peername.raw.family = storage.addr->sa_family;
3279 memio_SetPeerName(nss_fd_, &peername);
3281 // Set the peer ID for session reuse. This is necessary when we create an
3282 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
3283 // rather than the destination server's address in that case.
3284 std::string peer_id = host_and_port_.ToString();
3285 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
3286 // the session cache for incognito mode.
3287 peer_id += "/" + ssl_session_cache_shard_;
3288 peer_id += "/";
3289 // Shard the session cache based on maximum protocol version. This causes
3290 // fallback connections to use a separate session cache.
3291 switch (ssl_config_.version_max) {
3292 case SSL_PROTOCOL_VERSION_SSL3:
3293 peer_id += "ssl3";
3294 break;
3295 case SSL_PROTOCOL_VERSION_TLS1:
3296 peer_id += "tls1";
3297 break;
3298 case SSL_PROTOCOL_VERSION_TLS1_1:
3299 peer_id += "tls1.1";
3300 break;
3301 case SSL_PROTOCOL_VERSION_TLS1_2:
3302 peer_id += "tls1.2";
3303 break;
3304 default:
3305 NOTREACHED();
3307 peer_id += "/";
3308 if (ssl_config_.enable_deprecated_cipher_suites)
3309 peer_id += "deprecated";
3311 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
3312 if (rv != SECSuccess)
3313 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
3315 return OK;
3318 void SSLClientSocketNSS::DoConnectCallback(int rv) {
3319 EnterFunction(rv);
3320 DCHECK_NE(ERR_IO_PENDING, rv);
3321 DCHECK(!user_connect_callback_.is_null());
3323 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
3324 LeaveFunction("");
3327 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
3328 EnterFunction(result);
3329 int rv = DoHandshakeLoop(result);
3330 if (rv != ERR_IO_PENDING) {
3331 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
3332 DoConnectCallback(rv);
3334 LeaveFunction("");
3337 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
3338 EnterFunction(last_io_result);
3339 int rv = last_io_result;
3340 do {
3341 // Default to STATE_NONE for next state.
3342 // (This is a quirk carried over from the windows
3343 // implementation. It makes reading the logs a bit harder.)
3344 // State handlers can and often do call GotoState just
3345 // to stay in the current state.
3346 State state = next_handshake_state_;
3347 GotoState(STATE_NONE);
3348 switch (state) {
3349 case STATE_HANDSHAKE:
3350 rv = DoHandshake();
3351 break;
3352 case STATE_HANDSHAKE_COMPLETE:
3353 rv = DoHandshakeComplete(rv);
3354 break;
3355 case STATE_VERIFY_CERT:
3356 DCHECK(rv == OK);
3357 rv = DoVerifyCert(rv);
3358 break;
3359 case STATE_VERIFY_CERT_COMPLETE:
3360 rv = DoVerifyCertComplete(rv);
3361 break;
3362 case STATE_NONE:
3363 default:
3364 rv = ERR_UNEXPECTED;
3365 LOG(DFATAL) << "unexpected state " << state;
3366 break;
3368 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
3369 LeaveFunction("");
3370 return rv;
3373 int SSLClientSocketNSS::DoHandshake() {
3374 EnterFunction("");
3375 int rv = core_->Connect(
3376 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3377 base::Unretained(this)));
3378 GotoState(STATE_HANDSHAKE_COMPLETE);
3380 LeaveFunction(rv);
3381 return rv;
3384 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3385 EnterFunction(result);
3387 if (result == OK) {
3388 if (ssl_config_.version_fallback &&
3389 ssl_config_.version_max < ssl_config_.version_fallback_min) {
3390 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
3393 // SSL handshake is completed. Let's verify the certificate.
3394 GotoState(STATE_VERIFY_CERT);
3395 // Done!
3397 set_channel_id_sent(core_->state().channel_id_sent);
3398 set_signed_cert_timestamps_received(
3399 !core_->state().sct_list_from_tls_extension.empty());
3400 set_stapled_ocsp_response_received(
3401 !core_->state().stapled_ocsp_response.empty());
3402 set_negotiation_extension(core_->state().negotiation_extension_);
3404 LeaveFunction(result);
3405 return result;
3408 int SSLClientSocketNSS::DoVerifyCert(int result) {
3409 DCHECK(!core_->state().server_cert_chain.empty());
3410 DCHECK(core_->state().server_cert_chain[0]);
3412 GotoState(STATE_VERIFY_CERT_COMPLETE);
3414 // If the certificate is expected to be bad we can use the expectation as
3415 // the cert status.
3416 base::StringPiece der_cert(
3417 reinterpret_cast<char*>(
3418 core_->state().server_cert_chain[0]->derCert.data),
3419 core_->state().server_cert_chain[0]->derCert.len);
3420 CertStatus cert_status;
3421 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3422 DCHECK(start_cert_verification_time_.is_null());
3423 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3424 server_cert_verify_result_.Reset();
3425 server_cert_verify_result_.cert_status = cert_status;
3426 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3427 return OK;
3430 // We may have failed to create X509Certificate object if we are
3431 // running inside sandbox.
3432 if (!core_->state().server_cert.get()) {
3433 server_cert_verify_result_.Reset();
3434 server_cert_verify_result_.cert_status = CERT_STATUS_INVALID;
3435 return ERR_CERT_INVALID;
3438 start_cert_verification_time_ = base::TimeTicks::Now();
3440 int flags = 0;
3441 if (ssl_config_.rev_checking_enabled)
3442 flags |= CertVerifier::VERIFY_REV_CHECKING_ENABLED;
3443 if (ssl_config_.verify_ev_cert)
3444 flags |= CertVerifier::VERIFY_EV_CERT;
3445 if (ssl_config_.cert_io_enabled)
3446 flags |= CertVerifier::VERIFY_CERT_IO_ENABLED;
3447 if (ssl_config_.rev_checking_required_local_anchors)
3448 flags |= CertVerifier::VERIFY_REV_CHECKING_REQUIRED_LOCAL_ANCHORS;
3449 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_));
3450 return verifier_->Verify(
3451 core_->state().server_cert.get(),
3452 host_and_port_.host(),
3453 flags,
3454 SSLConfigService::GetCRLSet().get(),
3455 &server_cert_verify_result_,
3456 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3457 base::Unretained(this)),
3458 net_log_);
3461 // Derived from AuthCertificateCallback() in
3462 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3463 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3464 verifier_.reset();
3466 if (!start_cert_verification_time_.is_null()) {
3467 base::TimeDelta verify_time =
3468 base::TimeTicks::Now() - start_cert_verification_time_;
3469 if (result == OK)
3470 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3471 else
3472 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3475 // We used to remember the intermediate CA certs in the NSS database
3476 // persistently. However, NSS opens a connection to the SQLite database
3477 // during NSS initialization and doesn't close the connection until NSS
3478 // shuts down. If the file system where the database resides is gone,
3479 // the database connection goes bad. What's worse, the connection won't
3480 // recover when the file system comes back. Until this NSS or SQLite bug
3481 // is fixed, we need to avoid using the NSS database for non-essential
3482 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3483 // http://crbug.com/15630 for more info.
3485 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3486 if (transport_security_state_ &&
3487 (result == OK ||
3488 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3489 !transport_security_state_->CheckPublicKeyPins(
3490 host_and_port_.host(),
3491 server_cert_verify_result_.is_issued_by_known_root,
3492 server_cert_verify_result_.public_key_hashes,
3493 &pinning_failure_log_)) {
3494 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3497 if (result == OK) {
3498 // Only check Certificate Transparency if there were no other errors with
3499 // the connection.
3500 VerifyCT();
3502 // Only cache the session if the certificate verified successfully.
3503 core_->CacheSessionIfNecessary();
3506 completed_handshake_ = true;
3508 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3509 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3510 return result;
3513 void SSLClientSocketNSS::VerifyCT() {
3514 if (!cert_transparency_verifier_)
3515 return;
3517 // Note that this is a completely synchronous operation: The CT Log Verifier
3518 // gets all the data it needs for SCT verification and does not do any
3519 // external communication.
3520 cert_transparency_verifier_->Verify(
3521 server_cert_verify_result_.verified_cert.get(),
3522 core_->state().stapled_ocsp_response,
3523 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3524 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3525 // from the state after verification is complete, to conserve memory.
3527 if (!policy_enforcer_) {
3528 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3529 } else {
3530 if (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV) {
3531 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3532 SSLConfigService::GetEVCertsWhitelist();
3533 if (!policy_enforcer_->DoesConformToCTEVPolicy(
3534 server_cert_verify_result_.verified_cert.get(),
3535 ev_whitelist.get(), ct_verify_result_, net_log_)) {
3536 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3537 VLOG(1) << "EV certificate for "
3538 << server_cert_verify_result_.verified_cert->subject()
3539 .GetDisplayName()
3540 << " does not conform to CT policy, removing EV status.";
3541 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3547 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3548 base::AutoLock auto_lock(lock_);
3549 if (valid_thread_id_ != base::kInvalidThreadId)
3550 return;
3551 valid_thread_id_ = base::PlatformThread::CurrentId();
3554 bool SSLClientSocketNSS::CalledOnValidThread() const {
3555 EnsureThreadIdAssigned();
3556 base::AutoLock auto_lock(lock_);
3557 return valid_thread_id_ == base::PlatformThread::CurrentId();
3560 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3561 for (ct::SCTList::const_iterator iter =
3562 ct_verify_result_.verified_scts.begin();
3563 iter != ct_verify_result_.verified_scts.end(); ++iter) {
3564 ssl_info->signed_certificate_timestamps.push_back(
3565 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
3567 for (ct::SCTList::const_iterator iter =
3568 ct_verify_result_.invalid_scts.begin();
3569 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
3570 ssl_info->signed_certificate_timestamps.push_back(
3571 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
3573 for (ct::SCTList::const_iterator iter =
3574 ct_verify_result_.unknown_logs_scts.begin();
3575 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
3576 ssl_info->signed_certificate_timestamps.push_back(
3577 SignedCertificateTimestampAndStatus(*iter,
3578 ct::SCT_STATUS_LOG_UNKNOWN));
3582 scoped_refptr<X509Certificate>
3583 SSLClientSocketNSS::GetUnverifiedServerCertificateChain() const {
3584 return core_->state().server_cert.get();
3587 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3588 return channel_id_service_;
3591 } // namespace net