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