Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / socket / ssl_client_socket_nss.cc
blobf558e717ac4ea1ffa1374634f381decc586a00c3
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/location.h"
72 #include "base/logging.h"
73 #include "base/metrics/histogram_macros.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/base/net_util.h"
92 #include "net/cert/asn1_util.h"
93 #include "net/cert/cert_policy_enforcer.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/ct_ev_whitelist.h"
97 #include "net/cert/ct_verifier.h"
98 #include "net/cert/ct_verify_result.h"
99 #include "net/cert/scoped_nss_types.h"
100 #include "net/cert/sct_status_flags.h"
101 #include "net/cert/x509_certificate_net_log_param.h"
102 #include "net/cert/x509_util.h"
103 #include "net/cert_net/nss_ocsp.h"
104 #include "net/http/transport_security_state.h"
105 #include "net/log/net_log.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_failure_state.h"
112 #include "net/ssl/ssl_info.h"
114 #if defined(USE_NSS_CERTS)
115 #include <dlfcn.h>
116 #endif
118 namespace net {
120 // State machines are easier to debug if you log state transitions.
121 // Enable these if you want to see what's going on.
122 #if 1
123 #define EnterFunction(x)
124 #define LeaveFunction(x)
125 #define GotoState(s) next_handshake_state_ = s
126 #else
127 #define EnterFunction(x)\
128 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
129 << "; next_handshake_state " << next_handshake_state_
130 #define LeaveFunction(x)\
131 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
132 << "; next_handshake_state " << next_handshake_state_
133 #define GotoState(s)\
134 do {\
135 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
136 next_handshake_state_ = s;\
137 } while (0)
138 #endif
140 #if !defined(CKM_AES_GCM)
141 #define CKM_AES_GCM 0x00001087
142 #endif
144 #if !defined(CKM_NSS_CHACHA20_POLY1305)
145 #define CKM_NSS_CHACHA20_POLY1305 (CKM_NSS + 26)
146 #endif
148 namespace {
150 // SSL plaintext fragments are shorter than 16KB. Although the record layer
151 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
152 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
153 // entire SSL record.
154 const int kRecvBufferSize = 17 * 1024;
155 const int kSendBufferSize = 17 * 1024;
157 // Used by SSLClientSocketNSS::Core to indicate there is no read result
158 // obtained by a previous operation waiting to be returned to the caller.
159 // This constant can be any non-negative/non-zero value (eg: it does not
160 // overlap with any value of the net::Error range, including net::OK).
161 const int kNoPendingReadResult = 1;
163 // Helper functions to make it possible to log events from within the
164 // SSLClientSocketNSS::Core.
165 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
166 NetLog::EventType event_type) {
167 if (!net_log)
168 return;
169 net_log->AddEvent(event_type);
172 // Helper function to make it possible to log events from within the
173 // SSLClientSocketNSS::Core.
174 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
175 NetLog::EventType event_type,
176 const NetLog::ParametersCallback& callback) {
177 if (!net_log)
178 return;
179 net_log->AddEvent(event_type, callback);
182 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
183 // from within the SSLClientSocketNSS::Core.
184 // AddByteTransferEvent expects to receive a const char*, which within the
185 // Core is backed by an IOBuffer. If the "const char*" is bound via
186 // base::Bind and posted to another thread, and the IOBuffer that backs that
187 // pointer then goes out of scope on the origin thread, this would result in
188 // an invalid read of a stale pointer.
189 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
190 // to the owning IOBuffer can be bound to the Callback. This ensures that the
191 // IOBuffer will stay alive long enough to cross threads if needed.
192 void LogByteTransferEvent(
193 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
194 int len, IOBuffer* buffer) {
195 if (!net_log)
196 return;
197 net_log->AddByteTransferEvent(event_type, len, buffer->data());
200 // PeerCertificateChain is a helper object which extracts the certificate
201 // chain, as given by the server, from an NSS socket and performs the needed
202 // resource management. The first element of the chain is the leaf certificate
203 // and the other elements are in the order given by the server.
204 class PeerCertificateChain {
205 public:
206 PeerCertificateChain() {}
207 PeerCertificateChain(const PeerCertificateChain& other);
208 ~PeerCertificateChain();
209 PeerCertificateChain& operator=(const PeerCertificateChain& other);
211 // Resets the current chain, freeing any resources, and updates the current
212 // chain to be a copy of the chain stored in |nss_fd|.
213 // If |nss_fd| is NULL, then the current certificate chain will be freed.
214 void Reset(PRFileDesc* nss_fd);
216 // Returns the current certificate chain as a vector of DER-encoded
217 // base::StringPieces. The returned vector remains valid until Reset is
218 // called.
219 std::vector<base::StringPiece> AsStringPieceVector() const;
221 bool empty() const { return certs_.empty(); }
223 CERTCertificate* operator[](size_t index) const {
224 DCHECK_LT(index, certs_.size());
225 return certs_[index];
228 private:
229 std::vector<CERTCertificate*> certs_;
232 PeerCertificateChain::PeerCertificateChain(
233 const PeerCertificateChain& other) {
234 *this = other;
237 PeerCertificateChain::~PeerCertificateChain() {
238 Reset(NULL);
241 PeerCertificateChain& PeerCertificateChain::operator=(
242 const PeerCertificateChain& other) {
243 if (this == &other)
244 return *this;
246 Reset(NULL);
247 certs_.reserve(other.certs_.size());
248 for (size_t i = 0; i < other.certs_.size(); ++i)
249 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
251 return *this;
254 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
255 for (size_t i = 0; i < certs_.size(); ++i)
256 CERT_DestroyCertificate(certs_[i]);
257 certs_.clear();
259 if (nss_fd == NULL)
260 return;
262 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
263 // The handshake on |nss_fd| may not have completed.
264 if (list == NULL)
265 return;
267 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
268 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
269 certs_.push_back(CERT_DupCertificate(node->cert));
271 CERT_DestroyCertList(list);
274 std::vector<base::StringPiece>
275 PeerCertificateChain::AsStringPieceVector() const {
276 std::vector<base::StringPiece> v(certs_.size());
277 for (unsigned i = 0; i < certs_.size(); i++) {
278 v[i] = base::StringPiece(
279 reinterpret_cast<const char*>(certs_[i]->derCert.data),
280 certs_[i]->derCert.len);
283 return v;
286 // HandshakeState is a helper struct used to pass handshake state between
287 // the NSS task runner and the network task runner.
289 // It contains members that may be read or written on the NSS task runner,
290 // but which also need to be read from the network task runner. The NSS task
291 // runner will notify the network task runner whenever this state changes, so
292 // that the network task runner can safely make a copy, which avoids the need
293 // for locking.
294 struct HandshakeState {
295 HandshakeState() { Reset(); }
297 void Reset() {
298 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
299 next_proto.clear();
300 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
301 channel_id_sent = false;
302 server_cert_chain.Reset(NULL);
303 server_cert = NULL;
304 sct_list_from_tls_extension.clear();
305 stapled_ocsp_response.clear();
306 resumed_handshake = false;
307 ssl_connection_status = 0;
310 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
311 // negotiated protocol stored in |next_proto|.
312 SSLClientSocket::NextProtoStatus next_proto_status;
313 std::string next_proto;
315 // TLS extension used for protocol negotiation.
316 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
318 // True if a channel ID was sent.
319 bool channel_id_sent;
321 // List of DER-encoded X.509 DistinguishedName of certificate authorities
322 // allowed by the server.
323 std::vector<std::string> cert_authorities;
325 // Set when the handshake fully completes.
327 // The server certificate is first received from NSS as an NSS certificate
328 // chain (|server_cert_chain|) and then converted into a platform-specific
329 // X509Certificate object (|server_cert|). It's possible for some
330 // certificates to be successfully parsed by NSS, and not by the platform
331 // libraries (i.e.: when running within a sandbox, different parsing
332 // algorithms, etc), so it's not safe to assume that |server_cert| will
333 // always be non-NULL.
334 PeerCertificateChain server_cert_chain;
335 scoped_refptr<X509Certificate> server_cert;
336 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
337 std::string sct_list_from_tls_extension;
338 // Stapled OCSP response received.
339 std::string stapled_ocsp_response;
341 // True if the current handshake was the result of TLS session resumption.
342 bool resumed_handshake;
344 // The negotiated security parameters (TLS version, cipher, extensions) of
345 // the SSL connection.
346 int ssl_connection_status;
349 // Client-side error mapping functions.
351 // Map NSS error code to network error code.
352 int MapNSSClientError(PRErrorCode err) {
353 switch (err) {
354 case SSL_ERROR_BAD_CERT_ALERT:
355 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
356 case SSL_ERROR_REVOKED_CERT_ALERT:
357 case SSL_ERROR_EXPIRED_CERT_ALERT:
358 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
359 case SSL_ERROR_UNKNOWN_CA_ALERT:
360 case SSL_ERROR_ACCESS_DENIED_ALERT:
361 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
362 default:
363 return MapNSSError(err);
367 } // namespace
369 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
370 // able to marshal data between NSS functions and an underlying transport
371 // socket.
373 // All public functions are meant to be called from the network task runner,
374 // and any callbacks supplied will be invoked there as well, provided that
375 // Detach() has not been called yet.
377 /////////////////////////////////////////////////////////////////////////////
379 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
381 // Because NSS may block on either hardware or user input during operations
382 // such as signing, creating certificates, or locating private keys, the Core
383 // handles all of the interactions with the underlying NSS SSL socket, so
384 // that these blocking calls can be executed on a dedicated task runner.
386 // Note that the network task runner and the NSS task runner may be executing
387 // on the same thread. If that happens, then it's more performant to try to
388 // complete as much work as possible synchronously, even if it might block,
389 // rather than continually PostTask-ing to the same thread.
391 // Because NSS functions should only be called on the NSS task runner, while
392 // I/O resources should only be accessed on the network task runner, most
393 // public functions are implemented via three methods, each with different
394 // task runner affinities.
396 // In the single-threaded mode (where the network and NSS task runners run on
397 // the same thread), these are all attempted synchronously, while in the
398 // multi-threaded mode, message passing is used.
400 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
401 // DoHandshake)
402 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
403 // (BufferRecv, BufferSend)
404 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
405 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
406 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
407 // data from the network task runner back to NSS (BufferRecvComplete,
408 // BufferSendComplete, OnHandshakeIOComplete)
410 /////////////////////////////////////////////////////////////////////////////
411 // Single-threaded example
413 // |--------------------------Network Task Runner--------------------------|
414 // SSLClientSocketNSS Core (Transport Socket)
415 // Read()
416 // |-------------------------V
417 // Read()
418 // |
419 // DoPayloadRead()
420 // |
421 // BufferRecv()
422 // |
423 // DoBufferRecv()
424 // |-------------------------V
425 // Read()
426 // V-------------------------|
427 // BufferRecvComplete()
428 // |
429 // PostOrRunCallback()
430 // V-------------------------|
431 // (Read Callback)
433 /////////////////////////////////////////////////////////////////////////////
434 // Multi-threaded example:
436 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
437 // SSLClientSocketNSS Core Socket Core
438 // Read()
439 // |---------------------V
440 // Read()
441 // |-------------------------------V
442 // Read()
443 // |
444 // DoPayloadRead()
445 // |
446 // BufferRecv
447 // V-------------------------------|
448 // DoBufferRecv
449 // |----------------V
450 // Read()
451 // V----------------|
452 // BufferRecvComplete()
453 // |-------------------------------V
454 // BufferRecvComplete()
455 // |
456 // PostOrRunCallback()
457 // V-------------------------------|
458 // PostOrRunCallback()
459 // V---------------------|
460 // (Read Callback)
462 /////////////////////////////////////////////////////////////////////////////
463 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
464 public:
465 // Creates a new Core.
467 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
468 // that need to operate on the underlying transport, net log, or server
469 // bound certificate fetching will happen on the |network_task_runner|, so
470 // that their lifetimes match that of the owning SSLClientSocketNSS.
472 // The caller retains ownership of |transport|, |net_log|, and
473 // |channel_id_service|, and they will not be accessed once Detach()
474 // has been called.
475 Core(base::SequencedTaskRunner* network_task_runner,
476 base::SequencedTaskRunner* nss_task_runner,
477 ClientSocketHandle* transport,
478 const HostPortPair& host_and_port,
479 const SSLConfig& ssl_config,
480 BoundNetLog* net_log,
481 ChannelIDService* channel_id_service);
483 // Called on the network task runner.
484 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
485 // underlying memio implementation, to the Core. Returns true if the Core
486 // was successfully registered with the socket.
487 bool Init(PRFileDesc* socket, memio_Private* buffers);
489 // Called on the network task runner.
491 // Attempts to perform an SSL handshake. If the handshake cannot be
492 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
493 // the network task runner once the handshake has completed. Otherwise,
494 // returns OK on success or a network error code on failure.
495 int Connect(const CompletionCallback& callback);
497 // Called on the network task runner.
498 // Signals that the resources owned by the network task runner are going
499 // away. No further callbacks will be invoked on the network task runner.
500 // May be called at any time.
501 void Detach();
503 // Called on the network task runner.
504 // Returns the current state of the underlying SSL socket. May be called at
505 // any time.
506 const HandshakeState& state() const { return network_handshake_state_; }
508 // Called on the network task runner.
509 // Read() and Write() mirror the net::Socket functions of the same name.
510 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
511 // task runner at a later point, unless the caller calls Detach().
512 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
513 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
515 // Called on the network task runner.
516 bool IsConnected() const;
517 bool HasPendingAsyncOperation() const;
518 bool HasUnhandledReceivedData() const;
519 bool WasEverUsed() const;
521 // Called on the network task runner.
522 // Causes the associated SSL/TLS session ID to be added to NSS's session
523 // cache, but only if the connection has not been False Started.
525 // This should only be called after the server's certificate has been
526 // verified, and may not be called within an NSS callback.
527 void CacheSessionIfNecessary();
529 private:
530 friend class base::RefCountedThreadSafe<Core>;
531 ~Core();
533 enum State {
534 STATE_NONE,
535 STATE_HANDSHAKE,
536 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
539 bool OnNSSTaskRunner() const;
540 bool OnNetworkTaskRunner() const;
542 ////////////////////////////////////////////////////////////////////////////
543 // Methods that are ONLY called on the NSS task runner:
544 ////////////////////////////////////////////////////////////////////////////
546 // Called by NSS during full handshakes to allow the application to
547 // verify the certificate. Instead of verifying the certificate in the midst
548 // of the handshake, SECSuccess is always returned and the peer's certificate
549 // is verified afterwards.
550 // This behaviour is an artifact of the original SSLClientSocketWin
551 // implementation, which could not verify the peer's certificate until after
552 // the handshake had completed, as well as bugs in NSS that prevent
553 // SSL_RestartHandshakeAfterCertReq from working.
554 static SECStatus OwnAuthCertHandler(void* arg,
555 PRFileDesc* socket,
556 PRBool checksig,
557 PRBool is_server);
559 // Callbacks called by NSS when the peer requests client certificate
560 // authentication.
561 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
562 // the arguments.
563 static SECStatus ClientAuthHandler(void* arg,
564 PRFileDesc* socket,
565 CERTDistNames* ca_names,
566 CERTCertificate** result_certificate,
567 SECKEYPrivateKey** result_private_key);
569 // Called by NSS to determine if we can False Start.
570 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
571 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
572 void* arg,
573 PRBool* can_false_start);
575 // Called by NSS each time a handshake completely finishes.
576 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
577 static void HandshakeCallback(PRFileDesc* socket, void* arg);
579 // Called once for each successful handshake. If the initial handshake false
580 // starts, it is called when it false starts and not when it completely
581 // finishes. is_initial is true if this is the initial handshake.
582 void HandshakeSucceeded(bool is_initial);
584 // Handles an NSS error generated while handshaking or performing IO.
585 // Returns a network error code mapped from the original NSS error.
586 int HandleNSSError(PRErrorCode error);
588 int DoHandshakeLoop(int last_io_result);
589 int DoReadLoop(int result);
590 int DoWriteLoop(int result);
592 int DoHandshake();
593 int DoGetDBCertComplete(int result);
595 int DoPayloadRead();
596 int DoPayloadWrite();
598 bool DoTransportIO();
599 int BufferRecv();
600 int BufferSend();
602 void OnRecvComplete(int result);
603 void OnSendComplete(int result);
605 void DoConnectCallback(int result);
606 void DoReadCallback(int result);
607 void DoWriteCallback(int result);
609 // Client channel ID handler.
610 static SECStatus ClientChannelIDHandler(
611 void* arg,
612 PRFileDesc* socket,
613 SECKEYPublicKey **out_public_key,
614 SECKEYPrivateKey **out_private_key);
616 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
617 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
618 // and an error code otherwise.
619 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
620 // set by a call to ChannelIDService->GetChannelID. The caller
621 // takes ownership of the |*cert| and |*key|.
622 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
624 // Updates the NSS and platform specific certificates.
625 void UpdateServerCert();
626 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
627 // received in the handshake via a TLS extension.
628 void UpdateSignedCertTimestamps();
629 // Update the OCSP response cache with the stapled response received in the
630 // handshake, and update nss_handshake_state_ with
631 // the SignedCertificateTimestampList received in the stapled OCSP response.
632 void UpdateStapledOCSPResponse();
633 // Updates the nss_handshake_state_ with the negotiated security parameters.
634 void UpdateConnectionStatus();
635 // Record histograms for channel id support during full handshakes - resumed
636 // handshakes are ignored.
637 void RecordChannelIDSupportOnNSSTaskRunner();
638 // UpdateNextProto gets any application-layer protocol that may have been
639 // negotiated by the TLS connection.
640 void UpdateNextProto();
641 // Record TLS extension used for protocol negotiation (NPN or ALPN).
642 void UpdateExtensionUsed();
644 // Returns true if renegotiations are allowed.
645 bool IsRenegotiationAllowed() const;
647 ////////////////////////////////////////////////////////////////////////////
648 // Methods that are ONLY called on the network task runner:
649 ////////////////////////////////////////////////////////////////////////////
650 int DoBufferRecv(IOBuffer* buffer, int len);
651 int DoBufferSend(IOBuffer* buffer, int len);
652 int DoGetChannelID(const std::string& host);
654 void OnGetChannelIDComplete(int result);
655 void OnHandshakeStateUpdated(const HandshakeState& state);
656 void OnNSSBufferUpdated(int amount_in_read_buffer);
657 void DidNSSRead(int result);
658 void DidNSSWrite(int result);
659 void RecordChannelIDSupportOnNetworkTaskRunner(
660 bool negotiated_channel_id,
661 bool channel_id_enabled,
662 bool supports_ecc) const;
664 ////////////////////////////////////////////////////////////////////////////
665 // Methods that are called on both the network task runner and the NSS
666 // task runner.
667 ////////////////////////////////////////////////////////////////////////////
668 void OnHandshakeIOComplete(int result);
669 void BufferRecvComplete(IOBuffer* buffer, int result);
670 void BufferSendComplete(int result);
672 // PostOrRunCallback is a helper function to ensure that |callback| is
673 // invoked on the network task runner, but only if Detach() has not yet
674 // been called.
675 void PostOrRunCallback(const tracked_objects::Location& location,
676 const base::Closure& callback);
678 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
679 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
680 void AddCertProvidedEvent(int cert_count);
682 // Sets the handshake state |channel_id_sent| flag and logs the
683 // SSL_CHANNEL_ID_PROVIDED event.
684 void SetChannelIDProvided();
686 ////////////////////////////////////////////////////////////////////////////
687 // Members that are ONLY accessed on the network task runner:
688 ////////////////////////////////////////////////////////////////////////////
690 // True if the owning SSLClientSocketNSS has called Detach(). No further
691 // callbacks will be invoked nor access to members owned by the network
692 // task runner.
693 bool detached_;
695 // The underlying transport to use for network IO.
696 ClientSocketHandle* transport_;
697 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
699 // The current handshake state. Mirrors |nss_handshake_state_|.
700 HandshakeState network_handshake_state_;
702 // The service for retrieving Channel ID keys. May be NULL.
703 ChannelIDService* channel_id_service_;
704 ChannelIDService::Request channel_id_request_;
706 // The information about NSS task runner.
707 int unhandled_buffer_size_;
708 bool nss_waiting_read_;
709 bool nss_waiting_write_;
710 bool nss_is_closed_;
712 // Set when Read() or Write() successfully reads or writes data to or from the
713 // network.
714 bool was_ever_used_;
716 ////////////////////////////////////////////////////////////////////////////
717 // Members that are ONLY accessed on the NSS task runner:
718 ////////////////////////////////////////////////////////////////////////////
719 HostPortPair host_and_port_;
720 SSLConfig ssl_config_;
722 // NSS SSL socket.
723 PRFileDesc* nss_fd_;
725 // Buffers for the network end of the SSL state machine
726 memio_Private* nss_bufs_;
728 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
729 // as much data as possible, without blocking.
730 // If DoPayloadRead() encounters an error after having read some data, stores
731 // the results to return on the *next* call to DoPayloadRead(). A value of
732 // kNoPendingReadResult indicates there is no pending result, otherwise 0
733 // indicates EOF and < 0 indicates an error.
734 int pending_read_result_;
735 // Contains the previously observed NSS error. Only valid when
736 // pending_read_result_ != kNoPendingReadResult.
737 PRErrorCode pending_read_nss_error_;
739 // The certificate chain, in DER form, that is expected to be received from
740 // the server.
741 std::vector<std::string> predicted_certs_;
743 State next_handshake_state_;
745 // True if channel ID extension was negotiated.
746 bool channel_id_xtn_negotiated_;
747 // True if the handshake state machine was interrupted for channel ID.
748 bool channel_id_needed_;
749 // True if the handshake state machine was interrupted for client auth.
750 bool client_auth_cert_needed_;
751 // True if NSS has False Started in the initial handshake, but the initial
752 // handshake has not yet completely finished..
753 bool false_started_;
754 // True if NSS has called HandshakeCallback.
755 bool handshake_callback_called_;
757 HandshakeState nss_handshake_state_;
759 bool transport_recv_busy_;
760 bool transport_recv_eof_;
761 bool transport_send_busy_;
763 // Used by Read function.
764 scoped_refptr<IOBuffer> user_read_buf_;
765 int user_read_buf_len_;
767 // Used by Write function.
768 scoped_refptr<IOBuffer> user_write_buf_;
769 int user_write_buf_len_;
771 CompletionCallback user_connect_callback_;
772 CompletionCallback user_read_callback_;
773 CompletionCallback user_write_callback_;
775 ////////////////////////////////////////////////////////////////////////////
776 // Members that are accessed on both the network task runner and the NSS
777 // task runner.
778 ////////////////////////////////////////////////////////////////////////////
779 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
780 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
782 // Dereferenced only on the network task runner, but bound to tasks destined
783 // for the network task runner from the NSS task runner.
784 base::WeakPtr<BoundNetLog> weak_net_log_;
786 // Written on the network task runner by the |channel_id_service_|,
787 // prior to invoking OnHandshakeIOComplete.
788 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
789 // on the NSS task runner.
790 scoped_ptr<crypto::ECPrivateKey> channel_id_key_;
792 DISALLOW_COPY_AND_ASSIGN(Core);
795 SSLClientSocketNSS::Core::Core(
796 base::SequencedTaskRunner* network_task_runner,
797 base::SequencedTaskRunner* nss_task_runner,
798 ClientSocketHandle* transport,
799 const HostPortPair& host_and_port,
800 const SSLConfig& ssl_config,
801 BoundNetLog* net_log,
802 ChannelIDService* channel_id_service)
803 : detached_(false),
804 transport_(transport),
805 weak_net_log_factory_(net_log),
806 channel_id_service_(channel_id_service),
807 unhandled_buffer_size_(0),
808 nss_waiting_read_(false),
809 nss_waiting_write_(false),
810 nss_is_closed_(false),
811 was_ever_used_(false),
812 host_and_port_(host_and_port),
813 ssl_config_(ssl_config),
814 nss_fd_(NULL),
815 nss_bufs_(NULL),
816 pending_read_result_(kNoPendingReadResult),
817 pending_read_nss_error_(0),
818 next_handshake_state_(STATE_NONE),
819 channel_id_xtn_negotiated_(false),
820 channel_id_needed_(false),
821 client_auth_cert_needed_(false),
822 false_started_(false),
823 handshake_callback_called_(false),
824 transport_recv_busy_(false),
825 transport_recv_eof_(false),
826 transport_send_busy_(false),
827 user_read_buf_len_(0),
828 user_write_buf_len_(0),
829 network_task_runner_(network_task_runner),
830 nss_task_runner_(nss_task_runner),
831 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
834 SSLClientSocketNSS::Core::~Core() {
835 // TODO(wtc): Send SSL close_notify alert.
836 if (nss_fd_ != NULL) {
837 PR_Close(nss_fd_);
838 nss_fd_ = NULL;
840 nss_bufs_ = NULL;
843 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
844 memio_Private* buffers) {
845 DCHECK(OnNetworkTaskRunner());
846 DCHECK(!nss_fd_);
847 DCHECK(!nss_bufs_);
849 nss_fd_ = socket;
850 nss_bufs_ = buffers;
852 SECStatus rv = SECSuccess;
854 if (!ssl_config_.next_protos.empty()) {
855 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
856 const bool adequate_encryption =
857 PK11_TokenExists(CKM_AES_GCM) ||
858 PK11_TokenExists(CKM_NSS_CHACHA20_POLY1305);
859 const bool adequate_key_agreement = PK11_TokenExists(CKM_DH_PKCS_DERIVE) ||
860 PK11_TokenExists(CKM_ECDH1_DERIVE);
861 std::vector<uint8_t> wire_protos =
862 SerializeNextProtos(ssl_config_.next_protos,
863 adequate_encryption && adequate_key_agreement &&
864 IsTLSVersionAdequateForHTTP2(ssl_config_));
865 rv = SSL_SetNextProtoNego(
866 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
867 wire_protos.size());
868 if (rv != SECSuccess)
869 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
870 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
871 if (rv != SECSuccess)
872 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
873 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
874 if (rv != SECSuccess)
875 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
878 rv = SSL_AuthCertificateHook(
879 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this);
880 if (rv != SECSuccess) {
881 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", "");
882 return false;
885 rv = SSL_GetClientAuthDataHook(
886 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this);
887 if (rv != SECSuccess) {
888 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", "");
889 return false;
892 if (IsChannelIDEnabled(ssl_config_, channel_id_service_)) {
893 rv = SSL_SetClientChannelIDCallback(
894 nss_fd_, SSLClientSocketNSS::Core::ClientChannelIDHandler, this);
895 if (rv != SECSuccess) {
896 LogFailedNSSFunction(
897 *weak_net_log_, "SSL_SetClientChannelIDCallback", "");
901 rv = SSL_SetCanFalseStartCallback(
902 nss_fd_, SSLClientSocketNSS::Core::CanFalseStartCallback, this);
903 if (rv != SECSuccess) {
904 LogFailedNSSFunction(*weak_net_log_, "SSL_SetCanFalseStartCallback", "");
905 return false;
908 rv = SSL_HandshakeCallback(
909 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this);
910 if (rv != SECSuccess) {
911 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", "");
912 return false;
915 return true;
918 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) {
919 if (!OnNSSTaskRunner()) {
920 DCHECK(!detached_);
921 bool posted = nss_task_runner_->PostTask(
922 FROM_HERE,
923 base::Bind(IgnoreResult(&Core::Connect), this, callback));
924 return posted ? ERR_IO_PENDING : ERR_ABORTED;
927 DCHECK(OnNSSTaskRunner());
928 DCHECK_EQ(STATE_NONE, next_handshake_state_);
929 DCHECK(user_read_callback_.is_null());
930 DCHECK(user_write_callback_.is_null());
931 DCHECK(user_connect_callback_.is_null());
932 DCHECK(!user_read_buf_.get());
933 DCHECK(!user_write_buf_.get());
935 next_handshake_state_ = STATE_HANDSHAKE;
936 int rv = DoHandshakeLoop(OK);
937 if (rv == ERR_IO_PENDING) {
938 user_connect_callback_ = callback;
939 } else if (rv > OK) {
940 rv = OK;
942 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
943 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
944 return ERR_IO_PENDING;
947 return rv;
950 void SSLClientSocketNSS::Core::Detach() {
951 DCHECK(OnNetworkTaskRunner());
953 detached_ = true;
954 transport_ = NULL;
955 weak_net_log_factory_.InvalidateWeakPtrs();
957 network_handshake_state_.Reset();
959 channel_id_request_.Cancel();
962 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len,
963 const CompletionCallback& callback) {
964 if (!OnNSSTaskRunner()) {
965 DCHECK(OnNetworkTaskRunner());
966 DCHECK(!detached_);
967 DCHECK(transport_);
968 DCHECK(!nss_waiting_read_);
970 nss_waiting_read_ = true;
971 bool posted = nss_task_runner_->PostTask(
972 FROM_HERE,
973 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf),
974 buf_len, callback));
975 if (!posted) {
976 nss_is_closed_ = true;
977 nss_waiting_read_ = false;
979 return posted ? ERR_IO_PENDING : ERR_ABORTED;
982 DCHECK(OnNSSTaskRunner());
983 DCHECK(false_started_ || handshake_callback_called_);
984 DCHECK_EQ(STATE_NONE, next_handshake_state_);
985 DCHECK(user_read_callback_.is_null());
986 DCHECK(user_connect_callback_.is_null());
987 DCHECK(!user_read_buf_.get());
988 DCHECK(nss_bufs_);
990 user_read_buf_ = buf;
991 user_read_buf_len_ = buf_len;
993 int rv = DoReadLoop(OK);
994 if (rv == ERR_IO_PENDING) {
995 if (OnNetworkTaskRunner())
996 nss_waiting_read_ = true;
997 user_read_callback_ = callback;
998 } else {
999 user_read_buf_ = NULL;
1000 user_read_buf_len_ = 0;
1002 if (!OnNetworkTaskRunner()) {
1003 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1004 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1005 return ERR_IO_PENDING;
1006 } else {
1007 DCHECK(!nss_waiting_read_);
1008 if (rv <= 0) {
1009 nss_is_closed_ = true;
1010 } else {
1011 was_ever_used_ = true;
1016 return rv;
1019 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1020 const CompletionCallback& callback) {
1021 if (!OnNSSTaskRunner()) {
1022 DCHECK(OnNetworkTaskRunner());
1023 DCHECK(!detached_);
1024 DCHECK(transport_);
1025 DCHECK(!nss_waiting_write_);
1027 nss_waiting_write_ = true;
1028 bool posted = nss_task_runner_->PostTask(
1029 FROM_HERE,
1030 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf),
1031 buf_len, callback));
1032 if (!posted) {
1033 nss_is_closed_ = true;
1034 nss_waiting_write_ = false;
1036 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1039 DCHECK(OnNSSTaskRunner());
1040 DCHECK(false_started_ || handshake_callback_called_);
1041 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1042 DCHECK(user_write_callback_.is_null());
1043 DCHECK(user_connect_callback_.is_null());
1044 DCHECK(!user_write_buf_.get());
1045 DCHECK(nss_bufs_);
1047 user_write_buf_ = buf;
1048 user_write_buf_len_ = buf_len;
1050 int rv = DoWriteLoop(OK);
1051 if (rv == ERR_IO_PENDING) {
1052 if (OnNetworkTaskRunner())
1053 nss_waiting_write_ = true;
1054 user_write_callback_ = callback;
1055 } else {
1056 user_write_buf_ = NULL;
1057 user_write_buf_len_ = 0;
1059 if (!OnNetworkTaskRunner()) {
1060 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1061 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1062 return ERR_IO_PENDING;
1063 } else {
1064 DCHECK(!nss_waiting_write_);
1065 if (rv < 0) {
1066 nss_is_closed_ = true;
1067 } else if (rv > 0) {
1068 was_ever_used_ = true;
1073 return rv;
1076 bool SSLClientSocketNSS::Core::IsConnected() const {
1077 DCHECK(OnNetworkTaskRunner());
1078 return !nss_is_closed_;
1081 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1082 DCHECK(OnNetworkTaskRunner());
1083 return nss_waiting_read_ || nss_waiting_write_;
1086 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1087 DCHECK(OnNetworkTaskRunner());
1088 return unhandled_buffer_size_ != 0;
1091 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1092 DCHECK(OnNetworkTaskRunner());
1093 return was_ever_used_;
1096 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1097 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1098 // nss_fd_. However, it happens on the network task runner in order to match
1099 // the buggy behavior of ExportKeyingMaterial.
1101 // Once http://crbug.com/330360 is fixed, this should be moved to an
1102 // implementation that exclusively does this work on the NSS TaskRunner. This
1103 // is "safe" because it is only called during the certificate verification
1104 // state machine of the main socket, which is safe because no underlying
1105 // transport IO will be occuring in that state, and NSS will not be blocking
1106 // on any PKCS#11 related locks that might block the Network TaskRunner.
1107 DCHECK(OnNetworkTaskRunner());
1109 // Only cache the session if the connection was not False Started, because
1110 // sessions should only be cached *after* the peer's Finished message is
1111 // processed.
1112 // In the case of False Start, the session will be cached once the
1113 // HandshakeCallback is called, which signals the receipt and processing of
1114 // the Finished message, and which will happen during a call to
1115 // PR_Read/PR_Write.
1116 if (!false_started_)
1117 SSL_CacheSession(nss_fd_);
1120 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1121 return nss_task_runner_->RunsTasksOnCurrentThread();
1124 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1125 return network_task_runner_->RunsTasksOnCurrentThread();
1128 // static
1129 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1130 void* arg,
1131 PRFileDesc* socket,
1132 PRBool checksig,
1133 PRBool is_server) {
1134 Core* core = reinterpret_cast<Core*>(arg);
1135 if (core->handshake_callback_called_) {
1136 // Disallow the server certificate to change in a renegotiation.
1137 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1138 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1139 if (new_cert->derCert.len != old_cert->derCert.len ||
1140 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1141 new_cert->derCert.len) != 0) {
1142 // NSS doesn't have an error code that indicates the server certificate
1143 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1144 // for this purpose.
1145 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1146 return SECFailure;
1150 // Tell NSS to not verify the certificate.
1151 return SECSuccess;
1154 #if defined(OS_IOS)
1156 // static
1157 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1158 void* arg,
1159 PRFileDesc* socket,
1160 CERTDistNames* ca_names,
1161 CERTCertificate** result_certificate,
1162 SECKEYPrivateKey** result_private_key) {
1163 Core* core = reinterpret_cast<Core*>(arg);
1164 DCHECK(core->OnNSSTaskRunner());
1166 core->PostOrRunCallback(
1167 FROM_HERE,
1168 base::Bind(&AddLogEvent, core->weak_net_log_,
1169 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1171 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1172 LOG(WARNING) << "Client auth is not supported";
1174 // Never send a certificate.
1175 core->AddCertProvidedEvent(0);
1176 return SECFailure;
1179 #else // !OS_IOS
1181 // static
1182 // Based on Mozilla's NSS_GetClientAuthData.
1183 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1184 void* arg,
1185 PRFileDesc* socket,
1186 CERTDistNames* ca_names,
1187 CERTCertificate** result_certificate,
1188 SECKEYPrivateKey** result_private_key) {
1189 Core* core = reinterpret_cast<Core*>(arg);
1190 DCHECK(core->OnNSSTaskRunner());
1192 core->PostOrRunCallback(
1193 FROM_HERE,
1194 base::Bind(&AddLogEvent, core->weak_net_log_,
1195 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1197 // Regular client certificate requested.
1198 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1199 void* wincx = SSL_RevealPinArg(socket);
1201 if (core->ssl_config_.send_client_cert) {
1202 // Second pass: a client certificate should have been selected.
1203 if (core->ssl_config_.client_cert.get()) {
1204 CERTCertificate* cert =
1205 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1206 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1207 if (privkey) {
1208 // TODO(jsorianopastor): We should wait for server certificate
1209 // verification before sending our credentials. See
1210 // http://crbug.com/13934.
1211 *result_certificate = cert;
1212 *result_private_key = privkey;
1213 // A cert_count of -1 means the number of certificates is unknown.
1214 // NSS will construct the certificate chain.
1215 core->AddCertProvidedEvent(-1);
1217 return SECSuccess;
1219 LOG(WARNING) << "Client cert found without private key";
1221 // Send no client certificate.
1222 core->AddCertProvidedEvent(0);
1223 return SECFailure;
1226 // First pass: client certificate is needed.
1227 core->nss_handshake_state_.cert_authorities.clear();
1229 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1230 // the server and save them in |cert_authorities|.
1231 for (int i = 0; i < ca_names->nnames; i++) {
1232 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1233 reinterpret_cast<const char*>(ca_names->names[i].data),
1234 static_cast<size_t>(ca_names->names[i].len)));
1237 // Update the network task runner's view of the handshake state now that
1238 // server certificate request has been recorded.
1239 core->PostOrRunCallback(
1240 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1241 core->nss_handshake_state_));
1243 // Tell NSS to suspend the client authentication. We will then abort the
1244 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1245 return SECWouldBlock;
1247 #endif // OS_IOS
1249 // static
1250 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1251 PRFileDesc* socket,
1252 void* arg,
1253 PRBool* can_false_start) {
1254 // If the server doesn't support NPN or ALPN, then we don't do False
1255 // Start with it.
1256 PRBool negotiated_extension;
1257 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1258 ssl_app_layer_protocol_xtn,
1259 &negotiated_extension);
1260 if (rv != SECSuccess || !negotiated_extension) {
1261 rv = SSL_HandshakeNegotiatedExtension(socket,
1262 ssl_next_proto_nego_xtn,
1263 &negotiated_extension);
1265 if (rv != SECSuccess || !negotiated_extension) {
1266 *can_false_start = PR_FALSE;
1267 return SECSuccess;
1270 SSLChannelInfo channel_info;
1271 SECStatus ok =
1272 SSL_GetChannelInfo(socket, &channel_info, sizeof(channel_info));
1273 if (ok != SECSuccess || channel_info.length != sizeof(channel_info) ||
1274 channel_info.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_2 ||
1275 !IsFalseStartableTLSCipherSuite(channel_info.cipherSuite)) {
1276 *can_false_start = PR_FALSE;
1277 return SECSuccess;
1280 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1283 // static
1284 void SSLClientSocketNSS::Core::HandshakeCallback(
1285 PRFileDesc* socket,
1286 void* arg) {
1287 Core* core = reinterpret_cast<Core*>(arg);
1288 DCHECK(core->OnNSSTaskRunner());
1290 bool is_initial = !core->handshake_callback_called_;
1291 core->handshake_callback_called_ = true;
1292 if (core->false_started_) {
1293 core->false_started_ = false;
1294 // If the connection was False Started, then at the time of this callback,
1295 // the peer's certificate will have been verified or the caller will have
1296 // accepted the error.
1297 // This is guaranteed when using False Start because this callback will
1298 // not be invoked until processing the peer's Finished message, which
1299 // will only happen in a PR_Read/PR_Write call, which can only happen
1300 // after the peer's certificate is verified.
1301 SSL_CacheSessionUnlocked(socket);
1303 // Additionally, when False Starting, DoHandshake() will have already
1304 // called HandshakeSucceeded(), so return now.
1305 return;
1307 core->HandshakeSucceeded(is_initial);
1310 void SSLClientSocketNSS::Core::HandshakeSucceeded(bool is_initial) {
1311 DCHECK(OnNSSTaskRunner());
1313 PRBool last_handshake_resumed;
1314 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1315 if (rv == SECSuccess && last_handshake_resumed) {
1316 nss_handshake_state_.resumed_handshake = true;
1317 } else {
1318 nss_handshake_state_.resumed_handshake = false;
1321 RecordChannelIDSupportOnNSSTaskRunner();
1322 UpdateServerCert();
1323 UpdateSignedCertTimestamps();
1324 UpdateStapledOCSPResponse();
1325 UpdateConnectionStatus();
1326 UpdateNextProto();
1327 UpdateExtensionUsed();
1329 if (is_initial && IsRenegotiationAllowed()) {
1330 // For compatibility, do not enforce RFC 5746 support. Per section 4.1,
1331 // enforcement falls largely on the server.
1333 // This is done in a callback rather than after SSL_ForceHandshake returns
1334 // because SSL_ForceHandshake will otherwise greedly consume renegotiations
1335 // before returning if Finished and HelloRequest are in the same
1336 // record.
1338 // Note that SSL_OptionSet should only be called for an initial
1339 // handshake. See https://crbug.com/125299.
1340 SECStatus rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
1341 SSL_RENEGOTIATE_TRANSITIONAL);
1342 DCHECK_EQ(SECSuccess, rv);
1345 // Update the network task runners view of the handshake state whenever
1346 // a handshake has completed.
1347 PostOrRunCallback(
1348 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1349 nss_handshake_state_));
1352 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1353 DCHECK(OnNSSTaskRunner());
1355 return MapNSSClientError(nss_error);
1358 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1359 DCHECK(OnNSSTaskRunner());
1361 int rv = last_io_result;
1362 do {
1363 // Default to STATE_NONE for next state.
1364 State state = next_handshake_state_;
1365 GotoState(STATE_NONE);
1367 switch (state) {
1368 case STATE_HANDSHAKE:
1369 rv = DoHandshake();
1370 break;
1371 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1372 rv = DoGetDBCertComplete(rv);
1373 break;
1374 case STATE_NONE:
1375 default:
1376 rv = ERR_UNEXPECTED;
1377 LOG(DFATAL) << "unexpected state " << state;
1378 break;
1381 // Do the actual network I/O
1382 bool network_moved = DoTransportIO();
1383 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1384 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1385 // special case we keep looping even if rv is ERR_IO_PENDING because
1386 // the transport IO may allow DoHandshake to make progress.
1387 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1388 rv = OK; // This causes us to stay in the loop.
1390 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1391 return rv;
1394 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1395 DCHECK(OnNSSTaskRunner());
1396 DCHECK(false_started_ || handshake_callback_called_);
1397 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1399 if (result < 0)
1400 return result;
1402 if (!nss_bufs_) {
1403 LOG(DFATAL) << "!nss_bufs_";
1404 int rv = ERR_UNEXPECTED;
1405 PostOrRunCallback(
1406 FROM_HERE,
1407 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1408 NetLog::TYPE_SSL_READ_ERROR,
1409 CreateNetLogSSLErrorCallback(rv, 0)));
1410 return rv;
1413 bool network_moved;
1414 int rv;
1415 do {
1416 rv = DoPayloadRead();
1417 network_moved = DoTransportIO();
1418 } while (rv == ERR_IO_PENDING && network_moved);
1420 return rv;
1423 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1424 DCHECK(OnNSSTaskRunner());
1425 DCHECK(false_started_ || handshake_callback_called_);
1426 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1428 if (result < 0)
1429 return result;
1431 if (!nss_bufs_) {
1432 LOG(DFATAL) << "!nss_bufs_";
1433 int rv = ERR_UNEXPECTED;
1434 PostOrRunCallback(
1435 FROM_HERE,
1436 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1437 NetLog::TYPE_SSL_READ_ERROR,
1438 CreateNetLogSSLErrorCallback(rv, 0)));
1439 return rv;
1442 bool network_moved;
1443 int rv;
1444 do {
1445 rv = DoPayloadWrite();
1446 network_moved = DoTransportIO();
1447 } while (rv == ERR_IO_PENDING && network_moved);
1449 LeaveFunction(rv);
1450 return rv;
1453 int SSLClientSocketNSS::Core::DoHandshake() {
1454 DCHECK(OnNSSTaskRunner());
1456 int net_error = OK;
1457 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1459 // Note: this function may be called multiple times during the handshake, so
1460 // even though channel id and client auth are separate else cases, they can
1461 // both be used during a single SSL handshake.
1462 if (channel_id_needed_) {
1463 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1464 net_error = ERR_IO_PENDING;
1465 } else if (client_auth_cert_needed_) {
1466 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1467 PostOrRunCallback(
1468 FROM_HERE,
1469 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1470 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1471 CreateNetLogSSLErrorCallback(net_error, 0)));
1472 } else if (rv == SECSuccess) {
1473 if (!handshake_callback_called_) {
1474 false_started_ = true;
1475 HandshakeSucceeded(true);
1477 } else {
1478 PRErrorCode prerr = PR_GetError();
1479 net_error = HandleNSSError(prerr);
1481 // If not done, stay in this state
1482 if (net_error == ERR_IO_PENDING) {
1483 GotoState(STATE_HANDSHAKE);
1484 } else {
1485 PostOrRunCallback(
1486 FROM_HERE,
1487 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1488 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1489 CreateNetLogSSLErrorCallback(net_error, prerr)));
1493 return net_error;
1496 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1497 SECStatus rv;
1498 PostOrRunCallback(
1499 FROM_HERE,
1500 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1501 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1503 channel_id_needed_ = false;
1505 if (result != OK)
1506 return result;
1508 SECKEYPublicKey* public_key;
1509 SECKEYPrivateKey* private_key;
1510 int error = ImportChannelIDKeys(&public_key, &private_key);
1511 if (error != OK)
1512 return error;
1514 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1515 if (rv != SECSuccess)
1516 return MapNSSError(PORT_GetError());
1518 SetChannelIDProvided();
1519 GotoState(STATE_HANDSHAKE);
1520 return OK;
1523 int SSLClientSocketNSS::Core::DoPayloadRead() {
1524 DCHECK(OnNSSTaskRunner());
1525 DCHECK(user_read_buf_.get());
1526 DCHECK_GT(user_read_buf_len_, 0);
1528 int rv;
1529 // If a previous greedy read resulted in an error that was not consumed (eg:
1530 // due to the caller having read some data successfully), then return that
1531 // pending error now.
1532 if (pending_read_result_ != kNoPendingReadResult) {
1533 rv = pending_read_result_;
1534 PRErrorCode prerr = pending_read_nss_error_;
1535 pending_read_result_ = kNoPendingReadResult;
1536 pending_read_nss_error_ = 0;
1538 if (rv == 0) {
1539 PostOrRunCallback(
1540 FROM_HERE,
1541 base::Bind(&LogByteTransferEvent, weak_net_log_,
1542 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1543 scoped_refptr<IOBuffer>(user_read_buf_)));
1544 } else {
1545 PostOrRunCallback(
1546 FROM_HERE,
1547 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1548 NetLog::TYPE_SSL_READ_ERROR,
1549 CreateNetLogSSLErrorCallback(rv, prerr)));
1551 return rv;
1554 // Perform a greedy read, attempting to read as much as the caller has
1555 // requested. In the current NSS implementation, PR_Read will return
1556 // exactly one SSL application data record's worth of data per invocation.
1557 // The record size is dictated by the server, and may be noticeably smaller
1558 // than the caller's buffer. This may be as little as a single byte, if the
1559 // server is performing 1/n-1 record splitting.
1561 // However, this greedy read may result in renegotiations/re-handshakes
1562 // happening or may lead to some data being read, followed by an EOF (such as
1563 // a TLS close-notify). If at least some data was read, then that result
1564 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1565 // data was read, it's safe to return the error or EOF immediately.
1566 int total_bytes_read = 0;
1567 do {
1568 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1569 user_read_buf_len_ - total_bytes_read);
1570 if (rv > 0)
1571 total_bytes_read += rv;
1572 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1573 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1574 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1575 amount_in_read_buffer));
1577 if (total_bytes_read == user_read_buf_len_) {
1578 // The caller's entire request was satisfied without error. No further
1579 // processing needed.
1580 rv = total_bytes_read;
1581 } else {
1582 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1583 // immediately, while the NSPR/NSS errors are still available in
1584 // thread-local storage. However, the handled/remapped error code should
1585 // only be returned if no application data was already read; if it was, the
1586 // error code should be deferred until the next call of DoPayloadRead.
1588 // If no data was read, |*next_result| will point to the return value of
1589 // this function. If at least some data was read, |*next_result| will point
1590 // to |pending_read_error_|, to be returned in a future call to
1591 // DoPayloadRead() (e.g.: after the current data is handled).
1592 int* next_result = &rv;
1593 if (total_bytes_read > 0) {
1594 pending_read_result_ = rv;
1595 rv = total_bytes_read;
1596 next_result = &pending_read_result_;
1599 if (client_auth_cert_needed_) {
1600 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1601 pending_read_nss_error_ = 0;
1602 } else if (*next_result < 0) {
1603 // If *next_result == 0, then that indicates EOF, and no special error
1604 // handling is needed.
1605 pending_read_nss_error_ = PR_GetError();
1606 *next_result = HandleNSSError(pending_read_nss_error_);
1607 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1608 // If at least some data was read from PR_Read(), do not treat
1609 // insufficient data as an error to return in the next call to
1610 // DoPayloadRead() - instead, let the call fall through to check
1611 // PR_Read() again. This is because DoTransportIO() may complete
1612 // in between the next call to DoPayloadRead(), and thus it is
1613 // important to check PR_Read() on subsequent invocations to see
1614 // if a complete record may now be read.
1615 pending_read_nss_error_ = 0;
1616 pending_read_result_ = kNoPendingReadResult;
1621 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
1623 if (rv >= 0) {
1624 PostOrRunCallback(
1625 FROM_HERE,
1626 base::Bind(&LogByteTransferEvent, weak_net_log_,
1627 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1628 scoped_refptr<IOBuffer>(user_read_buf_)));
1629 } else if (rv != ERR_IO_PENDING) {
1630 PostOrRunCallback(
1631 FROM_HERE,
1632 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1633 NetLog::TYPE_SSL_READ_ERROR,
1634 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
1635 pending_read_nss_error_ = 0;
1637 return rv;
1640 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1641 DCHECK(OnNSSTaskRunner());
1643 DCHECK(user_write_buf_.get());
1645 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1646 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
1647 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1648 // PR_Write could potentially consume the unhandled data in the memio read
1649 // buffer if a renegotiation is in progress. If the buffer is consumed,
1650 // notify the latest buffer size to NetworkRunner.
1651 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
1652 PostOrRunCallback(
1653 FROM_HERE,
1654 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
1656 if (rv >= 0) {
1657 PostOrRunCallback(
1658 FROM_HERE,
1659 base::Bind(&LogByteTransferEvent, weak_net_log_,
1660 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1661 scoped_refptr<IOBuffer>(user_write_buf_)));
1662 return rv;
1664 PRErrorCode prerr = PR_GetError();
1665 if (prerr == PR_WOULD_BLOCK_ERROR)
1666 return ERR_IO_PENDING;
1668 rv = HandleNSSError(prerr);
1669 PostOrRunCallback(
1670 FROM_HERE,
1671 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1672 NetLog::TYPE_SSL_WRITE_ERROR,
1673 CreateNetLogSSLErrorCallback(rv, prerr)));
1674 return rv;
1677 // Do as much network I/O as possible between the buffer and the
1678 // transport socket. Return true if some I/O performed, false
1679 // otherwise (error or ERR_IO_PENDING).
1680 bool SSLClientSocketNSS::Core::DoTransportIO() {
1681 DCHECK(OnNSSTaskRunner());
1683 bool network_moved = false;
1684 if (nss_bufs_ != NULL) {
1685 int rv;
1686 // Read and write as much data as we can. The loop is neccessary
1687 // because Write() may return synchronously.
1688 do {
1689 rv = BufferSend();
1690 if (rv != ERR_IO_PENDING && rv != 0)
1691 network_moved = true;
1692 } while (rv > 0);
1693 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
1694 network_moved = true;
1696 return network_moved;
1699 int SSLClientSocketNSS::Core::BufferRecv() {
1700 DCHECK(OnNSSTaskRunner());
1702 if (transport_recv_busy_)
1703 return ERR_IO_PENDING;
1705 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
1706 // determine how much data NSS wants to read. If NSS was not blocked,
1707 // this will return 0.
1708 int requested = memio_GetReadRequest(nss_bufs_);
1709 if (requested == 0) {
1710 // This is not a perfect match of error codes, as no operation is
1711 // actually pending. However, returning 0 would be interpreted as a
1712 // possible sign of EOF, which is also an inappropriate match.
1713 return ERR_IO_PENDING;
1716 char* buf;
1717 int nb = memio_GetReadParams(nss_bufs_, &buf);
1718 int rv;
1719 if (!nb) {
1720 // buffer too full to read into, so no I/O possible at moment
1721 rv = ERR_IO_PENDING;
1722 } else {
1723 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
1724 if (OnNetworkTaskRunner()) {
1725 rv = DoBufferRecv(read_buffer.get(), nb);
1726 } else {
1727 bool posted = network_task_runner_->PostTask(
1728 FROM_HERE,
1729 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer,
1730 nb));
1731 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1734 if (rv == ERR_IO_PENDING) {
1735 transport_recv_busy_ = true;
1736 } else {
1737 if (rv > 0) {
1738 memcpy(buf, read_buffer->data(), rv);
1739 } else if (rv == 0) {
1740 transport_recv_eof_ = true;
1742 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
1745 return rv;
1748 // Return 0 if nss_bufs_ was empty,
1749 // > 0 for bytes transferred immediately,
1750 // < 0 for error (or the non-error ERR_IO_PENDING).
1751 int SSLClientSocketNSS::Core::BufferSend() {
1752 DCHECK(OnNSSTaskRunner());
1754 if (transport_send_busy_)
1755 return ERR_IO_PENDING;
1757 const char* buf1;
1758 const char* buf2;
1759 unsigned int len1, len2;
1760 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
1761 // It is important this return synchronously to prevent spinning infinitely
1762 // in the off-thread NSS case. The error code itself is ignored, so just
1763 // return ERR_ABORTED. See https://crbug.com/381160.
1764 return ERR_ABORTED;
1766 const size_t len = len1 + len2;
1768 int rv = 0;
1769 if (len) {
1770 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
1771 memcpy(send_buffer->data(), buf1, len1);
1772 memcpy(send_buffer->data() + len1, buf2, len2);
1774 if (OnNetworkTaskRunner()) {
1775 rv = DoBufferSend(send_buffer.get(), len);
1776 } else {
1777 bool posted = network_task_runner_->PostTask(
1778 FROM_HERE,
1779 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer,
1780 len));
1781 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1784 if (rv == ERR_IO_PENDING) {
1785 transport_send_busy_ = true;
1786 } else {
1787 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
1791 return rv;
1794 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
1795 DCHECK(OnNSSTaskRunner());
1797 if (next_handshake_state_ == STATE_HANDSHAKE) {
1798 OnHandshakeIOComplete(result);
1799 return;
1802 // Network layer received some data, check if client requested to read
1803 // decrypted data.
1804 if (!user_read_buf_.get())
1805 return;
1807 int rv = DoReadLoop(result);
1808 if (rv != ERR_IO_PENDING)
1809 DoReadCallback(rv);
1812 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
1813 DCHECK(OnNSSTaskRunner());
1815 if (next_handshake_state_ == STATE_HANDSHAKE) {
1816 OnHandshakeIOComplete(result);
1817 return;
1820 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1821 // handshake is in progress.
1822 int rv_read = ERR_IO_PENDING;
1823 int rv_write = ERR_IO_PENDING;
1824 bool network_moved;
1825 do {
1826 if (user_read_buf_.get())
1827 rv_read = DoPayloadRead();
1828 if (user_write_buf_.get())
1829 rv_write = DoPayloadWrite();
1830 network_moved = DoTransportIO();
1831 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1832 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1834 // If the parent SSLClientSocketNSS is deleted during the processing of the
1835 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
1836 // will be detached (and possibly deleted). Guard against deletion by taking
1837 // an extra reference, then check if the Core was detached before invoking the
1838 // next callback.
1839 scoped_refptr<Core> guard(this);
1840 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1841 DoReadCallback(rv_read);
1843 if (OnNetworkTaskRunner() && detached_)
1844 return;
1846 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1847 DoWriteCallback(rv_write);
1850 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
1851 // handshake. This requires network IO, which in turn calls
1852 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
1853 // winds its way through the state machine and ends up being passed to the
1854 // callback. For Read() and Write(), that's what we want. But for Connect(),
1855 // the caller expects OK (i.e. 0) for success.
1856 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
1857 DCHECK(OnNSSTaskRunner());
1858 DCHECK_NE(rv, ERR_IO_PENDING);
1859 DCHECK(!user_connect_callback_.is_null());
1861 base::Closure c = base::Bind(
1862 base::ResetAndReturn(&user_connect_callback_),
1863 rv > OK ? OK : rv);
1864 PostOrRunCallback(FROM_HERE, c);
1867 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
1868 DCHECK(OnNSSTaskRunner());
1869 DCHECK_NE(ERR_IO_PENDING, rv);
1870 DCHECK(!user_read_callback_.is_null());
1872 user_read_buf_ = NULL;
1873 user_read_buf_len_ = 0;
1874 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1875 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1876 // the network task runner.
1877 PostOrRunCallback(
1878 FROM_HERE,
1879 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1880 PostOrRunCallback(
1881 FROM_HERE,
1882 base::Bind(&Core::DidNSSRead, this, rv));
1883 PostOrRunCallback(
1884 FROM_HERE,
1885 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
1888 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
1889 DCHECK(OnNSSTaskRunner());
1890 DCHECK_NE(ERR_IO_PENDING, rv);
1891 DCHECK(!user_write_callback_.is_null());
1893 // Since Run may result in Write being called, clear |user_write_callback_|
1894 // up front.
1895 user_write_buf_ = NULL;
1896 user_write_buf_len_ = 0;
1897 // Update buffer status because DoWriteLoop called DoTransportIO which may
1898 // perform read operations.
1899 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1900 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1901 // the network task runner.
1902 PostOrRunCallback(
1903 FROM_HERE,
1904 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1905 PostOrRunCallback(
1906 FROM_HERE,
1907 base::Bind(&Core::DidNSSWrite, this, rv));
1908 PostOrRunCallback(
1909 FROM_HERE,
1910 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
1913 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
1914 void* arg,
1915 PRFileDesc* socket,
1916 SECKEYPublicKey **out_public_key,
1917 SECKEYPrivateKey **out_private_key) {
1918 Core* core = reinterpret_cast<Core*>(arg);
1919 DCHECK(core->OnNSSTaskRunner());
1921 core->PostOrRunCallback(
1922 FROM_HERE,
1923 base::Bind(&AddLogEvent, core->weak_net_log_,
1924 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
1926 // We have negotiated the TLS channel ID extension.
1927 core->channel_id_xtn_negotiated_ = true;
1928 std::string host = core->host_and_port_.host();
1929 int error = ERR_UNEXPECTED;
1930 if (core->OnNetworkTaskRunner()) {
1931 error = core->DoGetChannelID(host);
1932 } else {
1933 bool posted = core->network_task_runner_->PostTask(
1934 FROM_HERE,
1935 base::Bind(
1936 IgnoreResult(&Core::DoGetChannelID),
1937 core, host));
1938 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
1941 if (error == ERR_IO_PENDING) {
1942 // Asynchronous case.
1943 core->channel_id_needed_ = true;
1944 return SECWouldBlock;
1947 core->PostOrRunCallback(
1948 FROM_HERE,
1949 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
1950 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
1951 SECStatus rv = SECSuccess;
1952 if (error == OK) {
1953 // Synchronous success.
1954 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
1955 if (result == OK)
1956 core->SetChannelIDProvided();
1957 else
1958 rv = SECFailure;
1959 } else {
1960 rv = SECFailure;
1963 return rv;
1966 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
1967 SECKEYPrivateKey** key) {
1968 if (!channel_id_key_)
1969 return SECFailure;
1971 *public_key = SECKEY_CopyPublicKey(channel_id_key_->public_key());
1972 *key = SECKEY_CopyPrivateKey(channel_id_key_->key());
1974 return OK;
1977 void SSLClientSocketNSS::Core::UpdateServerCert() {
1978 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
1979 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
1980 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
1981 if (nss_handshake_state_.server_cert.get()) {
1982 // Since this will be called asynchronously on another thread, it needs to
1983 // own a reference to the certificate.
1984 NetLog::ParametersCallback net_log_callback =
1985 base::Bind(&NetLogX509CertificateCallback,
1986 nss_handshake_state_.server_cert);
1987 PostOrRunCallback(
1988 FROM_HERE,
1989 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1990 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1991 net_log_callback));
1995 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
1996 const SECItem* signed_cert_timestamps =
1997 SSL_PeerSignedCertTimestamps(nss_fd_);
1999 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
2000 return;
2002 nss_handshake_state_.sct_list_from_tls_extension = std::string(
2003 reinterpret_cast<char*>(signed_cert_timestamps->data),
2004 signed_cert_timestamps->len);
2007 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2008 PRBool ocsp_requested = PR_FALSE;
2009 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2010 const SECItemArray* ocsp_responses =
2011 SSL_PeerStapledOCSPResponses(nss_fd_);
2012 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2013 if (ocsp_requested)
2014 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2015 if (!ocsp_responses_present)
2016 return;
2018 nss_handshake_state_.stapled_ocsp_response = std::string(
2019 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2020 ocsp_responses->items[0].len);
2023 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2024 // Note: This function may be called multiple times for a single connection
2025 // if renegotiations occur.
2026 nss_handshake_state_.ssl_connection_status = 0;
2028 SSLChannelInfo channel_info;
2029 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2030 &channel_info, sizeof(channel_info));
2031 if (ok == SECSuccess &&
2032 channel_info.length == sizeof(channel_info) &&
2033 channel_info.cipherSuite) {
2034 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2036 nss_handshake_state_.ssl_connection_status |=
2037 (static_cast<int>(channel_info.compressionMethod) &
2038 SSL_CONNECTION_COMPRESSION_MASK) <<
2039 SSL_CONNECTION_COMPRESSION_SHIFT;
2041 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2042 if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2043 version = SSL_CONNECTION_VERSION_TLS1;
2044 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2045 version = SSL_CONNECTION_VERSION_TLS1_1;
2046 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2047 version = SSL_CONNECTION_VERSION_TLS1_2;
2049 DCHECK_NE(SSL_CONNECTION_VERSION_UNKNOWN, version);
2050 nss_handshake_state_.ssl_connection_status |=
2051 (version & SSL_CONNECTION_VERSION_MASK) <<
2052 SSL_CONNECTION_VERSION_SHIFT;
2055 PRBool peer_supports_renego_ext;
2056 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2057 &peer_supports_renego_ext);
2058 if (ok == SECSuccess) {
2059 if (!peer_supports_renego_ext) {
2060 nss_handshake_state_.ssl_connection_status |=
2061 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2062 // Log an informational message if the server does not support secure
2063 // renegotiation (RFC 5746).
2064 VLOG(1) << "The server " << host_and_port_.ToString()
2065 << " does not support the TLS renegotiation_info extension.";
2069 if (ssl_config_.version_fallback) {
2070 nss_handshake_state_.ssl_connection_status |=
2071 SSL_CONNECTION_VERSION_FALLBACK;
2075 void SSLClientSocketNSS::Core::UpdateNextProto() {
2076 uint8 buf[256];
2077 SSLNextProtoState state;
2078 unsigned buf_len;
2080 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2081 if (rv != SECSuccess)
2082 return;
2084 nss_handshake_state_.next_proto =
2085 std::string(reinterpret_cast<char*>(buf), buf_len);
2086 switch (state) {
2087 case SSL_NEXT_PROTO_NEGOTIATED:
2088 case SSL_NEXT_PROTO_SELECTED:
2089 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2090 break;
2091 case SSL_NEXT_PROTO_NO_OVERLAP:
2092 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2093 break;
2094 case SSL_NEXT_PROTO_NO_SUPPORT:
2095 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2096 break;
2097 default:
2098 NOTREACHED();
2099 break;
2103 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2104 PRBool negotiated_extension;
2105 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2106 ssl_app_layer_protocol_xtn,
2107 &negotiated_extension);
2108 if (rv == SECSuccess && negotiated_extension) {
2109 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2110 } else {
2111 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2112 ssl_next_proto_nego_xtn,
2113 &negotiated_extension);
2114 if (rv == SECSuccess && negotiated_extension) {
2115 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2120 bool SSLClientSocketNSS::Core::IsRenegotiationAllowed() const {
2121 DCHECK(OnNSSTaskRunner());
2123 if (nss_handshake_state_.next_proto_status == kNextProtoUnsupported)
2124 return ssl_config_.renego_allowed_default;
2126 NextProto next_proto = NextProtoFromString(nss_handshake_state_.next_proto);
2127 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
2128 if (next_proto == allowed)
2129 return true;
2131 return false;
2134 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2135 DCHECK(OnNSSTaskRunner());
2136 if (nss_handshake_state_.resumed_handshake)
2137 return;
2139 // Copy the NSS task runner-only state to the network task runner and
2140 // log histograms from there, since the histograms also need access to the
2141 // network task runner state.
2142 PostOrRunCallback(
2143 FROM_HERE,
2144 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner,
2145 this,
2146 channel_id_xtn_negotiated_,
2147 ssl_config_.channel_id_enabled,
2148 crypto::ECPrivateKey::IsSupported()));
2151 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2152 bool negotiated_channel_id,
2153 bool channel_id_enabled,
2154 bool supports_ecc) const {
2155 DCHECK(OnNetworkTaskRunner());
2157 RecordChannelIDSupport(channel_id_service_,
2158 negotiated_channel_id,
2159 channel_id_enabled,
2160 supports_ecc);
2163 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2164 DCHECK(OnNetworkTaskRunner());
2165 DCHECK_GT(len, 0);
2167 if (detached_)
2168 return ERR_ABORTED;
2170 int rv = transport_->socket()->Read(
2171 read_buffer, len,
2172 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2173 scoped_refptr<IOBuffer>(read_buffer)));
2175 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2176 nss_task_runner_->PostTask(
2177 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2178 scoped_refptr<IOBuffer>(read_buffer), rv));
2179 return rv;
2182 return rv;
2185 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2186 DCHECK(OnNetworkTaskRunner());
2187 DCHECK_GT(len, 0);
2189 if (detached_)
2190 return ERR_ABORTED;
2192 int rv = transport_->socket()->Write(
2193 send_buffer, len,
2194 base::Bind(&Core::BufferSendComplete,
2195 base::Unretained(this)));
2197 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2198 nss_task_runner_->PostTask(
2199 FROM_HERE,
2200 base::Bind(&Core::BufferSendComplete, this, rv));
2201 return rv;
2204 return rv;
2207 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2208 DCHECK(OnNetworkTaskRunner());
2210 if (detached_)
2211 return ERR_ABORTED;
2213 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2215 int rv = channel_id_service_->GetOrCreateChannelID(
2216 host, &channel_id_key_,
2217 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2218 &channel_id_request_);
2220 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2221 nss_task_runner_->PostTask(
2222 FROM_HERE,
2223 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2224 return ERR_IO_PENDING;
2227 return rv;
2230 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2231 const HandshakeState& state) {
2232 DCHECK(OnNetworkTaskRunner());
2233 network_handshake_state_ = state;
2236 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2237 DCHECK(OnNetworkTaskRunner());
2238 unhandled_buffer_size_ = amount_in_read_buffer;
2241 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2242 DCHECK(OnNetworkTaskRunner());
2243 DCHECK(nss_waiting_read_);
2244 nss_waiting_read_ = false;
2245 if (result <= 0) {
2246 nss_is_closed_ = true;
2247 } else {
2248 was_ever_used_ = true;
2252 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2253 DCHECK(OnNetworkTaskRunner());
2254 DCHECK(nss_waiting_write_);
2255 nss_waiting_write_ = false;
2256 if (result < 0) {
2257 nss_is_closed_ = true;
2258 } else if (result > 0) {
2259 was_ever_used_ = true;
2263 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2264 if (!OnNSSTaskRunner()) {
2265 if (detached_)
2266 return;
2268 nss_task_runner_->PostTask(
2269 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2270 return;
2273 DCHECK(OnNSSTaskRunner());
2275 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2276 transport_send_busy_ = false;
2277 OnSendComplete(result);
2280 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2281 if (!OnNSSTaskRunner()) {
2282 if (detached_)
2283 return;
2285 nss_task_runner_->PostTask(
2286 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2287 return;
2290 DCHECK(OnNSSTaskRunner());
2292 int rv = DoHandshakeLoop(result);
2293 if (rv != ERR_IO_PENDING)
2294 DoConnectCallback(rv);
2297 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2298 DVLOG(1) << __FUNCTION__ << " " << result;
2299 DCHECK(OnNetworkTaskRunner());
2301 OnHandshakeIOComplete(result);
2304 void SSLClientSocketNSS::Core::BufferRecvComplete(
2305 IOBuffer* read_buffer,
2306 int result) {
2307 DCHECK(read_buffer);
2309 if (!OnNSSTaskRunner()) {
2310 if (detached_)
2311 return;
2313 nss_task_runner_->PostTask(
2314 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2315 scoped_refptr<IOBuffer>(read_buffer), result));
2316 return;
2319 DCHECK(OnNSSTaskRunner());
2321 if (result > 0) {
2322 char* buf;
2323 int nb = memio_GetReadParams(nss_bufs_, &buf);
2324 CHECK_GE(nb, result);
2325 memcpy(buf, read_buffer->data(), result);
2326 } else if (result == 0) {
2327 transport_recv_eof_ = true;
2330 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2331 transport_recv_busy_ = false;
2332 OnRecvComplete(result);
2335 void SSLClientSocketNSS::Core::PostOrRunCallback(
2336 const tracked_objects::Location& location,
2337 const base::Closure& task) {
2338 if (!OnNetworkTaskRunner()) {
2339 network_task_runner_->PostTask(
2340 FROM_HERE,
2341 base::Bind(&Core::PostOrRunCallback, this, location, task));
2342 return;
2345 if (detached_ || task.is_null())
2346 return;
2347 task.Run();
2350 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2351 PostOrRunCallback(
2352 FROM_HERE,
2353 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2354 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2355 NetLog::IntegerCallback("cert_count", cert_count)));
2358 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2359 PostOrRunCallback(
2360 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2361 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2362 nss_handshake_state_.channel_id_sent = true;
2363 // Update the network task runner's view of the handshake state now that
2364 // channel id has been sent.
2365 PostOrRunCallback(
2366 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2367 nss_handshake_state_));
2370 SSLClientSocketNSS::SSLClientSocketNSS(
2371 base::SequencedTaskRunner* nss_task_runner,
2372 scoped_ptr<ClientSocketHandle> transport_socket,
2373 const HostPortPair& host_and_port,
2374 const SSLConfig& ssl_config,
2375 const SSLClientSocketContext& context)
2376 : nss_task_runner_(nss_task_runner),
2377 transport_(transport_socket.Pass()),
2378 host_and_port_(host_and_port),
2379 ssl_config_(ssl_config),
2380 cert_verifier_(context.cert_verifier),
2381 cert_transparency_verifier_(context.cert_transparency_verifier),
2382 channel_id_service_(context.channel_id_service),
2383 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2384 completed_handshake_(false),
2385 next_handshake_state_(STATE_NONE),
2386 disconnected_(false),
2387 nss_fd_(NULL),
2388 net_log_(transport_->socket()->NetLog()),
2389 transport_security_state_(context.transport_security_state),
2390 policy_enforcer_(context.cert_policy_enforcer),
2391 valid_thread_id_(base::kInvalidThreadId) {
2392 DCHECK(cert_verifier_);
2394 EnterFunction("");
2395 InitCore();
2396 LeaveFunction("");
2399 SSLClientSocketNSS::~SSLClientSocketNSS() {
2400 EnterFunction("");
2401 Disconnect();
2402 LeaveFunction("");
2405 // static
2406 void SSLClientSocket::ClearSessionCache() {
2407 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2408 // bother initializing NSS just to clear an empty SSL session cache.
2409 if (!NSS_IsInitialized())
2410 return;
2412 SSL_ClearSessionCache();
2415 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
2416 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
2417 #endif
2419 // static
2420 uint16 SSLClientSocket::GetMaxSupportedSSLVersion() {
2421 crypto::EnsureNSSInit();
2422 if (PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)) {
2423 return SSL_PROTOCOL_VERSION_TLS1_2;
2424 } else {
2425 return SSL_PROTOCOL_VERSION_TLS1_1;
2429 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2430 EnterFunction("");
2431 ssl_info->Reset();
2432 if (core_->state().server_cert_chain.empty() ||
2433 !core_->state().server_cert_chain[0]) {
2434 return false;
2437 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2438 ssl_info->cert = server_cert_verify_result_.verified_cert;
2439 ssl_info->unverified_cert = core_->state().server_cert;
2441 AddSCTInfoToSSLInfo(ssl_info);
2443 ssl_info->connection_status =
2444 core_->state().ssl_connection_status;
2445 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2446 ssl_info->is_issued_by_known_root =
2447 server_cert_verify_result_.is_issued_by_known_root;
2448 ssl_info->client_cert_sent =
2449 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2450 ssl_info->channel_id_sent = core_->state().channel_id_sent;
2451 ssl_info->pinning_failure_log = pinning_failure_log_;
2453 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2454 core_->state().ssl_connection_status);
2455 SSLCipherSuiteInfo cipher_info;
2456 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2457 &cipher_info, sizeof(cipher_info));
2458 if (ok == SECSuccess) {
2459 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2460 } else {
2461 ssl_info->security_bits = -1;
2462 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2463 << " for cipherSuite " << cipher_suite;
2466 ssl_info->handshake_type = core_->state().resumed_handshake ?
2467 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2469 LeaveFunction("");
2470 return true;
2473 void SSLClientSocketNSS::GetConnectionAttempts(ConnectionAttempts* out) const {
2474 out->clear();
2477 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2478 SSLCertRequestInfo* cert_request_info) {
2479 EnterFunction("");
2480 cert_request_info->host_and_port = host_and_port_;
2481 cert_request_info->cert_authorities = core_->state().cert_authorities;
2482 LeaveFunction("");
2485 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2486 bool has_context,
2487 const base::StringPiece& context,
2488 unsigned char* out,
2489 unsigned int outlen) {
2490 if (!IsConnected())
2491 return ERR_SOCKET_NOT_CONNECTED;
2493 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2494 // the midst of a handshake.
2495 SECStatus result = SSL_ExportKeyingMaterial(
2496 nss_fd_, label.data(), label.size(), has_context,
2497 reinterpret_cast<const unsigned char*>(context.data()),
2498 context.length(), out, outlen);
2499 if (result != SECSuccess) {
2500 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2501 return MapNSSError(PORT_GetError());
2503 return OK;
2506 int SSLClientSocketNSS::GetTLSUniqueChannelBinding(std::string* out) {
2507 if (!IsConnected())
2508 return ERR_SOCKET_NOT_CONNECTED;
2509 unsigned char buf[64];
2510 unsigned int len;
2511 SECStatus result = SSL_GetChannelBinding(nss_fd_,
2512 SSL_CHANNEL_BINDING_TLS_UNIQUE,
2513 buf, &len, arraysize(buf));
2514 if (result != SECSuccess) {
2515 LogFailedNSSFunction(net_log_, "SSL_GetChannelBinding", "");
2516 return MapNSSError(PORT_GetError());
2518 out->assign(reinterpret_cast<char*>(buf), len);
2519 return OK;
2522 SSLClientSocket::NextProtoStatus SSLClientSocketNSS::GetNextProto(
2523 std::string* proto) const {
2524 *proto = core_->state().next_proto;
2525 return core_->state().next_proto_status;
2528 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2529 EnterFunction("");
2530 DCHECK(transport_.get());
2531 // It is an error to create an SSLClientSocket whose context has no
2532 // TransportSecurityState.
2533 DCHECK(transport_security_state_);
2534 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2535 DCHECK(user_connect_callback_.is_null());
2536 DCHECK(!callback.is_null());
2538 // Although StreamSocket does allow calling Connect() after Disconnect(),
2539 // this has never worked for layered sockets. CHECK to detect any consumers
2540 // reconnecting an SSL socket.
2542 // TODO(davidben,mmenke): Remove this API feature. See
2543 // https://crbug.com/499289.
2544 CHECK(!disconnected_);
2546 EnsureThreadIdAssigned();
2548 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2550 int rv = Init();
2551 if (rv != OK) {
2552 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2553 return rv;
2556 rv = InitializeSSLOptions();
2557 if (rv != OK) {
2558 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2559 return rv;
2562 rv = InitializeSSLPeerName();
2563 if (rv != OK) {
2564 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2565 return rv;
2568 GotoState(STATE_HANDSHAKE);
2570 rv = DoHandshakeLoop(OK);
2571 if (rv == ERR_IO_PENDING) {
2572 user_connect_callback_ = callback;
2573 } else {
2574 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2577 LeaveFunction("");
2578 return rv > OK ? OK : rv;
2581 void SSLClientSocketNSS::Disconnect() {
2582 EnterFunction("");
2584 CHECK(CalledOnValidThread());
2586 // Shut down anything that may call us back.
2587 core_->Detach();
2588 cert_verifier_request_.reset();
2589 transport_->socket()->Disconnect();
2591 disconnected_ = true;
2593 // Reset object state.
2594 user_connect_callback_.Reset();
2595 server_cert_verify_result_.Reset();
2596 completed_handshake_ = false;
2597 start_cert_verification_time_ = base::TimeTicks();
2598 InitCore();
2600 LeaveFunction("");
2603 bool SSLClientSocketNSS::IsConnected() const {
2604 EnterFunction("");
2605 bool ret = completed_handshake_ &&
2606 (core_->HasPendingAsyncOperation() ||
2607 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2608 transport_->socket()->IsConnected());
2609 LeaveFunction("");
2610 return ret;
2613 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2614 EnterFunction("");
2615 bool ret = completed_handshake_ &&
2616 !core_->HasPendingAsyncOperation() &&
2617 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
2618 transport_->socket()->IsConnectedAndIdle();
2619 LeaveFunction("");
2620 return ret;
2623 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
2624 return transport_->socket()->GetPeerAddress(address);
2627 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
2628 return transport_->socket()->GetLocalAddress(address);
2631 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
2632 return net_log_;
2635 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2636 if (transport_.get() && transport_->socket()) {
2637 transport_->socket()->SetSubresourceSpeculation();
2638 } else {
2639 NOTREACHED();
2643 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2644 if (transport_.get() && transport_->socket()) {
2645 transport_->socket()->SetOmniboxSpeculation();
2646 } else {
2647 NOTREACHED();
2651 bool SSLClientSocketNSS::WasEverUsed() const {
2652 DCHECK(core_.get());
2654 return core_->WasEverUsed();
2657 bool SSLClientSocketNSS::UsingTCPFastOpen() const {
2658 if (transport_.get() && transport_->socket()) {
2659 return transport_->socket()->UsingTCPFastOpen();
2661 NOTREACHED();
2662 return false;
2665 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
2666 const CompletionCallback& callback) {
2667 DCHECK(core_.get());
2668 DCHECK(!callback.is_null());
2670 EnterFunction(buf_len);
2671 int rv = core_->Read(buf, buf_len, callback);
2672 LeaveFunction(rv);
2674 return rv;
2677 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
2678 const CompletionCallback& callback) {
2679 DCHECK(core_.get());
2680 DCHECK(!callback.is_null());
2682 EnterFunction(buf_len);
2683 int rv = core_->Write(buf, buf_len, callback);
2684 LeaveFunction(rv);
2686 return rv;
2689 int SSLClientSocketNSS::SetReceiveBufferSize(int32 size) {
2690 return transport_->socket()->SetReceiveBufferSize(size);
2693 int SSLClientSocketNSS::SetSendBufferSize(int32 size) {
2694 return transport_->socket()->SetSendBufferSize(size);
2697 int SSLClientSocketNSS::Init() {
2698 EnterFunction("");
2699 // Initialize the NSS SSL library in a threadsafe way. This also
2700 // initializes the NSS base library.
2701 EnsureNSSSSLInit();
2702 if (!NSS_IsInitialized())
2703 return ERR_UNEXPECTED;
2704 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
2705 if (ssl_config_.cert_io_enabled) {
2706 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
2707 // loop by MessageLoopForIO::current().
2708 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
2709 EnsureNSSHttpIOInit();
2711 #endif
2713 LeaveFunction("");
2714 return OK;
2717 void SSLClientSocketNSS::InitCore() {
2718 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
2719 nss_task_runner_.get(),
2720 transport_.get(),
2721 host_and_port_,
2722 ssl_config_,
2723 &net_log_,
2724 channel_id_service_);
2727 int SSLClientSocketNSS::InitializeSSLOptions() {
2728 // Transport connected, now hook it up to nss
2729 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
2730 if (nss_fd_ == NULL) {
2731 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
2734 // Grab pointer to buffers
2735 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
2737 /* Create SSL state machine */
2738 /* Push SSL onto our fake I/O socket */
2739 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
2740 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
2741 PR_Close(nss_fd_);
2742 nss_fd_ = NULL;
2743 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
2745 // TODO(port): set more ssl options! Check errors!
2747 int rv;
2749 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
2750 if (rv != SECSuccess) {
2751 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
2752 return ERR_UNEXPECTED;
2755 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
2756 if (rv != SECSuccess) {
2757 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
2758 return ERR_UNEXPECTED;
2761 // Don't do V2 compatible hellos because they don't support TLS extensions.
2762 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
2763 if (rv != SECSuccess) {
2764 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
2765 return ERR_UNEXPECTED;
2768 SSLVersionRange version_range;
2769 version_range.min = ssl_config_.version_min;
2770 version_range.max = ssl_config_.version_max;
2771 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
2772 if (rv != SECSuccess) {
2773 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
2774 return ERR_NO_SSL_VERSIONS_ENABLED;
2777 if (ssl_config_.require_ecdhe) {
2778 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2779 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2781 // Iterate over the cipher suites and disable those that don't use ECDHE.
2782 for (unsigned i = 0; i < num_ciphers; i++) {
2783 SSLCipherSuiteInfo info;
2784 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) ==
2785 SECSuccess) {
2786 if (strcmp(info.keaTypeName, "ECDHE") != 0) {
2787 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2793 if (ssl_config_.version_fallback) {
2794 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
2795 if (rv != SECSuccess) {
2796 LogFailedNSSFunction(
2797 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
2801 for (std::vector<uint16>::const_iterator it =
2802 ssl_config_.disabled_cipher_suites.begin();
2803 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
2804 // This will fail if the specified cipher is not implemented by NSS, but
2805 // the failure is harmless.
2806 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
2809 if (!ssl_config_.enable_deprecated_cipher_suites) {
2810 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2811 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2812 for (int i = 0; i < num_ciphers; i++) {
2813 SSLCipherSuiteInfo info;
2814 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) !=
2815 SECSuccess) {
2816 continue;
2818 if (info.symCipher == ssl_calg_rc4)
2819 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2823 // Support RFC 5077
2824 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
2825 if (rv != SECSuccess) {
2826 LogFailedNSSFunction(
2827 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
2830 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
2831 ssl_config_.false_start_enabled);
2832 if (rv != SECSuccess)
2833 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
2835 // By default, renegotiations are rejected. After the initial handshake
2836 // completes, some application protocols may re-enable it.
2837 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION, SSL_RENEGOTIATE_NEVER);
2838 if (rv != SECSuccess) {
2839 LogFailedNSSFunction(
2840 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
2843 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
2844 if (rv != SECSuccess)
2845 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
2847 // Added in NSS 3.15
2848 #ifdef SSL_ENABLE_OCSP_STAPLING
2849 // Request OCSP stapling even on platforms that don't support it, in
2850 // order to extract Certificate Transparency information.
2851 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
2852 cert_verifier_->SupportsOCSPStapling() ||
2853 ssl_config_.signed_cert_timestamps_enabled);
2854 if (rv != SECSuccess) {
2855 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2856 "SSL_ENABLE_OCSP_STAPLING");
2858 #endif
2860 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
2861 ssl_config_.signed_cert_timestamps_enabled);
2862 if (rv != SECSuccess) {
2863 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2864 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
2867 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
2868 if (rv != SECSuccess) {
2869 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
2870 return ERR_UNEXPECTED;
2873 if (!core_->Init(nss_fd_, nss_bufs))
2874 return ERR_UNEXPECTED;
2876 // Tell SSL the hostname we're trying to connect to.
2877 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
2879 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
2880 SSL_ResetHandshake(nss_fd_, PR_FALSE);
2882 return OK;
2885 int SSLClientSocketNSS::InitializeSSLPeerName() {
2886 // Tell NSS who we're connected to
2887 IPEndPoint peer_address;
2888 int err = transport_->socket()->GetPeerAddress(&peer_address);
2889 if (err != OK)
2890 return err;
2892 SockaddrStorage storage;
2893 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
2894 return ERR_ADDRESS_INVALID;
2896 PRNetAddr peername;
2897 memset(&peername, 0, sizeof(peername));
2898 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
2899 size_t len = std::min(static_cast<size_t>(storage.addr_len),
2900 sizeof(peername));
2901 memcpy(&peername, storage.addr, len);
2903 // Adjust the address family field for BSD, whose sockaddr
2904 // structure has a one-byte length and one-byte address family
2905 // field at the beginning. PRNetAddr has a two-byte address
2906 // family field at the beginning.
2907 peername.raw.family = storage.addr->sa_family;
2909 memio_SetPeerName(nss_fd_, &peername);
2911 // Set the peer ID for session reuse. This is necessary when we create an
2912 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
2913 // rather than the destination server's address in that case.
2914 std::string peer_id = host_and_port_.ToString();
2915 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
2916 // the session cache for incognito mode.
2917 peer_id += "/" + ssl_session_cache_shard_;
2918 peer_id += "/";
2919 // Shard the session cache based on maximum protocol version. This causes
2920 // fallback connections to use a separate session cache.
2921 switch (ssl_config_.version_max) {
2922 case SSL_PROTOCOL_VERSION_TLS1:
2923 peer_id += "tls1";
2924 break;
2925 case SSL_PROTOCOL_VERSION_TLS1_1:
2926 peer_id += "tls1.1";
2927 break;
2928 case SSL_PROTOCOL_VERSION_TLS1_2:
2929 peer_id += "tls1.2";
2930 break;
2931 default:
2932 NOTREACHED();
2934 peer_id += "/";
2935 if (ssl_config_.enable_deprecated_cipher_suites)
2936 peer_id += "deprecated";
2938 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
2939 if (rv != SECSuccess)
2940 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
2942 return OK;
2945 void SSLClientSocketNSS::DoConnectCallback(int rv) {
2946 EnterFunction(rv);
2947 DCHECK_NE(ERR_IO_PENDING, rv);
2948 DCHECK(!user_connect_callback_.is_null());
2950 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
2951 LeaveFunction("");
2954 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
2955 EnterFunction(result);
2956 int rv = DoHandshakeLoop(result);
2957 if (rv != ERR_IO_PENDING) {
2958 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2959 DoConnectCallback(rv);
2961 LeaveFunction("");
2964 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
2965 EnterFunction(last_io_result);
2966 int rv = last_io_result;
2967 do {
2968 // Default to STATE_NONE for next state.
2969 // (This is a quirk carried over from the windows
2970 // implementation. It makes reading the logs a bit harder.)
2971 // State handlers can and often do call GotoState just
2972 // to stay in the current state.
2973 State state = next_handshake_state_;
2974 GotoState(STATE_NONE);
2975 switch (state) {
2976 case STATE_HANDSHAKE:
2977 rv = DoHandshake();
2978 break;
2979 case STATE_HANDSHAKE_COMPLETE:
2980 rv = DoHandshakeComplete(rv);
2981 break;
2982 case STATE_VERIFY_CERT:
2983 DCHECK(rv == OK);
2984 rv = DoVerifyCert(rv);
2985 break;
2986 case STATE_VERIFY_CERT_COMPLETE:
2987 rv = DoVerifyCertComplete(rv);
2988 break;
2989 case STATE_NONE:
2990 default:
2991 rv = ERR_UNEXPECTED;
2992 LOG(DFATAL) << "unexpected state " << state;
2993 break;
2995 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
2996 LeaveFunction("");
2997 return rv;
3000 int SSLClientSocketNSS::DoHandshake() {
3001 EnterFunction("");
3003 int rv = core_->Connect(
3004 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3005 base::Unretained(this)));
3006 GotoState(STATE_HANDSHAKE_COMPLETE);
3008 LeaveFunction(rv);
3009 return rv;
3012 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
3013 EnterFunction(result);
3015 if (result == OK) {
3016 if (ssl_config_.version_fallback &&
3017 ssl_config_.version_max < ssl_config_.version_fallback_min) {
3018 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
3021 RecordNegotiationExtension();
3023 // SSL handshake is completed. Let's verify the certificate.
3024 GotoState(STATE_VERIFY_CERT);
3025 // Done!
3027 set_signed_cert_timestamps_received(
3028 !core_->state().sct_list_from_tls_extension.empty());
3029 set_stapled_ocsp_response_received(
3030 !core_->state().stapled_ocsp_response.empty());
3031 set_negotiation_extension(core_->state().negotiation_extension_);
3033 LeaveFunction(result);
3034 return result;
3037 int SSLClientSocketNSS::DoVerifyCert(int result) {
3038 DCHECK(!core_->state().server_cert_chain.empty());
3039 DCHECK(core_->state().server_cert_chain[0]);
3041 GotoState(STATE_VERIFY_CERT_COMPLETE);
3043 // NSS decoded the certificate, but the platform certificate implementation
3044 // could not. This is treated as a fatal SSL-level protocol error rather than
3045 // a certificate error. See https://crbug.com/91341.
3046 if (!core_->state().server_cert.get())
3047 return ERR_SSL_SERVER_CERT_BAD_FORMAT;
3049 // If the certificate is expected to be bad we can use the expectation as
3050 // the cert status.
3051 base::StringPiece der_cert(
3052 reinterpret_cast<char*>(
3053 core_->state().server_cert_chain[0]->derCert.data),
3054 core_->state().server_cert_chain[0]->derCert.len);
3055 CertStatus cert_status;
3056 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3057 DCHECK(start_cert_verification_time_.is_null());
3058 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3059 server_cert_verify_result_.Reset();
3060 server_cert_verify_result_.cert_status = cert_status;
3061 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3062 return OK;
3065 start_cert_verification_time_ = base::TimeTicks::Now();
3067 return cert_verifier_->Verify(
3068 core_->state().server_cert.get(), host_and_port_.host(),
3069 core_->state().stapled_ocsp_response, ssl_config_.GetCertVerifyFlags(),
3070 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
3071 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3072 base::Unretained(this)),
3073 &cert_verifier_request_, net_log_);
3076 // Derived from AuthCertificateCallback() in
3077 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3078 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3079 cert_verifier_request_.reset();
3081 if (!start_cert_verification_time_.is_null()) {
3082 base::TimeDelta verify_time =
3083 base::TimeTicks::Now() - start_cert_verification_time_;
3084 if (result == OK)
3085 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3086 else
3087 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3090 // We used to remember the intermediate CA certs in the NSS database
3091 // persistently. However, NSS opens a connection to the SQLite database
3092 // during NSS initialization and doesn't close the connection until NSS
3093 // shuts down. If the file system where the database resides is gone,
3094 // the database connection goes bad. What's worse, the connection won't
3095 // recover when the file system comes back. Until this NSS or SQLite bug
3096 // is fixed, we need to avoid using the NSS database for non-essential
3097 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3098 // http://crbug.com/15630 for more info.
3100 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3101 if (transport_security_state_ &&
3102 (result == OK ||
3103 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3104 !transport_security_state_->CheckPublicKeyPins(
3105 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
3106 server_cert_verify_result_.public_key_hashes,
3107 core_->state().server_cert.get(),
3108 server_cert_verify_result_.verified_cert.get(),
3109 TransportSecurityState::ENABLE_PIN_REPORTS, &pinning_failure_log_)) {
3110 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3113 if (result == OK) {
3114 // Only check Certificate Transparency if there were no other errors with
3115 // the connection.
3116 VerifyCT();
3118 // Only cache the session if the certificate verified successfully.
3119 core_->CacheSessionIfNecessary();
3122 completed_handshake_ = true;
3124 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3125 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3126 return result;
3129 void SSLClientSocketNSS::VerifyCT() {
3130 if (!cert_transparency_verifier_)
3131 return;
3133 // Note that this is a completely synchronous operation: The CT Log Verifier
3134 // gets all the data it needs for SCT verification and does not do any
3135 // external communication.
3136 cert_transparency_verifier_->Verify(
3137 server_cert_verify_result_.verified_cert.get(),
3138 core_->state().stapled_ocsp_response,
3139 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3140 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3141 // from the state after verification is complete, to conserve memory.
3143 if (policy_enforcer_ &&
3144 (server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV)) {
3145 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3146 SSLConfigService::GetEVCertsWhitelist();
3147 if (!policy_enforcer_->DoesConformToCTEVPolicy(
3148 server_cert_verify_result_.verified_cert.get(), ev_whitelist.get(),
3149 ct_verify_result_, net_log_)) {
3150 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3151 VLOG(1) << "EV certificate for "
3152 << server_cert_verify_result_.verified_cert->subject()
3153 .GetDisplayName()
3154 << " does not conform to CT policy, removing EV status.";
3155 server_cert_verify_result_.cert_status |=
3156 CERT_STATUS_CT_COMPLIANCE_FAILED;
3157 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3162 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3163 base::AutoLock auto_lock(lock_);
3164 if (valid_thread_id_ != base::kInvalidThreadId)
3165 return;
3166 valid_thread_id_ = base::PlatformThread::CurrentId();
3169 bool SSLClientSocketNSS::CalledOnValidThread() const {
3170 EnsureThreadIdAssigned();
3171 base::AutoLock auto_lock(lock_);
3172 return valid_thread_id_ == base::PlatformThread::CurrentId();
3175 void SSLClientSocketNSS::AddSCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3176 for (ct::SCTList::const_iterator iter =
3177 ct_verify_result_.verified_scts.begin();
3178 iter != ct_verify_result_.verified_scts.end(); ++iter) {
3179 ssl_info->signed_certificate_timestamps.push_back(
3180 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_OK));
3182 for (ct::SCTList::const_iterator iter =
3183 ct_verify_result_.invalid_scts.begin();
3184 iter != ct_verify_result_.invalid_scts.end(); ++iter) {
3185 ssl_info->signed_certificate_timestamps.push_back(
3186 SignedCertificateTimestampAndStatus(*iter, ct::SCT_STATUS_INVALID));
3188 for (ct::SCTList::const_iterator iter =
3189 ct_verify_result_.unknown_logs_scts.begin();
3190 iter != ct_verify_result_.unknown_logs_scts.end(); ++iter) {
3191 ssl_info->signed_certificate_timestamps.push_back(
3192 SignedCertificateTimestampAndStatus(*iter,
3193 ct::SCT_STATUS_LOG_UNKNOWN));
3197 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3198 return channel_id_service_;
3201 SSLFailureState SSLClientSocketNSS::GetSSLFailureState() const {
3202 if (completed_handshake_)
3203 return SSL_FAILURE_NONE;
3204 return SSL_FAILURE_UNKNOWN;
3207 } // namespace net