Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1018)

Side by Side Diff: net/socket/ssl_client_socket_nss.cc

Issue 1882433002: Removing NSS files and USE_OPENSSL flag (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase. Created 4 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « net/socket/ssl_client_socket_nss.h ('k') | net/socket/ssl_client_socket_openssl.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived
6 // from AuthCertificateCallback() in
7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp.
8
9 /* ***** BEGIN LICENSE BLOCK *****
10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
11 *
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/
16 *
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.
21 *
22 * The Original Code is the Netscape security libraries.
23 *
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.
28 *
29 * Contributor(s):
30 * Ian McGreer <mcgreer@netscape.com>
31 * Javier Delgadillo <javi@netscape.com>
32 * Kai Engert <kengert@redhat.com>
33 *
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.
45 *
46 * ***** END LICENSE BLOCK ***** */
47
48 #include "net/socket/ssl_client_socket_nss.h"
49
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>
62
63 #include <algorithm>
64 #include <limits>
65 #include <map>
66 #include <utility>
67
68 #include "base/bind.h"
69 #include "base/bind_helpers.h"
70 #include "base/callback_helpers.h"
71 #include "base/compiler_specific.h"
72 #include "base/location.h"
73 #include "base/logging.h"
74 #include "base/macros.h"
75 #include "base/metrics/histogram_macros.h"
76 #include "base/single_thread_task_runner.h"
77 #include "base/stl_util.h"
78 #include "base/strings/string_number_conversions.h"
79 #include "base/strings/string_util.h"
80 #include "base/strings/stringprintf.h"
81 #include "base/thread_task_runner_handle.h"
82 #include "base/threading/thread_restrictions.h"
83 #include "base/values.h"
84 #include "crypto/ec_private_key.h"
85 #include "crypto/nss_util.h"
86 #include "crypto/nss_util_internal.h"
87 #include "crypto/rsa_private_key.h"
88 #include "crypto/scoped_nss_types.h"
89 #include "net/base/address_list.h"
90 #include "net/base/io_buffer.h"
91 #include "net/base/net_errors.h"
92 #include "net/base/sockaddr_storage.h"
93 #include "net/cert/asn1_util.h"
94 #include "net/cert/cert_status_flags.h"
95 #include "net/cert/cert_verifier.h"
96 #include "net/cert/ct_ev_whitelist.h"
97 #include "net/cert/ct_policy_enforcer.h"
98 #include "net/cert/ct_policy_status.h"
99 #include "net/cert/ct_verifier.h"
100 #include "net/cert/ct_verify_result.h"
101 #include "net/cert/scoped_nss_types.h"
102 #include "net/cert/sct_status_flags.h"
103 #include "net/cert/x509_certificate_net_log_param.h"
104 #include "net/cert/x509_util.h"
105 #include "net/cert_net/nss_ocsp.h"
106 #include "net/dns/dns_util.h"
107 #include "net/http/transport_security_state.h"
108 #include "net/log/net_log.h"
109 #include "net/socket/client_socket_handle.h"
110 #include "net/socket/nss_ssl_util.h"
111 #include "net/ssl/ssl_cert_request_info.h"
112 #include "net/ssl/ssl_cipher_suite_names.h"
113 #include "net/ssl/ssl_connection_status_flags.h"
114 #include "net/ssl/ssl_failure_state.h"
115 #include "net/ssl/ssl_info.h"
116
117 #if defined(USE_NSS_CERTS)
118 #include <dlfcn.h>
119 #endif
120
121 namespace net {
122
123 // State machines are easier to debug if you log state transitions.
124 // Enable these if you want to see what's going on.
125 #if 1
126 #define EnterFunction(x)
127 #define LeaveFunction(x)
128 #define GotoState(s) next_handshake_state_ = s
129 #else
130 #define EnterFunction(x)\
131 VLOG(1) << (void *)this << " " << __FUNCTION__ << " enter " << x\
132 << "; next_handshake_state " << next_handshake_state_
133 #define LeaveFunction(x)\
134 VLOG(1) << (void *)this << " " << __FUNCTION__ << " leave " << x\
135 << "; next_handshake_state " << next_handshake_state_
136 #define GotoState(s)\
137 do {\
138 VLOG(1) << (void *)this << " " << __FUNCTION__ << " jump to state " << s;\
139 next_handshake_state_ = s;\
140 } while (0)
141 #endif
142
143 namespace {
144
145 // SSL plaintext fragments are shorter than 16KB. Although the record layer
146 // overhead is allowed to be 2K + 5 bytes, in practice the overhead is much
147 // smaller than 1KB. So a 17KB buffer should be large enough to hold an
148 // entire SSL record.
149 const int kRecvBufferSize = 17 * 1024;
150 const int kSendBufferSize = 17 * 1024;
151
152 // Used by SSLClientSocketNSS::Core to indicate there is no read result
153 // obtained by a previous operation waiting to be returned to the caller.
154 // This constant can be any non-negative/non-zero value (eg: it does not
155 // overlap with any value of the net::Error range, including net::OK).
156 const int kNoPendingReadResult = 1;
157
158 // Helper functions to make it possible to log events from within the
159 // SSLClientSocketNSS::Core.
160 void AddLogEvent(const base::WeakPtr<BoundNetLog>& net_log,
161 NetLog::EventType event_type) {
162 if (!net_log)
163 return;
164 net_log->AddEvent(event_type);
165 }
166
167 // Helper function to make it possible to log events from within the
168 // SSLClientSocketNSS::Core.
169 void AddLogEventWithCallback(const base::WeakPtr<BoundNetLog>& net_log,
170 NetLog::EventType event_type,
171 const NetLog::ParametersCallback& callback) {
172 if (!net_log)
173 return;
174 net_log->AddEvent(event_type, callback);
175 }
176
177 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent
178 // from within the SSLClientSocketNSS::Core.
179 // AddByteTransferEvent expects to receive a const char*, which within the
180 // Core is backed by an IOBuffer. If the "const char*" is bound via
181 // base::Bind and posted to another thread, and the IOBuffer that backs that
182 // pointer then goes out of scope on the origin thread, this would result in
183 // an invalid read of a stale pointer.
184 // Instead, provide a signature that accepts an IOBuffer*, so that a reference
185 // to the owning IOBuffer can be bound to the Callback. This ensures that the
186 // IOBuffer will stay alive long enough to cross threads if needed.
187 void LogByteTransferEvent(
188 const base::WeakPtr<BoundNetLog>& net_log, NetLog::EventType event_type,
189 int len, IOBuffer* buffer) {
190 if (!net_log)
191 return;
192 net_log->AddByteTransferEvent(event_type, len, buffer->data());
193 }
194
195 // PeerCertificateChain is a helper object which extracts the certificate
196 // chain, as given by the server, from an NSS socket and performs the needed
197 // resource management. The first element of the chain is the leaf certificate
198 // and the other elements are in the order given by the server.
199 class PeerCertificateChain {
200 public:
201 PeerCertificateChain() {}
202 PeerCertificateChain(const PeerCertificateChain& other);
203 ~PeerCertificateChain();
204 PeerCertificateChain& operator=(const PeerCertificateChain& other);
205
206 // Resets the current chain, freeing any resources, and updates the current
207 // chain to be a copy of the chain stored in |nss_fd|.
208 // If |nss_fd| is NULL, then the current certificate chain will be freed.
209 void Reset(PRFileDesc* nss_fd);
210
211 // Returns the current certificate chain as a vector of DER-encoded
212 // base::StringPieces. The returned vector remains valid until Reset is
213 // called.
214 std::vector<base::StringPiece> AsStringPieceVector() const;
215
216 bool empty() const { return certs_.empty(); }
217
218 CERTCertificate* operator[](size_t index) const {
219 DCHECK_LT(index, certs_.size());
220 return certs_[index];
221 }
222
223 private:
224 std::vector<CERTCertificate*> certs_;
225 };
226
227 PeerCertificateChain::PeerCertificateChain(
228 const PeerCertificateChain& other) {
229 *this = other;
230 }
231
232 PeerCertificateChain::~PeerCertificateChain() {
233 Reset(NULL);
234 }
235
236 PeerCertificateChain& PeerCertificateChain::operator=(
237 const PeerCertificateChain& other) {
238 if (this == &other)
239 return *this;
240
241 Reset(NULL);
242 certs_.reserve(other.certs_.size());
243 for (size_t i = 0; i < other.certs_.size(); ++i)
244 certs_.push_back(CERT_DupCertificate(other.certs_[i]));
245
246 return *this;
247 }
248
249 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) {
250 for (size_t i = 0; i < certs_.size(); ++i)
251 CERT_DestroyCertificate(certs_[i]);
252 certs_.clear();
253
254 if (nss_fd == NULL)
255 return;
256
257 CERTCertList* list = SSL_PeerCertificateChain(nss_fd);
258 // The handshake on |nss_fd| may not have completed.
259 if (list == NULL)
260 return;
261
262 for (CERTCertListNode* node = CERT_LIST_HEAD(list);
263 !CERT_LIST_END(node, list); node = CERT_LIST_NEXT(node)) {
264 certs_.push_back(CERT_DupCertificate(node->cert));
265 }
266 CERT_DestroyCertList(list);
267 }
268
269 std::vector<base::StringPiece>
270 PeerCertificateChain::AsStringPieceVector() const {
271 std::vector<base::StringPiece> v(certs_.size());
272 for (unsigned i = 0; i < certs_.size(); i++) {
273 v[i] = base::StringPiece(
274 reinterpret_cast<const char*>(certs_[i]->derCert.data),
275 certs_[i]->derCert.len);
276 }
277
278 return v;
279 }
280
281 // HandshakeState is a helper struct used to pass handshake state between
282 // the NSS task runner and the network task runner.
283 //
284 // It contains members that may be read or written on the NSS task runner,
285 // but which also need to be read from the network task runner. The NSS task
286 // runner will notify the network task runner whenever this state changes, so
287 // that the network task runner can safely make a copy, which avoids the need
288 // for locking.
289 struct HandshakeState {
290 HandshakeState() { Reset(); }
291
292 void Reset() {
293 next_proto_status = SSLClientSocket::kNextProtoUnsupported;
294 next_proto.clear();
295 negotiation_extension_ = SSLClientSocket::kExtensionUnknown;
296 channel_id_sent = false;
297 server_cert_chain.Reset(NULL);
298 server_cert = NULL;
299 sct_list_from_tls_extension.clear();
300 stapled_ocsp_response.clear();
301 resumed_handshake = false;
302 ssl_connection_status = 0;
303 }
304
305 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the
306 // negotiated protocol stored in |next_proto|.
307 SSLClientSocket::NextProtoStatus next_proto_status;
308 std::string next_proto;
309
310 // TLS extension used for protocol negotiation.
311 SSLClientSocket::SSLNegotiationExtension negotiation_extension_;
312
313 // True if a channel ID was sent.
314 bool channel_id_sent;
315
316 // List of DER-encoded X.509 DistinguishedName of certificate authorities
317 // allowed by the server.
318 std::vector<std::string> cert_authorities;
319
320 // Set when the handshake fully completes.
321 //
322 // The server certificate is first received from NSS as an NSS certificate
323 // chain (|server_cert_chain|) and then converted into a platform-specific
324 // X509Certificate object (|server_cert|). It's possible for some
325 // certificates to be successfully parsed by NSS, and not by the platform
326 // libraries (i.e.: when running within a sandbox, different parsing
327 // algorithms, etc), so it's not safe to assume that |server_cert| will
328 // always be non-NULL.
329 PeerCertificateChain server_cert_chain;
330 scoped_refptr<X509Certificate> server_cert;
331 // SignedCertificateTimestampList received via TLS extension (RFC 6962).
332 std::string sct_list_from_tls_extension;
333 // Stapled OCSP response received.
334 std::string stapled_ocsp_response;
335
336 // True if the current handshake was the result of TLS session resumption.
337 bool resumed_handshake;
338
339 // The negotiated security parameters (TLS version, cipher, extensions) of
340 // the SSL connection.
341 int ssl_connection_status;
342 };
343
344 // Client-side error mapping functions.
345
346 // Map NSS error code to network error code.
347 int MapNSSClientError(PRErrorCode err) {
348 switch (err) {
349 case SSL_ERROR_BAD_CERT_ALERT:
350 case SSL_ERROR_UNSUPPORTED_CERT_ALERT:
351 case SSL_ERROR_REVOKED_CERT_ALERT:
352 case SSL_ERROR_EXPIRED_CERT_ALERT:
353 case SSL_ERROR_CERTIFICATE_UNKNOWN_ALERT:
354 case SSL_ERROR_UNKNOWN_CA_ALERT:
355 case SSL_ERROR_ACCESS_DENIED_ALERT:
356 return ERR_BAD_SSL_CLIENT_AUTH_CERT;
357 default:
358 return MapNSSError(err);
359 }
360 }
361
362 } // namespace
363
364 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is
365 // able to marshal data between NSS functions and an underlying transport
366 // socket.
367 //
368 // All public functions are meant to be called from the network task runner,
369 // and any callbacks supplied will be invoked there as well, provided that
370 // Detach() has not been called yet.
371 //
372 /////////////////////////////////////////////////////////////////////////////
373 //
374 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core:
375 //
376 // Because NSS may block on either hardware or user input during operations
377 // such as signing, creating certificates, or locating private keys, the Core
378 // handles all of the interactions with the underlying NSS SSL socket, so
379 // that these blocking calls can be executed on a dedicated task runner.
380 //
381 // Note that the network task runner and the NSS task runner may be executing
382 // on the same thread. If that happens, then it's more performant to try to
383 // complete as much work as possible synchronously, even if it might block,
384 // rather than continually PostTask-ing to the same thread.
385 //
386 // Because NSS functions should only be called on the NSS task runner, while
387 // I/O resources should only be accessed on the network task runner, most
388 // public functions are implemented via three methods, each with different
389 // task runner affinities.
390 //
391 // In the single-threaded mode (where the network and NSS task runners run on
392 // the same thread), these are all attempted synchronously, while in the
393 // multi-threaded mode, message passing is used.
394 //
395 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite,
396 // DoHandshake)
397 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function:
398 // (BufferRecv, BufferSend)
399 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv,
400 // DoBufferSend, DoGetChannelID, OnGetChannelIDComplete)
401 // 4) Both Task Runners: Callback for asynchronous completion or to marshal
402 // data from the network task runner back to NSS (BufferRecvComplete,
403 // BufferSendComplete, OnHandshakeIOComplete)
404 //
405 /////////////////////////////////////////////////////////////////////////////
406 // Single-threaded example
407 //
408 // |--------------------------Network Task Runner--------------------------|
409 // SSLClientSocketNSS Core (Transport Socket)
410 // Read()
411 // |-------------------------V
412 // Read()
413 // |
414 // DoPayloadRead()
415 // |
416 // BufferRecv()
417 // |
418 // DoBufferRecv()
419 // |-------------------------V
420 // Read()
421 // V-------------------------|
422 // BufferRecvComplete()
423 // |
424 // PostOrRunCallback()
425 // V-------------------------|
426 // (Read Callback)
427 //
428 /////////////////////////////////////////////////////////////////////////////
429 // Multi-threaded example:
430 //
431 // |--------------------Network Task Runner-------------|--NSS Task Runner--|
432 // SSLClientSocketNSS Core Socket Core
433 // Read()
434 // |---------------------V
435 // Read()
436 // |-------------------------------V
437 // Read()
438 // |
439 // DoPayloadRead()
440 // |
441 // BufferRecv
442 // V-------------------------------|
443 // DoBufferRecv
444 // |----------------V
445 // Read()
446 // V----------------|
447 // BufferRecvComplete()
448 // |-------------------------------V
449 // BufferRecvComplete()
450 // |
451 // PostOrRunCallback()
452 // V-------------------------------|
453 // PostOrRunCallback()
454 // V---------------------|
455 // (Read Callback)
456 //
457 /////////////////////////////////////////////////////////////////////////////
458 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> {
459 public:
460 // Creates a new Core.
461 //
462 // Any calls to NSS are executed on the |nss_task_runner|, while any calls
463 // that need to operate on the underlying transport, net log, or server
464 // bound certificate fetching will happen on the |network_task_runner|, so
465 // that their lifetimes match that of the owning SSLClientSocketNSS.
466 //
467 // The caller retains ownership of |transport|, |net_log|, and
468 // |channel_id_service|, and they will not be accessed once Detach()
469 // has been called.
470 Core(base::SequencedTaskRunner* network_task_runner,
471 base::SequencedTaskRunner* nss_task_runner,
472 ClientSocketHandle* transport,
473 const HostPortPair& host_and_port,
474 const SSLConfig& ssl_config,
475 BoundNetLog* net_log,
476 ChannelIDService* channel_id_service);
477
478 // Called on the network task runner.
479 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the
480 // underlying memio implementation, to the Core. Returns true if the Core
481 // was successfully registered with the socket.
482 bool Init(PRFileDesc* socket, memio_Private* buffers);
483
484 // Called on the network task runner.
485 //
486 // Attempts to perform an SSL handshake. If the handshake cannot be
487 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on
488 // the network task runner once the handshake has completed. Otherwise,
489 // returns OK on success or a network error code on failure.
490 int Connect(const CompletionCallback& callback);
491
492 // Called on the network task runner.
493 // Signals that the resources owned by the network task runner are going
494 // away. No further callbacks will be invoked on the network task runner.
495 // May be called at any time.
496 void Detach();
497
498 // Called on the network task runner.
499 // Returns the current state of the underlying SSL socket. May be called at
500 // any time.
501 const HandshakeState& state() const { return network_handshake_state_; }
502
503 // Called on the network task runner.
504 // Read() and Write() mirror the net::Socket functions of the same name.
505 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network
506 // task runner at a later point, unless the caller calls Detach().
507 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
508 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
509
510 // Called on the network task runner.
511 bool IsConnected() const;
512 bool HasPendingAsyncOperation() const;
513 bool HasUnhandledReceivedData() const;
514 bool WasEverUsed() const;
515
516 // Called on the network task runner.
517 // Causes the associated SSL/TLS session ID to be added to NSS's session
518 // cache, but only if the connection has not been False Started.
519 //
520 // This should only be called after the server's certificate has been
521 // verified, and may not be called within an NSS callback.
522 void CacheSessionIfNecessary();
523
524 crypto::ECPrivateKey* GetChannelIDKey() const {
525 return channel_id_key_.get();
526 }
527
528 private:
529 friend class base::RefCountedThreadSafe<Core>;
530 ~Core();
531
532 enum State {
533 STATE_NONE,
534 STATE_HANDSHAKE,
535 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE,
536 };
537
538 bool OnNSSTaskRunner() const;
539 bool OnNetworkTaskRunner() const;
540
541 ////////////////////////////////////////////////////////////////////////////
542 // Methods that are ONLY called on the NSS task runner:
543 ////////////////////////////////////////////////////////////////////////////
544
545 // Called by NSS during full handshakes to allow the application to
546 // verify the certificate. Instead of verifying the certificate in the midst
547 // of the handshake, SECSuccess is always returned and the peer's certificate
548 // is verified afterwards.
549 // This behaviour is an artifact of the original SSLClientSocketWin
550 // implementation, which could not verify the peer's certificate until after
551 // the handshake had completed, as well as bugs in NSS that prevent
552 // SSL_RestartHandshakeAfterCertReq from working.
553 static SECStatus OwnAuthCertHandler(void* arg,
554 PRFileDesc* socket,
555 PRBool checksig,
556 PRBool is_server);
557
558 // Callbacks called by NSS when the peer requests client certificate
559 // authentication.
560 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of
561 // the arguments.
562 static SECStatus ClientAuthHandler(void* arg,
563 PRFileDesc* socket,
564 CERTDistNames* ca_names,
565 CERTCertificate** result_certificate,
566 SECKEYPrivateKey** result_private_key);
567
568 // Called by NSS to determine if we can False Start.
569 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
570 static SECStatus CanFalseStartCallback(PRFileDesc* socket,
571 void* arg,
572 PRBool* can_false_start);
573
574 // Called by NSS each time a handshake completely finishes.
575 // |arg| contains a pointer to the current SSLClientSocketNSS::Core.
576 static void HandshakeCallback(PRFileDesc* socket, void* arg);
577
578 // Called once for each successful handshake. If the initial handshake false
579 // starts, it is called when it false starts and not when it completely
580 // finishes. is_initial is true if this is the initial handshake.
581 void HandshakeSucceeded(bool is_initial);
582
583 // Handles an NSS error generated while handshaking or performing IO.
584 // Returns a network error code mapped from the original NSS error.
585 int HandleNSSError(PRErrorCode error);
586
587 int DoHandshakeLoop(int last_io_result);
588 int DoReadLoop(int result);
589 int DoWriteLoop(int result);
590
591 int DoHandshake();
592 int DoGetDBCertComplete(int result);
593
594 int DoPayloadRead();
595 int DoPayloadWrite();
596
597 bool DoTransportIO();
598 int BufferRecv();
599 int BufferSend();
600
601 void OnRecvComplete(int result);
602 void OnSendComplete(int result);
603
604 void DoConnectCallback(int result);
605 void DoReadCallback(int result);
606 void DoWriteCallback(int result);
607
608 // Client channel ID handler.
609 static SECStatus ClientChannelIDHandler(
610 void* arg,
611 PRFileDesc* socket,
612 SECKEYPublicKey **out_public_key,
613 SECKEYPrivateKey **out_private_key);
614
615 // ImportChannelIDKeys is a helper function for turning a DER-encoded cert and
616 // key into a SECKEYPublicKey and SECKEYPrivateKey. Returns OK upon success
617 // and an error code otherwise.
618 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been
619 // set by a call to ChannelIDService->GetChannelID. The caller
620 // takes ownership of the |*cert| and |*key|.
621 int ImportChannelIDKeys(SECKEYPublicKey** public_key, SECKEYPrivateKey** key);
622
623 // Updates the NSS and platform specific certificates.
624 void UpdateServerCert();
625 // Update the nss_handshake_state_ with the SignedCertificateTimestampList
626 // received in the handshake via a TLS extension.
627 void UpdateSignedCertTimestamps();
628 // Update the OCSP response cache with the stapled response received in the
629 // handshake, and update nss_handshake_state_ with
630 // the SignedCertificateTimestampList received in the stapled OCSP response.
631 void UpdateStapledOCSPResponse();
632 // Updates the nss_handshake_state_ with the negotiated security parameters.
633 void UpdateConnectionStatus();
634 // Record histograms for channel id support during full handshakes - resumed
635 // handshakes are ignored.
636 void RecordChannelIDSupportOnNSSTaskRunner();
637 // UpdateNextProto gets any application-layer protocol that may have been
638 // negotiated by the TLS connection.
639 void UpdateNextProto();
640 // Record TLS extension used for protocol negotiation (NPN or ALPN).
641 void UpdateExtensionUsed();
642
643 // Returns true if renegotiations are allowed.
644 bool IsRenegotiationAllowed() const;
645
646 ////////////////////////////////////////////////////////////////////////////
647 // Methods that are ONLY called on the network task runner:
648 ////////////////////////////////////////////////////////////////////////////
649 int DoBufferRecv(IOBuffer* buffer, int len);
650 int DoBufferSend(IOBuffer* buffer, int len);
651 int DoGetChannelID(const std::string& host);
652
653 void OnGetChannelIDComplete(int result);
654 void OnHandshakeStateUpdated(const HandshakeState& state);
655 void OnNSSBufferUpdated(int amount_in_read_buffer);
656 void DidNSSRead(int result);
657 void DidNSSWrite(int result);
658 void RecordChannelIDSupportOnNetworkTaskRunner(bool negotiated_channel_id,
659 bool channel_id_enabled) const;
660
661 ////////////////////////////////////////////////////////////////////////////
662 // Methods that are called on both the network task runner and the NSS
663 // task runner.
664 ////////////////////////////////////////////////////////////////////////////
665 void OnHandshakeIOComplete(int result);
666 void BufferRecvComplete(IOBuffer* buffer, int result);
667 void BufferSendComplete(int result);
668
669 // PostOrRunCallback is a helper function to ensure that |callback| is
670 // invoked on the network task runner, but only if Detach() has not yet
671 // been called.
672 void PostOrRunCallback(const tracked_objects::Location& location,
673 const base::Closure& callback);
674
675 // Uses PostOrRunCallback and |weak_net_log_| to try and log a
676 // SSL_CLIENT_CERT_PROVIDED event, with the indicated count.
677 void AddCertProvidedEvent(int cert_count);
678
679 // Sets the handshake state |channel_id_sent| flag and logs the
680 // SSL_CHANNEL_ID_PROVIDED event.
681 void SetChannelIDProvided();
682
683 ////////////////////////////////////////////////////////////////////////////
684 // Members that are ONLY accessed on the network task runner:
685 ////////////////////////////////////////////////////////////////////////////
686
687 // True if the owning SSLClientSocketNSS has called Detach(). No further
688 // callbacks will be invoked nor access to members owned by the network
689 // task runner.
690 bool detached_;
691
692 // The underlying transport to use for network IO.
693 ClientSocketHandle* transport_;
694 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_;
695
696 // The current handshake state. Mirrors |nss_handshake_state_|.
697 HandshakeState network_handshake_state_;
698
699 // The service for retrieving Channel ID keys. May be NULL.
700 ChannelIDService* channel_id_service_;
701 ChannelIDService::Request channel_id_request_;
702
703 // The information about NSS task runner.
704 int unhandled_buffer_size_;
705 bool nss_waiting_read_;
706 bool nss_waiting_write_;
707 bool nss_is_closed_;
708
709 // Set when Read() or Write() successfully reads or writes data to or from the
710 // network.
711 bool was_ever_used_;
712
713 ////////////////////////////////////////////////////////////////////////////
714 // Members that are ONLY accessed on the NSS task runner:
715 ////////////////////////////////////////////////////////////////////////////
716 HostPortPair host_and_port_;
717 SSLConfig ssl_config_;
718
719 // NSS SSL socket.
720 PRFileDesc* nss_fd_;
721
722 // Buffers for the network end of the SSL state machine
723 memio_Private* nss_bufs_;
724
725 // Used by DoPayloadRead() when attempting to fill the caller's buffer with
726 // as much data as possible, without blocking.
727 // If DoPayloadRead() encounters an error after having read some data, stores
728 // the results to return on the *next* call to DoPayloadRead(). A value of
729 // kNoPendingReadResult indicates there is no pending result, otherwise 0
730 // indicates EOF and < 0 indicates an error.
731 int pending_read_result_;
732 // Contains the previously observed NSS error. Only valid when
733 // pending_read_result_ != kNoPendingReadResult.
734 PRErrorCode pending_read_nss_error_;
735
736 // The certificate chain, in DER form, that is expected to be received from
737 // the server.
738 std::vector<std::string> predicted_certs_;
739
740 State next_handshake_state_;
741
742 // True if channel ID extension was negotiated.
743 bool channel_id_xtn_negotiated_;
744 // True if the handshake state machine was interrupted for channel ID.
745 bool channel_id_needed_;
746 // True if the handshake state machine was interrupted for client auth.
747 bool client_auth_cert_needed_;
748 // True if NSS has False Started in the initial handshake, but the initial
749 // handshake has not yet completely finished..
750 bool false_started_;
751 // True if NSS has called HandshakeCallback.
752 bool handshake_callback_called_;
753
754 HandshakeState nss_handshake_state_;
755
756 bool transport_recv_busy_;
757 bool transport_recv_eof_;
758 bool transport_send_busy_;
759
760 // Used by Read function.
761 scoped_refptr<IOBuffer> user_read_buf_;
762 int user_read_buf_len_;
763
764 // Used by Write function.
765 scoped_refptr<IOBuffer> user_write_buf_;
766 int user_write_buf_len_;
767
768 CompletionCallback user_connect_callback_;
769 CompletionCallback user_read_callback_;
770 CompletionCallback user_write_callback_;
771
772 ////////////////////////////////////////////////////////////////////////////
773 // Members that are accessed on both the network task runner and the NSS
774 // task runner.
775 ////////////////////////////////////////////////////////////////////////////
776 scoped_refptr<base::SequencedTaskRunner> network_task_runner_;
777 scoped_refptr<base::SequencedTaskRunner> nss_task_runner_;
778
779 // Dereferenced only on the network task runner, but bound to tasks destined
780 // for the network task runner from the NSS task runner.
781 base::WeakPtr<BoundNetLog> weak_net_log_;
782
783 // Written on the network task runner by the |channel_id_service_|,
784 // prior to invoking OnHandshakeIOComplete.
785 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked
786 // on the NSS task runner.
787 std::unique_ptr<crypto::ECPrivateKey> channel_id_key_;
788
789 DISALLOW_COPY_AND_ASSIGN(Core);
790 };
791
792 SSLClientSocketNSS::Core::Core(
793 base::SequencedTaskRunner* network_task_runner,
794 base::SequencedTaskRunner* nss_task_runner,
795 ClientSocketHandle* transport,
796 const HostPortPair& host_and_port,
797 const SSLConfig& ssl_config,
798 BoundNetLog* net_log,
799 ChannelIDService* channel_id_service)
800 : detached_(false),
801 transport_(transport),
802 weak_net_log_factory_(net_log),
803 channel_id_service_(channel_id_service),
804 unhandled_buffer_size_(0),
805 nss_waiting_read_(false),
806 nss_waiting_write_(false),
807 nss_is_closed_(false),
808 was_ever_used_(false),
809 host_and_port_(host_and_port),
810 ssl_config_(ssl_config),
811 nss_fd_(NULL),
812 nss_bufs_(NULL),
813 pending_read_result_(kNoPendingReadResult),
814 pending_read_nss_error_(0),
815 next_handshake_state_(STATE_NONE),
816 channel_id_xtn_negotiated_(false),
817 channel_id_needed_(false),
818 client_auth_cert_needed_(false),
819 false_started_(false),
820 handshake_callback_called_(false),
821 transport_recv_busy_(false),
822 transport_recv_eof_(false),
823 transport_send_busy_(false),
824 user_read_buf_len_(0),
825 user_write_buf_len_(0),
826 network_task_runner_(network_task_runner),
827 nss_task_runner_(nss_task_runner),
828 weak_net_log_(weak_net_log_factory_.GetWeakPtr()) {
829 }
830
831 SSLClientSocketNSS::Core::~Core() {
832 // TODO(wtc): Send SSL close_notify alert.
833 if (nss_fd_ != NULL) {
834 PR_Close(nss_fd_);
835 nss_fd_ = NULL;
836 }
837 nss_bufs_ = NULL;
838 }
839
840 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket,
841 memio_Private* buffers) {
842 DCHECK(OnNetworkTaskRunner());
843 DCHECK(!nss_fd_);
844 DCHECK(!nss_bufs_);
845
846 nss_fd_ = socket;
847 nss_bufs_ = buffers;
848
849 SECStatus rv = SECSuccess;
850
851 if (!ssl_config_.alpn_protos.empty()) {
852 NextProtoVector alpn_protos = ssl_config_.alpn_protos;
853 // TODO(bnc): Check ssl_config_.disabled_cipher_suites.
854 if (!IsTLSVersionAdequateForHTTP2(ssl_config_))
855 DisableHTTP2(&alpn_protos);
856 // |ssl_config_| has fallback protocol at the end of the list, but NSS
857 // expects fallback at the first place, thus protocols need to be reordered.
858 ReorderNextProtos(&alpn_protos);
859 // NSS only supports a single protocol vector to be used with ALPN and NPN.
860 // Because of this limitation, |alpn_prototos| will be used for both.
861 // However, it is possible to enable ALPN and NPN separately.
862 std::vector<uint8_t> wire_protos = SerializeNextProtos(alpn_protos);
863 rv = SSL_SetNextProtoNego(
864 nss_fd_, wire_protos.empty() ? NULL : &wire_protos[0],
865 wire_protos.size());
866 if (rv != SECSuccess)
867 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoNego", "");
868 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_ALPN, PR_TRUE);
869 if (rv != SECSuccess)
870 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_ALPN");
871 if (!ssl_config_.npn_protos.empty()) {
872 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_NPN, PR_TRUE);
873 if (rv != SECSuccess)
874 LogFailedNSSFunction(*weak_net_log_, "SSL_OptionSet", "SSL_ENABLE_NPN");
875 }
876 }
877
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;
883 }
884
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;
890 }
891
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", "");
898 }
899 }
900
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;
906 }
907
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;
913 }
914
915 return true;
916 }
917
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;
925 }
926
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());
934
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;
941 }
942 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) {
943 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
944 return ERR_IO_PENDING;
945 }
946
947 return rv;
948 }
949
950 void SSLClientSocketNSS::Core::Detach() {
951 DCHECK(OnNetworkTaskRunner());
952
953 detached_ = true;
954 transport_ = NULL;
955 weak_net_log_factory_.InvalidateWeakPtrs();
956
957 network_handshake_state_.Reset();
958
959 channel_id_request_.Cancel();
960 }
961
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_);
969
970 nss_waiting_read_ = true;
971 bool posted = nss_task_runner_->PostTask(
972 FROM_HERE, base::Bind(IgnoreResult(&Core::Read), this,
973 base::RetainedRef(buf), buf_len, callback));
974 if (!posted) {
975 nss_is_closed_ = true;
976 nss_waiting_read_ = false;
977 }
978 return posted ? ERR_IO_PENDING : ERR_ABORTED;
979 }
980
981 DCHECK(OnNSSTaskRunner());
982 DCHECK(false_started_ || handshake_callback_called_);
983 DCHECK_EQ(STATE_NONE, next_handshake_state_);
984 DCHECK(user_read_callback_.is_null());
985 DCHECK(user_connect_callback_.is_null());
986 DCHECK(!user_read_buf_.get());
987 DCHECK(nss_bufs_);
988
989 user_read_buf_ = buf;
990 user_read_buf_len_ = buf_len;
991
992 int rv = DoReadLoop(OK);
993 if (rv == ERR_IO_PENDING) {
994 if (OnNetworkTaskRunner())
995 nss_waiting_read_ = true;
996 user_read_callback_ = callback;
997 } else {
998 user_read_buf_ = NULL;
999 user_read_buf_len_ = 0;
1000
1001 if (!OnNetworkTaskRunner()) {
1002 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSRead, this, rv));
1003 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1004 return ERR_IO_PENDING;
1005 } else {
1006 DCHECK(!nss_waiting_read_);
1007 if (rv <= 0) {
1008 nss_is_closed_ = true;
1009 } else {
1010 was_ever_used_ = true;
1011 }
1012 }
1013 }
1014
1015 return rv;
1016 }
1017
1018 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len,
1019 const CompletionCallback& callback) {
1020 if (!OnNSSTaskRunner()) {
1021 DCHECK(OnNetworkTaskRunner());
1022 DCHECK(!detached_);
1023 DCHECK(transport_);
1024 DCHECK(!nss_waiting_write_);
1025
1026 nss_waiting_write_ = true;
1027 bool posted = nss_task_runner_->PostTask(
1028 FROM_HERE, base::Bind(IgnoreResult(&Core::Write), this,
1029 base::RetainedRef(buf), buf_len, callback));
1030 if (!posted) {
1031 nss_is_closed_ = true;
1032 nss_waiting_write_ = false;
1033 }
1034 return posted ? ERR_IO_PENDING : ERR_ABORTED;
1035 }
1036
1037 DCHECK(OnNSSTaskRunner());
1038 DCHECK(false_started_ || handshake_callback_called_);
1039 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1040 DCHECK(user_write_callback_.is_null());
1041 DCHECK(user_connect_callback_.is_null());
1042 DCHECK(!user_write_buf_.get());
1043 DCHECK(nss_bufs_);
1044
1045 user_write_buf_ = buf;
1046 user_write_buf_len_ = buf_len;
1047
1048 int rv = DoWriteLoop(OK);
1049 if (rv == ERR_IO_PENDING) {
1050 if (OnNetworkTaskRunner())
1051 nss_waiting_write_ = true;
1052 user_write_callback_ = callback;
1053 } else {
1054 user_write_buf_ = NULL;
1055 user_write_buf_len_ = 0;
1056
1057 if (!OnNetworkTaskRunner()) {
1058 PostOrRunCallback(FROM_HERE, base::Bind(&Core::DidNSSWrite, this, rv));
1059 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv));
1060 return ERR_IO_PENDING;
1061 } else {
1062 DCHECK(!nss_waiting_write_);
1063 if (rv < 0) {
1064 nss_is_closed_ = true;
1065 } else if (rv > 0) {
1066 was_ever_used_ = true;
1067 }
1068 }
1069 }
1070
1071 return rv;
1072 }
1073
1074 bool SSLClientSocketNSS::Core::IsConnected() const {
1075 DCHECK(OnNetworkTaskRunner());
1076 return !nss_is_closed_;
1077 }
1078
1079 bool SSLClientSocketNSS::Core::HasPendingAsyncOperation() const {
1080 DCHECK(OnNetworkTaskRunner());
1081 return nss_waiting_read_ || nss_waiting_write_;
1082 }
1083
1084 bool SSLClientSocketNSS::Core::HasUnhandledReceivedData() const {
1085 DCHECK(OnNetworkTaskRunner());
1086 return unhandled_buffer_size_ != 0;
1087 }
1088
1089 bool SSLClientSocketNSS::Core::WasEverUsed() const {
1090 DCHECK(OnNetworkTaskRunner());
1091 return was_ever_used_;
1092 }
1093
1094 void SSLClientSocketNSS::Core::CacheSessionIfNecessary() {
1095 // TODO(rsleevi): This should occur on the NSS task runner, due to the use of
1096 // nss_fd_. However, it happens on the network task runner in order to match
1097 // the buggy behavior of ExportKeyingMaterial.
1098 //
1099 // Once http://crbug.com/330360 is fixed, this should be moved to an
1100 // implementation that exclusively does this work on the NSS TaskRunner. This
1101 // is "safe" because it is only called during the certificate verification
1102 // state machine of the main socket, which is safe because no underlying
1103 // transport IO will be occuring in that state, and NSS will not be blocking
1104 // on any PKCS#11 related locks that might block the Network TaskRunner.
1105 DCHECK(OnNetworkTaskRunner());
1106
1107 // Only cache the session if the connection was not False Started, because
1108 // sessions should only be cached *after* the peer's Finished message is
1109 // processed.
1110 // In the case of False Start, the session will be cached once the
1111 // HandshakeCallback is called, which signals the receipt and processing of
1112 // the Finished message, and which will happen during a call to
1113 // PR_Read/PR_Write.
1114 if (!false_started_)
1115 SSL_CacheSession(nss_fd_);
1116 }
1117
1118 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const {
1119 return nss_task_runner_->RunsTasksOnCurrentThread();
1120 }
1121
1122 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const {
1123 return network_task_runner_->RunsTasksOnCurrentThread();
1124 }
1125
1126 // static
1127 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler(
1128 void* arg,
1129 PRFileDesc* socket,
1130 PRBool checksig,
1131 PRBool is_server) {
1132 Core* core = reinterpret_cast<Core*>(arg);
1133 if (core->handshake_callback_called_) {
1134 // Disallow the server certificate to change in a renegotiation.
1135 CERTCertificate* old_cert = core->nss_handshake_state_.server_cert_chain[0];
1136 ScopedCERTCertificate new_cert(SSL_PeerCertificate(socket));
1137 if (new_cert->derCert.len != old_cert->derCert.len ||
1138 memcmp(new_cert->derCert.data, old_cert->derCert.data,
1139 new_cert->derCert.len) != 0) {
1140 // NSS doesn't have an error code that indicates the server certificate
1141 // changed. Borrow SSL_ERROR_WRONG_CERTIFICATE (which NSS isn't using)
1142 // for this purpose.
1143 PORT_SetError(SSL_ERROR_WRONG_CERTIFICATE);
1144 return SECFailure;
1145 }
1146 }
1147
1148 // Tell NSS to not verify the certificate.
1149 return SECSuccess;
1150 }
1151
1152 #if defined(OS_IOS)
1153
1154 // static
1155 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1156 void* arg,
1157 PRFileDesc* socket,
1158 CERTDistNames* ca_names,
1159 CERTCertificate** result_certificate,
1160 SECKEYPrivateKey** result_private_key) {
1161 Core* core = reinterpret_cast<Core*>(arg);
1162 DCHECK(core->OnNSSTaskRunner());
1163
1164 core->PostOrRunCallback(
1165 FROM_HERE,
1166 base::Bind(&AddLogEvent, core->weak_net_log_,
1167 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1168
1169 // TODO(droger): Support client auth on iOS. See http://crbug.com/145954).
1170 LOG(WARNING) << "Client auth is not supported";
1171
1172 // Never send a certificate.
1173 core->AddCertProvidedEvent(0);
1174 return SECFailure;
1175 }
1176
1177 #else // !OS_IOS
1178
1179 // static
1180 // Based on Mozilla's NSS_GetClientAuthData.
1181 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler(
1182 void* arg,
1183 PRFileDesc* socket,
1184 CERTDistNames* ca_names,
1185 CERTCertificate** result_certificate,
1186 SECKEYPrivateKey** result_private_key) {
1187 Core* core = reinterpret_cast<Core*>(arg);
1188 DCHECK(core->OnNSSTaskRunner());
1189
1190 core->PostOrRunCallback(
1191 FROM_HERE,
1192 base::Bind(&AddLogEvent, core->weak_net_log_,
1193 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED));
1194
1195 // Regular client certificate requested.
1196 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert;
1197 void* wincx = SSL_RevealPinArg(socket);
1198
1199 if (core->ssl_config_.send_client_cert) {
1200 // Second pass: a client certificate should have been selected.
1201 if (core->ssl_config_.client_cert.get()) {
1202 CERTCertificate* cert =
1203 CERT_DupCertificate(core->ssl_config_.client_cert->os_cert_handle());
1204 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx);
1205 if (privkey) {
1206 // TODO(jsorianopastor): We should wait for server certificate
1207 // verification before sending our credentials. See
1208 // http://crbug.com/13934.
1209 *result_certificate = cert;
1210 *result_private_key = privkey;
1211 // A cert_count of -1 means the number of certificates is unknown.
1212 // NSS will construct the certificate chain.
1213 core->AddCertProvidedEvent(-1);
1214
1215 return SECSuccess;
1216 }
1217 LOG(WARNING) << "Client cert found without private key";
1218 }
1219 // Send no client certificate.
1220 core->AddCertProvidedEvent(0);
1221 return SECFailure;
1222 }
1223
1224 // First pass: client certificate is needed.
1225 core->nss_handshake_state_.cert_authorities.clear();
1226
1227 // Retrieve the DER-encoded DistinguishedName of the cert issuers accepted by
1228 // the server and save them in |cert_authorities|.
1229 for (int i = 0; i < ca_names->nnames; i++) {
1230 core->nss_handshake_state_.cert_authorities.push_back(std::string(
1231 reinterpret_cast<const char*>(ca_names->names[i].data),
1232 static_cast<size_t>(ca_names->names[i].len)));
1233 }
1234
1235 // Update the network task runner's view of the handshake state now that
1236 // server certificate request has been recorded.
1237 core->PostOrRunCallback(
1238 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core,
1239 core->nss_handshake_state_));
1240
1241 // Tell NSS to suspend the client authentication. We will then abort the
1242 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED.
1243 return SECWouldBlock;
1244 }
1245 #endif // OS_IOS
1246
1247 // static
1248 SECStatus SSLClientSocketNSS::Core::CanFalseStartCallback(
1249 PRFileDesc* socket,
1250 void* arg,
1251 PRBool* can_false_start) {
1252 // If the server doesn't support NPN or ALPN, then we don't do False
1253 // Start with it.
1254 PRBool negotiated_extension;
1255 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket,
1256 ssl_app_layer_protocol_xtn,
1257 &negotiated_extension);
1258 if (rv != SECSuccess || !negotiated_extension) {
1259 rv = SSL_HandshakeNegotiatedExtension(socket,
1260 ssl_next_proto_nego_xtn,
1261 &negotiated_extension);
1262 }
1263 if (rv != SECSuccess || !negotiated_extension) {
1264 *can_false_start = PR_FALSE;
1265 return SECSuccess;
1266 }
1267
1268 SSLChannelInfo channel_info;
1269 SECStatus ok =
1270 SSL_GetChannelInfo(socket, &channel_info, sizeof(channel_info));
1271 if (ok != SECSuccess || channel_info.length != sizeof(channel_info) ||
1272 channel_info.protocolVersion < SSL_LIBRARY_VERSION_TLS_1_2 ||
1273 !IsSecureTLSCipherSuite(channel_info.cipherSuite)) {
1274 *can_false_start = PR_FALSE;
1275 return SECSuccess;
1276 }
1277
1278 return SSL_RecommendedCanFalseStart(socket, can_false_start);
1279 }
1280
1281 // static
1282 void SSLClientSocketNSS::Core::HandshakeCallback(
1283 PRFileDesc* socket,
1284 void* arg) {
1285 Core* core = reinterpret_cast<Core*>(arg);
1286 DCHECK(core->OnNSSTaskRunner());
1287
1288 bool is_initial = !core->handshake_callback_called_;
1289 core->handshake_callback_called_ = true;
1290 if (core->false_started_) {
1291 core->false_started_ = false;
1292 // If the connection was False Started, then at the time of this callback,
1293 // the peer's certificate will have been verified or the caller will have
1294 // accepted the error.
1295 // This is guaranteed when using False Start because this callback will
1296 // not be invoked until processing the peer's Finished message, which
1297 // will only happen in a PR_Read/PR_Write call, which can only happen
1298 // after the peer's certificate is verified.
1299 SSL_CacheSessionUnlocked(socket);
1300
1301 // Additionally, when False Starting, DoHandshake() will have already
1302 // called HandshakeSucceeded(), so return now.
1303 return;
1304 }
1305 core->HandshakeSucceeded(is_initial);
1306 }
1307
1308 void SSLClientSocketNSS::Core::HandshakeSucceeded(bool is_initial) {
1309 DCHECK(OnNSSTaskRunner());
1310
1311 PRBool last_handshake_resumed;
1312 SECStatus rv = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed);
1313 if (rv == SECSuccess && last_handshake_resumed) {
1314 nss_handshake_state_.resumed_handshake = true;
1315 } else {
1316 nss_handshake_state_.resumed_handshake = false;
1317 }
1318
1319 RecordChannelIDSupportOnNSSTaskRunner();
1320 UpdateServerCert();
1321 UpdateSignedCertTimestamps();
1322 UpdateStapledOCSPResponse();
1323 UpdateConnectionStatus();
1324 UpdateNextProto();
1325 UpdateExtensionUsed();
1326
1327 if (is_initial && IsRenegotiationAllowed()) {
1328 // For compatibility, do not enforce RFC 5746 support. Per section 4.1,
1329 // enforcement falls largely on the server.
1330 //
1331 // This is done in a callback rather than after SSL_ForceHandshake returns
1332 // because SSL_ForceHandshake will otherwise greedly consume renegotiations
1333 // before returning if Finished and HelloRequest are in the same
1334 // record.
1335 //
1336 // Note that SSL_OptionSet should only be called for an initial
1337 // handshake. See https://crbug.com/125299.
1338 SECStatus rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION,
1339 SSL_RENEGOTIATE_TRANSITIONAL);
1340 DCHECK_EQ(SECSuccess, rv);
1341 }
1342
1343 // Update the network task runners view of the handshake state whenever
1344 // a handshake has completed.
1345 PostOrRunCallback(
1346 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
1347 nss_handshake_state_));
1348 }
1349
1350 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error) {
1351 DCHECK(OnNSSTaskRunner());
1352
1353 return MapNSSClientError(nss_error);
1354 }
1355
1356 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) {
1357 DCHECK(OnNSSTaskRunner());
1358
1359 int rv = last_io_result;
1360 do {
1361 // Default to STATE_NONE for next state.
1362 State state = next_handshake_state_;
1363 GotoState(STATE_NONE);
1364
1365 switch (state) {
1366 case STATE_HANDSHAKE:
1367 rv = DoHandshake();
1368 break;
1369 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE:
1370 rv = DoGetDBCertComplete(rv);
1371 break;
1372 case STATE_NONE:
1373 default:
1374 rv = ERR_UNEXPECTED;
1375 LOG(DFATAL) << "unexpected state " << state;
1376 break;
1377 }
1378
1379 // Do the actual network I/O
1380 bool network_moved = DoTransportIO();
1381 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) {
1382 // In general we exit the loop if rv is ERR_IO_PENDING. In this
1383 // special case we keep looping even if rv is ERR_IO_PENDING because
1384 // the transport IO may allow DoHandshake to make progress.
1385 DCHECK(rv == OK || rv == ERR_IO_PENDING);
1386 rv = OK; // This causes us to stay in the loop.
1387 }
1388 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
1389 return rv;
1390 }
1391
1392 int SSLClientSocketNSS::Core::DoReadLoop(int result) {
1393 DCHECK(OnNSSTaskRunner());
1394 DCHECK(false_started_ || handshake_callback_called_);
1395 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1396
1397 if (result < 0)
1398 return result;
1399
1400 if (!nss_bufs_) {
1401 LOG(DFATAL) << "!nss_bufs_";
1402 int rv = ERR_UNEXPECTED;
1403 PostOrRunCallback(
1404 FROM_HERE,
1405 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1406 NetLog::TYPE_SSL_READ_ERROR,
1407 CreateNetLogSSLErrorCallback(rv, 0)));
1408 return rv;
1409 }
1410
1411 bool network_moved;
1412 int rv;
1413 do {
1414 rv = DoPayloadRead();
1415 network_moved = DoTransportIO();
1416 } while (rv == ERR_IO_PENDING && network_moved);
1417
1418 return rv;
1419 }
1420
1421 int SSLClientSocketNSS::Core::DoWriteLoop(int result) {
1422 DCHECK(OnNSSTaskRunner());
1423 DCHECK(false_started_ || handshake_callback_called_);
1424 DCHECK_EQ(STATE_NONE, next_handshake_state_);
1425
1426 if (result < 0)
1427 return result;
1428
1429 if (!nss_bufs_) {
1430 LOG(DFATAL) << "!nss_bufs_";
1431 int rv = ERR_UNEXPECTED;
1432 PostOrRunCallback(
1433 FROM_HERE,
1434 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1435 NetLog::TYPE_SSL_READ_ERROR,
1436 CreateNetLogSSLErrorCallback(rv, 0)));
1437 return rv;
1438 }
1439
1440 bool network_moved;
1441 int rv;
1442 do {
1443 rv = DoPayloadWrite();
1444 network_moved = DoTransportIO();
1445 } while (rv == ERR_IO_PENDING && network_moved);
1446
1447 LeaveFunction(rv);
1448 return rv;
1449 }
1450
1451 int SSLClientSocketNSS::Core::DoHandshake() {
1452 DCHECK(OnNSSTaskRunner());
1453
1454 int net_error = OK;
1455 SECStatus rv = SSL_ForceHandshake(nss_fd_);
1456
1457 // Note: this function may be called multiple times during the handshake, so
1458 // even though channel id and client auth are separate else cases, they can
1459 // both be used during a single SSL handshake.
1460 if (channel_id_needed_) {
1461 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE);
1462 net_error = ERR_IO_PENDING;
1463 } else if (client_auth_cert_needed_) {
1464 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1465 PostOrRunCallback(
1466 FROM_HERE,
1467 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1468 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1469 CreateNetLogSSLErrorCallback(net_error, 0)));
1470 } else if (rv == SECSuccess) {
1471 if (!handshake_callback_called_) {
1472 false_started_ = true;
1473 HandshakeSucceeded(true);
1474 }
1475 } else {
1476 PRErrorCode prerr = PR_GetError();
1477 net_error = HandleNSSError(prerr);
1478
1479 // If not done, stay in this state
1480 if (net_error == ERR_IO_PENDING) {
1481 GotoState(STATE_HANDSHAKE);
1482 } else {
1483 PostOrRunCallback(
1484 FROM_HERE,
1485 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1486 NetLog::TYPE_SSL_HANDSHAKE_ERROR,
1487 CreateNetLogSSLErrorCallback(net_error, prerr)));
1488 }
1489 }
1490
1491 return net_error;
1492 }
1493
1494 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) {
1495 SECStatus rv;
1496 PostOrRunCallback(
1497 FROM_HERE,
1498 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_,
1499 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result));
1500
1501 channel_id_needed_ = false;
1502
1503 if (result != OK)
1504 return result;
1505
1506 SECKEYPublicKey* public_key;
1507 SECKEYPrivateKey* private_key;
1508 int error = ImportChannelIDKeys(&public_key, &private_key);
1509 if (error != OK)
1510 return error;
1511
1512 rv = SSL_RestartHandshakeAfterChannelIDReq(nss_fd_, public_key, private_key);
1513 if (rv != SECSuccess)
1514 return MapNSSError(PORT_GetError());
1515
1516 SetChannelIDProvided();
1517 GotoState(STATE_HANDSHAKE);
1518 return OK;
1519 }
1520
1521 int SSLClientSocketNSS::Core::DoPayloadRead() {
1522 DCHECK(OnNSSTaskRunner());
1523 DCHECK(user_read_buf_.get());
1524 DCHECK_GT(user_read_buf_len_, 0);
1525
1526 int rv;
1527 // If a previous greedy read resulted in an error that was not consumed (eg:
1528 // due to the caller having read some data successfully), then return that
1529 // pending error now.
1530 if (pending_read_result_ != kNoPendingReadResult) {
1531 rv = pending_read_result_;
1532 PRErrorCode prerr = pending_read_nss_error_;
1533 pending_read_result_ = kNoPendingReadResult;
1534 pending_read_nss_error_ = 0;
1535
1536 if (rv == 0) {
1537 PostOrRunCallback(FROM_HERE,
1538 base::Bind(&LogByteTransferEvent, weak_net_log_,
1539 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1540 base::RetainedRef(user_read_buf_)));
1541 } else {
1542 PostOrRunCallback(
1543 FROM_HERE,
1544 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1545 NetLog::TYPE_SSL_READ_ERROR,
1546 CreateNetLogSSLErrorCallback(rv, prerr)));
1547 }
1548 return rv;
1549 }
1550
1551 // Perform a greedy read, attempting to read as much as the caller has
1552 // requested. In the current NSS implementation, PR_Read will return
1553 // exactly one SSL application data record's worth of data per invocation.
1554 // The record size is dictated by the server, and may be noticeably smaller
1555 // than the caller's buffer. This may be as little as a single byte, if the
1556 // server is performing 1/n-1 record splitting.
1557 //
1558 // However, this greedy read may result in renegotiations/re-handshakes
1559 // happening or may lead to some data being read, followed by an EOF (such as
1560 // a TLS close-notify). If at least some data was read, then that result
1561 // should be deferred until the next call to DoPayloadRead(). Otherwise, if no
1562 // data was read, it's safe to return the error or EOF immediately.
1563 int total_bytes_read = 0;
1564 do {
1565 rv = PR_Read(nss_fd_, user_read_buf_->data() + total_bytes_read,
1566 user_read_buf_len_ - total_bytes_read);
1567 if (rv > 0)
1568 total_bytes_read += rv;
1569 } while (total_bytes_read < user_read_buf_len_ && rv > 0);
1570 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1571 PostOrRunCallback(FROM_HERE, base::Bind(&Core::OnNSSBufferUpdated, this,
1572 amount_in_read_buffer));
1573
1574 if (total_bytes_read == user_read_buf_len_) {
1575 // The caller's entire request was satisfied without error. No further
1576 // processing needed.
1577 rv = total_bytes_read;
1578 } else {
1579 // Otherwise, an error occurred (rv <= 0). The error needs to be handled
1580 // immediately, while the NSPR/NSS errors are still available in
1581 // thread-local storage. However, the handled/remapped error code should
1582 // only be returned if no application data was already read; if it was, the
1583 // error code should be deferred until the next call of DoPayloadRead.
1584 //
1585 // If no data was read, |*next_result| will point to the return value of
1586 // this function. If at least some data was read, |*next_result| will point
1587 // to |pending_read_error_|, to be returned in a future call to
1588 // DoPayloadRead() (e.g.: after the current data is handled).
1589 int* next_result = &rv;
1590 if (total_bytes_read > 0) {
1591 pending_read_result_ = rv;
1592 rv = total_bytes_read;
1593 next_result = &pending_read_result_;
1594 }
1595
1596 if (client_auth_cert_needed_) {
1597 *next_result = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
1598 pending_read_nss_error_ = 0;
1599 } else if (*next_result < 0) {
1600 // If *next_result == 0, then that indicates EOF, and no special error
1601 // handling is needed.
1602 pending_read_nss_error_ = PR_GetError();
1603 *next_result = HandleNSSError(pending_read_nss_error_);
1604 if (rv > 0 && *next_result == ERR_IO_PENDING) {
1605 // If at least some data was read from PR_Read(), do not treat
1606 // insufficient data as an error to return in the next call to
1607 // DoPayloadRead() - instead, let the call fall through to check
1608 // PR_Read() again. This is because DoTransportIO() may complete
1609 // in between the next call to DoPayloadRead(), and thus it is
1610 // important to check PR_Read() on subsequent invocations to see
1611 // if a complete record may now be read.
1612 pending_read_nss_error_ = 0;
1613 pending_read_result_ = kNoPendingReadResult;
1614 }
1615 }
1616 }
1617
1618 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
1619
1620 if (rv >= 0) {
1621 PostOrRunCallback(FROM_HERE,
1622 base::Bind(&LogByteTransferEvent, weak_net_log_,
1623 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv,
1624 base::RetainedRef(user_read_buf_)));
1625 } else if (rv != ERR_IO_PENDING) {
1626 PostOrRunCallback(
1627 FROM_HERE,
1628 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1629 NetLog::TYPE_SSL_READ_ERROR,
1630 CreateNetLogSSLErrorCallback(rv, pending_read_nss_error_)));
1631 pending_read_nss_error_ = 0;
1632 }
1633 return rv;
1634 }
1635
1636 int SSLClientSocketNSS::Core::DoPayloadWrite() {
1637 DCHECK(OnNSSTaskRunner());
1638
1639 DCHECK(user_write_buf_.get());
1640
1641 int old_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1642 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_);
1643 int new_amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1644 // PR_Write could potentially consume the unhandled data in the memio read
1645 // buffer if a renegotiation is in progress. If the buffer is consumed,
1646 // notify the latest buffer size to NetworkRunner.
1647 if (old_amount_in_read_buffer != new_amount_in_read_buffer) {
1648 PostOrRunCallback(
1649 FROM_HERE,
1650 base::Bind(&Core::OnNSSBufferUpdated, this, new_amount_in_read_buffer));
1651 }
1652 if (rv >= 0) {
1653 PostOrRunCallback(FROM_HERE,
1654 base::Bind(&LogByteTransferEvent, weak_net_log_,
1655 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv,
1656 base::RetainedRef(user_write_buf_)));
1657 return rv;
1658 }
1659 PRErrorCode prerr = PR_GetError();
1660 if (prerr == PR_WOULD_BLOCK_ERROR)
1661 return ERR_IO_PENDING;
1662
1663 rv = HandleNSSError(prerr);
1664 PostOrRunCallback(
1665 FROM_HERE,
1666 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1667 NetLog::TYPE_SSL_WRITE_ERROR,
1668 CreateNetLogSSLErrorCallback(rv, prerr)));
1669 return rv;
1670 }
1671
1672 // Do as much network I/O as possible between the buffer and the
1673 // transport socket. Return true if some I/O performed, false
1674 // otherwise (error or ERR_IO_PENDING).
1675 bool SSLClientSocketNSS::Core::DoTransportIO() {
1676 DCHECK(OnNSSTaskRunner());
1677
1678 bool network_moved = false;
1679 if (nss_bufs_ != NULL) {
1680 int rv;
1681 // Read and write as much data as we can. The loop is neccessary
1682 // because Write() may return synchronously.
1683 do {
1684 rv = BufferSend();
1685 if (rv != ERR_IO_PENDING && rv != 0)
1686 network_moved = true;
1687 } while (rv > 0);
1688 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING)
1689 network_moved = true;
1690 }
1691 return network_moved;
1692 }
1693
1694 int SSLClientSocketNSS::Core::BufferRecv() {
1695 DCHECK(OnNSSTaskRunner());
1696
1697 if (transport_recv_busy_)
1698 return ERR_IO_PENDING;
1699
1700 // If NSS is blocked on reading from |nss_bufs_|, because it is empty,
1701 // determine how much data NSS wants to read. If NSS was not blocked,
1702 // this will return 0.
1703 int requested = memio_GetReadRequest(nss_bufs_);
1704 if (requested == 0) {
1705 // This is not a perfect match of error codes, as no operation is
1706 // actually pending. However, returning 0 would be interpreted as a
1707 // possible sign of EOF, which is also an inappropriate match.
1708 return ERR_IO_PENDING;
1709 }
1710
1711 char* buf;
1712 int nb = memio_GetReadParams(nss_bufs_, &buf);
1713 int rv;
1714 if (!nb) {
1715 // buffer too full to read into, so no I/O possible at moment
1716 rv = ERR_IO_PENDING;
1717 } else {
1718 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb));
1719 if (OnNetworkTaskRunner()) {
1720 rv = DoBufferRecv(read_buffer.get(), nb);
1721 } else {
1722 bool posted = network_task_runner_->PostTask(
1723 FROM_HERE, base::Bind(IgnoreResult(&Core::DoBufferRecv), this,
1724 base::RetainedRef(read_buffer), nb));
1725 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1726 }
1727
1728 if (rv == ERR_IO_PENDING) {
1729 transport_recv_busy_ = true;
1730 } else {
1731 if (rv > 0) {
1732 memcpy(buf, read_buffer->data(), rv);
1733 } else if (rv == 0) {
1734 transport_recv_eof_ = true;
1735 }
1736 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv));
1737 }
1738 }
1739 return rv;
1740 }
1741
1742 // Return 0 if nss_bufs_ was empty,
1743 // > 0 for bytes transferred immediately,
1744 // < 0 for error (or the non-error ERR_IO_PENDING).
1745 int SSLClientSocketNSS::Core::BufferSend() {
1746 DCHECK(OnNSSTaskRunner());
1747
1748 if (transport_send_busy_)
1749 return ERR_IO_PENDING;
1750
1751 const char* buf1;
1752 const char* buf2;
1753 unsigned int len1, len2;
1754 if (memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2)) {
1755 // It is important this return synchronously to prevent spinning infinitely
1756 // in the off-thread NSS case. The error code itself is ignored, so just
1757 // return ERR_ABORTED. See https://crbug.com/381160.
1758 return ERR_ABORTED;
1759 }
1760 const size_t len = len1 + len2;
1761
1762 int rv = 0;
1763 if (len) {
1764 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len));
1765 memcpy(send_buffer->data(), buf1, len1);
1766 memcpy(send_buffer->data() + len1, buf2, len2);
1767
1768 if (OnNetworkTaskRunner()) {
1769 rv = DoBufferSend(send_buffer.get(), len);
1770 } else {
1771 bool posted = network_task_runner_->PostTask(
1772 FROM_HERE, base::Bind(IgnoreResult(&Core::DoBufferSend), this,
1773 base::RetainedRef(send_buffer), len));
1774 rv = posted ? ERR_IO_PENDING : ERR_ABORTED;
1775 }
1776
1777 if (rv == ERR_IO_PENDING) {
1778 transport_send_busy_ = true;
1779 } else {
1780 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv));
1781 }
1782 }
1783
1784 return rv;
1785 }
1786
1787 void SSLClientSocketNSS::Core::OnRecvComplete(int result) {
1788 DCHECK(OnNSSTaskRunner());
1789
1790 if (next_handshake_state_ == STATE_HANDSHAKE) {
1791 OnHandshakeIOComplete(result);
1792 return;
1793 }
1794
1795 // Network layer received some data, check if client requested to read
1796 // decrypted data.
1797 if (!user_read_buf_.get())
1798 return;
1799
1800 int rv = DoReadLoop(result);
1801 if (rv != ERR_IO_PENDING)
1802 DoReadCallback(rv);
1803 }
1804
1805 void SSLClientSocketNSS::Core::OnSendComplete(int result) {
1806 DCHECK(OnNSSTaskRunner());
1807
1808 if (next_handshake_state_ == STATE_HANDSHAKE) {
1809 OnHandshakeIOComplete(result);
1810 return;
1811 }
1812
1813 // OnSendComplete may need to call DoPayloadRead while the renegotiation
1814 // handshake is in progress.
1815 int rv_read = ERR_IO_PENDING;
1816 int rv_write = ERR_IO_PENDING;
1817 bool network_moved;
1818 do {
1819 if (user_read_buf_.get())
1820 rv_read = DoPayloadRead();
1821 if (user_write_buf_.get())
1822 rv_write = DoPayloadWrite();
1823 network_moved = DoTransportIO();
1824 } while (rv_read == ERR_IO_PENDING && rv_write == ERR_IO_PENDING &&
1825 (user_read_buf_.get() || user_write_buf_.get()) && network_moved);
1826
1827 // If the parent SSLClientSocketNSS is deleted during the processing of the
1828 // Read callback and OnNSSTaskRunner() == OnNetworkTaskRunner(), then the Core
1829 // will be detached (and possibly deleted). Guard against deletion by taking
1830 // an extra reference, then check if the Core was detached before invoking the
1831 // next callback.
1832 scoped_refptr<Core> guard(this);
1833 if (user_read_buf_.get() && rv_read != ERR_IO_PENDING)
1834 DoReadCallback(rv_read);
1835
1836 if (OnNetworkTaskRunner() && detached_)
1837 return;
1838
1839 if (user_write_buf_.get() && rv_write != ERR_IO_PENDING)
1840 DoWriteCallback(rv_write);
1841 }
1842
1843 // As part of Connect(), the SSLClientSocketNSS object performs an SSL
1844 // handshake. This requires network IO, which in turn calls
1845 // BufferRecvComplete() with a non-zero byte count. This byte count eventually
1846 // winds its way through the state machine and ends up being passed to the
1847 // callback. For Read() and Write(), that's what we want. But for Connect(),
1848 // the caller expects OK (i.e. 0) for success.
1849 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) {
1850 DCHECK(OnNSSTaskRunner());
1851 DCHECK_NE(rv, ERR_IO_PENDING);
1852 DCHECK(!user_connect_callback_.is_null());
1853
1854 base::Closure c = base::Bind(
1855 base::ResetAndReturn(&user_connect_callback_),
1856 rv > OK ? OK : rv);
1857 PostOrRunCallback(FROM_HERE, c);
1858 }
1859
1860 void SSLClientSocketNSS::Core::DoReadCallback(int rv) {
1861 DCHECK(OnNSSTaskRunner());
1862 DCHECK_NE(ERR_IO_PENDING, rv);
1863 DCHECK(!user_read_callback_.is_null());
1864
1865 user_read_buf_ = NULL;
1866 user_read_buf_len_ = 0;
1867 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1868 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1869 // the network task runner.
1870 PostOrRunCallback(
1871 FROM_HERE,
1872 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1873 PostOrRunCallback(
1874 FROM_HERE,
1875 base::Bind(&Core::DidNSSRead, this, rv));
1876 PostOrRunCallback(
1877 FROM_HERE,
1878 base::Bind(base::ResetAndReturn(&user_read_callback_), rv));
1879 }
1880
1881 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) {
1882 DCHECK(OnNSSTaskRunner());
1883 DCHECK_NE(ERR_IO_PENDING, rv);
1884 DCHECK(!user_write_callback_.is_null());
1885
1886 // Since Run may result in Write being called, clear |user_write_callback_|
1887 // up front.
1888 user_write_buf_ = NULL;
1889 user_write_buf_len_ = 0;
1890 // Update buffer status because DoWriteLoop called DoTransportIO which may
1891 // perform read operations.
1892 int amount_in_read_buffer = memio_GetReadableBufferSize(nss_bufs_);
1893 // This is used to curry the |amount_int_read_buffer| and |user_cb| back to
1894 // the network task runner.
1895 PostOrRunCallback(
1896 FROM_HERE,
1897 base::Bind(&Core::OnNSSBufferUpdated, this, amount_in_read_buffer));
1898 PostOrRunCallback(
1899 FROM_HERE,
1900 base::Bind(&Core::DidNSSWrite, this, rv));
1901 PostOrRunCallback(
1902 FROM_HERE,
1903 base::Bind(base::ResetAndReturn(&user_write_callback_), rv));
1904 }
1905
1906 SECStatus SSLClientSocketNSS::Core::ClientChannelIDHandler(
1907 void* arg,
1908 PRFileDesc* socket,
1909 SECKEYPublicKey **out_public_key,
1910 SECKEYPrivateKey **out_private_key) {
1911 Core* core = reinterpret_cast<Core*>(arg);
1912 DCHECK(core->OnNSSTaskRunner());
1913
1914 core->PostOrRunCallback(
1915 FROM_HERE,
1916 base::Bind(&AddLogEvent, core->weak_net_log_,
1917 NetLog::TYPE_SSL_CHANNEL_ID_REQUESTED));
1918
1919 // We have negotiated the TLS channel ID extension.
1920 core->channel_id_xtn_negotiated_ = true;
1921 std::string host = core->host_and_port_.host();
1922 int error = ERR_UNEXPECTED;
1923 if (core->OnNetworkTaskRunner()) {
1924 error = core->DoGetChannelID(host);
1925 } else {
1926 bool posted = core->network_task_runner_->PostTask(
1927 FROM_HERE,
1928 base::Bind(
1929 IgnoreResult(&Core::DoGetChannelID),
1930 core, host));
1931 error = posted ? ERR_IO_PENDING : ERR_ABORTED;
1932 }
1933
1934 if (error == ERR_IO_PENDING) {
1935 // Asynchronous case.
1936 core->channel_id_needed_ = true;
1937 return SECWouldBlock;
1938 }
1939
1940 core->PostOrRunCallback(
1941 FROM_HERE,
1942 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, core->weak_net_log_,
1943 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error));
1944 SECStatus rv = SECSuccess;
1945 if (error == OK) {
1946 // Synchronous success.
1947 int result = core->ImportChannelIDKeys(out_public_key, out_private_key);
1948 if (result == OK)
1949 core->SetChannelIDProvided();
1950 else
1951 rv = SECFailure;
1952 } else {
1953 rv = SECFailure;
1954 }
1955
1956 return rv;
1957 }
1958
1959 int SSLClientSocketNSS::Core::ImportChannelIDKeys(SECKEYPublicKey** public_key,
1960 SECKEYPrivateKey** key) {
1961 if (!channel_id_key_)
1962 return SECFailure;
1963
1964 *public_key = SECKEY_CopyPublicKey(channel_id_key_->public_key());
1965 *key = SECKEY_CopyPrivateKey(channel_id_key_->key());
1966
1967 return OK;
1968 }
1969
1970 void SSLClientSocketNSS::Core::UpdateServerCert() {
1971 nss_handshake_state_.server_cert_chain.Reset(nss_fd_);
1972 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain(
1973 nss_handshake_state_.server_cert_chain.AsStringPieceVector());
1974 if (nss_handshake_state_.server_cert.get()) {
1975 // Since this will be called asynchronously on another thread, it needs to
1976 // own a reference to the certificate.
1977 NetLog::ParametersCallback net_log_callback =
1978 base::Bind(&NetLogX509CertificateCallback,
1979 base::RetainedRef(nss_handshake_state_.server_cert));
1980 PostOrRunCallback(
1981 FROM_HERE,
1982 base::Bind(&AddLogEventWithCallback, weak_net_log_,
1983 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED,
1984 net_log_callback));
1985 }
1986 }
1987
1988 void SSLClientSocketNSS::Core::UpdateSignedCertTimestamps() {
1989 const SECItem* signed_cert_timestamps =
1990 SSL_PeerSignedCertTimestamps(nss_fd_);
1991
1992 if (!signed_cert_timestamps || !signed_cert_timestamps->len)
1993 return;
1994
1995 nss_handshake_state_.sct_list_from_tls_extension = std::string(
1996 reinterpret_cast<char*>(signed_cert_timestamps->data),
1997 signed_cert_timestamps->len);
1998 }
1999
2000 void SSLClientSocketNSS::Core::UpdateStapledOCSPResponse() {
2001 PRBool ocsp_requested = PR_FALSE;
2002 SSL_OptionGet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, &ocsp_requested);
2003 const SECItemArray* ocsp_responses =
2004 SSL_PeerStapledOCSPResponses(nss_fd_);
2005 bool ocsp_responses_present = ocsp_responses && ocsp_responses->len;
2006 if (ocsp_requested)
2007 UMA_HISTOGRAM_BOOLEAN("Net.OCSPResponseStapled", ocsp_responses_present);
2008 if (!ocsp_responses_present)
2009 return;
2010
2011 nss_handshake_state_.stapled_ocsp_response = std::string(
2012 reinterpret_cast<char*>(ocsp_responses->items[0].data),
2013 ocsp_responses->items[0].len);
2014 }
2015
2016 void SSLClientSocketNSS::Core::UpdateConnectionStatus() {
2017 // Note: This function may be called multiple times for a single connection
2018 // if renegotiations occur.
2019 nss_handshake_state_.ssl_connection_status = 0;
2020
2021 SSLChannelInfo channel_info;
2022 SECStatus ok = SSL_GetChannelInfo(nss_fd_,
2023 &channel_info, sizeof(channel_info));
2024 if (ok == SECSuccess &&
2025 channel_info.length == sizeof(channel_info) &&
2026 channel_info.cipherSuite) {
2027 nss_handshake_state_.ssl_connection_status |= channel_info.cipherSuite;
2028
2029 nss_handshake_state_.ssl_connection_status |=
2030 (static_cast<int>(channel_info.compressionMethod) &
2031 SSL_CONNECTION_COMPRESSION_MASK) <<
2032 SSL_CONNECTION_COMPRESSION_SHIFT;
2033
2034 int version = SSL_CONNECTION_VERSION_UNKNOWN;
2035 if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_0) {
2036 version = SSL_CONNECTION_VERSION_TLS1;
2037 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_1) {
2038 version = SSL_CONNECTION_VERSION_TLS1_1;
2039 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_TLS_1_2) {
2040 version = SSL_CONNECTION_VERSION_TLS1_2;
2041 }
2042 DCHECK_NE(SSL_CONNECTION_VERSION_UNKNOWN, version);
2043 nss_handshake_state_.ssl_connection_status |=
2044 (version & SSL_CONNECTION_VERSION_MASK) <<
2045 SSL_CONNECTION_VERSION_SHIFT;
2046 }
2047
2048 PRBool peer_supports_renego_ext;
2049 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn,
2050 &peer_supports_renego_ext);
2051 if (ok == SECSuccess) {
2052 if (!peer_supports_renego_ext) {
2053 nss_handshake_state_.ssl_connection_status |=
2054 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION;
2055 // Log an informational message if the server does not support secure
2056 // renegotiation (RFC 5746).
2057 VLOG(1) << "The server " << host_and_port_.ToString()
2058 << " does not support the TLS renegotiation_info extension.";
2059 }
2060 }
2061
2062 if (ssl_config_.version_fallback) {
2063 nss_handshake_state_.ssl_connection_status |=
2064 SSL_CONNECTION_VERSION_FALLBACK;
2065 }
2066 }
2067
2068 void SSLClientSocketNSS::Core::UpdateNextProto() {
2069 uint8_t buf[256];
2070 SSLNextProtoState state;
2071 unsigned buf_len;
2072
2073 SECStatus rv = SSL_GetNextProto(nss_fd_, &state, buf, &buf_len, sizeof(buf));
2074 if (rv != SECSuccess)
2075 return;
2076
2077 nss_handshake_state_.next_proto =
2078 std::string(reinterpret_cast<char*>(buf), buf_len);
2079 switch (state) {
2080 case SSL_NEXT_PROTO_NEGOTIATED:
2081 case SSL_NEXT_PROTO_SELECTED:
2082 nss_handshake_state_.next_proto_status = kNextProtoNegotiated;
2083 break;
2084 case SSL_NEXT_PROTO_NO_OVERLAP:
2085 nss_handshake_state_.next_proto_status = kNextProtoNoOverlap;
2086 break;
2087 case SSL_NEXT_PROTO_NO_SUPPORT:
2088 nss_handshake_state_.next_proto_status = kNextProtoUnsupported;
2089 break;
2090 default:
2091 NOTREACHED();
2092 break;
2093 }
2094 }
2095
2096 void SSLClientSocketNSS::Core::UpdateExtensionUsed() {
2097 PRBool negotiated_extension;
2098 SECStatus rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2099 ssl_app_layer_protocol_xtn,
2100 &negotiated_extension);
2101 if (rv == SECSuccess && negotiated_extension) {
2102 nss_handshake_state_.negotiation_extension_ = kExtensionALPN;
2103 } else {
2104 rv = SSL_HandshakeNegotiatedExtension(nss_fd_,
2105 ssl_next_proto_nego_xtn,
2106 &negotiated_extension);
2107 if (rv == SECSuccess && negotiated_extension) {
2108 nss_handshake_state_.negotiation_extension_ = kExtensionNPN;
2109 }
2110 }
2111 }
2112
2113 bool SSLClientSocketNSS::Core::IsRenegotiationAllowed() const {
2114 DCHECK(OnNSSTaskRunner());
2115
2116 if (nss_handshake_state_.next_proto_status == kNextProtoUnsupported)
2117 return ssl_config_.renego_allowed_default;
2118
2119 NextProto next_proto = NextProtoFromString(nss_handshake_state_.next_proto);
2120 for (NextProto allowed : ssl_config_.renego_allowed_for_protos) {
2121 if (next_proto == allowed)
2122 return true;
2123 }
2124 return false;
2125 }
2126
2127 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNSSTaskRunner() {
2128 DCHECK(OnNSSTaskRunner());
2129 if (nss_handshake_state_.resumed_handshake)
2130 return;
2131
2132 // Copy the NSS task runner-only state to the network task runner and
2133 // log histograms from there, since the histograms also need access to the
2134 // network task runner state.
2135 PostOrRunCallback(
2136 FROM_HERE,
2137 base::Bind(&Core::RecordChannelIDSupportOnNetworkTaskRunner, this,
2138 channel_id_xtn_negotiated_, ssl_config_.channel_id_enabled));
2139 }
2140
2141 void SSLClientSocketNSS::Core::RecordChannelIDSupportOnNetworkTaskRunner(
2142 bool negotiated_channel_id,
2143 bool channel_id_enabled) const {
2144 DCHECK(OnNetworkTaskRunner());
2145
2146 RecordChannelIDSupport(channel_id_service_, negotiated_channel_id,
2147 channel_id_enabled);
2148 }
2149
2150 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) {
2151 DCHECK(OnNetworkTaskRunner());
2152 DCHECK_GT(len, 0);
2153
2154 if (detached_)
2155 return ERR_ABORTED;
2156
2157 int rv = transport_->socket()->Read(
2158 read_buffer, len,
2159 base::Bind(&Core::BufferRecvComplete, base::Unretained(this),
2160 base::RetainedRef(read_buffer)));
2161
2162 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2163 nss_task_runner_->PostTask(FROM_HERE,
2164 base::Bind(&Core::BufferRecvComplete, this,
2165 base::RetainedRef(read_buffer), rv));
2166 return rv;
2167 }
2168
2169 return rv;
2170 }
2171
2172 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) {
2173 DCHECK(OnNetworkTaskRunner());
2174 DCHECK_GT(len, 0);
2175
2176 if (detached_)
2177 return ERR_ABORTED;
2178
2179 int rv = transport_->socket()->Write(
2180 send_buffer, len,
2181 base::Bind(&Core::BufferSendComplete,
2182 base::Unretained(this)));
2183
2184 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) {
2185 nss_task_runner_->PostTask(
2186 FROM_HERE,
2187 base::Bind(&Core::BufferSendComplete, this, rv));
2188 return rv;
2189 }
2190
2191 return rv;
2192 }
2193
2194 int SSLClientSocketNSS::Core::DoGetChannelID(const std::string& host) {
2195 DCHECK(OnNetworkTaskRunner());
2196
2197 if (detached_)
2198 return ERR_ABORTED;
2199
2200 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT);
2201
2202 int rv = channel_id_service_->GetOrCreateChannelID(
2203 host, &channel_id_key_,
2204 base::Bind(&Core::OnGetChannelIDComplete, base::Unretained(this)),
2205 &channel_id_request_);
2206
2207 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) {
2208 nss_task_runner_->PostTask(
2209 FROM_HERE,
2210 base::Bind(&Core::OnHandshakeIOComplete, this, rv));
2211 return ERR_IO_PENDING;
2212 }
2213
2214 return rv;
2215 }
2216
2217 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated(
2218 const HandshakeState& state) {
2219 DCHECK(OnNetworkTaskRunner());
2220 network_handshake_state_ = state;
2221 }
2222
2223 void SSLClientSocketNSS::Core::OnNSSBufferUpdated(int amount_in_read_buffer) {
2224 DCHECK(OnNetworkTaskRunner());
2225 unhandled_buffer_size_ = amount_in_read_buffer;
2226 }
2227
2228 void SSLClientSocketNSS::Core::DidNSSRead(int result) {
2229 DCHECK(OnNetworkTaskRunner());
2230 DCHECK(nss_waiting_read_);
2231 nss_waiting_read_ = false;
2232 if (result <= 0) {
2233 nss_is_closed_ = true;
2234 } else {
2235 was_ever_used_ = true;
2236 }
2237 }
2238
2239 void SSLClientSocketNSS::Core::DidNSSWrite(int result) {
2240 DCHECK(OnNetworkTaskRunner());
2241 DCHECK(nss_waiting_write_);
2242 nss_waiting_write_ = false;
2243 if (result < 0) {
2244 nss_is_closed_ = true;
2245 } else if (result > 0) {
2246 was_ever_used_ = true;
2247 }
2248 }
2249
2250 void SSLClientSocketNSS::Core::BufferSendComplete(int result) {
2251 if (!OnNSSTaskRunner()) {
2252 if (detached_)
2253 return;
2254
2255 nss_task_runner_->PostTask(
2256 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result));
2257 return;
2258 }
2259
2260 DCHECK(OnNSSTaskRunner());
2261
2262 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result));
2263 transport_send_busy_ = false;
2264 OnSendComplete(result);
2265 }
2266
2267 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) {
2268 if (!OnNSSTaskRunner()) {
2269 if (detached_)
2270 return;
2271
2272 nss_task_runner_->PostTask(
2273 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result));
2274 return;
2275 }
2276
2277 DCHECK(OnNSSTaskRunner());
2278
2279 int rv = DoHandshakeLoop(result);
2280 if (rv != ERR_IO_PENDING)
2281 DoConnectCallback(rv);
2282 }
2283
2284 void SSLClientSocketNSS::Core::OnGetChannelIDComplete(int result) {
2285 DVLOG(1) << __FUNCTION__ << " " << result;
2286 DCHECK(OnNetworkTaskRunner());
2287
2288 OnHandshakeIOComplete(result);
2289 }
2290
2291 void SSLClientSocketNSS::Core::BufferRecvComplete(
2292 IOBuffer* read_buffer,
2293 int result) {
2294 DCHECK(read_buffer);
2295
2296 if (!OnNSSTaskRunner()) {
2297 if (detached_)
2298 return;
2299
2300 nss_task_runner_->PostTask(
2301 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this,
2302 base::RetainedRef(read_buffer), result));
2303 return;
2304 }
2305
2306 DCHECK(OnNSSTaskRunner());
2307
2308 if (result > 0) {
2309 char* buf;
2310 int nb = memio_GetReadParams(nss_bufs_, &buf);
2311 CHECK_GE(nb, result);
2312 memcpy(buf, read_buffer->data(), result);
2313 } else if (result == 0) {
2314 transport_recv_eof_ = true;
2315 }
2316
2317 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result));
2318 transport_recv_busy_ = false;
2319 OnRecvComplete(result);
2320 }
2321
2322 void SSLClientSocketNSS::Core::PostOrRunCallback(
2323 const tracked_objects::Location& location,
2324 const base::Closure& task) {
2325 if (!OnNetworkTaskRunner()) {
2326 network_task_runner_->PostTask(
2327 FROM_HERE,
2328 base::Bind(&Core::PostOrRunCallback, this, location, task));
2329 return;
2330 }
2331
2332 if (detached_ || task.is_null())
2333 return;
2334 task.Run();
2335 }
2336
2337 void SSLClientSocketNSS::Core::AddCertProvidedEvent(int cert_count) {
2338 PostOrRunCallback(FROM_HERE,
2339 base::Bind(&AddLogEventWithCallback, weak_net_log_,
2340 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED,
2341 NetLog::IntCallback("cert_count", cert_count)));
2342 }
2343
2344 void SSLClientSocketNSS::Core::SetChannelIDProvided() {
2345 PostOrRunCallback(
2346 FROM_HERE, base::Bind(&AddLogEvent, weak_net_log_,
2347 NetLog::TYPE_SSL_CHANNEL_ID_PROVIDED));
2348 nss_handshake_state_.channel_id_sent = true;
2349 // Update the network task runner's view of the handshake state now that
2350 // channel id has been sent.
2351 PostOrRunCallback(
2352 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, this,
2353 nss_handshake_state_));
2354 }
2355
2356 SSLClientSocketNSS::SSLClientSocketNSS(
2357 std::unique_ptr<ClientSocketHandle> transport_socket,
2358 const HostPortPair& host_and_port,
2359 const SSLConfig& ssl_config,
2360 const SSLClientSocketContext& context)
2361 : transport_(std::move(transport_socket)),
2362 host_and_port_(host_and_port),
2363 ssl_config_(ssl_config),
2364 cert_verifier_(context.cert_verifier),
2365 cert_transparency_verifier_(context.cert_transparency_verifier),
2366 channel_id_service_(context.channel_id_service),
2367 ssl_session_cache_shard_(context.ssl_session_cache_shard),
2368 completed_handshake_(false),
2369 next_handshake_state_(STATE_NONE),
2370 disconnected_(false),
2371 nss_fd_(NULL),
2372 net_log_(transport_->socket()->NetLog()),
2373 transport_security_state_(context.transport_security_state),
2374 policy_enforcer_(context.ct_policy_enforcer),
2375 valid_thread_id_(base::kInvalidThreadId) {
2376 DCHECK(cert_verifier_);
2377
2378 EnterFunction("");
2379 InitCore();
2380 LeaveFunction("");
2381 }
2382
2383 SSLClientSocketNSS::~SSLClientSocketNSS() {
2384 EnterFunction("");
2385 Disconnect();
2386 LeaveFunction("");
2387 }
2388
2389 // static
2390 void SSLClientSocket::ClearSessionCache() {
2391 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't
2392 // bother initializing NSS just to clear an empty SSL session cache.
2393 if (!NSS_IsInitialized())
2394 return;
2395
2396 SSL_ClearSessionCache();
2397 }
2398
2399 bool SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) {
2400 EnterFunction("");
2401 ssl_info->Reset();
2402 if (core_->state().server_cert_chain.empty() ||
2403 !core_->state().server_cert_chain[0]) {
2404 return false;
2405 }
2406
2407 ssl_info->cert_status = server_cert_verify_result_.cert_status;
2408 ssl_info->cert = server_cert_verify_result_.verified_cert;
2409 ssl_info->unverified_cert = core_->state().server_cert;
2410
2411 AddCTInfoToSSLInfo(ssl_info);
2412
2413 ssl_info->connection_status =
2414 core_->state().ssl_connection_status;
2415 ssl_info->public_key_hashes = server_cert_verify_result_.public_key_hashes;
2416 ssl_info->is_issued_by_known_root =
2417 server_cert_verify_result_.is_issued_by_known_root;
2418 ssl_info->client_cert_sent =
2419 ssl_config_.send_client_cert && ssl_config_.client_cert.get();
2420 ssl_info->channel_id_sent = core_->state().channel_id_sent;
2421 ssl_info->pinning_failure_log = pinning_failure_log_;
2422
2423 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite(
2424 core_->state().ssl_connection_status);
2425 SSLCipherSuiteInfo cipher_info;
2426 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite,
2427 &cipher_info, sizeof(cipher_info));
2428 if (ok == SECSuccess) {
2429 ssl_info->security_bits = cipher_info.effectiveKeyBits;
2430 } else {
2431 ssl_info->security_bits = -1;
2432 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError()
2433 << " for cipherSuite " << cipher_suite;
2434 }
2435
2436 ssl_info->handshake_type = core_->state().resumed_handshake ?
2437 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL;
2438
2439 LeaveFunction("");
2440 return true;
2441 }
2442
2443 void SSLClientSocketNSS::GetConnectionAttempts(ConnectionAttempts* out) const {
2444 out->clear();
2445 }
2446
2447 int64_t SSLClientSocketNSS::GetTotalReceivedBytes() const {
2448 NOTIMPLEMENTED();
2449 return 0;
2450 }
2451
2452 void SSLClientSocketNSS::GetSSLCertRequestInfo(
2453 SSLCertRequestInfo* cert_request_info) {
2454 EnterFunction("");
2455 cert_request_info->host_and_port = host_and_port_;
2456 cert_request_info->cert_authorities = core_->state().cert_authorities;
2457 LeaveFunction("");
2458 }
2459
2460 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label,
2461 bool has_context,
2462 const base::StringPiece& context,
2463 unsigned char* out,
2464 unsigned int outlen) {
2465 if (!IsConnected())
2466 return ERR_SOCKET_NOT_CONNECTED;
2467
2468 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in
2469 // the midst of a handshake.
2470 SECStatus result = SSL_ExportKeyingMaterial(
2471 nss_fd_, label.data(), label.size(), has_context,
2472 reinterpret_cast<const unsigned char*>(context.data()),
2473 context.length(), out, outlen);
2474 if (result != SECSuccess) {
2475 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", "");
2476 return MapNSSError(PORT_GetError());
2477 }
2478 return OK;
2479 }
2480
2481 SSLClientSocket::NextProtoStatus SSLClientSocketNSS::GetNextProto(
2482 std::string* proto) const {
2483 *proto = core_->state().next_proto;
2484 return core_->state().next_proto_status;
2485 }
2486
2487 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) {
2488 EnterFunction("");
2489 DCHECK(transport_.get());
2490 // It is an error to create an SSLClientSocket whose context has no
2491 // TransportSecurityState.
2492 DCHECK(transport_security_state_);
2493 DCHECK_EQ(STATE_NONE, next_handshake_state_);
2494 DCHECK(user_connect_callback_.is_null());
2495 DCHECK(!callback.is_null());
2496
2497 // Although StreamSocket does allow calling Connect() after Disconnect(),
2498 // this has never worked for layered sockets. CHECK to detect any consumers
2499 // reconnecting an SSL socket.
2500 //
2501 // TODO(davidben,mmenke): Remove this API feature. See
2502 // https://crbug.com/499289.
2503 CHECK(!disconnected_);
2504
2505 EnsureThreadIdAssigned();
2506
2507 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT);
2508
2509 int rv = Init();
2510 if (rv != OK) {
2511 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2512 return rv;
2513 }
2514
2515 rv = InitializeSSLOptions();
2516 if (rv != OK) {
2517 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2518 return rv;
2519 }
2520
2521 rv = InitializeSSLPeerName();
2522 if (rv != OK) {
2523 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2524 return rv;
2525 }
2526
2527 GotoState(STATE_HANDSHAKE);
2528
2529 rv = DoHandshakeLoop(OK);
2530 if (rv == ERR_IO_PENDING) {
2531 user_connect_callback_ = callback;
2532 } else {
2533 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2534 }
2535
2536 LeaveFunction("");
2537 return rv > OK ? OK : rv;
2538 }
2539
2540 void SSLClientSocketNSS::Disconnect() {
2541 EnterFunction("");
2542
2543 CHECK(CalledOnValidThread());
2544
2545 // Shut down anything that may call us back.
2546 core_->Detach();
2547 cert_verifier_request_.reset();
2548 transport_->socket()->Disconnect();
2549
2550 disconnected_ = true;
2551
2552 // Reset object state.
2553 user_connect_callback_.Reset();
2554 server_cert_verify_result_.Reset();
2555 completed_handshake_ = false;
2556 start_cert_verification_time_ = base::TimeTicks();
2557 InitCore();
2558
2559 LeaveFunction("");
2560 }
2561
2562 bool SSLClientSocketNSS::IsConnected() const {
2563 EnterFunction("");
2564 bool ret = completed_handshake_ &&
2565 (core_->HasPendingAsyncOperation() ||
2566 (core_->IsConnected() && core_->HasUnhandledReceivedData()) ||
2567 transport_->socket()->IsConnected());
2568 LeaveFunction("");
2569 return ret;
2570 }
2571
2572 bool SSLClientSocketNSS::IsConnectedAndIdle() const {
2573 EnterFunction("");
2574 bool ret = completed_handshake_ &&
2575 !core_->HasPendingAsyncOperation() &&
2576 !(core_->IsConnected() && core_->HasUnhandledReceivedData()) &&
2577 transport_->socket()->IsConnectedAndIdle();
2578 LeaveFunction("");
2579 return ret;
2580 }
2581
2582 int SSLClientSocketNSS::GetPeerAddress(IPEndPoint* address) const {
2583 return transport_->socket()->GetPeerAddress(address);
2584 }
2585
2586 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const {
2587 return transport_->socket()->GetLocalAddress(address);
2588 }
2589
2590 const BoundNetLog& SSLClientSocketNSS::NetLog() const {
2591 return net_log_;
2592 }
2593
2594 void SSLClientSocketNSS::SetSubresourceSpeculation() {
2595 if (transport_.get() && transport_->socket()) {
2596 transport_->socket()->SetSubresourceSpeculation();
2597 } else {
2598 NOTREACHED();
2599 }
2600 }
2601
2602 void SSLClientSocketNSS::SetOmniboxSpeculation() {
2603 if (transport_.get() && transport_->socket()) {
2604 transport_->socket()->SetOmniboxSpeculation();
2605 } else {
2606 NOTREACHED();
2607 }
2608 }
2609
2610 bool SSLClientSocketNSS::WasEverUsed() const {
2611 DCHECK(core_.get());
2612
2613 return core_->WasEverUsed();
2614 }
2615
2616 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len,
2617 const CompletionCallback& callback) {
2618 DCHECK(core_.get());
2619 DCHECK(!callback.is_null());
2620
2621 EnterFunction(buf_len);
2622 int rv = core_->Read(buf, buf_len, callback);
2623 LeaveFunction(rv);
2624
2625 return rv;
2626 }
2627
2628 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len,
2629 const CompletionCallback& callback) {
2630 DCHECK(core_.get());
2631 DCHECK(!callback.is_null());
2632
2633 EnterFunction(buf_len);
2634 int rv = core_->Write(buf, buf_len, callback);
2635 LeaveFunction(rv);
2636
2637 return rv;
2638 }
2639
2640 int SSLClientSocketNSS::SetReceiveBufferSize(int32_t size) {
2641 return transport_->socket()->SetReceiveBufferSize(size);
2642 }
2643
2644 int SSLClientSocketNSS::SetSendBufferSize(int32_t size) {
2645 return transport_->socket()->SetSendBufferSize(size);
2646 }
2647
2648 int SSLClientSocketNSS::Init() {
2649 EnterFunction("");
2650 // Initialize the NSS SSL library in a threadsafe way. This also
2651 // initializes the NSS base library.
2652 EnsureNSSSSLInit();
2653 if (!NSS_IsInitialized())
2654 return ERR_UNEXPECTED;
2655 #if defined(USE_NSS_VERIFIER)
2656 if (ssl_config_.cert_io_enabled) {
2657 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO
2658 // loop by MessageLoopForIO::current().
2659 // X509Certificate::Verify() runs on a worker thread of CertVerifier.
2660 EnsureNSSHttpIOInit();
2661 }
2662 #endif
2663
2664 LeaveFunction("");
2665 return OK;
2666 }
2667
2668 void SSLClientSocketNSS::InitCore() {
2669 // TODO(davidben): Both task runners are now always the same. Unwind this code
2670 // further, although the entire class is due to be deleted eventually, so it
2671 // may not be worth bothering.
2672 core_ = new Core(base::ThreadTaskRunnerHandle::Get().get(),
2673 base::ThreadTaskRunnerHandle::Get().get(), transport_.get(),
2674 host_and_port_, ssl_config_, &net_log_, channel_id_service_);
2675 }
2676
2677 int SSLClientSocketNSS::InitializeSSLOptions() {
2678 // Transport connected, now hook it up to nss
2679 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize, kSendBufferSize);
2680 if (nss_fd_ == NULL) {
2681 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code.
2682 }
2683
2684 // Grab pointer to buffers
2685 memio_Private* nss_bufs = memio_GetSecret(nss_fd_);
2686
2687 /* Create SSL state machine */
2688 /* Push SSL onto our fake I/O socket */
2689 if (SSL_ImportFD(GetNSSModelSocket(), nss_fd_) == NULL) {
2690 LogFailedNSSFunction(net_log_, "SSL_ImportFD", "");
2691 PR_Close(nss_fd_);
2692 nss_fd_ = NULL;
2693 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code.
2694 }
2695 // TODO(port): set more ssl options! Check errors!
2696
2697 int rv;
2698
2699 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE);
2700 if (rv != SECSuccess) {
2701 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY");
2702 return ERR_UNEXPECTED;
2703 }
2704
2705 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE);
2706 if (rv != SECSuccess) {
2707 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2");
2708 return ERR_UNEXPECTED;
2709 }
2710
2711 // Don't do V2 compatible hellos because they don't support TLS extensions.
2712 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE);
2713 if (rv != SECSuccess) {
2714 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO");
2715 return ERR_UNEXPECTED;
2716 }
2717
2718 SSLVersionRange version_range;
2719 version_range.min = ssl_config_.version_min;
2720 version_range.max = ssl_config_.version_max;
2721 rv = SSL_VersionRangeSet(nss_fd_, &version_range);
2722 if (rv != SECSuccess) {
2723 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", "");
2724 return ERR_NO_SSL_VERSIONS_ENABLED;
2725 }
2726
2727 if (ssl_config_.require_ecdhe) {
2728 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2729 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2730
2731 // Iterate over the cipher suites and disable those that don't use ECDHE.
2732 for (unsigned i = 0; i < num_ciphers; i++) {
2733 SSLCipherSuiteInfo info;
2734 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) ==
2735 SECSuccess) {
2736 if (strcmp(info.keaTypeName, "ECDHE") != 0) {
2737 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2738 }
2739 }
2740 }
2741 }
2742
2743 if (ssl_config_.version_fallback) {
2744 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALLBACK_SCSV, PR_TRUE);
2745 if (rv != SECSuccess) {
2746 LogFailedNSSFunction(
2747 net_log_, "SSL_OptionSet", "SSL_ENABLE_FALLBACK_SCSV");
2748 }
2749 }
2750
2751 for (std::vector<uint16_t>::const_iterator it =
2752 ssl_config_.disabled_cipher_suites.begin();
2753 it != ssl_config_.disabled_cipher_suites.end(); ++it) {
2754 // This will fail if the specified cipher is not implemented by NSS, but
2755 // the failure is harmless.
2756 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE);
2757 }
2758
2759 const PRUint16* const ssl_ciphers = SSL_GetImplementedCiphers();
2760 const PRUint16 num_ciphers = SSL_GetNumImplementedCiphers();
2761 for (int i = 0; i < num_ciphers; i++) {
2762 SSLCipherSuiteInfo info;
2763 if (SSL_GetCipherSuiteInfo(ssl_ciphers[i], &info, sizeof(info)) !=
2764 SECSuccess) {
2765 continue;
2766 }
2767 if (info.symCipher == ssl_calg_rc4 &&
2768 !(ssl_config_.rc4_enabled &&
2769 ssl_config_.deprecated_cipher_suites_enabled)) {
2770 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2771 }
2772 if (info.keaType == ssl_kea_dh &&
2773 !ssl_config_.deprecated_cipher_suites_enabled) {
2774 // Only offer DHE on the second handshake. https://crbug.com/538690
2775 SSL_CipherPrefSet(nss_fd_, ssl_ciphers[i], PR_FALSE);
2776 }
2777 }
2778
2779 // Support RFC 5077
2780 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE);
2781 if (rv != SECSuccess) {
2782 LogFailedNSSFunction(
2783 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS");
2784 }
2785
2786 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START,
2787 ssl_config_.false_start_enabled);
2788 if (rv != SECSuccess)
2789 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START");
2790
2791 // By default, renegotiations are rejected. After the initial handshake
2792 // completes, some application protocols may re-enable it.
2793 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION, SSL_RENEGOTIATE_NEVER);
2794 if (rv != SECSuccess) {
2795 LogFailedNSSFunction(
2796 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION");
2797 }
2798
2799 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, PR_TRUE);
2800 if (rv != SECSuccess)
2801 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV");
2802
2803 // Added in NSS 3.15
2804 #ifdef SSL_ENABLE_OCSP_STAPLING
2805 // Request OCSP stapling even on platforms that don't support it, in
2806 // order to extract Certificate Transparency information.
2807 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING,
2808 cert_verifier_->SupportsOCSPStapling() ||
2809 ssl_config_.signed_cert_timestamps_enabled);
2810 if (rv != SECSuccess) {
2811 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2812 "SSL_ENABLE_OCSP_STAPLING");
2813 }
2814 #endif
2815
2816 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SIGNED_CERT_TIMESTAMPS,
2817 ssl_config_.signed_cert_timestamps_enabled);
2818 if (rv != SECSuccess) {
2819 LogFailedNSSFunction(net_log_, "SSL_OptionSet",
2820 "SSL_ENABLE_SIGNED_CERT_TIMESTAMPS");
2821 }
2822
2823 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE);
2824 if (rv != SECSuccess) {
2825 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT");
2826 return ERR_UNEXPECTED;
2827 }
2828
2829 if (!core_->Init(nss_fd_, nss_bufs))
2830 return ERR_UNEXPECTED;
2831
2832 // Tell SSL the hostname we're trying to connect to.
2833 SSL_SetURL(nss_fd_, host_and_port_.host().c_str());
2834
2835 // Tell SSL we're a client; needed if not letting NSPR do socket I/O
2836 SSL_ResetHandshake(nss_fd_, PR_FALSE);
2837
2838 return OK;
2839 }
2840
2841 int SSLClientSocketNSS::InitializeSSLPeerName() {
2842 // Tell NSS who we're connected to
2843 IPEndPoint peer_address;
2844 int err = transport_->socket()->GetPeerAddress(&peer_address);
2845 if (err != OK)
2846 return err;
2847
2848 SockaddrStorage storage;
2849 if (!peer_address.ToSockAddr(storage.addr, &storage.addr_len))
2850 return ERR_ADDRESS_INVALID;
2851
2852 PRNetAddr peername;
2853 memset(&peername, 0, sizeof(peername));
2854 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername));
2855 size_t len = std::min(static_cast<size_t>(storage.addr_len),
2856 sizeof(peername));
2857 memcpy(&peername, storage.addr, len);
2858
2859 // Adjust the address family field for BSD, whose sockaddr
2860 // structure has a one-byte length and one-byte address family
2861 // field at the beginning. PRNetAddr has a two-byte address
2862 // family field at the beginning.
2863 peername.raw.family = storage.addr->sa_family;
2864
2865 memio_SetPeerName(nss_fd_, &peername);
2866
2867 // Set the peer ID for session reuse. This is necessary when we create an
2868 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address
2869 // rather than the destination server's address in that case.
2870 std::string peer_id = host_and_port_.ToString();
2871 // Append |ssl_session_cache_shard_| to the peer id. This is used to partition
2872 // the session cache for incognito mode.
2873 peer_id += "/" + ssl_session_cache_shard_;
2874 peer_id += "/";
2875 // Shard the session cache based on maximum protocol version. This causes
2876 // fallback connections to use a separate session cache.
2877 switch (ssl_config_.version_max) {
2878 case SSL_PROTOCOL_VERSION_TLS1:
2879 peer_id += "tls1";
2880 break;
2881 case SSL_PROTOCOL_VERSION_TLS1_1:
2882 peer_id += "tls1.1";
2883 break;
2884 case SSL_PROTOCOL_VERSION_TLS1_2:
2885 peer_id += "tls1.2";
2886 break;
2887 default:
2888 NOTREACHED();
2889 }
2890 peer_id += "/";
2891 if (ssl_config_.deprecated_cipher_suites_enabled)
2892 peer_id += "deprecated";
2893
2894 peer_id += "/";
2895 if (ssl_config_.channel_id_enabled)
2896 peer_id += "channelid";
2897
2898 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str()));
2899 if (rv != SECSuccess)
2900 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str());
2901
2902 return OK;
2903 }
2904
2905 void SSLClientSocketNSS::DoConnectCallback(int rv) {
2906 EnterFunction(rv);
2907 DCHECK_NE(ERR_IO_PENDING, rv);
2908 DCHECK(!user_connect_callback_.is_null());
2909
2910 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv);
2911 LeaveFunction("");
2912 }
2913
2914 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) {
2915 EnterFunction(result);
2916 int rv = DoHandshakeLoop(result);
2917 if (rv != ERR_IO_PENDING) {
2918 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv);
2919 DoConnectCallback(rv);
2920 }
2921 LeaveFunction("");
2922 }
2923
2924 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) {
2925 EnterFunction(last_io_result);
2926 int rv = last_io_result;
2927 do {
2928 // Default to STATE_NONE for next state.
2929 // (This is a quirk carried over from the windows
2930 // implementation. It makes reading the logs a bit harder.)
2931 // State handlers can and often do call GotoState just
2932 // to stay in the current state.
2933 State state = next_handshake_state_;
2934 GotoState(STATE_NONE);
2935 switch (state) {
2936 case STATE_HANDSHAKE:
2937 rv = DoHandshake();
2938 break;
2939 case STATE_HANDSHAKE_COMPLETE:
2940 rv = DoHandshakeComplete(rv);
2941 break;
2942 case STATE_VERIFY_CERT:
2943 DCHECK(rv == OK);
2944 rv = DoVerifyCert(rv);
2945 break;
2946 case STATE_VERIFY_CERT_COMPLETE:
2947 rv = DoVerifyCertComplete(rv);
2948 break;
2949 case STATE_NONE:
2950 default:
2951 rv = ERR_UNEXPECTED;
2952 LOG(DFATAL) << "unexpected state " << state;
2953 break;
2954 }
2955 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE);
2956 LeaveFunction("");
2957 return rv;
2958 }
2959
2960 int SSLClientSocketNSS::DoHandshake() {
2961 EnterFunction("");
2962
2963 int rv = core_->Connect(
2964 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
2965 base::Unretained(this)));
2966 GotoState(STATE_HANDSHAKE_COMPLETE);
2967
2968 LeaveFunction(rv);
2969 return rv;
2970 }
2971
2972 int SSLClientSocketNSS::DoHandshakeComplete(int result) {
2973 EnterFunction(result);
2974
2975 if (result == OK) {
2976 if (ssl_config_.version_fallback &&
2977 ssl_config_.version_max < ssl_config_.version_fallback_min) {
2978 return ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION;
2979 }
2980
2981 RecordNegotiationExtension();
2982
2983 // SSL handshake is completed. Let's verify the certificate.
2984 GotoState(STATE_VERIFY_CERT);
2985 // Done!
2986 }
2987 set_signed_cert_timestamps_received(
2988 !core_->state().sct_list_from_tls_extension.empty());
2989 set_stapled_ocsp_response_received(
2990 !core_->state().stapled_ocsp_response.empty());
2991 set_negotiation_extension(core_->state().negotiation_extension_);
2992
2993 LeaveFunction(result);
2994 return result;
2995 }
2996
2997 int SSLClientSocketNSS::DoVerifyCert(int result) {
2998 DCHECK(!core_->state().server_cert_chain.empty());
2999 DCHECK(core_->state().server_cert_chain[0]);
3000
3001 GotoState(STATE_VERIFY_CERT_COMPLETE);
3002
3003 // NSS decoded the certificate, but the platform certificate implementation
3004 // could not. This is treated as a fatal SSL-level protocol error rather than
3005 // a certificate error. See https://crbug.com/91341.
3006 if (!core_->state().server_cert.get())
3007 return ERR_SSL_SERVER_CERT_BAD_FORMAT;
3008
3009 // If the certificate is expected to be bad we can use the expectation as
3010 // the cert status.
3011 base::StringPiece der_cert(
3012 reinterpret_cast<char*>(
3013 core_->state().server_cert_chain[0]->derCert.data),
3014 core_->state().server_cert_chain[0]->derCert.len);
3015 CertStatus cert_status;
3016 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) {
3017 DCHECK(start_cert_verification_time_.is_null());
3018 VLOG(1) << "Received an expected bad cert with status: " << cert_status;
3019 server_cert_verify_result_.Reset();
3020 server_cert_verify_result_.cert_status = cert_status;
3021 server_cert_verify_result_.verified_cert = core_->state().server_cert;
3022 return OK;
3023 }
3024
3025 start_cert_verification_time_ = base::TimeTicks::Now();
3026
3027 return cert_verifier_->Verify(
3028 core_->state().server_cert.get(), host_and_port_.host(),
3029 core_->state().stapled_ocsp_response, ssl_config_.GetCertVerifyFlags(),
3030 SSLConfigService::GetCRLSet().get(), &server_cert_verify_result_,
3031 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete,
3032 base::Unretained(this)),
3033 &cert_verifier_request_, net_log_);
3034 }
3035
3036 // Derived from AuthCertificateCallback() in
3037 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp.
3038 int SSLClientSocketNSS::DoVerifyCertComplete(int result) {
3039 cert_verifier_request_.reset();
3040
3041 if (!start_cert_verification_time_.is_null()) {
3042 base::TimeDelta verify_time =
3043 base::TimeTicks::Now() - start_cert_verification_time_;
3044 if (result == OK)
3045 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTime", verify_time);
3046 else
3047 UMA_HISTOGRAM_TIMES("Net.SSLCertVerificationTimeError", verify_time);
3048 }
3049
3050 // We used to remember the intermediate CA certs in the NSS database
3051 // persistently. However, NSS opens a connection to the SQLite database
3052 // during NSS initialization and doesn't close the connection until NSS
3053 // shuts down. If the file system where the database resides is gone,
3054 // the database connection goes bad. What's worse, the connection won't
3055 // recover when the file system comes back. Until this NSS or SQLite bug
3056 // is fixed, we need to avoid using the NSS database for non-essential
3057 // purposes. See https://bugzilla.mozilla.org/show_bug.cgi?id=508081 and
3058 // http://crbug.com/15630 for more info.
3059
3060 const CertStatus cert_status = server_cert_verify_result_.cert_status;
3061 if (transport_security_state_ &&
3062 (result == OK ||
3063 (IsCertificateError(result) && IsCertStatusMinorError(cert_status))) &&
3064 !transport_security_state_->CheckPublicKeyPins(
3065 host_and_port_, server_cert_verify_result_.is_issued_by_known_root,
3066 server_cert_verify_result_.public_key_hashes,
3067 core_->state().server_cert.get(),
3068 server_cert_verify_result_.verified_cert.get(),
3069 TransportSecurityState::ENABLE_PIN_REPORTS, &pinning_failure_log_)) {
3070 result = ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN;
3071 }
3072
3073 if (result == OK) {
3074 // Only check Certificate Transparency if there were no other errors with
3075 // the connection.
3076 VerifyCT();
3077
3078 // Only cache the session if the certificate verified successfully.
3079 core_->CacheSessionIfNecessary();
3080 }
3081
3082 completed_handshake_ = true;
3083
3084 // Exit DoHandshakeLoop and return the result to the caller to Connect.
3085 DCHECK_EQ(STATE_NONE, next_handshake_state_);
3086 return result;
3087 }
3088
3089 void SSLClientSocketNSS::VerifyCT() {
3090 if (!cert_transparency_verifier_)
3091 return;
3092
3093 // Note that this is a completely synchronous operation: The CT Log Verifier
3094 // gets all the data it needs for SCT verification and does not do any
3095 // external communication.
3096 cert_transparency_verifier_->Verify(
3097 server_cert_verify_result_.verified_cert.get(),
3098 core_->state().stapled_ocsp_response,
3099 core_->state().sct_list_from_tls_extension, &ct_verify_result_, net_log_);
3100 // TODO(ekasper): wipe stapled_ocsp_response and sct_list_from_tls_extension
3101 // from the state after verification is complete, to conserve memory.
3102
3103 ct_verify_result_.ct_policies_applied = (policy_enforcer_ != nullptr);
3104 ct_verify_result_.ev_policy_compliance =
3105 ct::EVPolicyCompliance::EV_POLICY_DOES_NOT_APPLY;
3106 if (policy_enforcer_) {
3107 if ((server_cert_verify_result_.cert_status & CERT_STATUS_IS_EV)) {
3108 scoped_refptr<ct::EVCertsWhitelist> ev_whitelist =
3109 SSLConfigService::GetEVCertsWhitelist();
3110 ct::EVPolicyCompliance ev_policy_compliance =
3111 policy_enforcer_->DoesConformToCTEVPolicy(
3112 server_cert_verify_result_.verified_cert.get(),
3113 ev_whitelist.get(), ct_verify_result_.verified_scts, net_log_);
3114 ct_verify_result_.ev_policy_compliance = ev_policy_compliance;
3115 if (ev_policy_compliance !=
3116 ct::EVPolicyCompliance::EV_POLICY_DOES_NOT_APPLY &&
3117 ev_policy_compliance !=
3118 ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_WHITELIST &&
3119 ev_policy_compliance !=
3120 ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS) {
3121 // TODO(eranm): Log via the BoundNetLog, see crbug.com/437766
3122 VLOG(1) << "EV certificate for "
3123 << server_cert_verify_result_.verified_cert->subject()
3124 .GetDisplayName()
3125 << " does not conform to CT policy, removing EV status.";
3126 server_cert_verify_result_.cert_status |=
3127 CERT_STATUS_CT_COMPLIANCE_FAILED;
3128 server_cert_verify_result_.cert_status &= ~CERT_STATUS_IS_EV;
3129 }
3130 }
3131 ct_verify_result_.cert_policy_compliance =
3132 policy_enforcer_->DoesConformToCertPolicy(
3133 server_cert_verify_result_.verified_cert.get(),
3134 ct_verify_result_.verified_scts, net_log_);
3135 }
3136 }
3137
3138 void SSLClientSocketNSS::EnsureThreadIdAssigned() const {
3139 base::AutoLock auto_lock(lock_);
3140 if (valid_thread_id_ != base::kInvalidThreadId)
3141 return;
3142 valid_thread_id_ = base::PlatformThread::CurrentId();
3143 }
3144
3145 bool SSLClientSocketNSS::CalledOnValidThread() const {
3146 EnsureThreadIdAssigned();
3147 base::AutoLock auto_lock(lock_);
3148 return valid_thread_id_ == base::PlatformThread::CurrentId();
3149 }
3150
3151 void SSLClientSocketNSS::AddCTInfoToSSLInfo(SSLInfo* ssl_info) const {
3152 ssl_info->UpdateCertificateTransparencyInfo(ct_verify_result_);
3153 }
3154
3155 // static
3156 void SSLClientSocketNSS::ReorderNextProtos(NextProtoVector* next_protos) {
3157 if (next_protos->size() < 2) {
3158 return;
3159 }
3160
3161 NextProto fallback_proto = next_protos->back();
3162 for (size_t i = next_protos->size() - 1; i > 0; --i) {
3163 (*next_protos)[i] = (*next_protos)[i - 1];
3164 }
3165 (*next_protos)[0] = fallback_proto;
3166 }
3167
3168 ChannelIDService* SSLClientSocketNSS::GetChannelIDService() const {
3169 return channel_id_service_;
3170 }
3171
3172 Error SSLClientSocketNSS::GetSignedEKMForTokenBinding(
3173 crypto::ECPrivateKey* key,
3174 std::vector<uint8_t>* out) {
3175 NOTREACHED();
3176 return ERR_NOT_IMPLEMENTED;
3177 }
3178
3179 crypto::ECPrivateKey* SSLClientSocketNSS::GetChannelIDKey() const {
3180 return core_->GetChannelIDKey();
3181 }
3182
3183 SSLFailureState SSLClientSocketNSS::GetSSLFailureState() const {
3184 if (completed_handshake_)
3185 return SSL_FAILURE_NONE;
3186 return SSL_FAILURE_UNKNOWN;
3187 }
3188
3189 } // namespace net
OLDNEW
« no previous file with comments | « net/socket/ssl_client_socket_nss.h ('k') | net/socket/ssl_client_socket_openssl.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698