Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived | 5 // This file includes code SSLClientSocketNSS::DoVerifyCertComplete() derived |
| 6 // from AuthCertificateCallback() in | 6 // from AuthCertificateCallback() in |
| 7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp. | 7 // mozilla/security/manager/ssl/src/nsNSSCallbacks.cpp. |
| 8 | 8 |
| 9 /* ***** BEGIN LICENSE BLOCK ***** | 9 /* ***** BEGIN LICENSE BLOCK ***** |
| 10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1 | 10 * Version: MPL 1.1/GPL 2.0/LGPL 2.1 |
| (...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 60 #include <sslerr.h> | 60 #include <sslerr.h> |
| 61 #include <sslproto.h> | 61 #include <sslproto.h> |
| 62 | 62 |
| 63 #include <algorithm> | 63 #include <algorithm> |
| 64 #include <limits> | 64 #include <limits> |
| 65 #include <map> | 65 #include <map> |
| 66 | 66 |
| 67 #include "base/bind.h" | 67 #include "base/bind.h" |
| 68 #include "base/bind_helpers.h" | 68 #include "base/bind_helpers.h" |
| 69 #include "base/build_time.h" | 69 #include "base/build_time.h" |
| 70 #include "base/callback_helpers.h" | |
| 70 #include "base/compiler_specific.h" | 71 #include "base/compiler_specific.h" |
| 71 #include "base/logging.h" | 72 #include "base/logging.h" |
| 72 #include "base/memory/singleton.h" | 73 #include "base/memory/singleton.h" |
| 73 #include "base/metrics/histogram.h" | 74 #include "base/metrics/histogram.h" |
| 75 #include "base/single_thread_task_runner.h" | |
| 76 #include "base/stl_util.h" | |
| 74 #include "base/string_number_conversions.h" | 77 #include "base/string_number_conversions.h" |
| 75 #include "base/string_util.h" | 78 #include "base/string_util.h" |
| 76 #include "base/stringprintf.h" | 79 #include "base/stringprintf.h" |
| 80 #include "base/thread_task_runner_handle.h" | |
| 77 #include "base/threading/thread_restrictions.h" | 81 #include "base/threading/thread_restrictions.h" |
| 78 #include "base/values.h" | 82 #include "base/values.h" |
| 79 #include "crypto/ec_private_key.h" | 83 #include "crypto/ec_private_key.h" |
| 80 #include "crypto/rsa_private_key.h" | 84 #include "crypto/rsa_private_key.h" |
| 81 #include "crypto/scoped_nss_types.h" | 85 #include "crypto/scoped_nss_types.h" |
| 82 #include "net/base/address_list.h" | 86 #include "net/base/address_list.h" |
| 83 #include "net/base/asn1_util.h" | 87 #include "net/base/asn1_util.h" |
| 84 #include "net/base/cert_status_flags.h" | 88 #include "net/base/cert_status_flags.h" |
| 85 #include "net/base/cert_verifier.h" | 89 #include "net/base/cert_verifier.h" |
| 86 #include "net/base/connection_type_histograms.h" | 90 #include "net/base/connection_type_histograms.h" |
| (...skipping 152 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 239 if (!CertGetCertificateContextProperty( | 243 if (!CertGetCertificateContextProperty( |
| 240 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) { | 244 cert_context, CERT_KEY_PROV_INFO_PROP_ID, NULL, &size)) { |
| 241 return FALSE; | 245 return FALSE; |
| 242 } | 246 } |
| 243 | 247 |
| 244 return TRUE; | 248 return TRUE; |
| 245 } | 249 } |
| 246 | 250 |
| 247 #endif | 251 #endif |
| 248 | 252 |
| 249 // PeerCertificateChain is a helper object which extracts the certificate | |
| 250 // chain, as given by the server, from an NSS socket and performs the needed | |
| 251 // resource management. The first element of the chain is the leaf certificate | |
| 252 // and the other elements are in the order given by the server. | |
| 253 class PeerCertificateChain { | |
| 254 public: | |
| 255 explicit PeerCertificateChain(PRFileDesc* nss_fd) | |
| 256 : num_certs_(0), | |
| 257 certs_(NULL) { | |
| 258 SECStatus rv = SSL_PeerCertificateChain(nss_fd, NULL, &num_certs_, 0); | |
| 259 DCHECK_EQ(rv, SECSuccess); | |
| 260 | |
| 261 certs_ = new CERTCertificate*[num_certs_]; | |
| 262 const unsigned expected_num_certs = num_certs_; | |
| 263 rv = SSL_PeerCertificateChain(nss_fd, certs_, &num_certs_, | |
| 264 expected_num_certs); | |
| 265 DCHECK_EQ(rv, SECSuccess); | |
| 266 DCHECK_EQ(num_certs_, expected_num_certs); | |
| 267 } | |
| 268 | |
| 269 ~PeerCertificateChain() { | |
| 270 for (unsigned i = 0; i < num_certs_; i++) | |
| 271 CERT_DestroyCertificate(certs_[i]); | |
| 272 delete[] certs_; | |
| 273 } | |
| 274 | |
| 275 unsigned size() const { return num_certs_; } | |
| 276 | |
| 277 CERTCertificate* operator[](unsigned i) { | |
| 278 DCHECK_LT(i, num_certs_); | |
| 279 return certs_[i]; | |
| 280 } | |
| 281 | |
| 282 std::vector<base::StringPiece> AsStringPieceVector() const { | |
| 283 std::vector<base::StringPiece> v(size()); | |
| 284 for (unsigned i = 0; i < size(); i++) { | |
| 285 v[i] = base::StringPiece( | |
| 286 reinterpret_cast<const char*>(certs_[i]->derCert.data), | |
| 287 certs_[i]->derCert.len); | |
| 288 } | |
| 289 | |
| 290 return v; | |
| 291 } | |
| 292 | |
| 293 private: | |
| 294 unsigned num_certs_; | |
| 295 CERTCertificate** certs_; | |
| 296 }; | |
| 297 | |
| 298 void DestroyCertificates(CERTCertificate** certs, unsigned len) { | |
| 299 for (unsigned i = 0; i < len; i++) | |
| 300 CERT_DestroyCertificate(certs[i]); | |
| 301 } | |
| 302 | |
| 303 // DNSValidationResult enumerates the possible outcomes from processing a | 253 // DNSValidationResult enumerates the possible outcomes from processing a |
| 304 // set of DNS records. | 254 // set of DNS records. |
| 305 enum DNSValidationResult { | 255 enum DNSValidationResult { |
| 306 DNSVR_SUCCESS, // the cert is immediately acceptable. | 256 DNSVR_SUCCESS, // the cert is immediately acceptable. |
| 307 DNSVR_FAILURE, // the cert is unconditionally rejected. | 257 DNSVR_FAILURE, // the cert is unconditionally rejected. |
| 308 DNSVR_CONTINUE, // perform CA validation as usual. | 258 DNSVR_CONTINUE, // perform CA validation as usual. |
| 309 }; | 259 }; |
| 310 | 260 |
| 311 // VerifyCAARecords processes DNSSEC validated RRDATA for a number of DNS CAA | 261 // VerifyCAARecords processes DNSSEC validated RRDATA for a number of DNS CAA |
| 312 // records and checks them against the given chain. | 262 // records and checks them against the given chain. |
| (...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 352 } | 302 } |
| 353 } | 303 } |
| 354 } | 304 } |
| 355 | 305 |
| 356 // If a CAA record was found, but nothing matched, then we reject the | 306 // If a CAA record was found, but nothing matched, then we reject the |
| 357 // certificate. | 307 // certificate. |
| 358 return DNSVR_FAILURE; | 308 return DNSVR_FAILURE; |
| 359 } | 309 } |
| 360 | 310 |
| 361 // CheckDNSSECChain tries to validate a DNSSEC chain embedded in | 311 // CheckDNSSECChain tries to validate a DNSSEC chain embedded in |
| 362 // |server_cert_nss_|. It returns true iff a chain is found that proves the | 312 // |server_cert_nss|. It returns true iff a chain is found that proves the |
| 363 // value of a CAA record that contains a valid public key fingerprint. | 313 // value of a CAA record that contains a valid public key fingerprint. |
| 364 // |port| contains the TCP port number that we connected to as CAA records can | 314 // |port| contains the TCP port number that we connected to as CAA records can |
| 365 // be specific to a given port. | 315 // be specific to a given port. |
| 366 DNSValidationResult CheckDNSSECChain( | 316 DNSValidationResult CheckDNSSECChain( |
| 367 const std::string& hostname, | 317 const std::string& hostname, |
| 368 CERTCertificate* server_cert_nss, | 318 CERTCertificate* server_cert_nss, |
| 369 uint16 port) { | 319 uint16 port) { |
| 370 if (!server_cert_nss) | 320 if (!server_cert_nss) |
| 371 return DNSVR_CONTINUE; | 321 return DNSVR_CONTINUE; |
| 372 | 322 |
| (...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 414 if (verifier.rrtype() != kDNS_CAA) | 364 if (verifier.rrtype() != kDNS_CAA) |
| 415 return DNSVR_CONTINUE; | 365 return DNSVR_CONTINUE; |
| 416 | 366 |
| 417 DNSValidationResult r = VerifyCAARecords( | 367 DNSValidationResult r = VerifyCAARecords( |
| 418 server_cert_nss, verifier.rrdatas(), port); | 368 server_cert_nss, verifier.rrdatas(), port); |
| 419 SECITEM_FreeItem(&dnssec_embedded_chain, PR_FALSE); | 369 SECITEM_FreeItem(&dnssec_embedded_chain, PR_FALSE); |
| 420 | 370 |
| 421 return r; | 371 return r; |
| 422 } | 372 } |
| 423 | 373 |
| 374 bool DomainBoundCertNegotiated(PRFileDesc* socket) { | |
| 375 // TODO(wtc,mattm): this is temporary while DBC support is changed into | |
| 376 // Channel ID. | |
| 377 return false; | |
| 378 } | |
| 379 | |
| 380 void DestroyCertificates(CERTCertificate** certs, size_t len) { | |
| 381 for (size_t i = 0; i < len; i++) | |
| 382 CERT_DestroyCertificate(certs[i]); | |
| 383 } | |
| 384 | |
| 385 // Helper function to make it easier to call BoundNetLog::AddByteTransferEvent | |
| 386 // from within the SSLClientSocketNSS::Core. | |
| 387 // AddByteTransferEvent expects to receive a const char*, which within the | |
| 388 // Core is backed by an IOBuffer. If the "const char*" is bound via | |
| 389 // base::Bind and posted to another thread, and the IOBuffer that backs that | |
| 390 // pointer then goes out of scope on the origin thread, this would result in | |
| 391 // an invalid read of a stale pointer. | |
| 392 // Instead, provide a signature that accepts an IOBuffer*, so that a reference | |
| 393 // to the owning IOBuffer can be bound to the Callback. This ensures that the | |
| 394 // IOBuffer will stay alive long enough to cross threads if needed. | |
| 395 void LogByteTransferEvent(BoundNetLog* net_log, NetLog::EventType event_type, | |
| 396 int len, IOBuffer* buffer) { | |
| 397 if (!net_log) | |
| 398 return; | |
| 399 net_log->AddByteTransferEvent(event_type, len, buffer->data()); | |
| 400 } | |
| 401 | |
| 402 // PeerCertificateChain is a helper object which extracts the certificate | |
| 403 // chain, as given by the server, from an NSS socket and performs the needed | |
| 404 // resource management. The first element of the chain is the leaf certificate | |
| 405 // and the other elements are in the order given by the server. | |
| 406 class PeerCertificateChain { | |
| 407 public: | |
| 408 PeerCertificateChain() {} | |
| 409 PeerCertificateChain(const PeerCertificateChain& other); | |
| 410 ~PeerCertificateChain(); | |
| 411 PeerCertificateChain& operator=(const PeerCertificateChain& other); | |
| 412 | |
| 413 // Resets the current chain, freeing any resources, and updates the current | |
| 414 // chain to be a copy of the chain stored in |nss_fd|. | |
| 415 // If |nss_fd| is NULL, then the current certificate chain will be freed. | |
| 416 void Reset(PRFileDesc* nss_fd); | |
| 417 | |
| 418 // Returns the current certificate chain as a vector of DER-encoded | |
| 419 // base::StringPieces. The returned vector remains valid until Reset is | |
| 420 // called. | |
| 421 std::vector<base::StringPiece> AsStringPieceVector() const; | |
| 422 | |
| 423 bool empty() const { return certs_.empty(); } | |
| 424 size_t size() const { return certs_.size(); } | |
| 425 | |
| 426 CERTCertificate* operator[](size_t index) const { | |
| 427 DCHECK_LT(index, certs_.size()); | |
| 428 return certs_[index]; | |
| 429 } | |
| 430 | |
| 431 private: | |
| 432 std::vector<CERTCertificate*> certs_; | |
| 433 }; | |
| 434 | |
| 435 PeerCertificateChain::PeerCertificateChain( | |
| 436 const PeerCertificateChain& other) { | |
| 437 *this = other; | |
| 438 } | |
| 439 | |
| 440 PeerCertificateChain::~PeerCertificateChain() { | |
| 441 Reset(NULL); | |
| 442 } | |
| 443 | |
| 444 PeerCertificateChain& PeerCertificateChain::operator=( | |
|
wtc
2012/06/01 01:02:38
Because OnHandshakeStateUpdated calls this operato
Ryan Sleevi
2012/06/01 01:30:04
Yes. They are thread-safe atomic ops, with no lock
| |
| 445 const PeerCertificateChain& other) { | |
| 446 if (this == &other) | |
| 447 return *this; | |
| 448 | |
| 449 Reset(NULL); | |
| 450 certs_.reserve(other.certs_.size()); | |
| 451 for (size_t i = 0; i < other.certs_.size(); ++i) | |
| 452 certs_.push_back(CERT_DupCertificate(other.certs_[i])); | |
| 453 | |
| 454 return *this; | |
| 455 } | |
| 456 | |
| 457 void PeerCertificateChain::Reset(PRFileDesc* nss_fd) { | |
| 458 for (size_t i = 0; i < certs_.size(); ++i) | |
| 459 CERT_DestroyCertificate(certs_[i]); | |
| 460 certs_.clear(); | |
| 461 | |
| 462 if (nss_fd == NULL) | |
| 463 return; | |
| 464 | |
| 465 unsigned int num_certs = 0; | |
| 466 SECStatus rv = SSL_PeerCertificateChain(nss_fd, NULL, &num_certs, 0); | |
| 467 DCHECK_EQ(SECSuccess, rv); | |
| 468 | |
| 469 // The handshake on |nss_fd| may not have completed. | |
|
wtc
2012/06/01 01:02:38
I believe we never call PeerCertificateChain::Rese
Ryan Sleevi
2012/06/01 01:30:04
This would either be a CHECK() (because vector_as_
| |
| 470 if (num_certs == 0) | |
| 471 return; | |
| 472 | |
| 473 certs_.resize(num_certs); | |
| 474 const unsigned int expected_num_certs = num_certs; | |
| 475 rv = SSL_PeerCertificateChain(nss_fd, vector_as_array(&certs_), | |
| 476 &num_certs, expected_num_certs); | |
| 477 DCHECK_EQ(SECSuccess, rv); | |
| 478 DCHECK_EQ(expected_num_certs, num_certs); | |
| 479 } | |
| 480 | |
| 481 std::vector<base::StringPiece> | |
| 482 PeerCertificateChain::AsStringPieceVector() const { | |
| 483 std::vector<base::StringPiece> v(certs_.size()); | |
| 484 for (unsigned i = 0; i < certs_.size(); i++) { | |
| 485 v[i] = base::StringPiece( | |
| 486 reinterpret_cast<const char*>(certs_[i]->derCert.data), | |
| 487 certs_[i]->derCert.len); | |
| 488 } | |
| 489 | |
| 490 return v; | |
| 491 } | |
| 492 | |
| 493 // HandshakeState is a helper struct used to pass handshake state between | |
| 494 // the NSS task runner and the network task runner. | |
| 495 // | |
| 496 // It contains variables that may be read or written on the NSS task runner, | |
|
wtc
2012/06/01 01:02:38
Nit: variables => members
| |
| 497 // but which also need to be read from the network task runner. The NSS task | |
| 498 // runner will notify the network task runner whenever this state changes, so | |
| 499 // that the network task runner can safely make a copy, which avoids the need | |
| 500 // for locking. | |
| 501 struct HandshakeState { | |
| 502 HandshakeState() { Reset(); } | |
| 503 | |
| 504 void Reset() { | |
| 505 next_proto_status = SSLClientSocket::kNextProtoUnsupported; | |
| 506 next_proto.clear(); | |
| 507 server_protos.clear(); | |
| 508 domain_bound_cert_type = CLIENT_CERT_INVALID_TYPE; | |
| 509 client_certs.clear(); | |
| 510 server_cert_chain.Reset(NULL); | |
| 511 server_cert = NULL; | |
| 512 predicted_cert_chain_correct = false; | |
| 513 resumed_handshake = false; | |
| 514 ssl_connection_status = 0; | |
| 515 } | |
| 516 | |
| 517 // Set to kNextProtoNegotiated if NPN was successfully negotiated, with the | |
| 518 // negotiated protocol stored in |next_proto|. | |
| 519 SSLClientSocket::NextProtoStatus next_proto_status; | |
| 520 std::string next_proto; | |
| 521 // If the server supports NPN, the protocols supported by the server. | |
| 522 std::string server_protos; | |
| 523 | |
| 524 // The type of domain bound cert that was exchanged, or | |
| 525 // CLIENT_CERT_INVALID_TYPE if no domain bound cert was negotiated or sent. | |
| 526 SSLClientCertType domain_bound_cert_type; | |
| 527 | |
| 528 // If the peer requests client certificate authentication, the set of | |
| 529 // certificates that matched the peer's criteria. | |
| 530 CertificateList client_certs; | |
| 531 | |
| 532 // Set when the handshake fully completes. | |
| 533 // | |
| 534 // The server certificate is first received from NSS as an NSS certificate | |
| 535 // chain (|server_cert_chain|) and then converted into a platform-specific | |
| 536 // X509Certificate object (|server_cert|). It's possible for some | |
| 537 // certificates to be successfully parsed by NSS, and not by the platform | |
| 538 // libraries (i.e.: when running within a sandbox, different parsing | |
| 539 // algorithms, etc), so it's not safe to assume that |server_cert| will | |
| 540 // always be non-NULL. | |
| 541 PeerCertificateChain server_cert_chain; | |
| 542 scoped_refptr<X509Certificate> server_cert; | |
| 543 | |
| 544 // True if the peer predicted a certificate chain (via | |
|
wtc
2012/06/01 01:02:38
"the peer predicted a certificate chain" is wrong.
| |
| 545 // Core::SetPredictedCertificates) and that prediction matched what the | |
| 546 // server sent. | |
| 547 bool predicted_cert_chain_correct; | |
| 548 | |
| 549 // True if the current handshake was the result of TLS session resumption. | |
| 550 bool resumed_handshake; | |
| 551 | |
| 552 // The negotiated security parameters (TLS version, cipher, extensions) | |
|
wtc
2012/06/01 01:02:38
Nit: add "of the SSL connection" at the end.
| |
| 553 int ssl_connection_status; | |
| 554 }; | |
| 555 | |
| 424 } // namespace | 556 } // namespace |
| 425 | 557 |
|
wtc
2012/06/01 01:02:38
Nit: delete this blank line.
| |
| 426 SSLClientSocketNSS::SSLClientSocketNSS(ClientSocketHandle* transport_socket, | 558 |
| 427 const HostPortPair& host_and_port, | 559 // SSLClientSocketNSS::Core provides a thread-safe, ref-counted core that is |
| 428 const SSLConfig& ssl_config, | 560 // able to marshal data between NSS functions and an underlying transport |
| 429 SSLHostInfo* ssl_host_info, | 561 // socket. |
| 430 const SSLClientSocketContext& context) | 562 // |
| 431 : transport_send_busy_(false), | 563 // All public functions are meant to be called from the network task runner, |
| 564 // and any callbacks supplied will be invoked there as well, provided that | |
| 565 // Detach() has not been called yet. | |
| 566 // | |
| 567 ///////////////////////////////////////////////////////////////////////////// | |
| 568 // | |
| 569 // Threading within SSLClientSocketNSS and SSLClientSocketNSS::Core: | |
| 570 // | |
| 571 // Because NSS may block on either hardware or user input during operations | |
| 572 // such as signing, creating certificates, or locating private keys, the Core | |
| 573 // handles all of the interactions with the underlying NSS SSL socket, so | |
| 574 // that these blocking calls can be executed on a dedicated task runner. | |
| 575 // | |
| 576 // Note that the network task runner and the NSS task runner may be executing | |
| 577 // on the same thread. If that happens, then it's more performant to try to | |
| 578 // complete as much work as possible synchronously, even if it might block, | |
| 579 // rather than continually PostTask-ing to the same thread. | |
| 580 // | |
| 581 // Because NSS functions should only be called on the NSS task runner, while | |
| 582 // I/O resources should only be accessed on the network task runner, most | |
| 583 // public functions are implemented via three methods, each with different | |
| 584 // task runner affinities. | |
| 585 // | |
| 586 // In the single-threaded mode (where the network and NSS task runners run on | |
| 587 // the same thread), these are all attempted synchronously, while in the | |
| 588 // multi-threaded mode, message passing is used. | |
| 589 // | |
| 590 // 1) NSS Task Runner: Execute NSS function (DoPayloadRead, DoPayloadWrite, | |
| 591 // DoHandshake) | |
| 592 // 2) NSS Task Runner: Prepare data to go from NSS to an IO function: | |
| 593 // (BufferRecv, BufferSend) | |
| 594 // 3) Network Task Runner: Perform IO on that data (DoBufferRecv, | |
| 595 // DoBufferSend, DoGetDomainBoundCert, OnGetDomainBoundCertComplete) | |
| 596 // 4) Both Task Runners: Callback for asynchronous completion or to marshal | |
| 597 // data from the network task runner back to NSS (BufferRecvComplete, | |
| 598 // BufferSendComplete, OnHandshakeIOComplete) | |
| 599 // | |
| 600 ///////////////////////////////////////////////////////////////////////////// | |
| 601 // Single-threaded example | |
| 602 // | |
| 603 // |--------------------------Network Task Runner--------------------------| | |
| 604 // SSLClientSocketNSS Core (Transport Socket) | |
| 605 // Read() | |
| 606 // |-------------------------V | |
| 607 // Read() | |
| 608 // | | |
| 609 // DoPayloadRead() | |
| 610 // | | |
| 611 // BufferRecv() | |
| 612 // | | |
| 613 // DoBufferRecv() | |
| 614 // |-------------------------V | |
| 615 // Read() | |
| 616 // V-------------------------| | |
| 617 // BufferRecvComplete() | |
| 618 // | | |
| 619 // PostOrRunCallback() | |
| 620 // V-------------------------| | |
| 621 // (Read Callback) | |
| 622 // | |
| 623 ///////////////////////////////////////////////////////////////////////////// | |
| 624 // Multi-threaded example: | |
| 625 // | |
| 626 // |--------------------Network Task Runner-------------|--NSS Task Runner--| | |
| 627 // SSLClientSocketNSS Core Socket Core | |
| 628 // Read() | |
| 629 // |---------------------V | |
| 630 // Read() | |
| 631 // |-------------------------------V | |
| 632 // Read() | |
| 633 // | | |
| 634 // DoPayloadRead() | |
| 635 // | | |
| 636 // BufferRecv | |
| 637 // V-------------------------------| | |
| 638 // DoBufferRecv | |
| 639 // |----------------V | |
| 640 // Read() | |
| 641 // V----------------| | |
| 642 // BufferRecvComplete() | |
| 643 // |-------------------------------V | |
| 644 // BufferRecvComplete() | |
| 645 // | | |
| 646 // PostOrRunCallback() | |
| 647 // V-------------------------------| | |
| 648 // PostOrRunCallback() | |
| 649 // V---------------------| | |
| 650 // (Read Callback) | |
| 651 // | |
| 652 ///////////////////////////////////////////////////////////////////////////// | |
| 653 class SSLClientSocketNSS::Core : public base::RefCountedThreadSafe<Core> { | |
| 654 public: | |
| 655 // Creates a new Core. | |
| 656 // | |
| 657 // Any calls to NSS are executed on the |nss_task_runner|, while any calls | |
| 658 // that need to operate on the underlying transport, net log, or server | |
| 659 // bound certificate fetching will happen on the |network_task_runner|, so | |
| 660 // that their lifetimes match that of the owning SSLClientSocketNSS. | |
| 661 // | |
| 662 // The caller retains ownership of |transport|, |net_log|, and | |
| 663 // |server_bound_cert_service|, and they will not be accessed once Detach() | |
| 664 // has been called. | |
| 665 Core(base::SequencedTaskRunner* network_task_runner, | |
| 666 base::SingleThreadTaskRunner* nss_task_runner, | |
|
wtc
2012/06/01 01:02:38
Why do we use different types of task runners?
net
Ryan Sleevi
2012/06/01 01:30:04
willchan can probably provide more, but the prefer
| |
| 667 ClientSocketHandle* transport, | |
| 668 const HostPortPair& host_and_port, | |
| 669 const SSLConfig& ssl_config, | |
| 670 BoundNetLog* net_log, | |
| 671 ServerBoundCertService* server_bound_cert_service); | |
| 672 | |
| 673 // Called on the network task runner. | |
| 674 // Transfers ownership of |socket|, an NSS SSL socket, and |buffers|, the | |
| 675 // underlying memio implementation, to the Core. Returns true if the Core | |
| 676 // was successfully registered with the socket. | |
| 677 bool Init(PRFileDesc* socket, memio_Private* buffers); | |
| 678 | |
| 679 // Called on the network task runner. | |
| 680 // Sets the predicted certificate chain that the peer will send, for use | |
| 681 // with the TLS CachedInfo extension. If called, it must not be called | |
| 682 // before Init() or after Connect(). | |
| 683 void SetPredictedCertificates( | |
| 684 const std::vector<std::string>& predicted_certificates); | |
| 685 | |
| 686 // Called on the network task runner. | |
| 687 // | |
| 688 // Attempts to perform an SSL handshake. If the handshake cannot be | |
| 689 // completed synchronously, returns ERR_IO_PENDING, invoking |callback| on | |
| 690 // the network task runner once the handshake has completed. Otherwise, | |
| 691 // returns OK on success or a network error code on failure. | |
| 692 int Connect(const CompletionCallback& callback); | |
| 693 | |
| 694 // Called on the network task runner. | |
| 695 // Signals that the resources owned by the network task runner are going | |
| 696 // away. No further callbacks will be invoked on the network task runner. | |
| 697 // May be called at any time. | |
| 698 void Detach(); | |
| 699 | |
| 700 // Called on the network task runner. | |
| 701 // Returns the current state of the underlying SSL socket. May be called at | |
| 702 // any time. | |
| 703 const HandshakeState& state() const { return network_handshake_state_; } | |
| 704 | |
| 705 // Called on the network task runner. | |
| 706 // Read() and Write() mirror the net::Socket functions of the same name. | |
| 707 // If ERR_IO_PENDING is returned, |callback| will be invoked on the network | |
| 708 // task runner at a later point, unless the caller calls Detach(). | |
| 709 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback); | |
| 710 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback); | |
| 711 | |
| 712 private: | |
| 713 friend class base::RefCountedThreadSafe<Core>; | |
| 714 ~Core(); | |
| 715 | |
| 716 enum State { | |
| 717 STATE_NONE, | |
| 718 STATE_HANDSHAKE, | |
| 719 STATE_GET_DOMAIN_BOUND_CERT_COMPLETE, | |
| 720 }; | |
| 721 | |
| 722 bool OnNSSTaskRunner() const; | |
| 723 bool OnNetworkTaskRunner() const; | |
| 724 | |
| 725 //////////////////////////////////////////////////////////////////////////// | |
| 726 // Methods that are ONLY called on the NSS task runner: | |
| 727 //////////////////////////////////////////////////////////////////////////// | |
| 728 | |
| 729 // Called by NSS during full handshakes to allow the application to | |
| 730 // verify the certificate. Instead of verifying the certificate in the midst | |
| 731 // of the handshake, SECSuccess is always returned and the peer's certificate | |
| 732 // is verified afterwards. | |
| 733 // This behaviour is an artifact of the original SSLClientSocketWin | |
| 734 // implementation, which could not verify the peer's certificate until after | |
| 735 // the handshake had completed, as well as bugs in NSS that prevent | |
| 736 // SSL_RestartHandshakeAfterCertReq from working. | |
| 737 static SECStatus OwnAuthCertHandler(void* arg, | |
| 738 PRFileDesc* socket, | |
| 739 PRBool checksig, | |
| 740 PRBool is_server); | |
| 741 | |
| 742 // Callbacks called by NSS when the peer requests client certificate | |
| 743 // authentication. | |
| 744 // See the documentation in third_party/nss/ssl/ssl.h for the meanings of | |
| 745 // the arguments. | |
| 746 #if defined(NSS_PLATFORM_CLIENT_AUTH) | |
| 747 // When NSS has been integrated with awareness of the underlying system | |
| 748 // cryptographic libraries, this callback allows the caller to supply a | |
| 749 // native platform certificate and key for use by NSS. At most, one of | |
| 750 // either (result_certs, result_private_key) or (result_nss_certificate, | |
| 751 // result_nss_private_key) should be set. | |
| 752 // |arg| contains a pointer to the current SSLClientSocketNSS::Core. | |
| 753 static SECStatus PlatformClientAuthHandler( | |
| 754 void* arg, | |
| 755 PRFileDesc* socket, | |
| 756 CERTDistNames* ca_names, | |
| 757 CERTCertList** result_certs, | |
| 758 void** result_private_key, | |
| 759 CERTCertificate** result_nss_certificate, | |
| 760 SECKEYPrivateKey** result_nss_private_key); | |
| 761 #else | |
| 762 static SECStatus ClientAuthHandler(void* arg, | |
| 763 PRFileDesc* socket, | |
| 764 CERTDistNames* ca_names, | |
| 765 CERTCertificate** result_certificate, | |
| 766 SECKEYPrivateKey** result_private_key); | |
| 767 #endif | |
| 768 | |
| 769 // Called by NSS once the handshake has completed. | |
| 770 // |arg| contains a pointer to the current SSLClientSocketNSS::Core. | |
| 771 static void HandshakeCallback(PRFileDesc* socket, void* arg); | |
| 772 | |
| 773 // Called by NSS if the peer supports the NPN handshake extension, to allow | |
| 774 // the application to select the protocol to use. | |
| 775 // See the documentation for SSLNextProtocolCallback in | |
| 776 // third_party/nss/ssl/ssl.h for the meanings of the arguments. | |
| 777 // |arg| contains a pointer to the current SSLClientSocketNSS::Core. | |
| 778 static SECStatus NextProtoCallback(void* arg, | |
| 779 PRFileDesc* fd, | |
| 780 const unsigned char* protos, | |
| 781 unsigned int protos_len, | |
| 782 unsigned char* proto_out, | |
| 783 unsigned int* proto_out_len, | |
| 784 unsigned int proto_max_len); | |
| 785 | |
| 786 // Handles an NSS error generated while handshaking or performing IO. | |
| 787 // Returns a network error code mapped from the original NSS error. | |
| 788 int HandleNSSError(PRErrorCode error, bool handshake_error); | |
| 789 | |
| 790 int DoHandshakeLoop(int last_io_result); | |
| 791 int DoReadLoop(int result); | |
| 792 int DoWriteLoop(int result); | |
| 793 | |
| 794 int DoHandshake(); | |
| 795 int DoGetDBCertComplete(int result); | |
| 796 | |
| 797 int DoPayloadRead(); | |
| 798 int DoPayloadWrite(); | |
| 799 | |
| 800 bool DoTransportIO(); | |
| 801 int BufferRecv(); | |
| 802 int BufferSend(); | |
| 803 | |
| 804 void OnRecvComplete(int result); | |
| 805 void OnSendComplete(int result); | |
| 806 | |
| 807 void DoConnectCallback(int result); | |
| 808 void DoReadCallback(int result); | |
| 809 void DoWriteCallback(int result); | |
| 810 | |
| 811 // Domain bound cert client auth handler. | |
| 812 // Returns the value the ClientAuthHandler function should return. | |
| 813 SECStatus DomainBoundClientAuthHandler( | |
| 814 const SECItem* cert_types, | |
| 815 CERTCertificate** result_certificate, | |
| 816 SECKEYPrivateKey** result_private_key); | |
| 817 | |
| 818 // ImportDBCertAndKey is a helper function for turning a DER-encoded cert and | |
| 819 // key into a CERTCertificate and SECKEYPrivateKey. Returns OK upon success | |
| 820 // and an error code otherwise. | |
| 821 // Requires |domain_bound_private_key_| and |domain_bound_cert_| to have been | |
| 822 // set by a call to ServerBoundCertService->GetDomainBoundCert. The caller | |
| 823 // takes ownership of the |*cert| and |*key|. | |
| 824 int ImportDBCertAndKey(CERTCertificate** cert, SECKEYPrivateKey** key); | |
| 825 | |
| 826 // Updates the NSS and platform specific certificates. | |
| 827 void UpdateServerCert(); | |
| 828 // Updates the nss_handshake_state_ with the negotiated security parameters. | |
| 829 void UpdateConnectionStatus(); | |
| 830 // Record histograms for DBC support during full handshakes - resumed | |
| 831 // handshakes are ignored. | |
| 832 void RecordDomainBoundCertSupport() const; | |
| 833 | |
| 834 //////////////////////////////////////////////////////////////////////////// | |
| 835 // Methods that are ONLY called on the network task runner: | |
| 836 //////////////////////////////////////////////////////////////////////////// | |
| 837 int DoBufferRecv(IOBuffer* buffer, int len); | |
| 838 int DoBufferSend(IOBuffer* buffer, int len); | |
| 839 int DoGetDomainBoundCert(const std::string& origin, | |
| 840 const std::vector<uint8>& requested_cert_types); | |
| 841 | |
| 842 void OnGetDomainBoundCertComplete(int result); | |
| 843 void OnHandshakeStateUpdated(const HandshakeState& state); | |
| 844 | |
| 845 //////////////////////////////////////////////////////////////////////////// | |
| 846 // Methods that are called on both the network task runner and the NSS | |
| 847 // task runner. | |
| 848 //////////////////////////////////////////////////////////////////////////// | |
| 849 void OnHandshakeIOComplete(int result); | |
| 850 void BufferRecvComplete(IOBuffer* buffer, int result); | |
| 851 void BufferSendComplete(int result); | |
| 852 | |
| 853 // PostOrRunCallback is a helper function to ensure that |callback| is | |
| 854 // invoked on the network task runner, but only if Detach() has not yet | |
| 855 // been called. | |
| 856 void PostOrRunCallback(const tracked_objects::Location& location, | |
| 857 const base::Closure& callback); | |
| 858 | |
| 859 //////////////////////////////////////////////////////////////////////////// | |
| 860 // Members that are ONLY accessed on the network task runner: | |
| 861 //////////////////////////////////////////////////////////////////////////// | |
| 862 | |
| 863 // True if the owning SSLClientSocketNSS has called Detach(). No further | |
| 864 // callbacks will be invoked nor access to variables owned by the network | |
| 865 // task runner. | |
| 866 bool detached_; | |
| 867 | |
| 868 // The underlying transport to use for network IO. | |
| 869 ClientSocketHandle* transport_; | |
| 870 base::WeakPtrFactory<BoundNetLog> weak_net_log_factory_; | |
| 871 | |
| 872 // The current connection state. Mirrors |nss_handshake_state_|. | |
|
wtc
2012/06/01 01:02:38
Nit: connection state => handshake state
Please f
| |
| 873 HandshakeState network_handshake_state_; | |
| 874 | |
| 875 ServerBoundCertService* server_bound_cert_service_; | |
| 876 ServerBoundCertService::RequestHandle domain_bound_cert_request_handle_; | |
| 877 | |
| 878 //////////////////////////////////////////////////////////////////////////// | |
| 879 // Members that are ONLY accessed on the NSS task runner: | |
| 880 //////////////////////////////////////////////////////////////////////////// | |
| 881 HostPortPair host_and_port_; | |
| 882 SSLConfig ssl_config_; | |
| 883 | |
| 884 // NSS SSL socket. | |
| 885 PRFileDesc* nss_fd_; | |
| 886 | |
| 887 // Buffers for the network end of the SSL state machine | |
| 888 memio_Private* nss_bufs_; | |
| 889 | |
| 890 // The certificate chain, in DER form, that is expected to be received from | |
| 891 // the server. | |
| 892 std::vector<std::string> predicted_certs_; | |
| 893 | |
| 894 State next_handshake_state_; | |
| 895 | |
| 896 // True if domain bound certs were negotiated. | |
| 897 bool domain_bound_cert_xtn_negotiated_; | |
| 898 // True if the handshake state machine was interrupted for client auth. | |
| 899 bool client_auth_cert_needed_; | |
| 900 // True if NSS has called HandshakeCallback. | |
| 901 bool handshake_callback_called_; | |
| 902 | |
| 903 HandshakeState nss_handshake_state_; | |
| 904 | |
| 905 bool transport_recv_busy_; | |
| 906 bool transport_recv_eof_; | |
| 907 bool transport_send_busy_; | |
| 908 | |
| 909 // Used by Read function. | |
| 910 scoped_refptr<IOBuffer> user_read_buf_; | |
| 911 int user_read_buf_len_; | |
| 912 | |
| 913 // Used by Write function. | |
| 914 scoped_refptr<IOBuffer> user_write_buf_; | |
| 915 int user_write_buf_len_; | |
| 916 | |
| 917 CompletionCallback user_connect_callback_; | |
| 918 CompletionCallback user_read_callback_; | |
| 919 CompletionCallback user_write_callback_; | |
| 920 | |
| 921 //////////////////////////////////////////////////////////////////////////// | |
| 922 // Members that are accessed on both the network task runner and the NSS | |
| 923 // task runner. | |
| 924 //////////////////////////////////////////////////////////////////////////// | |
| 925 scoped_refptr<base::SequencedTaskRunner> network_task_runner_; | |
| 926 scoped_refptr<base::SingleThreadTaskRunner> nss_task_runner_; | |
| 927 | |
| 928 // Dereferenced only on the network task runner, but bound to tasks destined | |
| 929 // for the network task runner from the NSS task runner. | |
| 930 base::WeakPtr<BoundNetLog> weak_net_log_; | |
| 931 | |
| 932 // Written on the network task runner by the |server_bound_cert_service_|, | |
| 933 // prior to invoking OnHandshakeIOComplete. | |
| 934 // Read on the NSS task runner when once OnHandshakeIOComplete is invoked | |
| 935 // on the NSS task runner. | |
| 936 SSLClientCertType domain_bound_cert_type_; | |
| 937 std::string domain_bound_private_key_; | |
| 938 std::string domain_bound_cert_; | |
| 939 | |
| 940 DISALLOW_COPY_AND_ASSIGN(Core); | |
| 941 }; | |
| 942 | |
| 943 SSLClientSocketNSS::Core::Core( | |
| 944 base::SequencedTaskRunner* network_task_runner, | |
| 945 base::SingleThreadTaskRunner* nss_task_runner, | |
| 946 ClientSocketHandle* transport, | |
| 947 const HostPortPair& host_and_port, | |
| 948 const SSLConfig& ssl_config, | |
| 949 BoundNetLog* net_log, | |
| 950 ServerBoundCertService* server_bound_cert_service) | |
| 951 : detached_(false), | |
| 952 transport_(transport), | |
| 953 weak_net_log_factory_(net_log), | |
| 954 server_bound_cert_service_(server_bound_cert_service), | |
| 955 domain_bound_cert_request_handle_(NULL), | |
| 956 host_and_port_(host_and_port), | |
| 957 ssl_config_(ssl_config), | |
| 958 nss_fd_(NULL), | |
| 959 nss_bufs_(NULL), | |
| 960 next_handshake_state_(STATE_NONE), | |
| 961 domain_bound_cert_xtn_negotiated_(false), | |
| 962 client_auth_cert_needed_(false), | |
| 963 handshake_callback_called_(false), | |
| 432 transport_recv_busy_(false), | 964 transport_recv_busy_(false), |
| 433 transport_recv_eof_(false), | 965 transport_recv_eof_(false), |
| 434 transport_(transport_socket), | 966 transport_send_busy_(false), |
| 435 host_and_port_(host_and_port), | |
| 436 ssl_config_(ssl_config), | |
| 437 user_read_buf_len_(0), | 967 user_read_buf_len_(0), |
| 438 user_write_buf_len_(0), | 968 user_write_buf_len_(0), |
| 439 server_cert_nss_(NULL), | 969 network_task_runner_(network_task_runner), |
| 440 server_cert_verify_result_(NULL), | 970 nss_task_runner_(nss_task_runner), |
| 441 ssl_connection_status_(0), | 971 weak_net_log_(weak_net_log_factory_.GetWeakPtr()), |
| 442 client_auth_cert_needed_(false), | 972 domain_bound_cert_type_(CLIENT_CERT_INVALID_TYPE) { |
| 443 cert_verifier_(context.cert_verifier), | 973 } |
| 444 domain_bound_cert_xtn_negotiated_(false), | 974 |
| 445 server_bound_cert_service_(context.server_bound_cert_service), | 975 SSLClientSocketNSS::Core::~Core() { |
| 446 domain_bound_cert_type_(CLIENT_CERT_INVALID_TYPE), | 976 // TODO(wtc): Send SSL close_notify alert. |
| 447 domain_bound_cert_request_handle_(NULL), | 977 if (nss_fd_ != NULL) { |
| 448 handshake_callback_called_(false), | 978 PR_Close(nss_fd_); |
| 449 completed_handshake_(false), | 979 nss_fd_ = NULL; |
| 450 ssl_session_cache_shard_(context.ssl_session_cache_shard), | 980 } |
| 451 predicted_cert_chain_correct_(false), | 981 } |
| 452 next_handshake_state_(STATE_NONE), | 982 |
| 453 nss_fd_(NULL), | 983 bool SSLClientSocketNSS::Core::Init(PRFileDesc* socket, |
| 454 nss_bufs_(NULL), | 984 memio_Private* buffers) { |
| 455 net_log_(transport_socket->socket()->NetLog()), | 985 DCHECK(OnNetworkTaskRunner()); |
| 456 ssl_host_info_(ssl_host_info), | 986 DCHECK(!nss_fd_); |
| 457 transport_security_state_(context.transport_security_state), | 987 DCHECK(!nss_bufs_); |
| 458 next_proto_status_(kNextProtoUnsupported), | 988 |
| 459 valid_thread_id_(base::kInvalidThreadId) { | 989 nss_fd_ = socket; |
| 460 EnterFunction(""); | 990 nss_bufs_ = buffers; |
| 461 } | 991 |
| 462 | 992 SECStatus rv = SECSuccess; |
| 463 SSLClientSocketNSS::~SSLClientSocketNSS() { | 993 |
| 464 EnterFunction(""); | 994 if (!ssl_config_.next_protos.empty()) { |
| 465 Disconnect(); | 995 rv = SSL_SetNextProtoCallback( |
| 466 LeaveFunction(""); | 996 nss_fd_, SSLClientSocketNSS::Core::NextProtoCallback, this); |
| 467 } | 997 if (rv != SECSuccess) |
| 468 | 998 LogFailedNSSFunction(*weak_net_log_, "SSL_SetNextProtoCallback", ""); |
| 469 // static | 999 } |
| 470 void SSLClientSocket::ClearSessionCache() { | 1000 |
| 471 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't | 1001 rv = SSL_AuthCertificateHook( |
| 472 // bother initializing NSS just to clear an empty SSL session cache. | 1002 nss_fd_, SSLClientSocketNSS::Core::OwnAuthCertHandler, this); |
| 473 if (!NSS_IsInitialized()) | 1003 if (rv != SECSuccess) { |
| 1004 LogFailedNSSFunction(*weak_net_log_, "SSL_AuthCertificateHook", ""); | |
| 1005 return false; | |
| 1006 } | |
| 1007 | |
| 1008 #if defined(NSS_PLATFORM_CLIENT_AUTH) | |
| 1009 rv = SSL_GetPlatformClientAuthDataHook( | |
| 1010 nss_fd_, SSLClientSocketNSS::Core::PlatformClientAuthHandler, | |
| 1011 this); | |
| 1012 #else | |
| 1013 rv = SSL_GetClientAuthDataHook( | |
| 1014 nss_fd_, SSLClientSocketNSS::Core::ClientAuthHandler, this); | |
| 1015 #endif | |
| 1016 if (rv != SECSuccess) { | |
| 1017 LogFailedNSSFunction(*weak_net_log_, "SSL_GetClientAuthDataHook", ""); | |
| 1018 return false; | |
| 1019 } | |
| 1020 | |
| 1021 rv = SSL_HandshakeCallback( | |
| 1022 nss_fd_, SSLClientSocketNSS::Core::HandshakeCallback, this); | |
| 1023 if (rv != SECSuccess) { | |
| 1024 LogFailedNSSFunction(*weak_net_log_, "SSL_HandshakeCallback", ""); | |
| 1025 return false; | |
| 1026 } | |
| 1027 | |
| 1028 return true; | |
| 1029 } | |
| 1030 | |
| 1031 void SSLClientSocketNSS::Core::SetPredictedCertificates( | |
| 1032 const std::vector<std::string>& predicted_certs) { | |
| 1033 if (predicted_certs.empty()) | |
| 474 return; | 1034 return; |
| 475 | 1035 |
| 476 SSL_ClearSessionCache(); | 1036 if (!OnNSSTaskRunner()) { |
| 477 } | 1037 DCHECK(!detached_); |
| 478 | 1038 nss_task_runner_->PostTask( |
| 479 void SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) { | 1039 FROM_HERE, |
| 480 EnterFunction(""); | 1040 base::Bind(&Core::SetPredictedCertificates, this, predicted_certs)); |
| 481 ssl_info->Reset(); | |
| 482 if (!server_cert_nss_) | |
| 483 return; | 1041 return; |
| 484 | 1042 } |
| 485 ssl_info->cert_status = server_cert_verify_result_->cert_status; | 1043 |
| 486 ssl_info->cert = server_cert_verify_result_->verified_cert; | 1044 DCHECK(nss_fd_); |
| 487 ssl_info->connection_status = ssl_connection_status_; | 1045 |
| 488 ssl_info->public_key_hashes = server_cert_verify_result_->public_key_hashes; | 1046 predicted_certs_ = predicted_certs; |
| 489 for (std::vector<SHA1Fingerprint>::const_iterator | 1047 |
| 490 i = side_pinned_public_keys_.begin(); | 1048 scoped_array<CERTCertificate*> certs( |
| 491 i != side_pinned_public_keys_.end(); i++) { | 1049 new CERTCertificate*[predicted_certs.size()]); |
| 492 ssl_info->public_key_hashes.push_back(*i); | 1050 |
| 493 } | 1051 for (size_t i = 0; i < predicted_certs.size(); i++) { |
| 494 ssl_info->is_issued_by_known_root = | 1052 SECItem derCert; |
| 495 server_cert_verify_result_->is_issued_by_known_root; | 1053 derCert.data = const_cast<uint8*>(reinterpret_cast<const uint8*>( |
| 496 ssl_info->client_cert_sent = WasDomainBoundCertSent() || | 1054 predicted_certs[i].data())); |
| 497 (ssl_config_.send_client_cert && ssl_config_.client_cert); | 1055 derCert.len = predicted_certs[i].size(); |
| 498 | 1056 certs[i] = CERT_NewTempCertificate( |
| 499 PRUint16 cipher_suite = | 1057 CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */, |
| 500 SSLConnectionStatusToCipherSuite(ssl_connection_status_); | 1058 PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */); |
| 501 SSLCipherSuiteInfo cipher_info; | 1059 if (!certs[i]) { |
| 502 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite, | 1060 DestroyCertificates(&certs[0], i); |
| 503 &cipher_info, sizeof(cipher_info)); | 1061 NOTREACHED(); |
| 504 if (ok == SECSuccess) { | 1062 return; |
| 505 ssl_info->security_bits = cipher_info.effectiveKeyBits; | |
| 506 } else { | |
| 507 ssl_info->security_bits = -1; | |
| 508 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError() | |
| 509 << " for cipherSuite " << cipher_suite; | |
| 510 } | |
| 511 | |
| 512 PRBool last_handshake_resumed; | |
| 513 ok = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed); | |
| 514 if (ok == SECSuccess) { | |
| 515 if (last_handshake_resumed) { | |
| 516 ssl_info->handshake_type = SSLInfo::HANDSHAKE_RESUME; | |
| 517 } else { | |
| 518 ssl_info->handshake_type = SSLInfo::HANDSHAKE_FULL; | |
| 519 } | 1063 } |
| 520 } | 1064 } |
| 521 | 1065 |
| 522 LeaveFunction(""); | 1066 SECStatus rv; |
| 523 } | 1067 #ifdef SSL_ENABLE_CACHED_INFO |
| 524 | 1068 rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(), |
| 525 void SSLClientSocketNSS::GetSSLCertRequestInfo( | 1069 predicted_certs.size()); |
| 526 SSLCertRequestInfo* cert_request_info) { | 1070 DCHECK_EQ(SECSuccess, rv); |
| 527 EnterFunction(""); | 1071 #else |
| 528 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair | 1072 rv = SECFailure; // Not implemented. |
| 529 cert_request_info->host_and_port = host_and_port_.ToString(); | 1073 #endif |
| 530 cert_request_info->client_certs = client_certs_; | 1074 DestroyCertificates(&certs[0], predicted_certs.size()); |
| 531 LeaveFunction(cert_request_info->client_certs.size()); | 1075 |
| 532 } | 1076 if (rv != SECSuccess) { |
| 533 | 1077 LOG(WARNING) << "SetPredictedCertificates failed: " |
| 534 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label, | 1078 << host_and_port_.ToString(); |
| 535 bool has_context, | 1079 } |
| 536 const base::StringPiece& context, | 1080 } |
| 537 unsigned char* out, | 1081 |
| 538 unsigned int outlen) { | 1082 int SSLClientSocketNSS::Core::Connect(const CompletionCallback& callback) { |
| 539 if (!IsConnected()) | 1083 if (!OnNSSTaskRunner()) { |
| 540 return ERR_SOCKET_NOT_CONNECTED; | 1084 DCHECK(!detached_); |
| 541 SECStatus result = SSL_ExportKeyingMaterial( | 1085 bool posted = nss_task_runner_->PostTask( |
| 542 nss_fd_, label.data(), label.size(), has_context, | 1086 FROM_HERE, |
| 543 reinterpret_cast<const unsigned char*>(context.data()), | 1087 base::Bind(IgnoreResult(&Core::Connect), this, callback)); |
| 544 context.length(), out, outlen); | 1088 return posted ? ERR_IO_PENDING : ERR_ABORTED; |
| 545 if (result != SECSuccess) { | 1089 } |
| 546 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", ""); | 1090 |
| 547 return MapNSSError(PORT_GetError()); | 1091 DCHECK(OnNSSTaskRunner()); |
| 548 } | 1092 DCHECK_EQ(STATE_NONE, next_handshake_state_); |
| 549 return OK; | |
| 550 } | |
| 551 | |
| 552 SSLClientSocket::NextProtoStatus | |
| 553 SSLClientSocketNSS::GetNextProto(std::string* proto, | |
| 554 std::string* server_protos) { | |
| 555 *proto = next_proto_; | |
| 556 *server_protos = server_protos_; | |
| 557 return next_proto_status_; | |
| 558 } | |
| 559 | |
| 560 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) { | |
| 561 EnterFunction(""); | |
| 562 DCHECK(transport_.get()); | |
| 563 DCHECK(next_handshake_state_ == STATE_NONE); | |
| 564 DCHECK(user_read_callback_.is_null()); | 1093 DCHECK(user_read_callback_.is_null()); |
| 565 DCHECK(user_write_callback_.is_null()); | 1094 DCHECK(user_write_callback_.is_null()); |
| 566 DCHECK(user_connect_callback_.is_null()); | 1095 DCHECK(user_connect_callback_.is_null()); |
| 567 DCHECK(!user_read_buf_); | 1096 DCHECK(!user_read_buf_); |
| 568 DCHECK(!user_write_buf_); | 1097 DCHECK(!user_write_buf_); |
| 569 | 1098 |
| 570 EnsureThreadIdAssigned(); | 1099 next_handshake_state_ = STATE_HANDSHAKE; |
| 571 | 1100 int rv = DoHandshakeLoop(OK); |
| 572 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL); | |
| 573 | |
| 574 int rv = Init(); | |
| 575 if (rv != OK) { | |
| 576 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 577 return rv; | |
| 578 } | |
| 579 | |
| 580 rv = InitializeSSLOptions(); | |
| 581 if (rv != OK) { | |
| 582 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 583 return rv; | |
| 584 } | |
| 585 | |
| 586 rv = InitializeSSLPeerName(); | |
| 587 if (rv != OK) { | |
| 588 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 589 return rv; | |
| 590 } | |
| 591 | |
| 592 if (ssl_config_.cached_info_enabled && ssl_host_info_.get()) { | |
| 593 GotoState(STATE_LOAD_SSL_HOST_INFO); | |
| 594 } else { | |
| 595 GotoState(STATE_HANDSHAKE); | |
| 596 } | |
| 597 | |
| 598 rv = DoHandshakeLoop(OK); | |
| 599 if (rv == ERR_IO_PENDING) { | 1101 if (rv == ERR_IO_PENDING) { |
| 600 user_connect_callback_ = callback; | 1102 user_connect_callback_ = callback; |
| 601 } else { | 1103 } else if (rv > OK) { |
| 602 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | 1104 rv = OK; |
| 603 } | 1105 } |
| 604 | 1106 if (rv != ERR_IO_PENDING && !OnNetworkTaskRunner()) |
| 605 LeaveFunction(""); | 1107 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv)); |
| 606 return rv > OK ? OK : rv; | 1108 |
| 607 } | 1109 return rv; |
| 608 | 1110 } |
| 609 void SSLClientSocketNSS::Disconnect() { | 1111 |
| 610 EnterFunction(""); | 1112 void SSLClientSocketNSS::Core::Detach() { |
| 611 | 1113 DCHECK(OnNetworkTaskRunner()); |
| 612 CHECK(CalledOnValidThread()); | 1114 |
| 613 | 1115 detached_ = true; |
| 614 // Shut down anything that may call us back. | 1116 transport_ = NULL; |
| 615 verifier_.reset(); | 1117 weak_net_log_factory_.InvalidateWeakPtrs(); |
| 616 transport_->socket()->Disconnect(); | 1118 |
| 1119 network_handshake_state_.Reset(); | |
| 617 | 1120 |
| 618 if (domain_bound_cert_request_handle_ != NULL) { | 1121 if (domain_bound_cert_request_handle_ != NULL) { |
| 619 server_bound_cert_service_->CancelRequest( | 1122 server_bound_cert_service_->CancelRequest( |
| 620 domain_bound_cert_request_handle_); | 1123 domain_bound_cert_request_handle_); |
| 621 domain_bound_cert_request_handle_ = NULL; | 1124 domain_bound_cert_request_handle_ = NULL; |
| 622 } | 1125 } |
| 623 | 1126 } |
| 624 // TODO(wtc): Send SSL close_notify alert. | 1127 |
| 625 if (nss_fd_ != NULL) { | 1128 int SSLClientSocketNSS::Core::Read(IOBuffer* buf, int buf_len, |
| 626 PR_Close(nss_fd_); | 1129 const CompletionCallback& callback) { |
| 627 nss_fd_ = NULL; | 1130 if (!OnNSSTaskRunner()) { |
| 628 } | 1131 DCHECK(OnNetworkTaskRunner()); |
| 629 | 1132 DCHECK(!detached_); |
| 630 // Reset object state. | 1133 DCHECK(transport_); |
| 631 user_connect_callback_.Reset(); | 1134 |
| 632 user_read_callback_.Reset(); | 1135 bool posted = nss_task_runner_->PostTask( |
| 633 user_write_callback_.Reset(); | 1136 FROM_HERE, |
| 634 transport_send_busy_ = false; | 1137 base::Bind(IgnoreResult(&Core::Read), this, make_scoped_refptr(buf), |
| 635 transport_recv_busy_ = false; | 1138 buf_len, callback)); |
| 636 transport_recv_eof_ = false; | 1139 return posted ? ERR_IO_PENDING : ERR_ABORTED; |
| 637 user_read_buf_ = NULL; | 1140 } |
| 638 user_read_buf_len_ = 0; | 1141 |
| 639 user_write_buf_ = NULL; | 1142 DCHECK(OnNSSTaskRunner()); |
| 640 user_write_buf_len_ = 0; | 1143 DCHECK(handshake_callback_called_); |
| 641 server_cert_ = NULL; | 1144 DCHECK_EQ(STATE_NONE, next_handshake_state_); |
| 642 if (server_cert_nss_) { | |
| 643 CERT_DestroyCertificate(server_cert_nss_); | |
| 644 server_cert_nss_ = NULL; | |
| 645 } | |
| 646 local_server_cert_verify_result_.Reset(); | |
| 647 server_cert_verify_result_ = NULL; | |
| 648 ssl_connection_status_ = 0; | |
| 649 completed_handshake_ = false; | |
| 650 start_cert_verification_time_ = base::TimeTicks(); | |
| 651 predicted_cert_chain_correct_ = false; | |
| 652 nss_bufs_ = NULL; | |
| 653 client_certs_.clear(); | |
| 654 client_auth_cert_needed_ = false; | |
| 655 domain_bound_cert_xtn_negotiated_ = false; | |
| 656 | |
| 657 LeaveFunction(""); | |
| 658 } | |
| 659 | |
| 660 bool SSLClientSocketNSS::IsConnected() const { | |
| 661 // Ideally, we should also check if we have received the close_notify alert | |
| 662 // message from the server, and return false in that case. We're not doing | |
| 663 // that, so this function may return a false positive. Since the upper | |
| 664 // layer (HttpNetworkTransaction) needs to handle a persistent connection | |
| 665 // closed by the server when we send a request anyway, a false positive in | |
| 666 // exchange for simpler code is a good trade-off. | |
| 667 EnterFunction(""); | |
| 668 bool ret = completed_handshake_ && transport_->socket()->IsConnected(); | |
| 669 LeaveFunction(""); | |
| 670 return ret; | |
| 671 } | |
| 672 | |
| 673 bool SSLClientSocketNSS::IsConnectedAndIdle() const { | |
| 674 // Unlike IsConnected, this method doesn't return a false positive. | |
| 675 // | |
| 676 // Strictly speaking, we should check if we have received the close_notify | |
| 677 // alert message from the server, and return false in that case. Although | |
| 678 // the close_notify alert message means EOF in the SSL layer, it is just | |
| 679 // bytes to the transport layer below, so | |
| 680 // transport_->socket()->IsConnectedAndIdle() returns the desired false | |
| 681 // when we receive close_notify. | |
| 682 EnterFunction(""); | |
| 683 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle(); | |
| 684 LeaveFunction(""); | |
| 685 return ret; | |
| 686 } | |
| 687 | |
| 688 int SSLClientSocketNSS::GetPeerAddress(AddressList* address) const { | |
| 689 return transport_->socket()->GetPeerAddress(address); | |
| 690 } | |
| 691 | |
| 692 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const { | |
| 693 return transport_->socket()->GetLocalAddress(address); | |
| 694 } | |
| 695 | |
| 696 const BoundNetLog& SSLClientSocketNSS::NetLog() const { | |
| 697 return net_log_; | |
| 698 } | |
| 699 | |
| 700 void SSLClientSocketNSS::SetSubresourceSpeculation() { | |
| 701 if (transport_.get() && transport_->socket()) { | |
| 702 transport_->socket()->SetSubresourceSpeculation(); | |
| 703 } else { | |
| 704 NOTREACHED(); | |
| 705 } | |
| 706 } | |
| 707 | |
| 708 void SSLClientSocketNSS::SetOmniboxSpeculation() { | |
| 709 if (transport_.get() && transport_->socket()) { | |
| 710 transport_->socket()->SetOmniboxSpeculation(); | |
| 711 } else { | |
| 712 NOTREACHED(); | |
| 713 } | |
| 714 } | |
| 715 | |
| 716 bool SSLClientSocketNSS::WasEverUsed() const { | |
| 717 if (transport_.get() && transport_->socket()) { | |
| 718 return transport_->socket()->WasEverUsed(); | |
| 719 } | |
| 720 NOTREACHED(); | |
| 721 return false; | |
| 722 } | |
| 723 | |
| 724 bool SSLClientSocketNSS::UsingTCPFastOpen() const { | |
| 725 if (transport_.get() && transport_->socket()) { | |
| 726 return transport_->socket()->UsingTCPFastOpen(); | |
| 727 } | |
| 728 NOTREACHED(); | |
| 729 return false; | |
| 730 } | |
| 731 | |
| 732 int64 SSLClientSocketNSS::NumBytesRead() const { | |
| 733 if (transport_.get() && transport_->socket()) { | |
| 734 return transport_->socket()->NumBytesRead(); | |
| 735 } | |
| 736 NOTREACHED(); | |
| 737 return -1; | |
| 738 } | |
| 739 | |
| 740 base::TimeDelta SSLClientSocketNSS::GetConnectTimeMicros() const { | |
| 741 if (transport_.get() && transport_->socket()) { | |
| 742 return transport_->socket()->GetConnectTimeMicros(); | |
| 743 } | |
| 744 NOTREACHED(); | |
| 745 return base::TimeDelta::FromMicroseconds(-1); | |
| 746 } | |
| 747 | |
| 748 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len, | |
| 749 const CompletionCallback& callback) { | |
| 750 EnterFunction(buf_len); | |
| 751 DCHECK(completed_handshake_); | |
| 752 DCHECK(next_handshake_state_ == STATE_NONE); | |
| 753 DCHECK(user_read_callback_.is_null()); | 1145 DCHECK(user_read_callback_.is_null()); |
| 754 DCHECK(user_connect_callback_.is_null()); | 1146 DCHECK(user_connect_callback_.is_null()); |
| 755 DCHECK(!user_read_buf_); | 1147 DCHECK(!user_read_buf_); |
| 756 DCHECK(nss_bufs_); | 1148 DCHECK(nss_bufs_); |
| 757 | 1149 |
| 758 user_read_buf_ = buf; | 1150 user_read_buf_ = buf; |
| 759 user_read_buf_len_ = buf_len; | 1151 user_read_buf_len_ = buf_len; |
| 760 | 1152 |
| 761 int rv = DoReadLoop(OK); | 1153 int rv = DoReadLoop(OK); |
| 762 | |
| 763 if (rv == ERR_IO_PENDING) { | 1154 if (rv == ERR_IO_PENDING) { |
| 764 user_read_callback_ = callback; | 1155 user_read_callback_ = callback; |
| 765 } else { | 1156 } else { |
| 766 user_read_buf_ = NULL; | 1157 user_read_buf_ = NULL; |
| 767 user_read_buf_len_ = 0; | 1158 user_read_buf_len_ = 0; |
| 1159 | |
| 1160 if (!OnNetworkTaskRunner()) | |
| 1161 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv)); | |
|
wtc
2012/06/01 01:02:38
Nit: it is slightly clearer to do:
if (!OnNetwor
| |
| 768 } | 1162 } |
| 769 LeaveFunction(rv); | 1163 |
| 770 return rv; | 1164 return rv; |
| 771 } | 1165 } |
| 772 | 1166 |
| 773 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len, | 1167 int SSLClientSocketNSS::Core::Write(IOBuffer* buf, int buf_len, |
| 774 const CompletionCallback& callback) { | 1168 const CompletionCallback& callback) { |
| 775 EnterFunction(buf_len); | 1169 if (!OnNSSTaskRunner()) { |
| 776 DCHECK(completed_handshake_); | 1170 DCHECK(OnNetworkTaskRunner()); |
| 777 DCHECK(next_handshake_state_ == STATE_NONE); | 1171 DCHECK(!detached_); |
| 1172 DCHECK(transport_); | |
| 1173 | |
| 1174 bool posted = nss_task_runner_->PostTask( | |
| 1175 FROM_HERE, | |
| 1176 base::Bind(IgnoreResult(&Core::Write), this, make_scoped_refptr(buf), | |
| 1177 buf_len, callback)); | |
| 1178 int rv = posted ? ERR_IO_PENDING : ERR_ABORTED; | |
| 1179 return rv; | |
| 1180 } | |
| 1181 | |
| 1182 DCHECK(OnNSSTaskRunner()); | |
| 1183 DCHECK(handshake_callback_called_); | |
| 1184 DCHECK_EQ(STATE_NONE, next_handshake_state_); | |
| 778 DCHECK(user_write_callback_.is_null()); | 1185 DCHECK(user_write_callback_.is_null()); |
| 779 DCHECK(user_connect_callback_.is_null()); | 1186 DCHECK(user_connect_callback_.is_null()); |
| 780 DCHECK(!user_write_buf_); | 1187 DCHECK(!user_write_buf_); |
| 781 DCHECK(nss_bufs_); | 1188 DCHECK(nss_bufs_); |
| 782 | 1189 |
| 783 user_write_buf_ = buf; | 1190 user_write_buf_ = buf; |
| 784 user_write_buf_len_ = buf_len; | 1191 user_write_buf_len_ = buf_len; |
| 785 | 1192 |
| 786 int rv = DoWriteLoop(OK); | 1193 int rv = DoWriteLoop(OK); |
| 787 | |
| 788 if (rv == ERR_IO_PENDING) { | 1194 if (rv == ERR_IO_PENDING) { |
| 789 user_write_callback_ = callback; | 1195 user_write_callback_ = callback; |
| 790 } else { | 1196 } else { |
| 791 user_write_buf_ = NULL; | 1197 user_write_buf_ = NULL; |
| 792 user_write_buf_len_ = 0; | 1198 user_write_buf_len_ = 0; |
| 793 } | 1199 |
| 1200 if (!OnNetworkTaskRunner()) | |
| 1201 PostOrRunCallback(FROM_HERE, base::Bind(callback, rv)); | |
| 1202 } | |
| 1203 | |
| 1204 return rv; | |
| 1205 } | |
| 1206 | |
| 1207 bool SSLClientSocketNSS::Core::OnNSSTaskRunner() const { | |
| 1208 return nss_task_runner_->RunsTasksOnCurrentThread(); | |
| 1209 } | |
| 1210 | |
| 1211 bool SSLClientSocketNSS::Core::OnNetworkTaskRunner() const { | |
| 1212 return network_task_runner_->RunsTasksOnCurrentThread(); | |
|
wtc
2012/06/01 01:02:38
Is this test cheap? We do these tests a lot.
Ryan Sleevi
2012/06/01 01:30:04
These are backed by MessageLoopProxyImpl::RunsTask
| |
| 1213 } | |
| 1214 | |
| 1215 // static | |
| 1216 SECStatus SSLClientSocketNSS::Core::OwnAuthCertHandler( | |
| 1217 void* arg, | |
| 1218 PRFileDesc* socket, | |
| 1219 PRBool checksig, | |
| 1220 PRBool is_server) { | |
| 1221 #ifdef SSL_ENABLE_FALSE_START | |
| 1222 Core* core = reinterpret_cast<Core*>(arg); | |
| 1223 if (!core->handshake_callback_called_) { | |
| 1224 // Only need to turn off False Start in the initial handshake. Also, it is | |
| 1225 // unsafe to call SSL_OptionSet in a renegotiation because the "first | |
| 1226 // handshake" lock isn't already held, which will result in an assertion | |
| 1227 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet. | |
| 1228 PRBool npn; | |
| 1229 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket, | |
| 1230 ssl_next_proto_nego_xtn, | |
| 1231 &npn); | |
| 1232 if (rv != SECSuccess || !npn) { | |
| 1233 // If the server doesn't support NPN, then we don't do False Start with | |
| 1234 // it. | |
| 1235 SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE); | |
| 1236 } | |
| 1237 } | |
| 1238 #endif | |
| 1239 | |
| 1240 // Tell NSS to not verify the certificate. | |
| 1241 return SECSuccess; | |
| 1242 } | |
| 1243 | |
| 1244 #if defined(NSS_PLATFORM_CLIENT_AUTH) | |
| 1245 // static | |
| 1246 SECStatus SSLClientSocketNSS::Core::PlatformClientAuthHandler( | |
| 1247 void* arg, | |
| 1248 PRFileDesc* socket, | |
| 1249 CERTDistNames* ca_names, | |
| 1250 CERTCertList** result_certs, | |
| 1251 void** result_private_key, | |
| 1252 CERTCertificate** result_nss_certificate, | |
| 1253 SECKEYPrivateKey** result_nss_private_key) { | |
| 1254 Core* core = reinterpret_cast<Core*>(arg); | |
| 1255 DCHECK(core->OnNSSTaskRunner()); | |
| 1256 | |
| 1257 core->PostOrRunCallback( | |
| 1258 FROM_HERE, | |
| 1259 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1260 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED, | |
| 1261 scoped_refptr<NetLog::EventParameters>())); | |
| 1262 | |
| 1263 const SECItem* cert_types = SSL_GetRequestedClientCertificateTypes(socket); | |
| 1264 | |
| 1265 // Check if a domain-bound certificate is requested. | |
| 1266 if (DomainBoundCertNegotiated(socket)) { | |
| 1267 return core->DomainBoundClientAuthHandler(cert_types, | |
| 1268 result_nss_certificate, | |
| 1269 result_nss_private_key); | |
| 1270 } | |
| 1271 | |
| 1272 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert; | |
| 1273 #if defined(OS_WIN) | |
| 1274 if (core->ssl_config_.send_client_cert) { | |
| 1275 if (core->ssl_config_.client_cert) { | |
| 1276 PCCERT_CONTEXT cert_context = | |
| 1277 core->ssl_config_.client_cert->os_cert_handle(); | |
| 1278 | |
| 1279 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0; | |
| 1280 DWORD key_spec = 0; | |
| 1281 BOOL must_free = FALSE; | |
| 1282 BOOL acquired_key = CryptAcquireCertificatePrivateKey( | |
| 1283 cert_context, CRYPT_ACQUIRE_CACHE_FLAG, NULL, | |
| 1284 &crypt_prov, &key_spec, &must_free); | |
| 1285 | |
| 1286 if (acquired_key) { | |
| 1287 // Since we passed CRYPT_ACQUIRE_CACHE_FLAG, |must_free| must be false | |
| 1288 // according to the MSDN documentation. | |
| 1289 CHECK_EQ(must_free, FALSE); | |
| 1290 DCHECK_NE(key_spec, CERT_NCRYPT_KEY_SPEC); | |
| 1291 | |
| 1292 SECItem der_cert; | |
| 1293 der_cert.type = siDERCertBuffer; | |
| 1294 der_cert.data = cert_context->pbCertEncoded; | |
| 1295 der_cert.len = cert_context->cbCertEncoded; | |
| 1296 | |
| 1297 // TODO(rsleevi): Error checking for NSS allocation errors. | |
| 1298 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB(); | |
| 1299 CERTCertificate* user_cert = CERT_NewTempCertificate( | |
| 1300 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 1301 if (!user_cert) { | |
| 1302 // Importing the certificate can fail for reasons including a serial | |
| 1303 // number collision. See crbug.com/97355. | |
| 1304 core->PostOrRunCallback( | |
| 1305 FROM_HERE, | |
| 1306 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1307 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1308 make_scoped_refptr( | |
| 1309 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1310 return SECFailure; | |
| 1311 } | |
| 1312 CERTCertList* cert_chain = CERT_NewCertList(); | |
| 1313 CERT_AddCertToListTail(cert_chain, user_cert); | |
| 1314 | |
| 1315 // Add the intermediates. | |
| 1316 X509Certificate::OSCertHandles intermediates = | |
| 1317 core->ssl_config_.client_cert->GetIntermediateCertificates(); | |
| 1318 for (X509Certificate::OSCertHandles::const_iterator it = | |
| 1319 intermediates.begin(); it != intermediates.end(); ++it) { | |
| 1320 der_cert.data = (*it)->pbCertEncoded; | |
| 1321 der_cert.len = (*it)->cbCertEncoded; | |
| 1322 | |
| 1323 CERTCertificate* intermediate = CERT_NewTempCertificate( | |
| 1324 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 1325 if (!intermediate) { | |
| 1326 CERT_DestroyCertList(cert_chain); | |
| 1327 core->PostOrRunCallback( | |
| 1328 FROM_HERE, | |
| 1329 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1330 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1331 make_scoped_refptr( | |
| 1332 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1333 return SECFailure; | |
| 1334 } | |
| 1335 CERT_AddCertToListTail(cert_chain, intermediate); | |
| 1336 } | |
| 1337 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>( | |
| 1338 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT))); | |
| 1339 key_context->cbSize = sizeof(*key_context); | |
| 1340 // NSS will free this context when no longer in use, but the | |
| 1341 // |must_free| result from CryptAcquireCertificatePrivateKey was false | |
| 1342 // so we increment the refcount to negate NSS's future decrement. | |
| 1343 CryptContextAddRef(crypt_prov, NULL, 0); | |
| 1344 key_context->hCryptProv = crypt_prov; | |
| 1345 key_context->dwKeySpec = key_spec; | |
| 1346 *result_private_key = key_context; | |
| 1347 *result_certs = cert_chain; | |
| 1348 | |
| 1349 int cert_count = 1 + intermediates.size(); | |
| 1350 core->PostOrRunCallback( | |
| 1351 FROM_HERE, | |
| 1352 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1353 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1354 make_scoped_refptr( | |
| 1355 new NetLogIntegerParameter("cert_count", | |
| 1356 cert_count)))); | |
| 1357 return SECSuccess; | |
| 1358 } | |
| 1359 LOG(WARNING) << "Client cert found without private key"; | |
| 1360 } | |
| 1361 | |
| 1362 // Send no client certificate. | |
| 1363 core->PostOrRunCallback( | |
| 1364 FROM_HERE, | |
| 1365 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1366 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1367 make_scoped_refptr( | |
| 1368 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1369 return SECFailure; | |
| 1370 } | |
| 1371 | |
| 1372 core->nss_handshake_state_.client_certs.clear(); | |
| 1373 | |
| 1374 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames); | |
| 1375 for (int i = 0; i < ca_names->nnames; ++i) { | |
| 1376 issuer_list[i].cbData = ca_names->names[i].len; | |
| 1377 issuer_list[i].pbData = ca_names->names[i].data; | |
| 1378 } | |
| 1379 | |
| 1380 // Client certificates of the user are in the "MY" system certificate store. | |
| 1381 HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY"); | |
| 1382 if (!my_cert_store) { | |
| 1383 PLOG(ERROR) << "Could not open the \"MY\" system certificate store"; | |
| 1384 | |
| 1385 core->PostOrRunCallback( | |
| 1386 FROM_HERE, | |
| 1387 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1388 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1389 make_scoped_refptr( | |
| 1390 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1391 return SECFailure; | |
| 1392 } | |
| 1393 | |
| 1394 // Enumerate the client certificates. | |
| 1395 CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para; | |
| 1396 memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para)); | |
| 1397 find_by_issuer_para.cbSize = sizeof(find_by_issuer_para); | |
| 1398 find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH; | |
| 1399 find_by_issuer_para.cIssuer = ca_names->nnames; | |
| 1400 find_by_issuer_para.rgIssuer = ca_names->nnames ? &issuer_list[0] : NULL; | |
| 1401 find_by_issuer_para.pfnFindCallback = ClientCertFindCallback; | |
| 1402 | |
| 1403 PCCERT_CHAIN_CONTEXT chain_context = NULL; | |
| 1404 DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG | | |
| 1405 CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG; | |
| 1406 | |
| 1407 for (;;) { | |
| 1408 // Find a certificate chain. | |
| 1409 chain_context = CertFindChainInStore(my_cert_store, | |
| 1410 X509_ASN_ENCODING, | |
| 1411 find_flags, | |
| 1412 CERT_CHAIN_FIND_BY_ISSUER, | |
| 1413 &find_by_issuer_para, | |
| 1414 chain_context); | |
| 1415 if (!chain_context) { | |
| 1416 DWORD err = GetLastError(); | |
| 1417 if (err != CRYPT_E_NOT_FOUND) | |
| 1418 DLOG(ERROR) << "CertFindChainInStore failed: " << err; | |
| 1419 break; | |
| 1420 } | |
| 1421 | |
| 1422 // Get the leaf certificate. | |
| 1423 PCCERT_CONTEXT cert_context = | |
| 1424 chain_context->rgpChain[0]->rgpElement[0]->pCertContext; | |
| 1425 // Create a copy the handle, so that we can close the "MY" certificate store | |
| 1426 // before returning from this function. | |
| 1427 PCCERT_CONTEXT cert_context2; | |
| 1428 BOOL ok = CertAddCertificateContextToStore(NULL, cert_context, | |
| 1429 CERT_STORE_ADD_USE_EXISTING, | |
| 1430 &cert_context2); | |
| 1431 if (!ok) { | |
| 1432 NOTREACHED(); | |
| 1433 continue; | |
| 1434 } | |
| 1435 | |
| 1436 // Copy the rest of the chain. Copying the chain stops gracefully if an | |
| 1437 // error is encountered, with the partial chain being used as the | |
| 1438 // intermediates, as opposed to failing to consider the client certificate | |
| 1439 // at all. | |
| 1440 net::X509Certificate::OSCertHandles intermediates; | |
| 1441 for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; i++) { | |
| 1442 PCCERT_CONTEXT intermediate_copy; | |
| 1443 ok = CertAddCertificateContextToStore( | |
| 1444 NULL, chain_context->rgpChain[0]->rgpElement[i]->pCertContext, | |
| 1445 CERT_STORE_ADD_USE_EXISTING, &intermediate_copy); | |
| 1446 if (!ok) { | |
| 1447 NOTREACHED(); | |
| 1448 break; | |
| 1449 } | |
| 1450 intermediates.push_back(intermediate_copy); | |
| 1451 } | |
| 1452 | |
| 1453 scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle( | |
| 1454 cert_context2, intermediates); | |
| 1455 core->nss_handshake_state_.client_certs.push_back(cert); | |
| 1456 | |
| 1457 X509Certificate::FreeOSCertHandle(cert_context2); | |
| 1458 for (net::X509Certificate::OSCertHandles::iterator it = | |
| 1459 intermediates.begin(); it != intermediates.end(); ++it) { | |
| 1460 net::X509Certificate::FreeOSCertHandle(*it); | |
| 1461 } | |
| 1462 } | |
| 1463 | |
| 1464 BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG); | |
| 1465 DCHECK(ok); | |
| 1466 | |
| 1467 // Update the network task runner's view of the connection state now that | |
| 1468 // client certs have been detected. | |
| 1469 core->PostOrRunCallback( | |
| 1470 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core, | |
| 1471 core->nss_handshake_state_)); | |
| 1472 | |
| 1473 // Tell NSS to suspend the client authentication. We will then abort the | |
| 1474 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 1475 return SECWouldBlock; | |
| 1476 #elif defined(OS_MACOSX) | |
| 1477 if (core->ssl_config_.send_client_cert) { | |
| 1478 if (core->ssl_config_.client_cert) { | |
| 1479 OSStatus os_error = noErr; | |
| 1480 SecIdentityRef identity = NULL; | |
| 1481 SecKeyRef private_key = NULL; | |
| 1482 CFArrayRef chain = | |
| 1483 core->ssl_config_.client_cert->CreateClientCertificateChain(); | |
| 1484 if (chain) { | |
| 1485 identity = reinterpret_cast<SecIdentityRef>( | |
| 1486 const_cast<void*>(CFArrayGetValueAtIndex(chain, 0))); | |
| 1487 } | |
| 1488 if (identity) | |
| 1489 os_error = SecIdentityCopyPrivateKey(identity, &private_key); | |
| 1490 | |
| 1491 if (chain && identity && os_error == noErr) { | |
| 1492 // TODO(rsleevi): Error checking for NSS allocation errors. | |
| 1493 *result_certs = CERT_NewCertList(); | |
| 1494 *result_private_key = private_key; | |
| 1495 | |
| 1496 for (CFIndex i = 0; i < CFArrayGetCount(chain); ++i) { | |
| 1497 CSSM_DATA cert_data; | |
| 1498 SecCertificateRef cert_ref; | |
| 1499 if (i == 0) { | |
| 1500 cert_ref = core->ssl_config_.client_cert->os_cert_handle(); | |
| 1501 } else { | |
| 1502 cert_ref = reinterpret_cast<SecCertificateRef>( | |
| 1503 const_cast<void*>(CFArrayGetValueAtIndex(chain, i))); | |
| 1504 } | |
| 1505 os_error = SecCertificateGetData(cert_ref, &cert_data); | |
| 1506 if (os_error != noErr) | |
| 1507 break; | |
| 1508 | |
| 1509 SECItem der_cert; | |
| 1510 der_cert.type = siDERCertBuffer; | |
| 1511 der_cert.data = cert_data.Data; | |
| 1512 der_cert.len = cert_data.Length; | |
| 1513 CERTCertificate* nss_cert = CERT_NewTempCertificate( | |
| 1514 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 1515 if (!nss_cert) { | |
| 1516 // In the event of an NSS error we make up an OS error and reuse | |
| 1517 // the error handling, below. | |
| 1518 os_error = errSecCreateChainFailed; | |
| 1519 break; | |
| 1520 } | |
| 1521 CERT_AddCertToListTail(*result_certs, nss_cert); | |
| 1522 } | |
| 1523 } | |
| 1524 if (os_error == noErr) { | |
| 1525 int cert_count = 0; | |
| 1526 if (chain) { | |
| 1527 cert_count = CFArrayGetCount(chain); | |
| 1528 CFRelease(chain); | |
| 1529 } | |
| 1530 core->PostOrRunCallback( | |
| 1531 FROM_HERE, | |
| 1532 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1533 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1534 make_scoped_refptr( | |
| 1535 new NetLogIntegerParameter("cert_count", | |
| 1536 cert_count)))); | |
| 1537 return SECSuccess; | |
| 1538 } | |
| 1539 OSSTATUS_LOG(WARNING, os_error) | |
| 1540 << "Client cert found, but could not be used"; | |
| 1541 if (*result_certs) { | |
| 1542 CERT_DestroyCertList(*result_certs); | |
| 1543 *result_certs = NULL; | |
| 1544 } | |
| 1545 if (*result_private_key) | |
| 1546 *result_private_key = NULL; | |
| 1547 if (private_key) | |
| 1548 CFRelease(private_key); | |
| 1549 if (chain) | |
| 1550 CFRelease(chain); | |
| 1551 } | |
| 1552 | |
| 1553 // Send no client certificate. | |
| 1554 core->PostOrRunCallback( | |
| 1555 FROM_HERE, | |
| 1556 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1557 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1558 make_scoped_refptr( | |
| 1559 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1560 return SECFailure; | |
| 1561 } | |
| 1562 | |
| 1563 core->nss_handshake_state_.client_certs.clear(); | |
| 1564 | |
| 1565 // First, get the cert issuer names allowed by the server. | |
| 1566 std::vector<CertPrincipal> valid_issuers; | |
| 1567 int n = ca_names->nnames; | |
| 1568 for (int i = 0; i < n; i++) { | |
| 1569 // Parse each name into a CertPrincipal object. | |
| 1570 CertPrincipal p; | |
| 1571 if (p.ParseDistinguishedName(ca_names->names[i].data, | |
| 1572 ca_names->names[i].len)) { | |
| 1573 valid_issuers.push_back(p); | |
| 1574 } | |
| 1575 } | |
| 1576 | |
| 1577 // Now get the available client certs whose issuers are allowed by the server. | |
| 1578 X509Certificate::GetSSLClientCertificates( | |
| 1579 core->host_and_port_.host(), valid_issuers, | |
| 1580 &core->nss_handshake_state_.client_certs); | |
| 1581 | |
| 1582 // Update the network task runner's view of the connection state now that | |
| 1583 // client certs have been detected. | |
| 1584 core->PostOrRunCallback( | |
| 1585 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core, | |
| 1586 core->nss_handshake_state_)); | |
| 1587 | |
| 1588 // Tell NSS to suspend the client authentication. We will then abort the | |
| 1589 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 1590 return SECWouldBlock; | |
| 1591 #else | |
| 1592 return SECFailure; | |
| 1593 #endif | |
| 1594 } | |
| 1595 | |
| 1596 #else // NSS_PLATFORM_CLIENT_AUTH | |
| 1597 | |
| 1598 // static | |
| 1599 // Based on Mozilla's NSS_GetClientAuthData. | |
| 1600 SECStatus SSLClientSocketNSS::Core::ClientAuthHandler( | |
| 1601 void* arg, | |
| 1602 PRFileDesc* socket, | |
| 1603 CERTDistNames* ca_names, | |
| 1604 CERTCertificate** result_certificate, | |
| 1605 SECKEYPrivateKey** result_private_key) { | |
| 1606 Core* core = reinterpret_cast<Core*>(arg); | |
| 1607 DCHECK(core->OnNSSTaskRunner()); | |
| 1608 | |
| 1609 core->PostOrRunCallback( | |
| 1610 FROM_HERE, | |
| 1611 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1612 NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED, | |
| 1613 scoped_refptr<NetLog::EventParameters>())); | |
| 1614 | |
| 1615 const SECItem* cert_types = SSL_GetRequestedClientCertificateTypes(socket); | |
| 1616 | |
| 1617 // Check if a domain-bound certificate is requested. | |
| 1618 if (DomainBoundCertNegotiated(socket)) { | |
| 1619 return core->DomainBoundClientAuthHandler( | |
| 1620 cert_types, result_certificate, result_private_key); | |
| 1621 } | |
| 1622 | |
| 1623 // Regular client certificate requested. | |
| 1624 core->client_auth_cert_needed_ = !core->ssl_config_.send_client_cert; | |
| 1625 void* wincx = SSL_RevealPinArg(socket); | |
| 1626 | |
| 1627 // Second pass: a client certificate should have been selected. | |
| 1628 if (core->ssl_config_.send_client_cert) { | |
| 1629 if (core->ssl_config_.client_cert) { | |
| 1630 CERTCertificate* cert = CERT_DupCertificate( | |
| 1631 core->ssl_config_.client_cert->os_cert_handle()); | |
| 1632 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx); | |
| 1633 if (privkey) { | |
| 1634 // TODO(jsorianopastor): We should wait for server certificate | |
| 1635 // verification before sending our credentials. See | |
| 1636 // http://crbug.com/13934. | |
| 1637 *result_certificate = cert; | |
| 1638 *result_private_key = privkey; | |
| 1639 // A cert_count of -1 means the number of certificates is unknown. | |
| 1640 // NSS will construct the certificate chain. | |
| 1641 core->PostOrRunCallback( | |
| 1642 FROM_HERE, | |
| 1643 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1644 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1645 make_scoped_refptr( | |
| 1646 new NetLogIntegerParameter("cert_count", -1)))); | |
| 1647 | |
| 1648 return SECSuccess; | |
| 1649 } | |
| 1650 LOG(WARNING) << "Client cert found without private key"; | |
| 1651 } | |
| 1652 // Send no client certificate. | |
| 1653 core->PostOrRunCallback( | |
| 1654 FROM_HERE, | |
| 1655 base::Bind(&BoundNetLog::AddEvent, core->weak_net_log_, | |
| 1656 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 1657 make_scoped_refptr( | |
| 1658 new NetLogIntegerParameter("cert_count", 0)))); | |
| 1659 return SECFailure; | |
| 1660 } | |
| 1661 | |
| 1662 core->nss_handshake_state_.client_certs.clear(); | |
| 1663 | |
| 1664 // Iterate over all client certificates. | |
| 1665 CERTCertList* client_certs = CERT_FindUserCertsByUsage( | |
| 1666 CERT_GetDefaultCertDB(), certUsageSSLClient, | |
| 1667 PR_FALSE, PR_FALSE, wincx); | |
| 1668 if (client_certs) { | |
| 1669 for (CERTCertListNode* node = CERT_LIST_HEAD(client_certs); | |
| 1670 !CERT_LIST_END(node, client_certs); | |
| 1671 node = CERT_LIST_NEXT(node)) { | |
| 1672 // Only offer unexpired certificates. | |
| 1673 if (CERT_CheckCertValidTimes(node->cert, PR_Now(), PR_TRUE) != | |
| 1674 secCertTimeValid) { | |
| 1675 continue; | |
| 1676 } | |
| 1677 // Filter by issuer. | |
| 1678 // | |
| 1679 // TODO(davidben): This does a binary comparison of the DER-encoded | |
| 1680 // issuers. We should match according to RFC 5280 sec. 7.1. We should find | |
| 1681 // an appropriate NSS function or add one if needbe. | |
| 1682 if (ca_names->nnames && | |
| 1683 NSS_CmpCertChainWCANames(node->cert, ca_names) != SECSuccess) { | |
| 1684 continue; | |
| 1685 } | |
| 1686 | |
| 1687 X509Certificate* x509_cert = X509Certificate::CreateFromHandle( | |
| 1688 node->cert, net::X509Certificate::OSCertHandles()); | |
| 1689 core->nss_handshake_state_.client_certs.push_back(x509_cert); | |
| 1690 } | |
| 1691 CERT_DestroyCertList(client_certs); | |
| 1692 } | |
| 1693 | |
| 1694 // Update the network task runner's view of the connection state now that | |
| 1695 // client certs have been detected. | |
| 1696 core->PostOrRunCallback( | |
| 1697 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core, | |
| 1698 core->nss_handshake_state_)); | |
| 1699 | |
| 1700 // Tell NSS to suspend the client authentication. We will then abort the | |
| 1701 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 1702 return SECWouldBlock; | |
| 1703 } | |
| 1704 #endif // NSS_PLATFORM_CLIENT_AUTH | |
| 1705 | |
| 1706 // static | |
| 1707 void SSLClientSocketNSS::Core::HandshakeCallback( | |
| 1708 PRFileDesc* socket, | |
| 1709 void* arg) { | |
| 1710 Core* core = reinterpret_cast<Core*>(arg); | |
| 1711 DCHECK(core->OnNSSTaskRunner()); | |
| 1712 | |
| 1713 core->handshake_callback_called_ = true; | |
| 1714 | |
| 1715 HandshakeState* nss_state = &core->nss_handshake_state_; | |
| 1716 | |
| 1717 PRBool last_handshake_resumed; | |
| 1718 SECStatus rv = SSL_HandshakeResumedSession(socket, &last_handshake_resumed); | |
| 1719 if (rv == SECSuccess && last_handshake_resumed) { | |
| 1720 nss_state->resumed_handshake = true; | |
| 1721 } else { | |
| 1722 nss_state->resumed_handshake = false; | |
| 1723 } | |
| 1724 | |
| 1725 core->RecordDomainBoundCertSupport(); | |
| 1726 core->UpdateServerCert(); | |
| 1727 core->UpdateConnectionStatus(); | |
| 1728 | |
| 1729 // We need to see if the predicted certificate chain (from | |
| 1730 // SetPredictedCertificates) matches the actual certificate chain. | |
| 1731 nss_state->predicted_cert_chain_correct = false; | |
| 1732 if (!core->predicted_certs_.empty()) { | |
| 1733 PeerCertificateChain& certs = nss_state->server_cert_chain; | |
| 1734 nss_state->predicted_cert_chain_correct = | |
| 1735 certs.size() == core->predicted_certs_.size(); | |
| 1736 | |
| 1737 if (nss_state->predicted_cert_chain_correct) { | |
| 1738 for (unsigned i = 0; i < certs.size(); i++) { | |
| 1739 if (certs[i]->derCert.len != core->predicted_certs_[i].size() || | |
| 1740 memcmp(certs[i]->derCert.data, core->predicted_certs_[i].data(), | |
| 1741 certs[i]->derCert.len) != 0) { | |
| 1742 nss_state->predicted_cert_chain_correct = false; | |
| 1743 break; | |
| 1744 } | |
| 1745 } | |
| 1746 } | |
| 1747 } | |
| 1748 | |
| 1749 // Update the network task runners view of the connection state whenever | |
| 1750 // a handshake has completed. | |
| 1751 core->PostOrRunCallback( | |
| 1752 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core, | |
| 1753 *nss_state)); | |
| 1754 } | |
| 1755 | |
| 1756 // static | |
| 1757 SECStatus SSLClientSocketNSS::Core::NextProtoCallback( | |
| 1758 void* arg, | |
| 1759 PRFileDesc* nss_fd, | |
| 1760 const unsigned char* protos, | |
| 1761 unsigned int protos_len, | |
| 1762 unsigned char* proto_out, | |
| 1763 unsigned int* proto_out_len, | |
| 1764 unsigned int proto_max_len) { | |
| 1765 Core* core = reinterpret_cast<Core*>(arg); | |
| 1766 DCHECK(core->OnNSSTaskRunner()); | |
| 1767 | |
| 1768 HandshakeState* nss_state = &core->nss_handshake_state_; | |
| 1769 | |
| 1770 // For each protocol in server preference, see if we support it. | |
| 1771 for (unsigned int i = 0; i < protos_len; ) { | |
| 1772 const size_t len = protos[i]; | |
| 1773 for (std::vector<std::string>::const_iterator | |
| 1774 j = core->ssl_config_.next_protos.begin(); | |
| 1775 j != core->ssl_config_.next_protos.end(); j++) { | |
| 1776 // Having very long elements in the |next_protos| vector isn't a disaster | |
| 1777 // because they'll never be selected, but it does indicate an error | |
| 1778 // somewhere. | |
| 1779 DCHECK_LT(j->size(), 256u); | |
| 1780 | |
| 1781 if (j->size() == len && | |
| 1782 memcmp(&protos[i + 1], j->data(), len) == 0) { | |
| 1783 nss_state->next_proto_status = kNextProtoNegotiated; | |
| 1784 nss_state->next_proto = *j; | |
| 1785 break; | |
| 1786 } | |
| 1787 } | |
| 1788 | |
| 1789 if (nss_state->next_proto_status == kNextProtoNegotiated) | |
| 1790 break; | |
| 1791 | |
| 1792 // NSS ensures that the data in |protos| is well formed, so this will not | |
| 1793 // cause a jump past the end of the buffer. | |
| 1794 i += len + 1; | |
| 1795 } | |
| 1796 | |
| 1797 nss_state->server_protos.assign( | |
| 1798 reinterpret_cast<const char*>(protos), protos_len); | |
| 1799 | |
| 1800 // If we didn't find a protocol, we select the first one from our list. | |
| 1801 if (nss_state->next_proto_status != kNextProtoNegotiated) { | |
| 1802 nss_state->next_proto_status = kNextProtoNoOverlap; | |
| 1803 nss_state->next_proto = core->ssl_config_.next_protos[0]; | |
| 1804 } | |
| 1805 | |
| 1806 if (nss_state->next_proto.size() > proto_max_len) { | |
| 1807 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
| 1808 return SECFailure; | |
| 1809 } | |
| 1810 memcpy(proto_out, nss_state->next_proto.data(), | |
| 1811 nss_state->next_proto.size()); | |
| 1812 *proto_out_len = nss_state->next_proto.size(); | |
| 1813 | |
| 1814 // Update the network task runner's view of the connection state now that | |
| 1815 // NPN negotiation has occurred. | |
| 1816 core->PostOrRunCallback( | |
| 1817 FROM_HERE, base::Bind(&Core::OnHandshakeStateUpdated, core, | |
| 1818 *nss_state)); | |
| 1819 | |
| 1820 return SECSuccess; | |
| 1821 } | |
| 1822 | |
| 1823 int SSLClientSocketNSS::Core::HandleNSSError(PRErrorCode nss_error, | |
| 1824 bool handshake_error) { | |
| 1825 DCHECK(OnNSSTaskRunner()); | |
| 1826 | |
| 1827 int net_error = handshake_error ? MapNSSHandshakeError(nss_error) : | |
| 1828 MapNSSError(nss_error); | |
| 1829 | |
| 1830 #if defined(OS_WIN) | |
| 1831 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate | |
| 1832 // os_cert_handle() as an optimization. However, if the certificate | |
| 1833 // private key is stored on a smart card, and the smart card is removed, | |
| 1834 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again, | |
| 1835 // preventing client certificate authentication. Because the | |
| 1836 // X509Certificate may outlive the individual SSLClientSocketNSS, due to | |
| 1837 // caching in X509Certificate, this failure ends up preventing client | |
| 1838 // certificate authentication with the same certificate for all future | |
| 1839 // attempts, even after the smart card has been re-inserted. By setting | |
| 1840 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will | |
| 1841 // typically be freed. This allows a new HCRYPTPROV to be obtained from | |
| 1842 // the certificate on the next attempt, which should succeed if the smart | |
| 1843 // card has been re-inserted, or will typically prompt the user to | |
| 1844 // re-insert the smart card if not. | |
| 1845 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY || | |
| 1846 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) && | |
| 1847 ssl_config_.send_client_cert && ssl_config_.client_cert) { | |
| 1848 CertSetCertificateContextProperty( | |
| 1849 ssl_config_.client_cert->os_cert_handle(), | |
| 1850 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL); | |
| 1851 } | |
| 1852 #endif | |
| 1853 | |
| 1854 return net_error; | |
| 1855 } | |
| 1856 | |
| 1857 int SSLClientSocketNSS::Core::DoHandshakeLoop(int last_io_result) { | |
| 1858 DCHECK(OnNSSTaskRunner()); | |
| 1859 | |
| 1860 int rv = last_io_result; | |
| 1861 do { | |
| 1862 // Default to STATE_NONE for next state. | |
| 1863 State state = next_handshake_state_; | |
| 1864 GotoState(STATE_NONE); | |
| 1865 | |
| 1866 switch (state) { | |
| 1867 case STATE_HANDSHAKE: | |
| 1868 rv = DoHandshake(); | |
| 1869 break; | |
| 1870 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE: | |
| 1871 rv = DoGetDBCertComplete(rv); | |
| 1872 break; | |
| 1873 case STATE_NONE: | |
| 1874 default: | |
| 1875 rv = ERR_UNEXPECTED; | |
| 1876 LOG(DFATAL) << "unexpected state " << state; | |
| 1877 break; | |
| 1878 } | |
| 1879 | |
| 1880 // Do the actual network I/O | |
| 1881 bool network_moved = DoTransportIO(); | |
| 1882 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) { | |
| 1883 // In general we exit the loop if rv is ERR_IO_PENDING. In this | |
| 1884 // special case we keep looping even if rv is ERR_IO_PENDING because | |
| 1885 // the transport IO may allow DoHandshake to make progress. | |
| 1886 DCHECK(rv == OK || rv == ERR_IO_PENDING); | |
| 1887 rv = OK; // This causes us to stay in the loop. | |
| 1888 } | |
| 1889 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE); | |
| 1890 return rv; | |
| 1891 } | |
| 1892 | |
| 1893 int SSLClientSocketNSS::Core::DoReadLoop(int result) { | |
| 1894 DCHECK(OnNSSTaskRunner()); | |
| 1895 DCHECK(handshake_callback_called_); | |
| 1896 DCHECK_EQ(STATE_NONE, next_handshake_state_); | |
| 1897 | |
| 1898 if (result < 0) | |
| 1899 return result; | |
| 1900 | |
| 1901 if (!nss_bufs_) { | |
| 1902 LOG(DFATAL) << "!nss_bufs_"; | |
| 1903 int rv = ERR_UNEXPECTED; | |
| 1904 PostOrRunCallback( | |
| 1905 FROM_HERE, | |
| 1906 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 1907 NetLog::TYPE_SSL_READ_ERROR, | |
| 1908 make_scoped_refptr(new SSLErrorParams(rv, 0)))); | |
| 1909 return rv; | |
| 1910 } | |
| 1911 | |
| 1912 bool network_moved; | |
| 1913 int rv; | |
| 1914 do { | |
| 1915 rv = DoPayloadRead(); | |
| 1916 network_moved = DoTransportIO(); | |
| 1917 } while (rv == ERR_IO_PENDING && network_moved); | |
| 1918 | |
| 1919 return rv; | |
| 1920 } | |
| 1921 | |
| 1922 int SSLClientSocketNSS::Core::DoWriteLoop(int result) { | |
| 1923 DCHECK(OnNSSTaskRunner()); | |
| 1924 DCHECK(handshake_callback_called_); | |
| 1925 DCHECK_EQ(STATE_NONE, next_handshake_state_); | |
| 1926 | |
| 1927 if (result < 0) | |
| 1928 return result; | |
| 1929 | |
| 1930 if (!nss_bufs_) { | |
| 1931 LOG(DFATAL) << "!nss_bufs_"; | |
| 1932 int rv = ERR_UNEXPECTED; | |
| 1933 PostOrRunCallback( | |
| 1934 FROM_HERE, | |
| 1935 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 1936 NetLog::TYPE_SSL_READ_ERROR, | |
| 1937 make_scoped_refptr(new SSLErrorParams(rv, 0)))); | |
| 1938 return rv; | |
| 1939 } | |
| 1940 | |
| 1941 bool network_moved; | |
| 1942 int rv; | |
| 1943 do { | |
| 1944 rv = DoPayloadWrite(); | |
| 1945 network_moved = DoTransportIO(); | |
| 1946 } while (rv == ERR_IO_PENDING && network_moved); | |
| 1947 | |
| 794 LeaveFunction(rv); | 1948 LeaveFunction(rv); |
| 795 return rv; | 1949 return rv; |
| 796 } | 1950 } |
| 797 | 1951 |
| 798 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) { | 1952 int SSLClientSocketNSS::Core::DoHandshake() { |
| 799 return transport_->socket()->SetReceiveBufferSize(size); | 1953 DCHECK(OnNSSTaskRunner()); |
| 800 } | 1954 |
| 801 | 1955 int net_error = net::OK; |
| 802 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) { | 1956 SECStatus rv = SSL_ForceHandshake(nss_fd_); |
| 803 return transport_->socket()->SetSendBufferSize(size); | 1957 |
| 804 } | 1958 // TODO(rkn): Handle the case in which server-bound cert generation takes |
| 805 | 1959 // too long and the server has closed the connection. Report some new error |
| 806 int SSLClientSocketNSS::Init() { | 1960 // code so that the higher level code will attempt to delete the socket and |
| 807 EnterFunction(""); | 1961 // redo the handshake. |
| 808 // Initialize the NSS SSL library in a threadsafe way. This also | 1962 if (client_auth_cert_needed_) { |
| 809 // initializes the NSS base library. | 1963 if (domain_bound_cert_xtn_negotiated_) { |
| 810 EnsureNSSSSLInit(); | 1964 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE); |
| 811 if (!NSS_IsInitialized()) | 1965 net_error = ERR_IO_PENDING; |
| 812 return ERR_UNEXPECTED; | 1966 } else { |
| 813 #if !defined(OS_MACOSX) && !defined(OS_WIN) | 1967 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; |
| 814 if (ssl_config_.cert_io_enabled) { | 1968 PostOrRunCallback( |
| 815 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO | 1969 FROM_HERE, |
| 816 // loop by MessageLoopForIO::current(). | 1970 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, |
| 817 // X509Certificate::Verify() runs on a worker thread of CertVerifier. | 1971 NetLog::TYPE_SSL_HANDSHAKE_ERROR, |
| 818 EnsureNSSHttpIOInit(); | 1972 make_scoped_refptr(new SSLErrorParams(net_error, 0)))); |
| 819 } | 1973 |
| 820 #endif | 1974 // If the handshake already succeeded (because the server requests but |
| 821 | 1975 // doesn't require a client cert), we need to invalidate the SSL session |
| 822 LeaveFunction(""); | 1976 // so that we won't try to resume the non-client-authenticated session in |
| 1977 // the next handshake. This will cause the server to ask for a client | |
| 1978 // cert again. | |
| 1979 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess) | |
| 1980 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError(); | |
| 1981 } | |
| 1982 } else if (rv == SECSuccess) { | |
| 1983 if (!handshake_callback_called_) { | |
| 1984 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 - | |
| 1985 // SSL_ForceHandshake returned SECSuccess prematurely. | |
| 1986 rv = SECFailure; | |
| 1987 net_error = ERR_SSL_PROTOCOL_ERROR; | |
| 1988 PostOrRunCallback( | |
| 1989 FROM_HERE, | |
| 1990 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 1991 NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
| 1992 make_scoped_refptr( | |
| 1993 new SSLErrorParams(net_error, 0)))); | |
| 1994 } else { | |
| 1995 #if defined(SSL_ENABLE_OCSP_STAPLING) | |
| 1996 // TODO(agl): figure out how to plumb an OCSP response into the Mac | |
| 1997 // system library and update IsOCSPStaplingSupported for Mac. | |
| 1998 if (!nss_handshake_state_.predicted_cert_chain_correct && | |
| 1999 IsOCSPStaplingSupported()) { | |
| 2000 unsigned int len = 0; | |
| 2001 SSL_GetStapledOCSPResponse(nss_fd_, NULL, &len); | |
| 2002 if (len) { | |
| 2003 const unsigned int orig_len = len; | |
| 2004 scoped_array<uint8> ocsp_response(new uint8[orig_len]); | |
| 2005 SSL_GetStapledOCSPResponse(nss_fd_, ocsp_response.get(), &len); | |
| 2006 DCHECK_EQ(orig_len, len); | |
| 2007 | |
| 2008 #if defined(OS_WIN) | |
| 2009 if (nss_handshake_state_.server_cert) { | |
| 2010 CRYPT_DATA_BLOB ocsp_response_blob; | |
| 2011 ocsp_response_blob.cbData = len; | |
| 2012 ocsp_response_blob.pbData = ocsp_response.get(); | |
| 2013 BOOL ok = CertSetCertificateContextProperty( | |
| 2014 nss_handshake_state_.server_cert->os_cert_handle(), | |
| 2015 CERT_OCSP_RESPONSE_PROP_ID, | |
| 2016 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG, | |
| 2017 &ocsp_response_blob); | |
| 2018 if (!ok) { | |
| 2019 VLOG(1) << "Failed to set OCSP response property: " | |
| 2020 << GetLastError(); | |
| 2021 } | |
| 2022 } | |
| 2023 #elif defined(USE_NSS) | |
| 2024 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response = | |
| 2025 GetCacheOCSPResponseFromSideChannelFunction(); | |
| 2026 SECItem ocsp_response_item; | |
| 2027 ocsp_response_item.type = siBuffer; | |
| 2028 ocsp_response_item.data = ocsp_response.get(); | |
| 2029 ocsp_response_item.len = len; | |
| 2030 | |
| 2031 cache_ocsp_response( | |
| 2032 CERT_GetDefaultCertDB(), | |
| 2033 nss_handshake_state_.server_cert_chain[0], PR_Now(), | |
| 2034 &ocsp_response_item, NULL); | |
| 2035 #endif | |
| 2036 } | |
| 2037 } | |
| 2038 #endif | |
| 2039 } | |
| 2040 // Done! | |
| 2041 } else { | |
| 2042 PRErrorCode prerr = PR_GetError(); | |
| 2043 net_error = HandleNSSError(prerr, true); | |
| 2044 | |
| 2045 // If not done, stay in this state | |
| 2046 if (net_error == ERR_IO_PENDING) { | |
| 2047 GotoState(STATE_HANDSHAKE); | |
| 2048 } else { | |
| 2049 PostOrRunCallback( | |
| 2050 FROM_HERE, | |
| 2051 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 2052 NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
| 2053 make_scoped_refptr( | |
| 2054 new SSLErrorParams(net_error, prerr)))); | |
| 2055 } | |
| 2056 } | |
| 2057 | |
| 2058 return net_error; | |
| 2059 } | |
| 2060 | |
| 2061 int SSLClientSocketNSS::Core::DoGetDBCertComplete(int result) { | |
| 2062 SECStatus rv; | |
| 2063 PostOrRunCallback( | |
| 2064 FROM_HERE, | |
| 2065 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_, | |
| 2066 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, result)); | |
| 2067 | |
| 2068 client_auth_cert_needed_ = false; | |
| 2069 domain_bound_cert_type_ = CLIENT_CERT_INVALID_TYPE; | |
| 2070 | |
| 2071 if (result != OK) { | |
| 2072 // Failed to get a DBC. Proceed without. | |
| 2073 rv = SSL_RestartHandshakeAfterCertReq(nss_fd_, NULL, NULL, NULL); | |
| 2074 if (rv != SECSuccess) | |
| 2075 return MapNSSError(PORT_GetError()); | |
| 2076 | |
| 2077 GotoState(STATE_HANDSHAKE); | |
| 2078 return OK; | |
| 2079 } | |
| 2080 | |
| 2081 CERTCertificate* cert; | |
| 2082 SECKEYPrivateKey* key; | |
| 2083 int error = ImportDBCertAndKey(&cert, &key); | |
| 2084 if (error != OK) | |
| 2085 return error; | |
| 2086 | |
| 2087 CERTCertificateList* cert_chain = | |
| 2088 CERT_CertChainFromCert(cert, certUsageSSLClient, PR_FALSE); | |
| 2089 | |
| 2090 PostOrRunCallback( | |
| 2091 FROM_HERE, | |
| 2092 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 2093 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2094 make_scoped_refptr( | |
| 2095 new NetLogIntegerParameter("cert_count", | |
| 2096 cert_chain->len)))); | |
| 2097 | |
| 2098 rv = SSL_RestartHandshakeAfterCertReq(nss_fd_, cert, key, cert_chain); | |
| 2099 if (rv != SECSuccess) | |
| 2100 return MapNSSError(PORT_GetError()); | |
| 2101 | |
| 2102 GotoState(STATE_HANDSHAKE); | |
| 823 return OK; | 2103 return OK; |
| 824 } | 2104 } |
| 825 | 2105 |
| 826 int SSLClientSocketNSS::InitializeSSLOptions() { | 2106 int SSLClientSocketNSS::Core::DoPayloadRead() { |
| 827 // Transport connected, now hook it up to nss | 2107 DCHECK(OnNSSTaskRunner()); |
| 828 // TODO(port): specify rx and tx buffer sizes separately | 2108 DCHECK(user_read_buf_); |
| 829 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize); | 2109 DCHECK_GT(user_read_buf_len_, 0); |
| 830 if (nss_fd_ == NULL) { | 2110 |
| 831 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code. | 2111 int rv = PR_Read(nss_fd_, user_read_buf_->data(), user_read_buf_len_); |
| 832 } | 2112 if (client_auth_cert_needed_) { |
| 833 | 2113 // We don't need to invalidate the non-client-authenticated SSL session |
| 834 // Grab pointer to buffers | 2114 // because the server will renegotiate anyway. |
| 835 nss_bufs_ = memio_GetSecret(nss_fd_); | 2115 rv = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; |
| 836 | 2116 PostOrRunCallback( |
| 837 /* Create SSL state machine */ | 2117 FROM_HERE, |
| 838 /* Push SSL onto our fake I/O socket */ | 2118 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, |
| 839 nss_fd_ = SSL_ImportFD(NULL, nss_fd_); | 2119 NetLog::TYPE_SSL_READ_ERROR, |
| 840 if (nss_fd_ == NULL) { | 2120 make_scoped_refptr(new SSLErrorParams(rv, 0)))); |
| 841 LogFailedNSSFunction(net_log_, "SSL_ImportFD", ""); | 2121 return rv; |
| 842 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code. | 2122 } |
| 843 } | 2123 if (rv >= 0) { |
| 844 // TODO(port): set more ssl options! Check errors! | 2124 PostOrRunCallback( |
| 845 | 2125 FROM_HERE, |
| 2126 base::Bind(&LogByteTransferEvent, weak_net_log_, | |
| 2127 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv, | |
| 2128 scoped_refptr<IOBuffer>(user_read_buf_))); | |
| 2129 return rv; | |
| 2130 } | |
| 2131 PRErrorCode prerr = PR_GetError(); | |
| 2132 if (prerr == PR_WOULD_BLOCK_ERROR) | |
| 2133 return ERR_IO_PENDING; | |
| 2134 | |
| 2135 rv = HandleNSSError(prerr, false); | |
| 2136 PostOrRunCallback( | |
| 2137 FROM_HERE, | |
| 2138 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 2139 NetLog::TYPE_SSL_READ_ERROR, | |
| 2140 make_scoped_refptr(new SSLErrorParams(rv, prerr)))); | |
| 2141 return rv; | |
| 2142 } | |
| 2143 | |
| 2144 int SSLClientSocketNSS::Core::DoPayloadWrite() { | |
| 2145 DCHECK(OnNSSTaskRunner()); | |
| 2146 | |
| 2147 DCHECK(user_write_buf_); | |
| 2148 | |
| 2149 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_); | |
| 2150 if (rv >= 0) { | |
| 2151 PostOrRunCallback( | |
| 2152 FROM_HERE, | |
| 2153 base::Bind(&LogByteTransferEvent, weak_net_log_, | |
| 2154 NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv, | |
| 2155 scoped_refptr<IOBuffer>(user_write_buf_))); | |
| 2156 return rv; | |
| 2157 } | |
| 2158 PRErrorCode prerr = PR_GetError(); | |
| 2159 if (prerr == PR_WOULD_BLOCK_ERROR) | |
| 2160 return ERR_IO_PENDING; | |
| 2161 | |
| 2162 rv = HandleNSSError(prerr, false); | |
| 2163 PostOrRunCallback( | |
| 2164 FROM_HERE, | |
| 2165 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 2166 NetLog::TYPE_SSL_WRITE_ERROR, | |
| 2167 make_scoped_refptr(new SSLErrorParams(rv, prerr)))); | |
| 2168 return rv; | |
| 2169 } | |
| 2170 | |
| 2171 // Do as much network I/O as possible between the buffer and the | |
| 2172 // transport socket. Return true if some I/O performed, false | |
| 2173 // otherwise (error or ERR_IO_PENDING). | |
| 2174 bool SSLClientSocketNSS::Core::DoTransportIO() { | |
| 2175 DCHECK(OnNSSTaskRunner()); | |
| 2176 | |
| 2177 bool network_moved = false; | |
| 2178 if (nss_bufs_ != NULL) { | |
| 2179 int rv; | |
| 2180 // Read and write as much data as we can. The loop is neccessary | |
| 2181 // because Write() may return synchronously. | |
| 2182 do { | |
| 2183 rv = BufferSend(); | |
| 2184 if (rv > 0) | |
| 2185 network_moved = true; | |
| 2186 } while (rv > 0); | |
| 2187 if (!transport_recv_eof_ && BufferRecv() >= 0) | |
| 2188 network_moved = true; | |
| 2189 } | |
| 2190 return network_moved; | |
| 2191 } | |
| 2192 | |
| 2193 int SSLClientSocketNSS::Core::BufferRecv() { | |
| 2194 DCHECK(OnNSSTaskRunner()); | |
| 2195 | |
| 2196 if (transport_recv_busy_) | |
| 2197 return ERR_IO_PENDING; | |
| 2198 | |
| 2199 char* buf; | |
| 2200 int nb = memio_GetReadParams(nss_bufs_, &buf); | |
| 846 int rv; | 2201 int rv; |
| 847 | 2202 if (!nb) { |
| 848 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE); | 2203 // buffer too full to read into, so no I/O possible at moment |
| 849 if (rv != SECSuccess) { | 2204 rv = ERR_IO_PENDING; |
| 850 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY"); | 2205 } else { |
| 851 return ERR_UNEXPECTED; | 2206 scoped_refptr<IOBuffer> read_buffer(new IOBuffer(nb)); |
| 852 } | 2207 if (OnNetworkTaskRunner()) { |
| 853 | 2208 rv = DoBufferRecv(read_buffer, nb); |
| 854 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE); | 2209 } else { |
| 855 if (rv != SECSuccess) { | 2210 bool posted = network_task_runner_->PostTask( |
| 856 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2"); | 2211 FROM_HERE, |
| 857 return ERR_UNEXPECTED; | 2212 base::Bind(IgnoreResult(&Core::DoBufferRecv), this, read_buffer, |
| 858 } | 2213 nb)); |
| 859 | 2214 rv = posted ? ERR_IO_PENDING : ERR_ABORTED; |
| 860 // Don't do V2 compatible hellos because they don't support TLS extensions. | 2215 } |
| 861 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE); | 2216 |
| 862 if (rv != SECSuccess) { | 2217 if (rv == ERR_IO_PENDING) { |
| 863 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO"); | 2218 transport_recv_busy_ = true; |
| 864 return ERR_UNEXPECTED; | 2219 } else { |
| 865 } | 2220 if (rv > 0) { |
| 866 | 2221 memcpy(buf, read_buffer->data(), rv); |
| 867 SSLVersionRange version_range; | 2222 } else if (rv == 0) { |
| 868 version_range.min = ssl_config_.version_min; | 2223 transport_recv_eof_ = true; |
| 869 version_range.max = ssl_config_.version_max; | 2224 } |
| 870 rv = SSL_VersionRangeSet(nss_fd_, &version_range); | 2225 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv)); |
| 871 if (rv != SECSuccess) { | 2226 } |
| 872 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", ""); | 2227 } |
| 873 return ERR_NO_SSL_VERSIONS_ENABLED; | 2228 return rv; |
| 874 } | 2229 } |
| 875 | 2230 |
| 876 for (std::vector<uint16>::const_iterator it = | 2231 // Return 0 for EOF, |
| 877 ssl_config_.disabled_cipher_suites.begin(); | 2232 // > 0 for bytes transferred immediately, |
| 878 it != ssl_config_.disabled_cipher_suites.end(); ++it) { | 2233 // < 0 for error (or the non-error ERR_IO_PENDING). |
| 879 // This will fail if the specified cipher is not implemented by NSS, but | 2234 int SSLClientSocketNSS::Core::BufferSend() { |
| 880 // the failure is harmless. | 2235 DCHECK(OnNSSTaskRunner()); |
| 881 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE); | 2236 |
| 882 } | 2237 if (transport_send_busy_) |
| 883 | 2238 return ERR_IO_PENDING; |
| 884 #ifdef SSL_ENABLE_SESSION_TICKETS | 2239 |
| 885 // Support RFC 5077 | 2240 const char* buf1; |
| 886 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE); | 2241 const char* buf2; |
| 887 if (rv != SECSuccess) { | 2242 unsigned int len1, len2; |
| 888 LogFailedNSSFunction( | 2243 memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2); |
| 889 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS"); | 2244 const unsigned int len = len1 + len2; |
| 890 } | 2245 |
| 891 #else | 2246 int rv = 0; |
| 892 #error "You need to install NSS-3.12 or later to build chromium" | 2247 if (len) { |
| 893 #endif | 2248 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len)); |
| 894 | 2249 memcpy(send_buffer->data(), buf1, len1); |
| 895 #ifdef SSL_ENABLE_DEFLATE | 2250 memcpy(send_buffer->data() + len1, buf2, len2); |
| 896 // Some web servers have been found to break if TLS is used *or* if DEFLATE | 2251 |
| 897 // is advertised. Thus, if TLS is disabled (probably because we are doing | 2252 if (OnNetworkTaskRunner()) { |
| 898 // SSLv3 fallback), we disable DEFLATE also. | 2253 rv = DoBufferSend(send_buffer, len); |
| 899 // See http://crbug.com/31628 | 2254 } else { |
| 900 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_DEFLATE, | 2255 bool posted = network_task_runner_->PostTask( |
| 901 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1); | 2256 FROM_HERE, |
| 902 if (rv != SECSuccess) | 2257 base::Bind(IgnoreResult(&Core::DoBufferSend), this, send_buffer, |
| 903 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_DEFLATE"); | 2258 len)); |
| 904 #endif | 2259 rv = posted ? ERR_IO_PENDING : ERR_ABORTED; |
| 905 | 2260 } |
| 906 #ifdef SSL_ENABLE_FALSE_START | 2261 |
| 907 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, | 2262 if (rv == ERR_IO_PENDING) { |
| 908 ssl_config_.false_start_enabled); | 2263 transport_send_busy_ = true; |
| 909 if (rv != SECSuccess) | 2264 } else { |
| 910 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START"); | 2265 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv)); |
| 911 #endif | 2266 } |
| 912 | 2267 } |
| 913 #ifdef SSL_ENABLE_RENEGOTIATION | 2268 |
| 914 // We allow servers to request renegotiation. Since we're a client, | 2269 return rv; |
| 915 // prohibiting this is rather a waste of time. Only servers are in a | 2270 } |
| 916 // position to prevent renegotiation attacks. | 2271 |
| 917 // http://extendedsubset.com/?p=8 | 2272 void SSLClientSocketNSS::Core::OnRecvComplete(int result) { |
| 918 | 2273 DCHECK(OnNSSTaskRunner()); |
| 919 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION, | 2274 |
| 920 SSL_RENEGOTIATE_TRANSITIONAL); | |
| 921 if (rv != SECSuccess) { | |
| 922 LogFailedNSSFunction( | |
| 923 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION"); | |
| 924 } | |
| 925 #endif // SSL_ENABLE_RENEGOTIATION | |
| 926 | |
| 927 if (!ssl_config_.next_protos.empty()) { | |
| 928 rv = SSL_SetNextProtoCallback( | |
| 929 nss_fd_, SSLClientSocketNSS::NextProtoCallback, this); | |
| 930 if (rv != SECSuccess) | |
| 931 LogFailedNSSFunction(net_log_, "SSL_SetNextProtoCallback", ""); | |
| 932 } | |
| 933 | |
| 934 #ifdef SSL_CBC_RANDOM_IV | |
| 935 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, | |
| 936 ssl_config_.false_start_enabled); | |
| 937 if (rv != SECSuccess) | |
| 938 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV"); | |
| 939 #endif | |
| 940 | |
| 941 #ifdef SSL_ENABLE_OCSP_STAPLING | |
| 942 if (IsOCSPStaplingSupported()) { | |
| 943 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE); | |
| 944 if (rv != SECSuccess) { | |
| 945 LogFailedNSSFunction(net_log_, "SSL_OptionSet", | |
| 946 "SSL_ENABLE_OCSP_STAPLING"); | |
| 947 } | |
| 948 } | |
| 949 #endif | |
| 950 | |
| 951 #ifdef SSL_ENABLE_CACHED_INFO | |
| 952 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO, | |
| 953 ssl_config_.cached_info_enabled); | |
| 954 if (rv != SECSuccess) | |
| 955 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO"); | |
| 956 #endif | |
| 957 | |
| 958 #ifdef SSL_ENABLE_OB_CERTS | |
| 959 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OB_CERTS, | |
| 960 ssl_config_.domain_bound_certs_enabled); | |
| 961 if (rv != SECSuccess) | |
| 962 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_OB_CERTS"); | |
| 963 #endif | |
| 964 | |
| 965 #ifdef SSL_ENCRYPT_CLIENT_CERTS | |
| 966 // For now, enable the encrypted client certificates extension only if | |
| 967 // server-bound certificates are enabled. | |
| 968 rv = SSL_OptionSet(nss_fd_, SSL_ENCRYPT_CLIENT_CERTS, | |
| 969 ssl_config_.domain_bound_certs_enabled); | |
| 970 if (rv != SECSuccess) | |
| 971 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENCRYPT_CLIENT_CERTS"); | |
| 972 #endif | |
| 973 | |
| 974 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE); | |
| 975 if (rv != SECSuccess) { | |
| 976 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT"); | |
| 977 return ERR_UNEXPECTED; | |
| 978 } | |
| 979 | |
| 980 rv = SSL_AuthCertificateHook(nss_fd_, OwnAuthCertHandler, this); | |
| 981 if (rv != SECSuccess) { | |
| 982 LogFailedNSSFunction(net_log_, "SSL_AuthCertificateHook", ""); | |
| 983 return ERR_UNEXPECTED; | |
| 984 } | |
| 985 | |
| 986 #if defined(NSS_PLATFORM_CLIENT_AUTH) | |
| 987 rv = SSL_GetPlatformClientAuthDataHook(nss_fd_, PlatformClientAuthHandler, | |
| 988 this); | |
| 989 #else | |
| 990 rv = SSL_GetClientAuthDataHook(nss_fd_, ClientAuthHandler, this); | |
| 991 #endif | |
| 992 if (rv != SECSuccess) { | |
| 993 LogFailedNSSFunction(net_log_, "SSL_GetClientAuthDataHook", ""); | |
| 994 return ERR_UNEXPECTED; | |
| 995 } | |
| 996 | |
| 997 rv = SSL_HandshakeCallback(nss_fd_, HandshakeCallback, this); | |
| 998 if (rv != SECSuccess) { | |
| 999 LogFailedNSSFunction(net_log_, "SSL_HandshakeCallback", ""); | |
| 1000 return ERR_UNEXPECTED; | |
| 1001 } | |
| 1002 | |
| 1003 // Tell SSL the hostname we're trying to connect to. | |
| 1004 SSL_SetURL(nss_fd_, host_and_port_.host().c_str()); | |
| 1005 | |
| 1006 // Tell SSL we're a client; needed if not letting NSPR do socket I/O | |
| 1007 SSL_ResetHandshake(nss_fd_, PR_FALSE); | |
| 1008 | |
| 1009 return OK; | |
| 1010 } | |
| 1011 | |
| 1012 int SSLClientSocketNSS::InitializeSSLPeerName() { | |
| 1013 // Tell NSS who we're connected to | |
| 1014 AddressList peer_address; | |
| 1015 int err = transport_->socket()->GetPeerAddress(&peer_address); | |
| 1016 if (err != OK) | |
| 1017 return err; | |
| 1018 | |
| 1019 SockaddrStorage storage; | |
| 1020 if (!peer_address.front().ToSockAddr(storage.addr, &storage.addr_len)) | |
| 1021 return ERR_UNEXPECTED; | |
| 1022 | |
| 1023 PRNetAddr peername; | |
| 1024 memset(&peername, 0, sizeof(peername)); | |
| 1025 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername)); | |
| 1026 size_t len = std::min(static_cast<size_t>(storage.addr_len), | |
| 1027 sizeof(peername)); | |
| 1028 memcpy(&peername, storage.addr, len); | |
| 1029 | |
| 1030 // Adjust the address family field for BSD, whose sockaddr | |
| 1031 // structure has a one-byte length and one-byte address family | |
| 1032 // field at the beginning. PRNetAddr has a two-byte address | |
| 1033 // family field at the beginning. | |
| 1034 peername.raw.family = storage.addr->sa_family; | |
| 1035 | |
| 1036 memio_SetPeerName(nss_fd_, &peername); | |
| 1037 | |
| 1038 // Set the peer ID for session reuse. This is necessary when we create an | |
| 1039 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address | |
| 1040 // rather than the destination server's address in that case. | |
| 1041 std::string peer_id = host_and_port_.ToString(); | |
| 1042 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id. | |
| 1043 // This will cause session cache misses between sockets with different values | |
| 1044 // of ssl_session_cache_shard_ and this is used to partition the session cache | |
| 1045 // for incognito mode. | |
| 1046 if (!ssl_session_cache_shard_.empty()) { | |
| 1047 peer_id += "/" + ssl_session_cache_shard_; | |
| 1048 } | |
| 1049 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str())); | |
| 1050 if (rv != SECSuccess) | |
| 1051 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str()); | |
| 1052 | |
| 1053 return OK; | |
| 1054 } | |
| 1055 | |
| 1056 | |
| 1057 // Sets server_cert_ and server_cert_nss_ if not yet set. | |
| 1058 void SSLClientSocketNSS::UpdateServerCert() { | |
| 1059 // We set the server_cert_ from HandshakeCallback(). | |
| 1060 if (server_cert_ == NULL) { | |
| 1061 server_cert_nss_ = SSL_PeerCertificate(nss_fd_); | |
| 1062 if (server_cert_nss_) { | |
| 1063 PeerCertificateChain certs(nss_fd_); | |
| 1064 // This call may fail when SSL is used inside sandbox. In that | |
| 1065 // case CreateFromDERCertChain() returns NULL. | |
| 1066 server_cert_ = X509Certificate::CreateFromDERCertChain( | |
| 1067 certs.AsStringPieceVector()); | |
| 1068 if (server_cert_) { | |
| 1069 net_log_.AddEvent( | |
| 1070 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED, | |
| 1071 make_scoped_refptr(new X509CertificateNetLogParam(server_cert_))); | |
| 1072 } | |
| 1073 } | |
| 1074 } | |
| 1075 } | |
| 1076 | |
| 1077 // Sets ssl_connection_status_. | |
| 1078 void SSLClientSocketNSS::UpdateConnectionStatus() { | |
| 1079 SSLChannelInfo channel_info; | |
| 1080 SECStatus ok = SSL_GetChannelInfo(nss_fd_, | |
| 1081 &channel_info, sizeof(channel_info)); | |
| 1082 if (ok == SECSuccess && | |
| 1083 channel_info.length == sizeof(channel_info) && | |
| 1084 channel_info.cipherSuite) { | |
| 1085 ssl_connection_status_ |= | |
| 1086 (static_cast<int>(channel_info.cipherSuite) & | |
| 1087 SSL_CONNECTION_CIPHERSUITE_MASK) << | |
| 1088 SSL_CONNECTION_CIPHERSUITE_SHIFT; | |
| 1089 | |
| 1090 ssl_connection_status_ |= | |
| 1091 (static_cast<int>(channel_info.compressionMethod) & | |
| 1092 SSL_CONNECTION_COMPRESSION_MASK) << | |
| 1093 SSL_CONNECTION_COMPRESSION_SHIFT; | |
| 1094 | |
| 1095 // NSS 3.12.x doesn't have version macros for TLS 1.1 and 1.2 (because NSS | |
| 1096 // doesn't support them yet), so we use 0x0302 and 0x0303 directly. | |
| 1097 int version = SSL_CONNECTION_VERSION_UNKNOWN; | |
| 1098 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) { | |
| 1099 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL | |
| 1100 // version 2. | |
| 1101 version = SSL_CONNECTION_VERSION_SSL2; | |
| 1102 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) { | |
| 1103 version = SSL_CONNECTION_VERSION_SSL3; | |
| 1104 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) { | |
| 1105 version = SSL_CONNECTION_VERSION_TLS1; | |
| 1106 } else if (channel_info.protocolVersion == 0x0302) { | |
| 1107 version = SSL_CONNECTION_VERSION_TLS1_1; | |
| 1108 } else if (channel_info.protocolVersion == 0x0303) { | |
| 1109 version = SSL_CONNECTION_VERSION_TLS1_2; | |
| 1110 } | |
| 1111 ssl_connection_status_ |= | |
| 1112 (version & SSL_CONNECTION_VERSION_MASK) << | |
| 1113 SSL_CONNECTION_VERSION_SHIFT; | |
| 1114 } | |
| 1115 | |
| 1116 // SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6. | |
| 1117 // Since SSL_MAX_EXTENSIONS was added at the same time, we can test | |
| 1118 // SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension. | |
| 1119 #if defined(SSL_MAX_EXTENSIONS) | |
| 1120 PRBool peer_supports_renego_ext; | |
| 1121 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn, | |
| 1122 &peer_supports_renego_ext); | |
| 1123 if (ok == SECSuccess) { | |
| 1124 if (!peer_supports_renego_ext) { | |
| 1125 ssl_connection_status_ |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION; | |
| 1126 // Log an informational message if the server does not support secure | |
| 1127 // renegotiation (RFC 5746). | |
| 1128 VLOG(1) << "The server " << host_and_port_.ToString() | |
| 1129 << " does not support the TLS renegotiation_info extension."; | |
| 1130 } | |
| 1131 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported", | |
| 1132 peer_supports_renego_ext, 2); | |
| 1133 } | |
| 1134 #endif | |
| 1135 | |
| 1136 if (ssl_config_.version_fallback) | |
| 1137 ssl_connection_status_ |= SSL_CONNECTION_VERSION_FALLBACK; | |
| 1138 } | |
| 1139 | |
| 1140 void SSLClientSocketNSS::DoReadCallback(int rv) { | |
| 1141 EnterFunction(rv); | |
| 1142 DCHECK(rv != ERR_IO_PENDING); | |
| 1143 DCHECK(!user_read_callback_.is_null()); | |
| 1144 | |
| 1145 // Since Run may result in Read being called, clear |user_read_callback_| | |
| 1146 // up front. | |
| 1147 CompletionCallback c = user_read_callback_; | |
| 1148 user_read_callback_.Reset(); | |
| 1149 user_read_buf_ = NULL; | |
| 1150 user_read_buf_len_ = 0; | |
| 1151 c.Run(rv); | |
| 1152 LeaveFunction(""); | |
| 1153 } | |
| 1154 | |
| 1155 void SSLClientSocketNSS::DoWriteCallback(int rv) { | |
| 1156 EnterFunction(rv); | |
| 1157 DCHECK(rv != ERR_IO_PENDING); | |
| 1158 DCHECK(!user_write_callback_.is_null()); | |
| 1159 | |
| 1160 // Since Run may result in Write being called, clear |user_write_callback_| | |
| 1161 // up front. | |
| 1162 CompletionCallback c = user_write_callback_; | |
| 1163 user_write_callback_.Reset(); | |
| 1164 user_write_buf_ = NULL; | |
| 1165 user_write_buf_len_ = 0; | |
| 1166 c.Run(rv); | |
| 1167 LeaveFunction(""); | |
| 1168 } | |
| 1169 | |
| 1170 // As part of Connect(), the SSLClientSocketNSS object performs an SSL | |
| 1171 // handshake. This requires network IO, which in turn calls | |
| 1172 // BufferRecvComplete() with a non-zero byte count. This byte count eventually | |
| 1173 // winds its way through the state machine and ends up being passed to the | |
| 1174 // callback. For Read() and Write(), that's what we want. But for Connect(), | |
| 1175 // the caller expects OK (i.e. 0) for success. | |
| 1176 // | |
| 1177 void SSLClientSocketNSS::DoConnectCallback(int rv) { | |
| 1178 EnterFunction(rv); | |
| 1179 DCHECK_NE(rv, ERR_IO_PENDING); | |
| 1180 DCHECK(!user_connect_callback_.is_null()); | |
| 1181 | |
| 1182 CompletionCallback c = user_connect_callback_; | |
| 1183 user_connect_callback_.Reset(); | |
| 1184 c.Run(rv > OK ? OK : rv); | |
| 1185 LeaveFunction(""); | |
| 1186 } | |
| 1187 | |
| 1188 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) { | |
| 1189 EnterFunction(result); | |
| 1190 int rv = DoHandshakeLoop(result); | |
| 1191 if (rv != ERR_IO_PENDING) { | |
| 1192 net_log_.EndEventWithNetErrorCode(net::NetLog::TYPE_SSL_CONNECT, rv); | |
| 1193 DoConnectCallback(rv); | |
| 1194 } | |
| 1195 LeaveFunction(""); | |
| 1196 } | |
| 1197 | |
| 1198 void SSLClientSocketNSS::OnSendComplete(int result) { | |
| 1199 EnterFunction(result); | |
| 1200 if (next_handshake_state_ == STATE_HANDSHAKE) { | 2275 if (next_handshake_state_ == STATE_HANDSHAKE) { |
| 1201 // In handshake phase. | |
| 1202 OnHandshakeIOComplete(result); | 2276 OnHandshakeIOComplete(result); |
| 1203 LeaveFunction(""); | |
| 1204 return; | 2277 return; |
| 1205 } | 2278 } |
| 1206 | 2279 |
| 2280 // Network layer received some data, check if client requested to read | |
| 2281 // decrypted data. | |
| 2282 if (!user_read_buf_) | |
| 2283 return; | |
| 2284 | |
| 2285 int rv = DoReadLoop(result); | |
| 2286 if (rv != ERR_IO_PENDING) | |
| 2287 DoReadCallback(rv); | |
| 2288 } | |
| 2289 | |
| 2290 void SSLClientSocketNSS::Core::OnSendComplete(int result) { | |
| 2291 DCHECK(OnNSSTaskRunner()); | |
| 2292 | |
| 2293 if (next_handshake_state_ == STATE_HANDSHAKE) { | |
| 2294 OnHandshakeIOComplete(result); | |
| 2295 return; | |
| 2296 } | |
| 2297 | |
| 1207 // OnSendComplete may need to call DoPayloadRead while the renegotiation | 2298 // OnSendComplete may need to call DoPayloadRead while the renegotiation |
| 1208 // handshake is in progress. | 2299 // handshake is in progress. |
| 1209 int rv_read = ERR_IO_PENDING; | 2300 int rv_read = ERR_IO_PENDING; |
| 1210 int rv_write = ERR_IO_PENDING; | 2301 int rv_write = ERR_IO_PENDING; |
| 1211 bool network_moved; | 2302 bool network_moved; |
| 1212 do { | 2303 do { |
| 1213 if (user_read_buf_) | 2304 if (user_read_buf_) |
| 1214 rv_read = DoPayloadRead(); | 2305 rv_read = DoPayloadRead(); |
| 1215 if (user_write_buf_) | 2306 if (user_write_buf_) |
| 1216 rv_write = DoPayloadWrite(); | 2307 rv_write = DoPayloadWrite(); |
| 1217 network_moved = DoTransportIO(); | 2308 network_moved = DoTransportIO(); |
| 1218 } while (rv_read == ERR_IO_PENDING && | 2309 } while (rv_read == ERR_IO_PENDING && |
| 1219 rv_write == ERR_IO_PENDING && | 2310 rv_write == ERR_IO_PENDING && |
| 1220 (user_read_buf_ || user_write_buf_) && | 2311 (user_read_buf_ || user_write_buf_) && |
| 1221 network_moved); | 2312 network_moved); |
| 1222 | 2313 |
| 1223 if (user_read_buf_ && rv_read != ERR_IO_PENDING) | 2314 if (user_read_buf_ && rv_read != ERR_IO_PENDING) |
| 1224 DoReadCallback(rv_read); | 2315 DoReadCallback(rv_read); |
| 1225 if (user_write_buf_ && rv_write != ERR_IO_PENDING) | 2316 if (user_write_buf_ && rv_write != ERR_IO_PENDING) |
| 1226 DoWriteCallback(rv_write); | 2317 DoWriteCallback(rv_write); |
| 1227 | |
| 1228 LeaveFunction(""); | |
| 1229 } | 2318 } |
| 1230 | 2319 |
| 1231 void SSLClientSocketNSS::OnRecvComplete(int result) { | 2320 // As part of Connect(), the SSLClientSocketNSS object performs an SSL |
| 1232 EnterFunction(result); | 2321 // handshake. This requires network IO, which in turn calls |
| 1233 if (next_handshake_state_ == STATE_HANDSHAKE) { | 2322 // BufferRecvComplete() with a non-zero byte count. This byte count eventually |
| 1234 // In handshake phase. | 2323 // winds its way through the state machine and ends up being passed to the |
| 1235 OnHandshakeIOComplete(result); | 2324 // callback. For Read() and Write(), that's what we want. But for Connect(), |
| 1236 LeaveFunction(""); | 2325 // the caller expects OK (i.e. 0) for success. |
| 1237 return; | 2326 void SSLClientSocketNSS::Core::DoConnectCallback(int rv) { |
| 2327 DCHECK(OnNSSTaskRunner()); | |
| 2328 DCHECK_NE(rv, ERR_IO_PENDING); | |
| 2329 DCHECK(!user_connect_callback_.is_null()); | |
| 2330 | |
| 2331 base::Closure c = base::Bind( | |
| 2332 base::ResetAndReturn(&user_connect_callback_), | |
| 2333 rv > OK ? OK : rv); | |
| 2334 PostOrRunCallback(FROM_HERE, c); | |
| 2335 } | |
| 2336 | |
| 2337 void SSLClientSocketNSS::Core::DoReadCallback(int rv) { | |
| 2338 DCHECK(OnNSSTaskRunner()); | |
| 2339 DCHECK_NE(ERR_IO_PENDING, rv); | |
| 2340 DCHECK(!user_read_callback_.is_null()); | |
| 2341 | |
| 2342 user_read_buf_ = NULL; | |
| 2343 user_read_buf_len_ = 0; | |
| 2344 base::Closure c = base::Bind( | |
| 2345 base::ResetAndReturn(&user_read_callback_), | |
| 2346 rv); | |
| 2347 PostOrRunCallback(FROM_HERE, c); | |
| 2348 } | |
| 2349 | |
| 2350 void SSLClientSocketNSS::Core::DoWriteCallback(int rv) { | |
| 2351 DCHECK(OnNSSTaskRunner()); | |
| 2352 DCHECK_NE(ERR_IO_PENDING, rv); | |
| 2353 DCHECK(!user_write_callback_.is_null()); | |
| 2354 | |
| 2355 // Since Run may result in Write being called, clear |user_write_callback_| | |
| 2356 // up front. | |
| 2357 user_write_buf_ = NULL; | |
| 2358 user_write_buf_len_ = 0; | |
| 2359 base::Closure c = base::Bind( | |
| 2360 base::ResetAndReturn(&user_write_callback_), | |
| 2361 rv); | |
| 2362 PostOrRunCallback(FROM_HERE, c); | |
| 2363 } | |
| 2364 | |
| 2365 SECStatus SSLClientSocketNSS::Core::DomainBoundClientAuthHandler( | |
| 2366 const SECItem* cert_types, | |
| 2367 CERTCertificate** result_certificate, | |
| 2368 SECKEYPrivateKey** result_private_key) { | |
| 2369 DCHECK(OnNSSTaskRunner()); | |
| 2370 | |
| 2371 domain_bound_cert_xtn_negotiated_ = true; | |
| 2372 | |
| 2373 // We have negotiated the domain-bound certificate extension. | |
| 2374 std::string origin = "https://" + host_and_port_.ToString(); | |
| 2375 std::vector<uint8> requested_cert_types(cert_types->data, | |
| 2376 cert_types->data + cert_types->len); | |
| 2377 int error = ERR_UNEXPECTED; | |
| 2378 if (OnNetworkTaskRunner()) { | |
| 2379 error = DoGetDomainBoundCert(origin, requested_cert_types); | |
| 2380 } else { | |
| 2381 bool posted = network_task_runner_->PostTask( | |
| 2382 FROM_HERE, | |
| 2383 base::Bind(IgnoreResult(&Core::DoGetDomainBoundCert), this, origin, | |
| 2384 requested_cert_types)); | |
| 2385 error = posted ? ERR_IO_PENDING : ERR_ABORTED; | |
| 1238 } | 2386 } |
| 1239 | 2387 |
| 1240 // Network layer received some data, check if client requested to read | 2388 if (error == ERR_IO_PENDING) { |
| 1241 // decrypted data. | 2389 // Asynchronous case. |
| 1242 if (!user_read_buf_) { | 2390 client_auth_cert_needed_ = true; |
| 1243 LeaveFunction(""); | 2391 return SECWouldBlock; |
| 1244 return; | |
| 1245 } | 2392 } |
| 1246 | 2393 |
| 1247 int rv = DoReadLoop(result); | 2394 PostOrRunCallback( |
| 1248 if (rv != ERR_IO_PENDING) | 2395 FROM_HERE, |
| 1249 DoReadCallback(rv); | 2396 base::Bind(&BoundNetLog::EndEventWithNetErrorCode, weak_net_log_, |
| 1250 LeaveFunction(""); | 2397 NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, error)); |
| 1251 } | 2398 SECStatus rv = SECSuccess; |
| 2399 if (error == OK) { | |
| 2400 // Synchronous success. | |
| 2401 int result = ImportDBCertAndKey(result_certificate, result_private_key); | |
| 2402 if (result != OK) { | |
| 2403 domain_bound_cert_type_ = CLIENT_CERT_INVALID_TYPE; | |
| 2404 rv = SECFailure; | |
| 2405 } | |
| 2406 } else { | |
| 2407 rv = SECFailure; | |
| 2408 } | |
| 1252 | 2409 |
| 1253 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) { | 2410 int cert_count = (rv == SECSuccess) ? 1 : 0; |
| 1254 EnterFunction(last_io_result); | 2411 PostOrRunCallback( |
| 1255 int rv = last_io_result; | 2412 FROM_HERE, |
| 1256 do { | 2413 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, |
| 1257 // Default to STATE_NONE for next state. | 2414 NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, |
| 1258 // (This is a quirk carried over from the windows | 2415 make_scoped_refptr( |
| 1259 // implementation. It makes reading the logs a bit harder.) | 2416 new NetLogIntegerParameter("cert_count", |
| 1260 // State handlers can and often do call GotoState just | 2417 cert_count)))); |
| 1261 // to stay in the current state. | |
| 1262 State state = next_handshake_state_; | |
| 1263 GotoState(STATE_NONE); | |
| 1264 switch (state) { | |
| 1265 case STATE_LOAD_SSL_HOST_INFO: | |
| 1266 DCHECK(rv == OK || rv == ERR_IO_PENDING); | |
| 1267 rv = DoLoadSSLHostInfo(); | |
| 1268 break; | |
| 1269 case STATE_HANDSHAKE: | |
| 1270 rv = DoHandshake(); | |
| 1271 break; | |
| 1272 case STATE_GET_DOMAIN_BOUND_CERT_COMPLETE: | |
| 1273 rv = DoGetDBCertComplete(rv); | |
| 1274 break; | |
| 1275 case STATE_VERIFY_DNSSEC: | |
| 1276 rv = DoVerifyDNSSEC(rv); | |
| 1277 break; | |
| 1278 case STATE_VERIFY_CERT: | |
| 1279 DCHECK(rv == OK); | |
| 1280 rv = DoVerifyCert(rv); | |
| 1281 break; | |
| 1282 case STATE_VERIFY_CERT_COMPLETE: | |
| 1283 rv = DoVerifyCertComplete(rv); | |
| 1284 break; | |
| 1285 case STATE_NONE: | |
| 1286 default: | |
| 1287 rv = ERR_UNEXPECTED; | |
| 1288 LOG(DFATAL) << "unexpected state " << state; | |
| 1289 break; | |
| 1290 } | |
| 1291 | |
| 1292 // Do the actual network I/O | |
| 1293 bool network_moved = DoTransportIO(); | |
| 1294 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) { | |
| 1295 // In general we exit the loop if rv is ERR_IO_PENDING. In this | |
| 1296 // special case we keep looping even if rv is ERR_IO_PENDING because | |
| 1297 // the transport IO may allow DoHandshake to make progress. | |
| 1298 DCHECK(rv == OK || rv == ERR_IO_PENDING); | |
| 1299 rv = OK; // This causes us to stay in the loop. | |
| 1300 } | |
| 1301 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE); | |
| 1302 LeaveFunction(""); | |
| 1303 return rv; | 2418 return rv; |
| 1304 } | 2419 } |
| 1305 | 2420 |
| 1306 int SSLClientSocketNSS::DoReadLoop(int result) { | 2421 int SSLClientSocketNSS::Core::ImportDBCertAndKey(CERTCertificate** cert, |
| 1307 EnterFunction(""); | 2422 SECKEYPrivateKey** key) { |
| 1308 DCHECK(completed_handshake_); | |
| 1309 DCHECK(next_handshake_state_ == STATE_NONE); | |
| 1310 | |
| 1311 if (result < 0) | |
| 1312 return result; | |
| 1313 | |
| 1314 if (!nss_bufs_) { | |
| 1315 LOG(DFATAL) << "!nss_bufs_"; | |
| 1316 int rv = ERR_UNEXPECTED; | |
| 1317 net_log_.AddEvent(NetLog::TYPE_SSL_READ_ERROR, | |
| 1318 make_scoped_refptr(new SSLErrorParams(rv, 0))); | |
| 1319 return rv; | |
| 1320 } | |
| 1321 | |
| 1322 bool network_moved; | |
| 1323 int rv; | |
| 1324 do { | |
| 1325 rv = DoPayloadRead(); | |
| 1326 network_moved = DoTransportIO(); | |
| 1327 } while (rv == ERR_IO_PENDING && network_moved); | |
| 1328 | |
| 1329 LeaveFunction(""); | |
| 1330 return rv; | |
| 1331 } | |
| 1332 | |
| 1333 int SSLClientSocketNSS::DoWriteLoop(int result) { | |
| 1334 EnterFunction(""); | |
| 1335 DCHECK(completed_handshake_); | |
| 1336 DCHECK(next_handshake_state_ == STATE_NONE); | |
| 1337 | |
| 1338 if (result < 0) | |
| 1339 return result; | |
| 1340 | |
| 1341 if (!nss_bufs_) { | |
| 1342 LOG(DFATAL) << "!nss_bufs_"; | |
| 1343 int rv = ERR_UNEXPECTED; | |
| 1344 net_log_.AddEvent(NetLog::TYPE_SSL_WRITE_ERROR, | |
| 1345 make_scoped_refptr(new SSLErrorParams(rv, 0))); | |
| 1346 return rv; | |
| 1347 } | |
| 1348 | |
| 1349 bool network_moved; | |
| 1350 int rv; | |
| 1351 do { | |
| 1352 rv = DoPayloadWrite(); | |
| 1353 network_moved = DoTransportIO(); | |
| 1354 } while (rv == ERR_IO_PENDING && network_moved); | |
| 1355 | |
| 1356 LeaveFunction(""); | |
| 1357 return rv; | |
| 1358 } | |
| 1359 | |
| 1360 bool SSLClientSocketNSS::LoadSSLHostInfo() { | |
| 1361 const SSLHostInfo::State& state(ssl_host_info_->state()); | |
| 1362 | |
| 1363 if (state.certs.empty()) | |
| 1364 return true; | |
| 1365 | |
| 1366 const std::vector<std::string>& certs_in = state.certs; | |
| 1367 scoped_array<CERTCertificate*> certs(new CERTCertificate*[certs_in.size()]); | |
| 1368 | |
| 1369 for (size_t i = 0; i < certs_in.size(); i++) { | |
| 1370 SECItem derCert; | |
| 1371 derCert.data = | |
| 1372 const_cast<uint8*>(reinterpret_cast<const uint8*>(certs_in[i].data())); | |
| 1373 derCert.len = certs_in[i].size(); | |
| 1374 certs[i] = CERT_NewTempCertificate( | |
| 1375 CERT_GetDefaultCertDB(), &derCert, NULL /* no nickname given */, | |
| 1376 PR_FALSE /* not permanent */, PR_TRUE /* copy DER data */); | |
| 1377 if (!certs[i]) { | |
| 1378 DestroyCertificates(&certs[0], i); | |
| 1379 NOTREACHED(); | |
| 1380 return false; | |
| 1381 } | |
| 1382 } | |
| 1383 | |
| 1384 SECStatus rv; | |
| 1385 #ifdef SSL_ENABLE_CACHED_INFO | |
| 1386 rv = SSL_SetPredictedPeerCertificates(nss_fd_, certs.get(), certs_in.size()); | |
| 1387 DCHECK_EQ(SECSuccess, rv); | |
| 1388 #else | |
| 1389 rv = SECFailure; // Not implemented. | |
| 1390 #endif | |
| 1391 DestroyCertificates(&certs[0], certs_in.size()); | |
| 1392 | |
| 1393 return rv == SECSuccess; | |
| 1394 } | |
| 1395 | |
| 1396 int SSLClientSocketNSS::DoLoadSSLHostInfo() { | |
| 1397 EnterFunction(""); | |
| 1398 int rv = ssl_host_info_->WaitForDataReady( | |
| 1399 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | |
| 1400 base::Unretained(this))); | |
| 1401 GotoState(STATE_HANDSHAKE); | |
| 1402 | |
| 1403 if (rv == OK) { | |
| 1404 if (!LoadSSLHostInfo()) | |
| 1405 LOG(WARNING) << "LoadSSLHostInfo failed: " << host_and_port_.ToString(); | |
| 1406 } else { | |
| 1407 DCHECK_EQ(ERR_IO_PENDING, rv); | |
| 1408 GotoState(STATE_LOAD_SSL_HOST_INFO); | |
| 1409 } | |
| 1410 | |
| 1411 LeaveFunction(""); | |
| 1412 return rv; | |
| 1413 } | |
| 1414 | |
| 1415 int SSLClientSocketNSS::DoHandshake() { | |
| 1416 EnterFunction(""); | |
| 1417 int net_error = net::OK; | |
| 1418 SECStatus rv = SSL_ForceHandshake(nss_fd_); | |
| 1419 | |
| 1420 // TODO(rkn): Handle the case in which server-bound cert generation takes | |
| 1421 // too long and the server has closed the connection. Report some new error | |
| 1422 // code so that the higher level code will attempt to delete the socket and | |
| 1423 // redo the handshake. | |
| 1424 | |
| 1425 if (client_auth_cert_needed_) { | |
| 1426 if (domain_bound_cert_xtn_negotiated_) { | |
| 1427 GotoState(STATE_GET_DOMAIN_BOUND_CERT_COMPLETE); | |
| 1428 net_error = ERR_IO_PENDING; | |
| 1429 } else { | |
| 1430 net_error = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; | |
| 1431 net_log_.AddEvent(NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
| 1432 make_scoped_refptr(new SSLErrorParams(net_error, 0))); | |
| 1433 // If the handshake already succeeded (because the server requests but | |
| 1434 // doesn't require a client cert), we need to invalidate the SSL session | |
| 1435 // so that we won't try to resume the non-client-authenticated session in | |
| 1436 // the next handshake. This will cause the server to ask for a client | |
| 1437 // cert again. | |
| 1438 if (rv == SECSuccess && SSL_InvalidateSession(nss_fd_) != SECSuccess) { | |
| 1439 LOG(WARNING) << "Couldn't invalidate SSL session: " << PR_GetError(); | |
| 1440 } | |
| 1441 } | |
| 1442 } else if (rv == SECSuccess) { | |
| 1443 if (handshake_callback_called_) { | |
| 1444 // We need to see if the predicted certificate chain (in | |
| 1445 // |ssl_host_info_->state().certs) matches the actual certificate chain | |
| 1446 // before we call SaveSSLHostInfo, as that will update | |
| 1447 // |ssl_host_info_|. | |
| 1448 if (ssl_host_info_.get() && !ssl_host_info_->state().certs.empty()) { | |
| 1449 PeerCertificateChain certs(nss_fd_); | |
| 1450 const SSLHostInfo::State& state = ssl_host_info_->state(); | |
| 1451 predicted_cert_chain_correct_ = certs.size() == state.certs.size(); | |
| 1452 if (predicted_cert_chain_correct_) { | |
| 1453 for (unsigned i = 0; i < certs.size(); i++) { | |
| 1454 if (certs[i]->derCert.len != state.certs[i].size() || | |
| 1455 memcmp(certs[i]->derCert.data, state.certs[i].data(), | |
| 1456 certs[i]->derCert.len) != 0) { | |
| 1457 predicted_cert_chain_correct_ = false; | |
| 1458 break; | |
| 1459 } | |
| 1460 } | |
| 1461 } | |
| 1462 } | |
| 1463 | |
| 1464 #if defined(SSL_ENABLE_OCSP_STAPLING) | |
| 1465 // TODO(agl): figure out how to plumb an OCSP response into the Mac | |
| 1466 // system library and update IsOCSPStaplingSupported for Mac. | |
| 1467 if (!predicted_cert_chain_correct_ && IsOCSPStaplingSupported()) { | |
| 1468 unsigned int len = 0; | |
| 1469 SSL_GetStapledOCSPResponse(nss_fd_, NULL, &len); | |
| 1470 if (len) { | |
| 1471 const unsigned int orig_len = len; | |
| 1472 scoped_array<uint8> ocsp_response(new uint8[orig_len]); | |
| 1473 SSL_GetStapledOCSPResponse(nss_fd_, ocsp_response.get(), &len); | |
| 1474 DCHECK_EQ(orig_len, len); | |
| 1475 | |
| 1476 #if defined(OS_WIN) | |
| 1477 CRYPT_DATA_BLOB ocsp_response_blob; | |
| 1478 ocsp_response_blob.cbData = len; | |
| 1479 ocsp_response_blob.pbData = ocsp_response.get(); | |
| 1480 BOOL ok = CertSetCertificateContextProperty( | |
| 1481 server_cert_->os_cert_handle(), | |
| 1482 CERT_OCSP_RESPONSE_PROP_ID, | |
| 1483 CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG, | |
| 1484 &ocsp_response_blob); | |
| 1485 if (!ok) { | |
| 1486 VLOG(1) << "Failed to set OCSP response property: " | |
| 1487 << GetLastError(); | |
| 1488 } | |
| 1489 #elif defined(USE_NSS) | |
| 1490 CacheOCSPResponseFromSideChannelFunction cache_ocsp_response = | |
| 1491 GetCacheOCSPResponseFromSideChannelFunction(); | |
| 1492 SECItem ocsp_response_item; | |
| 1493 ocsp_response_item.type = siBuffer; | |
| 1494 ocsp_response_item.data = ocsp_response.get(); | |
| 1495 ocsp_response_item.len = len; | |
| 1496 | |
| 1497 cache_ocsp_response( | |
| 1498 CERT_GetDefaultCertDB(), server_cert_nss_, PR_Now(), | |
| 1499 &ocsp_response_item, NULL); | |
| 1500 #endif | |
| 1501 } | |
| 1502 } | |
| 1503 #endif | |
| 1504 | |
| 1505 SaveSSLHostInfo(); | |
| 1506 // SSL handshake is completed. Let's verify the certificate. | |
| 1507 GotoState(STATE_VERIFY_DNSSEC); | |
| 1508 // Done! | |
| 1509 } else { | |
| 1510 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=562434 - | |
| 1511 // SSL_ForceHandshake returned SECSuccess prematurely. | |
| 1512 rv = SECFailure; | |
| 1513 net_error = ERR_SSL_PROTOCOL_ERROR; | |
| 1514 net_log_.AddEvent(NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
| 1515 make_scoped_refptr(new SSLErrorParams(net_error, 0))); | |
| 1516 } | |
| 1517 } else { | |
| 1518 PRErrorCode prerr = PR_GetError(); | |
| 1519 net_error = HandleNSSError(prerr, true); | |
| 1520 | |
| 1521 // If not done, stay in this state | |
| 1522 if (net_error == ERR_IO_PENDING) { | |
| 1523 GotoState(STATE_HANDSHAKE); | |
| 1524 } else { | |
| 1525 net_log_.AddEvent( | |
| 1526 NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
| 1527 make_scoped_refptr(new SSLErrorParams(net_error, prerr))); | |
| 1528 } | |
| 1529 } | |
| 1530 | |
| 1531 LeaveFunction(""); | |
| 1532 return net_error; | |
| 1533 } | |
| 1534 | |
| 1535 int SSLClientSocketNSS::ImportDBCertAndKey(CERTCertificate** cert, | |
| 1536 SECKEYPrivateKey** key) { | |
| 1537 // Set the certificate. | 2423 // Set the certificate. |
| 1538 SECItem cert_item; | 2424 SECItem cert_item; |
| 1539 cert_item.data = (unsigned char*) domain_bound_cert_.data(); | 2425 cert_item.data = (unsigned char*) domain_bound_cert_.data(); |
| 1540 cert_item.len = domain_bound_cert_.size(); | 2426 cert_item.len = domain_bound_cert_.size(); |
| 1541 *cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), | 2427 *cert = CERT_NewTempCertificate(CERT_GetDefaultCertDB(), |
| 1542 &cert_item, | 2428 &cert_item, |
| 1543 NULL, | 2429 NULL, |
| 1544 PR_FALSE, | 2430 PR_FALSE, |
| 1545 PR_TRUE); | 2431 PR_TRUE); |
| 1546 if (*cert == NULL) | 2432 if (*cert == NULL) |
| (...skipping 22 matching lines...) Expand all Loading... | |
| 1569 } | 2455 } |
| 1570 | 2456 |
| 1571 default: | 2457 default: |
| 1572 NOTREACHED(); | 2458 NOTREACHED(); |
| 1573 return ERR_INVALID_ARGUMENT; | 2459 return ERR_INVALID_ARGUMENT; |
| 1574 } | 2460 } |
| 1575 | 2461 |
| 1576 return OK; | 2462 return OK; |
| 1577 } | 2463 } |
| 1578 | 2464 |
| 1579 int SSLClientSocketNSS::DoGetDBCertComplete(int result) { | 2465 void SSLClientSocketNSS::Core::UpdateServerCert() { |
| 1580 SECStatus rv; | 2466 nss_handshake_state_.server_cert_chain.Reset(nss_fd_); |
| 1581 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, | 2467 nss_handshake_state_.server_cert = X509Certificate::CreateFromDERCertChain( |
| 1582 result); | 2468 nss_handshake_state_.server_cert_chain.AsStringPieceVector()); |
| 1583 client_auth_cert_needed_ = false; | 2469 if (nss_handshake_state_.server_cert) { |
| 2470 PostOrRunCallback( | |
| 2471 FROM_HERE, | |
| 2472 base::Bind(&BoundNetLog::AddEvent, weak_net_log_, | |
| 2473 NetLog::TYPE_SSL_CERTIFICATES_RECEIVED, | |
| 2474 make_scoped_refptr( | |
| 2475 new X509CertificateNetLogParam( | |
| 2476 nss_handshake_state_.server_cert)))); | |
| 2477 } | |
| 2478 } | |
| 2479 | |
| 2480 void SSLClientSocketNSS::Core::UpdateConnectionStatus() { | |
| 2481 SSLChannelInfo channel_info; | |
| 2482 SECStatus ok = SSL_GetChannelInfo(nss_fd_, | |
| 2483 &channel_info, sizeof(channel_info)); | |
| 2484 if (ok == SECSuccess && | |
| 2485 channel_info.length == sizeof(channel_info) && | |
| 2486 channel_info.cipherSuite) { | |
| 2487 nss_handshake_state_.ssl_connection_status |= | |
| 2488 (static_cast<int>(channel_info.cipherSuite) & | |
| 2489 SSL_CONNECTION_CIPHERSUITE_MASK) << | |
| 2490 SSL_CONNECTION_CIPHERSUITE_SHIFT; | |
| 2491 | |
| 2492 nss_handshake_state_.ssl_connection_status |= | |
| 2493 (static_cast<int>(channel_info.compressionMethod) & | |
| 2494 SSL_CONNECTION_COMPRESSION_MASK) << | |
| 2495 SSL_CONNECTION_COMPRESSION_SHIFT; | |
| 2496 | |
| 2497 // NSS 3.12.x doesn't have version macros for TLS 1.1 and 1.2 (because NSS | |
| 2498 // doesn't support them yet), so we use 0x0302 and 0x0303 directly. | |
| 2499 int version = SSL_CONNECTION_VERSION_UNKNOWN; | |
| 2500 if (channel_info.protocolVersion < SSL_LIBRARY_VERSION_3_0) { | |
| 2501 // All versions less than SSL_LIBRARY_VERSION_3_0 are treated as SSL | |
| 2502 // version 2. | |
| 2503 version = SSL_CONNECTION_VERSION_SSL2; | |
| 2504 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_0) { | |
| 2505 version = SSL_CONNECTION_VERSION_SSL3; | |
| 2506 } else if (channel_info.protocolVersion == SSL_LIBRARY_VERSION_3_1_TLS) { | |
| 2507 version = SSL_CONNECTION_VERSION_TLS1; | |
| 2508 } else if (channel_info.protocolVersion == 0x0302) { | |
| 2509 version = SSL_CONNECTION_VERSION_TLS1_1; | |
| 2510 } else if (channel_info.protocolVersion == 0x0303) { | |
| 2511 version = SSL_CONNECTION_VERSION_TLS1_2; | |
| 2512 } | |
| 2513 nss_handshake_state_.ssl_connection_status |= | |
| 2514 (version & SSL_CONNECTION_VERSION_MASK) << | |
| 2515 SSL_CONNECTION_VERSION_SHIFT; | |
| 2516 } | |
| 2517 | |
| 2518 // SSL_HandshakeNegotiatedExtension was added in NSS 3.12.6. | |
| 2519 // Since SSL_MAX_EXTENSIONS was added at the same time, we can test | |
| 2520 // SSL_MAX_EXTENSIONS for the presence of SSL_HandshakeNegotiatedExtension. | |
| 2521 #if defined(SSL_MAX_EXTENSIONS) | |
| 2522 PRBool peer_supports_renego_ext; | |
| 2523 ok = SSL_HandshakeNegotiatedExtension(nss_fd_, ssl_renegotiation_info_xtn, | |
| 2524 &peer_supports_renego_ext); | |
| 2525 if (ok == SECSuccess) { | |
| 2526 if (!peer_supports_renego_ext) { | |
| 2527 nss_handshake_state_.ssl_connection_status |= | |
| 2528 SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION; | |
| 2529 // Log an informational message if the server does not support secure | |
| 2530 // renegotiation (RFC 5746). | |
| 2531 VLOG(1) << "The server " << host_and_port_.ToString() | |
| 2532 << " does not support the TLS renegotiation_info extension."; | |
| 2533 } | |
| 2534 UMA_HISTOGRAM_ENUMERATION("Net.RenegotiationExtensionSupported", | |
| 2535 peer_supports_renego_ext, 2); | |
| 2536 } | |
| 2537 #endif | |
| 2538 | |
| 2539 if (ssl_config_.version_fallback) { | |
| 2540 nss_handshake_state_.ssl_connection_status |= | |
| 2541 SSL_CONNECTION_VERSION_FALLBACK; | |
| 2542 } | |
| 2543 } | |
| 2544 | |
| 2545 void SSLClientSocketNSS::Core::RecordDomainBoundCertSupport() const { | |
| 2546 if (nss_handshake_state_.resumed_handshake) | |
| 2547 return; | |
| 2548 | |
| 2549 // Since this enum is used for a histogram, do not change or re-use values. | |
| 2550 enum { | |
| 2551 DISABLED = 0, | |
| 2552 CLIENT_ONLY = 1, | |
| 2553 CLIENT_AND_SERVER = 2, | |
| 2554 DOMAIN_BOUND_CERT_USAGE_MAX | |
| 2555 } supported = DISABLED; | |
| 2556 #ifdef SSL_ENABLE_OB_CERTS | |
| 2557 if (domain_bound_cert_xtn_negotiated_) | |
| 2558 supported = CLIENT_AND_SERVER; | |
| 2559 else if (ssl_config_.domain_bound_certs_enabled) | |
| 2560 supported = CLIENT_ONLY; | |
| 2561 #endif | |
| 2562 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported, | |
| 2563 DOMAIN_BOUND_CERT_USAGE_MAX); | |
| 2564 } | |
| 2565 | |
| 2566 int SSLClientSocketNSS::Core::DoBufferRecv(IOBuffer* read_buffer, int len) { | |
| 2567 DCHECK(OnNetworkTaskRunner()); | |
| 2568 DCHECK_GT(len, 0); | |
| 2569 | |
| 2570 if (detached_) | |
| 2571 return ERR_ABORTED; | |
| 2572 | |
| 2573 int rv = transport_->socket()->Read( | |
| 2574 read_buffer, len, | |
| 2575 base::Bind(&Core::BufferRecvComplete, base::Unretained(this), | |
| 2576 scoped_refptr<IOBuffer>(read_buffer))); | |
| 2577 | |
| 2578 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) { | |
| 2579 nss_task_runner_->PostTask( | |
| 2580 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this, | |
| 2581 scoped_refptr<IOBuffer>(read_buffer), rv)); | |
| 2582 return rv; | |
| 2583 } | |
| 2584 | |
| 2585 return rv; | |
| 2586 } | |
| 2587 | |
| 2588 int SSLClientSocketNSS::Core::DoBufferSend(IOBuffer* send_buffer, int len) { | |
| 2589 DCHECK(OnNetworkTaskRunner()); | |
| 2590 DCHECK_GT(len, 0); | |
| 2591 | |
| 2592 if (detached_) | |
| 2593 return ERR_ABORTED; | |
| 2594 | |
| 2595 int rv = transport_->socket()->Write( | |
| 2596 send_buffer, len, | |
| 2597 base::Bind(&Core::BufferSendComplete, | |
| 2598 base::Unretained(this))); | |
| 2599 | |
| 2600 if (!OnNSSTaskRunner() && rv != ERR_IO_PENDING) { | |
| 2601 nss_task_runner_->PostTask( | |
| 2602 FROM_HERE, | |
| 2603 base::Bind(&Core::BufferSendComplete, this, rv)); | |
| 2604 return rv; | |
| 2605 } | |
| 2606 | |
| 2607 return rv; | |
| 2608 } | |
| 2609 | |
| 2610 int SSLClientSocketNSS::Core::DoGetDomainBoundCert( | |
| 2611 const std::string& origin, | |
| 2612 const std::vector<uint8>& requested_cert_types) { | |
| 2613 DCHECK(OnNetworkTaskRunner()); | |
| 2614 | |
| 2615 if (detached_) | |
| 2616 return ERR_FAILED; | |
| 2617 | |
| 2618 weak_net_log_->BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, NULL); | |
| 2619 | |
| 2620 int rv = server_bound_cert_service_->GetDomainBoundCert( | |
| 2621 origin, | |
| 2622 requested_cert_types, | |
| 2623 &domain_bound_cert_type_, | |
| 2624 &domain_bound_private_key_, | |
| 2625 &domain_bound_cert_, | |
| 2626 base::Bind(&Core::OnGetDomainBoundCertComplete, base::Unretained(this)), | |
| 2627 &domain_bound_cert_request_handle_); | |
| 2628 | |
| 2629 if (rv != ERR_IO_PENDING && !OnNSSTaskRunner()) { | |
| 2630 nss_task_runner_->PostTask( | |
| 2631 FROM_HERE, | |
| 2632 base::Bind(&Core::OnHandshakeIOComplete, this, rv)); | |
| 2633 return ERR_IO_PENDING; | |
| 2634 } | |
| 2635 | |
| 2636 return rv; | |
| 2637 } | |
| 2638 | |
| 2639 void SSLClientSocketNSS::Core::OnHandshakeStateUpdated( | |
| 2640 const HandshakeState& state) { | |
| 2641 network_handshake_state_ = state; | |
| 2642 } | |
| 2643 | |
| 2644 void SSLClientSocketNSS::Core::BufferSendComplete(int result) { | |
| 2645 if (!OnNSSTaskRunner()) { | |
| 2646 if (detached_) | |
| 2647 return; | |
| 2648 | |
| 2649 nss_task_runner_->PostTask( | |
| 2650 FROM_HERE, base::Bind(&Core::BufferSendComplete, this, result)); | |
| 2651 return; | |
| 2652 } | |
| 2653 | |
| 2654 DCHECK(OnNSSTaskRunner()); | |
| 2655 | |
| 2656 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result)); | |
| 2657 transport_send_busy_ = false; | |
| 2658 OnSendComplete(result); | |
| 2659 } | |
| 2660 | |
| 2661 void SSLClientSocketNSS::Core::OnHandshakeIOComplete(int result) { | |
| 2662 if (!OnNSSTaskRunner()) { | |
| 2663 if (detached_) | |
| 2664 return; | |
| 2665 | |
| 2666 nss_task_runner_->PostTask( | |
| 2667 FROM_HERE, base::Bind(&Core::OnHandshakeIOComplete, this, result)); | |
| 2668 return; | |
| 2669 } | |
| 2670 | |
| 2671 DCHECK(OnNSSTaskRunner()); | |
| 2672 | |
| 2673 int rv = DoHandshakeLoop(result); | |
| 2674 if (rv != ERR_IO_PENDING) | |
| 2675 DoConnectCallback(rv); | |
| 2676 } | |
| 2677 | |
| 2678 void SSLClientSocketNSS::Core::OnGetDomainBoundCertComplete(int result) { | |
| 2679 DCHECK(OnNetworkTaskRunner()); | |
| 2680 | |
| 1584 domain_bound_cert_request_handle_ = NULL; | 2681 domain_bound_cert_request_handle_ = NULL; |
| 1585 | 2682 OnHandshakeIOComplete(result); |
| 1586 if (result != OK) { | 2683 } |
| 1587 // Failed to get a DBC. Proceed without. | 2684 |
| 1588 rv = SSL_RestartHandshakeAfterCertReq(nss_fd_, NULL, NULL, NULL); | 2685 void SSLClientSocketNSS::Core::BufferRecvComplete( |
| 1589 if (rv != SECSuccess) | 2686 IOBuffer* read_buffer, |
| 1590 return MapNSSError(PORT_GetError()); | 2687 int result) { |
| 2688 DCHECK(read_buffer); | |
| 2689 | |
| 2690 if (!OnNSSTaskRunner()) { | |
| 2691 if (detached_) | |
| 2692 return; | |
| 2693 | |
| 2694 nss_task_runner_->PostTask( | |
| 2695 FROM_HERE, base::Bind(&Core::BufferRecvComplete, this, | |
| 2696 scoped_refptr<IOBuffer>(read_buffer), result)); | |
| 2697 return; | |
| 2698 } | |
| 2699 | |
| 2700 DCHECK(OnNSSTaskRunner()); | |
| 2701 | |
| 2702 if (result > 0) { | |
| 2703 char* buf; | |
| 2704 int nb = memio_GetReadParams(nss_bufs_, &buf); | |
| 2705 CHECK_GE(nb, result); | |
| 2706 memcpy(buf, read_buffer->data(), result); | |
| 2707 } else if (result == 0) { | |
| 2708 transport_recv_eof_ = true; | |
| 2709 } | |
| 2710 | |
| 2711 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result)); | |
| 2712 transport_recv_busy_ = false; | |
| 2713 OnRecvComplete(result); | |
| 2714 } | |
| 2715 | |
| 2716 void SSLClientSocketNSS::Core::PostOrRunCallback( | |
| 2717 const tracked_objects::Location& location, | |
| 2718 const base::Closure& task) { | |
| 2719 if (!OnNetworkTaskRunner()) { | |
| 2720 network_task_runner_->PostTask( | |
| 2721 FROM_HERE, | |
| 2722 base::Bind(&Core::PostOrRunCallback, this, | |
| 2723 location, task)); | |
| 2724 return; | |
| 2725 } | |
| 2726 | |
| 2727 DCHECK(OnNetworkTaskRunner()); | |
|
wtc
2012/06/01 01:02:38
Remove this DCHECK. It will never fail because of
Ryan Sleevi
2012/06/01 01:30:04
Note that I pretty liberally sprinkled DCHECKs as
| |
| 2728 | |
| 2729 if (detached_ || task.is_null()) | |
|
wtc
2012/06/01 01:02:38
It seems that |task| should not be null, right? D
Ryan Sleevi
2012/06/01 01:30:04
task.is_null() if bound to a WeakPtr that has been
| |
| 2730 return; | |
| 2731 task.Run(); | |
| 2732 } | |
| 2733 | |
| 2734 SSLClientSocketNSS::SSLClientSocketNSS( | |
| 2735 base::SingleThreadTaskRunner* nss_task_runner, | |
| 2736 ClientSocketHandle* transport_socket, | |
| 2737 const HostPortPair& host_and_port, | |
| 2738 const SSLConfig& ssl_config, | |
| 2739 SSLHostInfo* ssl_host_info, | |
| 2740 const SSLClientSocketContext& context) | |
| 2741 : nss_task_runner_(nss_task_runner), | |
| 2742 transport_(transport_socket), | |
| 2743 host_and_port_(host_and_port), | |
| 2744 ssl_config_(ssl_config), | |
| 2745 server_cert_verify_result_(NULL), | |
| 2746 cert_verifier_(context.cert_verifier), | |
| 2747 server_bound_cert_service_(context.server_bound_cert_service), | |
| 2748 ssl_session_cache_shard_(context.ssl_session_cache_shard), | |
| 2749 completed_handshake_(false), | |
| 2750 next_handshake_state_(STATE_NONE), | |
| 2751 nss_fd_(NULL), | |
| 2752 net_log_(transport_socket->socket()->NetLog()), | |
| 2753 ssl_host_info_(ssl_host_info), | |
| 2754 transport_security_state_(context.transport_security_state), | |
| 2755 valid_thread_id_(base::kInvalidThreadId) { | |
| 2756 EnterFunction(""); | |
| 2757 InitCore(); | |
| 2758 LeaveFunction(""); | |
| 2759 } | |
| 2760 | |
| 2761 SSLClientSocketNSS::~SSLClientSocketNSS() { | |
| 2762 EnterFunction(""); | |
| 2763 Disconnect(); | |
| 2764 LeaveFunction(""); | |
| 2765 } | |
| 2766 | |
| 2767 // static | |
| 2768 void SSLClientSocket::ClearSessionCache() { | |
| 2769 // SSL_ClearSessionCache can't be called before NSS is initialized. Don't | |
| 2770 // bother initializing NSS just to clear an empty SSL session cache. | |
| 2771 if (!NSS_IsInitialized()) | |
| 2772 return; | |
| 2773 | |
| 2774 SSL_ClearSessionCache(); | |
| 2775 } | |
| 2776 | |
| 2777 void SSLClientSocketNSS::GetSSLInfo(SSLInfo* ssl_info) { | |
| 2778 EnterFunction(""); | |
| 2779 ssl_info->Reset(); | |
| 2780 if (core_->state().server_cert_chain.empty() || | |
| 2781 !core_->state().server_cert_chain[0]) { | |
| 2782 return; | |
| 2783 } | |
| 2784 | |
| 2785 ssl_info->cert_status = server_cert_verify_result_->cert_status; | |
| 2786 ssl_info->cert = server_cert_verify_result_->verified_cert; | |
| 2787 ssl_info->connection_status = | |
| 2788 core_->state().ssl_connection_status; | |
| 2789 ssl_info->public_key_hashes = server_cert_verify_result_->public_key_hashes; | |
| 2790 for (std::vector<SHA1Fingerprint>::const_iterator | |
| 2791 i = side_pinned_public_keys_.begin(); | |
| 2792 i != side_pinned_public_keys_.end(); i++) { | |
| 2793 ssl_info->public_key_hashes.push_back(*i); | |
| 2794 } | |
| 2795 ssl_info->is_issued_by_known_root = | |
| 2796 server_cert_verify_result_->is_issued_by_known_root; | |
| 2797 ssl_info->client_cert_sent = WasDomainBoundCertSent() || | |
| 2798 (ssl_config_.send_client_cert && ssl_config_.client_cert); | |
| 2799 | |
| 2800 PRUint16 cipher_suite = SSLConnectionStatusToCipherSuite( | |
| 2801 core_->state().ssl_connection_status); | |
| 2802 SSLCipherSuiteInfo cipher_info; | |
| 2803 SECStatus ok = SSL_GetCipherSuiteInfo(cipher_suite, | |
| 2804 &cipher_info, sizeof(cipher_info)); | |
| 2805 if (ok == SECSuccess) { | |
| 2806 ssl_info->security_bits = cipher_info.effectiveKeyBits; | |
| 2807 } else { | |
| 2808 ssl_info->security_bits = -1; | |
| 2809 LOG(DFATAL) << "SSL_GetCipherSuiteInfo returned " << PR_GetError() | |
| 2810 << " for cipherSuite " << cipher_suite; | |
| 2811 } | |
| 2812 | |
| 2813 ssl_info->handshake_type = core_->state().resumed_handshake ? | |
| 2814 SSLInfo::HANDSHAKE_RESUME : SSLInfo::HANDSHAKE_FULL; | |
| 2815 | |
| 2816 LeaveFunction(""); | |
| 2817 } | |
| 2818 | |
| 2819 void SSLClientSocketNSS::GetSSLCertRequestInfo( | |
| 2820 SSLCertRequestInfo* cert_request_info) { | |
| 2821 EnterFunction(""); | |
| 2822 // TODO(rch): switch SSLCertRequestInfo.host_and_port to a HostPortPair | |
| 2823 cert_request_info->host_and_port = host_and_port_.ToString(); | |
| 2824 cert_request_info->client_certs = core_->state().client_certs; | |
| 2825 LeaveFunction(cert_request_info->client_certs.size()); | |
| 2826 } | |
| 2827 | |
| 2828 int SSLClientSocketNSS::ExportKeyingMaterial(const base::StringPiece& label, | |
| 2829 bool has_context, | |
| 2830 const base::StringPiece& context, | |
| 2831 unsigned char* out, | |
| 2832 unsigned int outlen) { | |
| 2833 if (!IsConnected()) | |
| 2834 return ERR_SOCKET_NOT_CONNECTED; | |
| 2835 | |
| 2836 // SSL_ExportKeyingMaterial may block the current thread if |core_| is in | |
| 2837 // the midst of a handshake. | |
| 2838 SECStatus result = SSL_ExportKeyingMaterial( | |
| 2839 nss_fd_, label.data(), label.size(), has_context, | |
| 2840 reinterpret_cast<const unsigned char*>(context.data()), | |
| 2841 context.length(), out, outlen); | |
| 2842 if (result != SECSuccess) { | |
| 2843 LogFailedNSSFunction(net_log_, "SSL_ExportKeyingMaterial", ""); | |
| 2844 return MapNSSError(PORT_GetError()); | |
| 2845 } | |
| 2846 return OK; | |
| 2847 } | |
| 2848 | |
| 2849 SSLClientSocket::NextProtoStatus | |
| 2850 SSLClientSocketNSS::GetNextProto(std::string* proto, | |
| 2851 std::string* server_protos) { | |
| 2852 *proto = core_->state().next_proto; | |
| 2853 *server_protos = core_->state().server_protos; | |
| 2854 return core_->state().next_proto_status; | |
| 2855 } | |
| 2856 | |
| 2857 int SSLClientSocketNSS::Connect(const CompletionCallback& callback) { | |
| 2858 EnterFunction(""); | |
| 2859 DCHECK(transport_.get()); | |
| 2860 DCHECK_EQ(STATE_NONE, next_handshake_state_); | |
| 2861 DCHECK(user_connect_callback_.is_null()); | |
| 2862 | |
| 2863 EnsureThreadIdAssigned(); | |
| 2864 | |
| 2865 net_log_.BeginEvent(NetLog::TYPE_SSL_CONNECT, NULL); | |
| 2866 | |
| 2867 int rv = Init(); | |
| 2868 if (rv != OK) { | |
| 2869 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 2870 return rv; | |
| 2871 } | |
| 2872 | |
| 2873 rv = InitializeSSLOptions(); | |
| 2874 if (rv != OK) { | |
| 2875 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 2876 return rv; | |
| 2877 } | |
| 2878 | |
| 2879 rv = InitializeSSLPeerName(); | |
| 2880 if (rv != OK) { | |
| 2881 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 2882 return rv; | |
| 2883 } | |
| 2884 | |
| 2885 if (ssl_config_.cached_info_enabled && ssl_host_info_.get()) { | |
| 2886 GotoState(STATE_LOAD_SSL_HOST_INFO); | |
| 2887 } else { | |
| 1591 GotoState(STATE_HANDSHAKE); | 2888 GotoState(STATE_HANDSHAKE); |
| 1592 return OK; | 2889 } |
| 1593 } | 2890 |
| 1594 | 2891 rv = DoHandshakeLoop(OK); |
| 1595 CERTCertificate* cert; | 2892 if (rv == ERR_IO_PENDING) { |
| 1596 SECKEYPrivateKey* key; | 2893 user_connect_callback_ = callback; |
| 1597 int error = ImportDBCertAndKey(&cert, &key); | 2894 } else { |
| 1598 if (error != OK) | 2895 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); |
| 1599 return error; | 2896 } |
| 1600 | 2897 |
| 1601 CERTCertificateList* cert_chain = CERT_CertChainFromCert(cert, | 2898 LeaveFunction(""); |
| 1602 certUsageSSLClient, | 2899 return rv > OK ? OK : rv; |
| 1603 PR_FALSE); | 2900 } |
| 1604 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | 2901 |
| 1605 make_scoped_refptr(new NetLogIntegerParameter("cert_count", | 2902 void SSLClientSocketNSS::Disconnect() { |
| 1606 cert_chain->len))); | 2903 EnterFunction(""); |
| 1607 rv = SSL_RestartHandshakeAfterCertReq(nss_fd_, cert, key, cert_chain); | 2904 |
| 2905 CHECK(CalledOnValidThread()); | |
| 2906 | |
| 2907 // Shut down anything that may call us back. | |
| 2908 core_->Detach(); | |
| 2909 verifier_.reset(); | |
| 2910 transport_->socket()->Disconnect(); | |
| 2911 | |
| 2912 // Reset object state. | |
| 2913 user_connect_callback_.Reset(); | |
| 2914 local_server_cert_verify_result_.Reset(); | |
| 2915 server_cert_verify_result_ = NULL; | |
| 2916 completed_handshake_ = false; | |
| 2917 start_cert_verification_time_ = base::TimeTicks(); | |
| 2918 InitCore(); | |
| 2919 | |
| 2920 LeaveFunction(""); | |
| 2921 } | |
| 2922 | |
| 2923 bool SSLClientSocketNSS::IsConnected() const { | |
| 2924 // Ideally, we should also check if we have received the close_notify alert | |
| 2925 // message from the server, and return false in that case. We're not doing | |
| 2926 // that, so this function may return a false positive. Since the upper | |
| 2927 // layer (HttpNetworkTransaction) needs to handle a persistent connection | |
| 2928 // closed by the server when we send a request anyway, a false positive in | |
| 2929 // exchange for simpler code is a good trade-off. | |
| 2930 EnterFunction(""); | |
| 2931 bool ret = completed_handshake_ && transport_->socket()->IsConnected(); | |
| 2932 LeaveFunction(""); | |
| 2933 return ret; | |
| 2934 } | |
| 2935 | |
| 2936 bool SSLClientSocketNSS::IsConnectedAndIdle() const { | |
| 2937 // Unlike IsConnected, this method doesn't return a false positive. | |
| 2938 // | |
| 2939 // Strictly speaking, we should check if we have received the close_notify | |
| 2940 // alert message from the server, and return false in that case. Although | |
| 2941 // the close_notify alert message means EOF in the SSL layer, it is just | |
| 2942 // bytes to the transport layer below, so | |
| 2943 // transport_->socket()->IsConnectedAndIdle() returns the desired false | |
| 2944 // when we receive close_notify. | |
| 2945 EnterFunction(""); | |
| 2946 bool ret = completed_handshake_ && transport_->socket()->IsConnectedAndIdle(); | |
| 2947 LeaveFunction(""); | |
| 2948 return ret; | |
| 2949 } | |
| 2950 | |
| 2951 int SSLClientSocketNSS::GetPeerAddress(AddressList* address) const { | |
| 2952 return transport_->socket()->GetPeerAddress(address); | |
| 2953 } | |
| 2954 | |
| 2955 int SSLClientSocketNSS::GetLocalAddress(IPEndPoint* address) const { | |
| 2956 return transport_->socket()->GetLocalAddress(address); | |
| 2957 } | |
| 2958 | |
| 2959 const BoundNetLog& SSLClientSocketNSS::NetLog() const { | |
| 2960 return net_log_; | |
| 2961 } | |
| 2962 | |
| 2963 void SSLClientSocketNSS::SetSubresourceSpeculation() { | |
| 2964 if (transport_.get() && transport_->socket()) { | |
| 2965 transport_->socket()->SetSubresourceSpeculation(); | |
| 2966 } else { | |
| 2967 NOTREACHED(); | |
| 2968 } | |
| 2969 } | |
| 2970 | |
| 2971 void SSLClientSocketNSS::SetOmniboxSpeculation() { | |
| 2972 if (transport_.get() && transport_->socket()) { | |
| 2973 transport_->socket()->SetOmniboxSpeculation(); | |
| 2974 } else { | |
| 2975 NOTREACHED(); | |
| 2976 } | |
| 2977 } | |
| 2978 | |
| 2979 bool SSLClientSocketNSS::WasEverUsed() const { | |
| 2980 if (transport_.get() && transport_->socket()) { | |
| 2981 return transport_->socket()->WasEverUsed(); | |
| 2982 } | |
| 2983 NOTREACHED(); | |
| 2984 return false; | |
| 2985 } | |
| 2986 | |
| 2987 bool SSLClientSocketNSS::UsingTCPFastOpen() const { | |
| 2988 if (transport_.get() && transport_->socket()) { | |
| 2989 return transport_->socket()->UsingTCPFastOpen(); | |
| 2990 } | |
| 2991 NOTREACHED(); | |
| 2992 return false; | |
| 2993 } | |
| 2994 | |
| 2995 int64 SSLClientSocketNSS::NumBytesRead() const { | |
| 2996 if (transport_.get() && transport_->socket()) { | |
| 2997 return transport_->socket()->NumBytesRead(); | |
| 2998 } | |
| 2999 NOTREACHED(); | |
| 3000 return -1; | |
| 3001 } | |
| 3002 | |
| 3003 base::TimeDelta SSLClientSocketNSS::GetConnectTimeMicros() const { | |
| 3004 if (transport_.get() && transport_->socket()) { | |
| 3005 return transport_->socket()->GetConnectTimeMicros(); | |
| 3006 } | |
| 3007 NOTREACHED(); | |
| 3008 return base::TimeDelta::FromMicroseconds(-1); | |
| 3009 } | |
| 3010 | |
| 3011 int SSLClientSocketNSS::Read(IOBuffer* buf, int buf_len, | |
| 3012 const CompletionCallback& callback) { | |
| 3013 DCHECK(core_); | |
| 3014 | |
| 3015 EnterFunction(buf_len); | |
| 3016 int rv = core_->Read(buf, buf_len, callback); | |
| 3017 LeaveFunction(rv); | |
| 3018 | |
| 3019 return rv; | |
| 3020 } | |
| 3021 | |
| 3022 int SSLClientSocketNSS::Write(IOBuffer* buf, int buf_len, | |
| 3023 const CompletionCallback& callback) { | |
| 3024 DCHECK(core_); | |
| 3025 | |
| 3026 EnterFunction(buf_len); | |
| 3027 int rv = core_->Write(buf, buf_len, callback); | |
| 3028 LeaveFunction(rv); | |
| 3029 | |
| 3030 return rv; | |
| 3031 } | |
| 3032 | |
| 3033 bool SSLClientSocketNSS::SetReceiveBufferSize(int32 size) { | |
| 3034 return transport_->socket()->SetReceiveBufferSize(size); | |
| 3035 } | |
| 3036 | |
| 3037 bool SSLClientSocketNSS::SetSendBufferSize(int32 size) { | |
| 3038 return transport_->socket()->SetSendBufferSize(size); | |
| 3039 } | |
| 3040 | |
| 3041 int SSLClientSocketNSS::Init() { | |
| 3042 EnterFunction(""); | |
| 3043 // Initialize the NSS SSL library in a threadsafe way. This also | |
| 3044 // initializes the NSS base library. | |
| 3045 EnsureNSSSSLInit(); | |
| 3046 if (!NSS_IsInitialized()) | |
| 3047 return ERR_UNEXPECTED; | |
| 3048 #if !defined(OS_MACOSX) && !defined(OS_WIN) | |
| 3049 if (ssl_config_.cert_io_enabled) { | |
| 3050 // We must call EnsureNSSHttpIOInit() here, on the IO thread, to get the IO | |
| 3051 // loop by MessageLoopForIO::current(). | |
| 3052 // X509Certificate::Verify() runs on a worker thread of CertVerifier. | |
| 3053 EnsureNSSHttpIOInit(); | |
| 3054 } | |
| 3055 #endif | |
| 3056 | |
| 3057 LeaveFunction(""); | |
| 3058 return OK; | |
| 3059 } | |
| 3060 | |
| 3061 void SSLClientSocketNSS::InitCore() { | |
| 3062 core_ = new Core(base::ThreadTaskRunnerHandle::Get(), nss_task_runner_, | |
| 3063 transport_.get(), host_and_port_, ssl_config_, &net_log_, | |
| 3064 server_bound_cert_service_); | |
| 3065 } | |
| 3066 | |
| 3067 int SSLClientSocketNSS::InitializeSSLOptions() { | |
| 3068 // Transport connected, now hook it up to nss | |
| 3069 // TODO(port): specify rx and tx buffer sizes separately | |
| 3070 nss_fd_ = memio_CreateIOLayer(kRecvBufferSize); | |
| 3071 if (nss_fd_ == NULL) { | |
| 3072 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR error code. | |
| 3073 } | |
| 3074 | |
| 3075 // Grab pointer to buffers | |
| 3076 memio_Private* nss_bufs = memio_GetSecret(nss_fd_); | |
| 3077 | |
| 3078 /* Create SSL state machine */ | |
| 3079 /* Push SSL onto our fake I/O socket */ | |
| 3080 nss_fd_ = SSL_ImportFD(NULL, nss_fd_); | |
| 3081 if (nss_fd_ == NULL) { | |
| 3082 LogFailedNSSFunction(net_log_, "SSL_ImportFD", ""); | |
| 3083 return ERR_OUT_OF_MEMORY; // TODO(port): map NSPR/NSS error code. | |
| 3084 } | |
| 3085 // TODO(port): set more ssl options! Check errors! | |
| 3086 | |
| 3087 int rv; | |
| 3088 | |
| 3089 rv = SSL_OptionSet(nss_fd_, SSL_SECURITY, PR_TRUE); | |
| 3090 if (rv != SECSuccess) { | |
| 3091 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_SECURITY"); | |
| 3092 return ERR_UNEXPECTED; | |
| 3093 } | |
| 3094 | |
| 3095 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SSL2, PR_FALSE); | |
| 3096 if (rv != SECSuccess) { | |
| 3097 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_SSL2"); | |
| 3098 return ERR_UNEXPECTED; | |
| 3099 } | |
| 3100 | |
| 3101 // Don't do V2 compatible hellos because they don't support TLS extensions. | |
| 3102 rv = SSL_OptionSet(nss_fd_, SSL_V2_COMPATIBLE_HELLO, PR_FALSE); | |
| 3103 if (rv != SECSuccess) { | |
| 3104 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_V2_COMPATIBLE_HELLO"); | |
| 3105 return ERR_UNEXPECTED; | |
| 3106 } | |
| 3107 | |
| 3108 SSLVersionRange version_range; | |
| 3109 version_range.min = ssl_config_.version_min; | |
| 3110 version_range.max = ssl_config_.version_max; | |
| 3111 rv = SSL_VersionRangeSet(nss_fd_, &version_range); | |
| 3112 if (rv != SECSuccess) { | |
| 3113 LogFailedNSSFunction(net_log_, "SSL_VersionRangeSet", ""); | |
| 3114 return ERR_NO_SSL_VERSIONS_ENABLED; | |
| 3115 } | |
| 3116 | |
| 3117 for (std::vector<uint16>::const_iterator it = | |
| 3118 ssl_config_.disabled_cipher_suites.begin(); | |
| 3119 it != ssl_config_.disabled_cipher_suites.end(); ++it) { | |
| 3120 // This will fail if the specified cipher is not implemented by NSS, but | |
| 3121 // the failure is harmless. | |
| 3122 SSL_CipherPrefSet(nss_fd_, *it, PR_FALSE); | |
| 3123 } | |
| 3124 | |
| 3125 #ifdef SSL_ENABLE_SESSION_TICKETS | |
| 3126 // Support RFC 5077 | |
| 3127 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_SESSION_TICKETS, PR_TRUE); | |
| 3128 if (rv != SECSuccess) { | |
| 3129 LogFailedNSSFunction( | |
| 3130 net_log_, "SSL_OptionSet", "SSL_ENABLE_SESSION_TICKETS"); | |
| 3131 } | |
| 3132 #else | |
| 3133 #error "You need to install NSS-3.12 or later to build chromium" | |
| 3134 #endif | |
| 3135 | |
| 3136 #ifdef SSL_ENABLE_DEFLATE | |
| 3137 // Some web servers have been found to break if TLS is used *or* if DEFLATE | |
| 3138 // is advertised. Thus, if TLS is disabled (probably because we are doing | |
| 3139 // SSLv3 fallback), we disable DEFLATE also. | |
| 3140 // See http://crbug.com/31628 | |
| 3141 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_DEFLATE, | |
| 3142 ssl_config_.version_max >= SSL_PROTOCOL_VERSION_TLS1); | |
| 1608 if (rv != SECSuccess) | 3143 if (rv != SECSuccess) |
| 1609 return MapNSSError(PORT_GetError()); | 3144 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_DEFLATE"); |
| 1610 | 3145 #endif |
| 3146 | |
| 3147 #ifdef SSL_ENABLE_FALSE_START | |
| 3148 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_FALSE_START, | |
| 3149 ssl_config_.false_start_enabled); | |
| 3150 if (rv != SECSuccess) | |
| 3151 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_FALSE_START"); | |
| 3152 #endif | |
| 3153 | |
| 3154 #ifdef SSL_ENABLE_RENEGOTIATION | |
| 3155 // We allow servers to request renegotiation. Since we're a client, | |
| 3156 // prohibiting this is rather a waste of time. Only servers are in a | |
| 3157 // position to prevent renegotiation attacks. | |
| 3158 // http://extendedsubset.com/?p=8 | |
| 3159 | |
| 3160 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_RENEGOTIATION, | |
| 3161 SSL_RENEGOTIATE_TRANSITIONAL); | |
| 3162 if (rv != SECSuccess) { | |
| 3163 LogFailedNSSFunction( | |
| 3164 net_log_, "SSL_OptionSet", "SSL_ENABLE_RENEGOTIATION"); | |
| 3165 } | |
| 3166 #endif // SSL_ENABLE_RENEGOTIATION | |
| 3167 | |
| 3168 #ifdef SSL_CBC_RANDOM_IV | |
| 3169 rv = SSL_OptionSet(nss_fd_, SSL_CBC_RANDOM_IV, | |
| 3170 ssl_config_.false_start_enabled); | |
| 3171 if (rv != SECSuccess) | |
| 3172 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_CBC_RANDOM_IV"); | |
| 3173 #endif | |
| 3174 | |
| 3175 #ifdef SSL_ENABLE_OCSP_STAPLING | |
| 3176 if (IsOCSPStaplingSupported()) { | |
| 3177 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OCSP_STAPLING, PR_TRUE); | |
| 3178 if (rv != SECSuccess) { | |
| 3179 LogFailedNSSFunction(net_log_, "SSL_OptionSet", | |
| 3180 "SSL_ENABLE_OCSP_STAPLING"); | |
| 3181 } | |
| 3182 } | |
| 3183 #endif | |
| 3184 | |
| 3185 #ifdef SSL_ENABLE_CACHED_INFO | |
| 3186 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_CACHED_INFO, | |
| 3187 ssl_config_.cached_info_enabled); | |
| 3188 if (rv != SECSuccess) | |
| 3189 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_CACHED_INFO"); | |
| 3190 #endif | |
| 3191 | |
| 3192 #ifdef SSL_ENABLE_OB_CERTS | |
| 3193 rv = SSL_OptionSet(nss_fd_, SSL_ENABLE_OB_CERTS, | |
| 3194 ssl_config_.domain_bound_certs_enabled); | |
| 3195 if (rv != SECSuccess) | |
| 3196 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENABLE_OB_CERTS"); | |
| 3197 #endif | |
| 3198 | |
| 3199 #ifdef SSL_ENCRYPT_CLIENT_CERTS | |
| 3200 // For now, enable the encrypted client certificates extension only if | |
| 3201 // server-bound certificates are enabled. | |
| 3202 rv = SSL_OptionSet(nss_fd_, SSL_ENCRYPT_CLIENT_CERTS, | |
| 3203 ssl_config_.domain_bound_certs_enabled); | |
| 3204 if (rv != SECSuccess) | |
| 3205 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_ENCRYPT_CLIENT_CERTS"); | |
| 3206 #endif | |
| 3207 | |
| 3208 rv = SSL_OptionSet(nss_fd_, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE); | |
| 3209 if (rv != SECSuccess) { | |
| 3210 LogFailedNSSFunction(net_log_, "SSL_OptionSet", "SSL_HANDSHAKE_AS_CLIENT"); | |
| 3211 return ERR_UNEXPECTED; | |
| 3212 } | |
| 3213 | |
| 3214 if (!core_->Init(nss_fd_, nss_bufs)) | |
| 3215 return ERR_UNEXPECTED; | |
| 3216 | |
| 3217 // Tell SSL the hostname we're trying to connect to. | |
| 3218 SSL_SetURL(nss_fd_, host_and_port_.host().c_str()); | |
| 3219 | |
| 3220 // Tell SSL we're a client; needed if not letting NSPR do socket I/O | |
| 3221 SSL_ResetHandshake(nss_fd_, PR_FALSE); | |
| 3222 | |
| 3223 return OK; | |
| 3224 } | |
| 3225 | |
| 3226 int SSLClientSocketNSS::InitializeSSLPeerName() { | |
| 3227 // Tell NSS who we're connected to | |
| 3228 AddressList peer_address; | |
| 3229 int err = transport_->socket()->GetPeerAddress(&peer_address); | |
| 3230 if (err != OK) | |
| 3231 return err; | |
| 3232 | |
| 3233 SockaddrStorage storage; | |
| 3234 if (!peer_address.front().ToSockAddr(storage.addr, &storage.addr_len)) | |
| 3235 return ERR_UNEXPECTED; | |
| 3236 | |
| 3237 PRNetAddr peername; | |
| 3238 memset(&peername, 0, sizeof(peername)); | |
| 3239 DCHECK_LE(static_cast<size_t>(storage.addr_len), sizeof(peername)); | |
| 3240 size_t len = std::min(static_cast<size_t>(storage.addr_len), | |
| 3241 sizeof(peername)); | |
| 3242 memcpy(&peername, storage.addr, len); | |
| 3243 | |
| 3244 // Adjust the address family field for BSD, whose sockaddr | |
| 3245 // structure has a one-byte length and one-byte address family | |
| 3246 // field at the beginning. PRNetAddr has a two-byte address | |
| 3247 // family field at the beginning. | |
| 3248 peername.raw.family = storage.addr->sa_family; | |
| 3249 | |
| 3250 memio_SetPeerName(nss_fd_, &peername); | |
| 3251 | |
| 3252 // Set the peer ID for session reuse. This is necessary when we create an | |
| 3253 // SSL tunnel through a proxy -- GetPeerName returns the proxy's address | |
| 3254 // rather than the destination server's address in that case. | |
| 3255 std::string peer_id = host_and_port_.ToString(); | |
| 3256 // If the ssl_session_cache_shard_ is non-empty, we append it to the peer id. | |
| 3257 // This will cause session cache misses between sockets with different values | |
| 3258 // of ssl_session_cache_shard_ and this is used to partition the session cache | |
| 3259 // for incognito mode. | |
| 3260 if (!ssl_session_cache_shard_.empty()) { | |
| 3261 peer_id += "/" + ssl_session_cache_shard_; | |
| 3262 } | |
| 3263 SECStatus rv = SSL_SetSockPeerID(nss_fd_, const_cast<char*>(peer_id.c_str())); | |
| 3264 if (rv != SECSuccess) | |
| 3265 LogFailedNSSFunction(net_log_, "SSL_SetSockPeerID", peer_id.c_str()); | |
| 3266 | |
| 3267 return OK; | |
| 3268 } | |
| 3269 | |
| 3270 void SSLClientSocketNSS::DoConnectCallback(int rv) { | |
| 3271 EnterFunction(rv); | |
| 3272 DCHECK_NE(ERR_IO_PENDING, rv); | |
| 3273 DCHECK(!user_connect_callback_.is_null()); | |
| 3274 | |
| 3275 base::ResetAndReturn(&user_connect_callback_).Run(rv > OK ? OK : rv); | |
| 3276 LeaveFunction(""); | |
| 3277 } | |
| 3278 | |
| 3279 void SSLClientSocketNSS::OnHandshakeIOComplete(int result) { | |
| 3280 EnterFunction(result); | |
| 3281 int rv = DoHandshakeLoop(result); | |
| 3282 if (rv != ERR_IO_PENDING) { | |
| 3283 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_CONNECT, rv); | |
| 3284 DoConnectCallback(rv); | |
| 3285 } | |
| 3286 LeaveFunction(""); | |
| 3287 } | |
| 3288 | |
| 3289 void SSLClientSocketNSS::LoadSSLHostInfo() { | |
| 3290 const SSLHostInfo::State& state(ssl_host_info_->state()); | |
| 3291 | |
| 3292 if (state.certs.empty()) | |
| 3293 return; | |
| 3294 | |
| 3295 const std::vector<std::string>& certs_in = state.certs; | |
| 3296 core_->SetPredictedCertificates(certs_in); | |
| 3297 } | |
| 3298 | |
| 3299 int SSLClientSocketNSS::DoLoadSSLHostInfo() { | |
| 3300 EnterFunction(""); | |
| 3301 int rv = ssl_host_info_->WaitForDataReady( | |
| 3302 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | |
| 3303 base::Unretained(this))); | |
| 1611 GotoState(STATE_HANDSHAKE); | 3304 GotoState(STATE_HANDSHAKE); |
| 1612 set_domain_bound_cert_type(domain_bound_cert_type_); | 3305 |
| 1613 return OK; | 3306 if (rv == OK) { |
| 1614 } | 3307 LoadSSLHostInfo(); |
| 3308 } else { | |
| 3309 DCHECK_EQ(ERR_IO_PENDING, rv); | |
| 3310 GotoState(STATE_LOAD_SSL_HOST_INFO); | |
| 3311 } | |
| 3312 | |
| 3313 LeaveFunction(""); | |
| 3314 return rv; | |
| 3315 } | |
| 3316 | |
| 3317 int SSLClientSocketNSS::DoHandshakeLoop(int last_io_result) { | |
| 3318 EnterFunction(last_io_result); | |
| 3319 int rv = last_io_result; | |
| 3320 do { | |
| 3321 // Default to STATE_NONE for next state. | |
| 3322 // (This is a quirk carried over from the windows | |
| 3323 // implementation. It makes reading the logs a bit harder.) | |
| 3324 // State handlers can and often do call GotoState just | |
| 3325 // to stay in the current state. | |
| 3326 State state = next_handshake_state_; | |
| 3327 GotoState(STATE_NONE); | |
| 3328 switch (state) { | |
| 3329 case STATE_LOAD_SSL_HOST_INFO: | |
| 3330 DCHECK(rv == OK || rv == ERR_IO_PENDING); | |
| 3331 rv = DoLoadSSLHostInfo(); | |
| 3332 break; | |
| 3333 case STATE_HANDSHAKE: | |
| 3334 rv = DoHandshake(); | |
| 3335 break; | |
| 3336 case STATE_HANDSHAKE_COMPLETE: | |
| 3337 rv = DoHandshakeComplete(rv); | |
| 3338 break; | |
| 3339 case STATE_VERIFY_DNSSEC: | |
| 3340 rv = DoVerifyDNSSEC(rv); | |
| 3341 break; | |
| 3342 case STATE_VERIFY_CERT: | |
| 3343 DCHECK(rv == OK); | |
| 3344 rv = DoVerifyCert(rv); | |
| 3345 break; | |
| 3346 case STATE_VERIFY_CERT_COMPLETE: | |
| 3347 rv = DoVerifyCertComplete(rv); | |
| 3348 break; | |
| 3349 case STATE_NONE: | |
| 3350 default: | |
| 3351 rv = ERR_UNEXPECTED; | |
| 3352 LOG(DFATAL) << "unexpected state " << state; | |
| 3353 break; | |
| 3354 } | |
| 3355 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE); | |
| 3356 LeaveFunction(""); | |
| 3357 return rv; | |
| 3358 } | |
| 3359 | |
| 3360 int SSLClientSocketNSS::DoHandshake() { | |
| 3361 EnterFunction(""); | |
| 3362 int rv = core_->Connect( | |
| 3363 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | |
| 3364 base::Unretained(this))); | |
| 3365 GotoState(STATE_HANDSHAKE_COMPLETE); | |
| 3366 | |
| 3367 LeaveFunction(rv); | |
| 3368 return rv; | |
| 3369 } | |
| 3370 | |
| 3371 int SSLClientSocketNSS::DoHandshakeComplete(int result) { | |
| 3372 EnterFunction(result); | |
| 3373 | |
| 3374 if (result == OK) { | |
| 3375 SaveSSLHostInfo(); | |
| 3376 // SSL handshake is completed. Let's verify the certificate. | |
| 3377 GotoState(STATE_VERIFY_DNSSEC); | |
| 3378 // Done! | |
| 3379 } | |
| 3380 if (core_->state().domain_bound_cert_type != CLIENT_CERT_INVALID_TYPE) | |
| 3381 set_domain_bound_cert_type(core_->state().domain_bound_cert_type); | |
| 3382 | |
| 3383 LeaveFunction(result); | |
| 3384 return result; | |
| 3385 } | |
| 3386 | |
| 1615 | 3387 |
| 1616 int SSLClientSocketNSS::DoVerifyDNSSEC(int result) { | 3388 int SSLClientSocketNSS::DoVerifyDNSSEC(int result) { |
| 1617 DNSValidationResult r = CheckDNSSECChain(host_and_port_.host(), | 3389 DCHECK(!core_->state().server_cert_chain.empty()); |
| 1618 server_cert_nss_, | 3390 DCHECK(core_->state().server_cert_chain[0]); |
| 1619 host_and_port_.port()); | 3391 |
| 3392 DNSValidationResult r = CheckDNSSECChain( | |
| 3393 host_and_port_.host(), core_->state().server_cert_chain[0], | |
| 3394 host_and_port_.port()); | |
| 1620 if (r == DNSVR_SUCCESS) { | 3395 if (r == DNSVR_SUCCESS) { |
| 1621 local_server_cert_verify_result_.cert_status |= CERT_STATUS_IS_DNSSEC; | 3396 local_server_cert_verify_result_.cert_status |= CERT_STATUS_IS_DNSSEC; |
| 1622 local_server_cert_verify_result_.verified_cert = server_cert_; | 3397 local_server_cert_verify_result_.verified_cert = |
| 3398 core_->state().server_cert; | |
| 1623 server_cert_verify_result_ = &local_server_cert_verify_result_; | 3399 server_cert_verify_result_ = &local_server_cert_verify_result_; |
| 1624 GotoState(STATE_VERIFY_CERT_COMPLETE); | 3400 GotoState(STATE_VERIFY_CERT_COMPLETE); |
| 1625 return OK; | 3401 return OK; |
| 1626 } | 3402 } |
| 1627 | 3403 |
| 1628 GotoState(STATE_VERIFY_CERT); | 3404 GotoState(STATE_VERIFY_CERT); |
| 1629 | 3405 |
| 1630 return OK; | 3406 return OK; |
| 1631 } | 3407 } |
| 1632 | 3408 |
| 1633 int SSLClientSocketNSS::DoVerifyCert(int result) { | 3409 int SSLClientSocketNSS::DoVerifyCert(int result) { |
| 1634 DCHECK(server_cert_nss_); | 3410 DCHECK(!core_->state().server_cert_chain.empty()); |
| 3411 DCHECK(core_->state().server_cert_chain[0]); | |
| 1635 | 3412 |
| 1636 GotoState(STATE_VERIFY_CERT_COMPLETE); | 3413 GotoState(STATE_VERIFY_CERT_COMPLETE); |
| 1637 | 3414 |
| 1638 // If the certificate is expected to be bad we can use the | 3415 // If the certificate is expected to be bad we can use the expectation as |
| 1639 // expectation as the cert status. Don't use |server_cert_| here | 3416 // the cert status. |
| 1640 // because it can be set to NULL in case we failed to create | |
| 1641 // X509Certificate in UpdateServerCert(). This may happen when this | |
| 1642 // code is used inside sandbox. | |
| 1643 base::StringPiece der_cert( | 3417 base::StringPiece der_cert( |
| 1644 reinterpret_cast<char*>(server_cert_nss_->derCert.data), | 3418 reinterpret_cast<char*>( |
| 1645 server_cert_nss_->derCert.len); | 3419 core_->state().server_cert_chain[0]->derCert.data), |
| 3420 core_->state().server_cert_chain[0]->derCert.len); | |
| 1646 CertStatus cert_status; | 3421 CertStatus cert_status; |
| 1647 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) { | 3422 if (ssl_config_.IsAllowedBadCert(der_cert, &cert_status)) { |
| 1648 DCHECK(start_cert_verification_time_.is_null()); | 3423 DCHECK(start_cert_verification_time_.is_null()); |
| 1649 VLOG(1) << "Received an expected bad cert with status: " << cert_status; | 3424 VLOG(1) << "Received an expected bad cert with status: " << cert_status; |
| 1650 server_cert_verify_result_ = &local_server_cert_verify_result_; | 3425 server_cert_verify_result_ = &local_server_cert_verify_result_; |
| 1651 local_server_cert_verify_result_.Reset(); | 3426 local_server_cert_verify_result_.Reset(); |
| 1652 local_server_cert_verify_result_.cert_status = cert_status; | 3427 local_server_cert_verify_result_.cert_status = cert_status; |
| 1653 local_server_cert_verify_result_.verified_cert = server_cert_; | 3428 local_server_cert_verify_result_.verified_cert = |
| 3429 core_->state().server_cert; | |
| 1654 return OK; | 3430 return OK; |
| 1655 } | 3431 } |
| 1656 | 3432 |
| 1657 // We may have failed to create X509Certificate object if we are | 3433 // We may have failed to create X509Certificate object if we are |
| 1658 // running inside sandbox. | 3434 // running inside sandbox. |
| 1659 if (!server_cert_) { | 3435 if (!core_->state().server_cert) { |
| 1660 server_cert_verify_result_ = &local_server_cert_verify_result_; | 3436 server_cert_verify_result_ = &local_server_cert_verify_result_; |
| 1661 local_server_cert_verify_result_.Reset(); | 3437 local_server_cert_verify_result_.Reset(); |
| 1662 local_server_cert_verify_result_.cert_status = CERT_STATUS_INVALID; | 3438 local_server_cert_verify_result_.cert_status = CERT_STATUS_INVALID; |
| 1663 return ERR_CERT_INVALID; | 3439 return ERR_CERT_INVALID; |
| 1664 } | 3440 } |
| 1665 | 3441 |
| 1666 start_cert_verification_time_ = base::TimeTicks::Now(); | 3442 start_cert_verification_time_ = base::TimeTicks::Now(); |
| 1667 | 3443 |
| 1668 if (ssl_host_info_.get() && !ssl_host_info_->state().certs.empty() && | 3444 if (ssl_host_info_.get() && !ssl_host_info_->state().certs.empty() && |
| 1669 predicted_cert_chain_correct_) { | 3445 core_->state().predicted_cert_chain_correct) { |
| 1670 // If the SSLHostInfo had a prediction for the certificate chain of this | 3446 // If the SSLHostInfo had a prediction for the certificate chain of this |
| 1671 // server then it will have optimistically started a verification of that | 3447 // server then it will have optimistically started a verification of that |
| 1672 // chain. So, if the prediction was correct, we should wait for that | 3448 // chain. So, if the prediction was correct, we should wait for that |
| 1673 // verification to finish rather than start our own. | 3449 // verification to finish rather than start our own. |
| 1674 net_log_.AddEvent(NetLog::TYPE_SSL_VERIFICATION_MERGED, NULL); | 3450 net_log_.AddEvent(NetLog::TYPE_SSL_VERIFICATION_MERGED, NULL); |
| 1675 UMA_HISTOGRAM_ENUMERATION("Net.SSLVerificationMerged", 1 /* true */, 2); | 3451 UMA_HISTOGRAM_ENUMERATION("Net.SSLVerificationMerged", 1 /* true */, 2); |
| 1676 base::TimeTicks end_time = ssl_host_info_->verification_end_time(); | 3452 base::TimeTicks end_time = ssl_host_info_->verification_end_time(); |
| 1677 if (end_time.is_null()) | 3453 if (end_time.is_null()) |
| 1678 end_time = base::TimeTicks::Now(); | 3454 end_time = base::TimeTicks::Now(); |
| 1679 UMA_HISTOGRAM_TIMES("Net.SSLVerificationMergedMsSaved", | 3455 UMA_HISTOGRAM_TIMES("Net.SSLVerificationMergedMsSaved", |
| 1680 end_time - ssl_host_info_->verification_start_time()); | 3456 end_time - ssl_host_info_->verification_start_time()); |
| 1681 server_cert_verify_result_ = &ssl_host_info_->cert_verify_result(); | 3457 server_cert_verify_result_ = &ssl_host_info_->cert_verify_result(); |
| 1682 return ssl_host_info_->WaitForCertVerification( | 3458 return ssl_host_info_->WaitForCertVerification( |
| 1683 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | 3459 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, |
| 1684 base::Unretained(this))); | 3460 base::Unretained(this))); |
| 1685 } else { | 3461 } else { |
| 1686 UMA_HISTOGRAM_ENUMERATION("Net.SSLVerificationMerged", 0 /* false */, 2); | 3462 UMA_HISTOGRAM_ENUMERATION("Net.SSLVerificationMerged", 0 /* false */, 2); |
| 1687 } | 3463 } |
| 1688 | 3464 |
| 1689 int flags = 0; | 3465 int flags = 0; |
| 1690 if (ssl_config_.rev_checking_enabled) | 3466 if (ssl_config_.rev_checking_enabled) |
| 1691 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED; | 3467 flags |= X509Certificate::VERIFY_REV_CHECKING_ENABLED; |
| 1692 if (ssl_config_.verify_ev_cert) | 3468 if (ssl_config_.verify_ev_cert) |
| 1693 flags |= X509Certificate::VERIFY_EV_CERT; | 3469 flags |= X509Certificate::VERIFY_EV_CERT; |
| 1694 if (ssl_config_.cert_io_enabled) | 3470 if (ssl_config_.cert_io_enabled) |
| 1695 flags |= X509Certificate::VERIFY_CERT_IO_ENABLED; | 3471 flags |= X509Certificate::VERIFY_CERT_IO_ENABLED; |
| 1696 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_)); | 3472 verifier_.reset(new SingleRequestCertVerifier(cert_verifier_)); |
| 1697 server_cert_verify_result_ = &local_server_cert_verify_result_; | 3473 server_cert_verify_result_ = &local_server_cert_verify_result_; |
| 1698 return verifier_->Verify( | 3474 return verifier_->Verify( |
| 1699 server_cert_, host_and_port_.host(), flags, | 3475 core_->state().server_cert, host_and_port_.host(), flags, |
| 1700 SSLConfigService::GetCRLSet(), | 3476 SSLConfigService::GetCRLSet(), &local_server_cert_verify_result_, |
| 1701 &local_server_cert_verify_result_, | |
| 1702 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | 3477 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, |
| 1703 base::Unretained(this)), | 3478 base::Unretained(this)), |
| 1704 net_log_); | 3479 net_log_); |
| 1705 } | 3480 } |
| 1706 | 3481 |
| 1707 // Derived from AuthCertificateCallback() in | 3482 // Derived from AuthCertificateCallback() in |
| 1708 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp. | 3483 // mozilla/source/security/manager/ssl/src/nsNSSCallbacks.cpp. |
| 1709 int SSLClientSocketNSS::DoVerifyCertComplete(int result) { | 3484 int SSLClientSocketNSS::DoVerifyCertComplete(int result) { |
| 1710 verifier_.reset(); | 3485 verifier_.reset(); |
| 1711 | 3486 |
| (...skipping 17 matching lines...) Expand all Loading... | |
| 1729 // http://crbug.com/15630 for more info. | 3504 // http://crbug.com/15630 for more info. |
| 1730 | 3505 |
| 1731 // TODO(hclam): Skip logging if server cert was expected to be bad because | 3506 // TODO(hclam): Skip logging if server cert was expected to be bad because |
| 1732 // |server_cert_verify_result_| doesn't contain all the information about | 3507 // |server_cert_verify_result_| doesn't contain all the information about |
| 1733 // the cert. | 3508 // the cert. |
| 1734 if (result == OK) | 3509 if (result == OK) |
| 1735 LogConnectionTypeMetrics(); | 3510 LogConnectionTypeMetrics(); |
| 1736 | 3511 |
| 1737 completed_handshake_ = true; | 3512 completed_handshake_ = true; |
| 1738 | 3513 |
| 1739 if (!user_read_callback_.is_null()) { | |
| 1740 int rv = DoReadLoop(OK); | |
| 1741 if (rv != ERR_IO_PENDING) | |
| 1742 DoReadCallback(rv); | |
| 1743 } | |
| 1744 | |
| 1745 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) | 3514 #if defined(OFFICIAL_BUILD) && !defined(OS_ANDROID) |
| 1746 // Take care of any mandates for public key pinning. | 3515 // Take care of any mandates for public key pinning. |
| 1747 // | 3516 // |
| 1748 // Pinning is only enabled for official builds to make sure that others don't | 3517 // Pinning is only enabled for official builds to make sure that others don't |
| 1749 // end up with pins that cannot be easily updated. | 3518 // end up with pins that cannot be easily updated. |
| 1750 // | 3519 // |
| 1751 // TODO(agl): we might have an issue here where a request for foo.example.com | 3520 // TODO(agl): we might have an issue here where a request for foo.example.com |
| 1752 // merges into a SPDY connection to www.example.com, and gets a different | 3521 // merges into a SPDY connection to www.example.com, and gets a different |
| 1753 // certificate. | 3522 // certificate. |
| 1754 | 3523 |
| (...skipping 25 matching lines...) Expand all Loading... | |
| 1780 TransportSecurityState::ReportUMAOnPinFailure(host); | 3549 TransportSecurityState::ReportUMAOnPinFailure(host); |
| 1781 } | 3550 } |
| 1782 } else { | 3551 } else { |
| 1783 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true); | 3552 UMA_HISTOGRAM_BOOLEAN("Net.PublicKeyPinSuccess", true); |
| 1784 } | 3553 } |
| 1785 } | 3554 } |
| 1786 } | 3555 } |
| 1787 #endif | 3556 #endif |
| 1788 | 3557 |
| 1789 // Exit DoHandshakeLoop and return the result to the caller to Connect. | 3558 // Exit DoHandshakeLoop and return the result to the caller to Connect. |
| 1790 DCHECK(next_handshake_state_ == STATE_NONE); | 3559 DCHECK_EQ(STATE_NONE, next_handshake_state_); |
| 1791 return result; | 3560 return result; |
| 1792 } | 3561 } |
| 1793 | 3562 |
| 1794 int SSLClientSocketNSS::DoPayloadRead() { | |
| 1795 EnterFunction(user_read_buf_len_); | |
| 1796 DCHECK(user_read_buf_); | |
| 1797 DCHECK_GT(user_read_buf_len_, 0); | |
| 1798 int rv = PR_Read(nss_fd_, user_read_buf_->data(), user_read_buf_len_); | |
| 1799 if (client_auth_cert_needed_) { | |
| 1800 // We don't need to invalidate the non-client-authenticated SSL session | |
| 1801 // because the server will renegotiate anyway. | |
| 1802 LeaveFunction(""); | |
| 1803 rv = ERR_SSL_CLIENT_AUTH_CERT_NEEDED; | |
| 1804 net_log_.AddEvent(NetLog::TYPE_SSL_READ_ERROR, | |
| 1805 make_scoped_refptr(new SSLErrorParams(rv, 0))); | |
| 1806 return rv; | |
| 1807 } | |
| 1808 if (rv >= 0) { | |
| 1809 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, rv, | |
| 1810 user_read_buf_->data()); | |
| 1811 LeaveFunction(""); | |
| 1812 return rv; | |
| 1813 } | |
| 1814 PRErrorCode prerr = PR_GetError(); | |
| 1815 if (prerr == PR_WOULD_BLOCK_ERROR) { | |
| 1816 LeaveFunction(""); | |
| 1817 return ERR_IO_PENDING; | |
| 1818 } | |
| 1819 LeaveFunction(""); | |
| 1820 rv = HandleNSSError(prerr, false); | |
| 1821 net_log_.AddEvent(NetLog::TYPE_SSL_READ_ERROR, | |
| 1822 make_scoped_refptr(new SSLErrorParams(rv, prerr))); | |
| 1823 return rv; | |
| 1824 } | |
| 1825 | |
| 1826 int SSLClientSocketNSS::DoPayloadWrite() { | |
| 1827 EnterFunction(user_write_buf_len_); | |
| 1828 DCHECK(user_write_buf_); | |
| 1829 int rv = PR_Write(nss_fd_, user_write_buf_->data(), user_write_buf_len_); | |
| 1830 if (rv >= 0) { | |
| 1831 net_log_.AddByteTransferEvent(NetLog::TYPE_SSL_SOCKET_BYTES_SENT, rv, | |
| 1832 user_write_buf_->data()); | |
| 1833 LeaveFunction(""); | |
| 1834 return rv; | |
| 1835 } | |
| 1836 PRErrorCode prerr = PR_GetError(); | |
| 1837 if (prerr == PR_WOULD_BLOCK_ERROR) { | |
| 1838 LeaveFunction(""); | |
| 1839 return ERR_IO_PENDING; | |
| 1840 } | |
| 1841 LeaveFunction(""); | |
| 1842 rv = HandleNSSError(prerr, false); | |
| 1843 net_log_.AddEvent(NetLog::TYPE_SSL_WRITE_ERROR, | |
| 1844 make_scoped_refptr(new SSLErrorParams(rv, prerr))); | |
| 1845 return rv; | |
| 1846 } | |
| 1847 | |
| 1848 void SSLClientSocketNSS::LogConnectionTypeMetrics() const { | 3563 void SSLClientSocketNSS::LogConnectionTypeMetrics() const { |
| 1849 UpdateConnectionTypeHistograms(CONNECTION_SSL); | 3564 UpdateConnectionTypeHistograms(CONNECTION_SSL); |
| 1850 if (server_cert_verify_result_->has_md5) | 3565 if (server_cert_verify_result_->has_md5) |
| 1851 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5); | 3566 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5); |
| 1852 if (server_cert_verify_result_->has_md2) | 3567 if (server_cert_verify_result_->has_md2) |
| 1853 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2); | 3568 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2); |
| 1854 if (server_cert_verify_result_->has_md4) | 3569 if (server_cert_verify_result_->has_md4) |
| 1855 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4); | 3570 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD4); |
| 1856 if (server_cert_verify_result_->has_md5_ca) | 3571 if (server_cert_verify_result_->has_md5_ca) |
| 1857 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA); | 3572 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD5_CA); |
| 1858 if (server_cert_verify_result_->has_md2_ca) | 3573 if (server_cert_verify_result_->has_md2_ca) |
| 1859 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA); | 3574 UpdateConnectionTypeHistograms(CONNECTION_SSL_MD2_CA); |
| 1860 int ssl_version = SSLConnectionStatusToVersion(ssl_connection_status_); | 3575 int ssl_version = SSLConnectionStatusToVersion( |
| 3576 core_->state().ssl_connection_status); | |
| 1861 switch (ssl_version) { | 3577 switch (ssl_version) { |
| 1862 case SSL_CONNECTION_VERSION_SSL2: | 3578 case SSL_CONNECTION_VERSION_SSL2: |
| 1863 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2); | 3579 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL2); |
| 1864 break; | 3580 break; |
| 1865 case SSL_CONNECTION_VERSION_SSL3: | 3581 case SSL_CONNECTION_VERSION_SSL3: |
| 1866 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3); | 3582 UpdateConnectionTypeHistograms(CONNECTION_SSL_SSL3); |
| 1867 break; | 3583 break; |
| 1868 case SSL_CONNECTION_VERSION_TLS1: | 3584 case SSL_CONNECTION_VERSION_TLS1: |
| 1869 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1); | 3585 UpdateConnectionTypeHistograms(CONNECTION_SSL_TLS1); |
| 1870 break; | 3586 break; |
| (...skipping 13 matching lines...) Expand all Loading... | |
| 1884 return; | 3600 return; |
| 1885 | 3601 |
| 1886 // If the SSLHostInfo hasn't managed to load from disk yet then we can't save | 3602 // If the SSLHostInfo hasn't managed to load from disk yet then we can't save |
| 1887 // anything. | 3603 // anything. |
| 1888 if (ssl_host_info_->WaitForDataReady(net::CompletionCallback()) != OK) | 3604 if (ssl_host_info_->WaitForDataReady(net::CompletionCallback()) != OK) |
| 1889 return; | 3605 return; |
| 1890 | 3606 |
| 1891 SSLHostInfo::State* state = ssl_host_info_->mutable_state(); | 3607 SSLHostInfo::State* state = ssl_host_info_->mutable_state(); |
| 1892 | 3608 |
| 1893 state->certs.clear(); | 3609 state->certs.clear(); |
| 1894 PeerCertificateChain certs(nss_fd_); | 3610 const PeerCertificateChain& certs = core_->state().server_cert_chain; |
| 1895 for (unsigned i = 0; i < certs.size(); i++) { | 3611 for (unsigned i = 0; i < certs.size(); i++) { |
| 1896 if (certs[i]->derCert.len > std::numeric_limits<uint16>::max()) | 3612 if (certs[i] == NULL || |
| 3613 certs[i]->derCert.len > std::numeric_limits<uint16>::max()) { | |
| 1897 return; | 3614 return; |
| 3615 } | |
| 1898 | 3616 |
| 1899 state->certs.push_back(std::string( | 3617 state->certs.push_back(std::string( |
| 1900 reinterpret_cast<char*>(certs[i]->derCert.data), | 3618 reinterpret_cast<char*>(certs[i]->derCert.data), |
| 1901 certs[i]->derCert.len)); | 3619 certs[i]->derCert.len)); |
| 1902 } | 3620 } |
| 1903 | 3621 |
| 1904 ssl_host_info_->Persist(); | 3622 ssl_host_info_->Persist(); |
| 1905 } | 3623 } |
| 1906 | 3624 |
| 1907 // Do as much network I/O as possible between the buffer and the | |
| 1908 // transport socket. Return true if some I/O performed, false | |
| 1909 // otherwise (error or ERR_IO_PENDING). | |
| 1910 bool SSLClientSocketNSS::DoTransportIO() { | |
| 1911 EnterFunction(""); | |
| 1912 bool network_moved = false; | |
| 1913 if (nss_bufs_ != NULL) { | |
| 1914 int rv; | |
| 1915 // Read and write as much data as we can. The loop is neccessary | |
| 1916 // because Write() may return synchronously. | |
| 1917 do { | |
| 1918 rv = BufferSend(); | |
| 1919 if (rv > 0) | |
| 1920 network_moved = true; | |
| 1921 } while (rv > 0); | |
| 1922 if (!transport_recv_eof_ && BufferRecv() >= 0) | |
| 1923 network_moved = true; | |
| 1924 } | |
| 1925 LeaveFunction(network_moved); | |
| 1926 return network_moved; | |
| 1927 } | |
| 1928 | |
| 1929 // Return 0 for EOF, | |
| 1930 // > 0 for bytes transferred immediately, | |
| 1931 // < 0 for error (or the non-error ERR_IO_PENDING). | |
| 1932 int SSLClientSocketNSS::BufferSend() { | |
| 1933 if (transport_send_busy_) | |
| 1934 return ERR_IO_PENDING; | |
| 1935 | |
| 1936 EnterFunction(""); | |
| 1937 const char* buf1; | |
| 1938 const char* buf2; | |
| 1939 unsigned int len1, len2; | |
| 1940 memio_GetWriteParams(nss_bufs_, &buf1, &len1, &buf2, &len2); | |
| 1941 const unsigned int len = len1 + len2; | |
| 1942 | |
| 1943 int rv = 0; | |
| 1944 if (len) { | |
| 1945 scoped_refptr<IOBuffer> send_buffer(new IOBuffer(len)); | |
| 1946 memcpy(send_buffer->data(), buf1, len1); | |
| 1947 memcpy(send_buffer->data() + len1, buf2, len2); | |
| 1948 rv = transport_->socket()->Write( | |
| 1949 send_buffer, len, | |
| 1950 base::Bind(&SSLClientSocketNSS::BufferSendComplete, | |
| 1951 base::Unretained(this))); | |
| 1952 if (rv == ERR_IO_PENDING) { | |
| 1953 transport_send_busy_ = true; | |
| 1954 } else { | |
| 1955 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(rv)); | |
| 1956 } | |
| 1957 } | |
| 1958 | |
| 1959 LeaveFunction(rv); | |
| 1960 return rv; | |
| 1961 } | |
| 1962 | |
| 1963 void SSLClientSocketNSS::BufferSendComplete(int result) { | |
| 1964 EnterFunction(result); | |
| 1965 memio_PutWriteResult(nss_bufs_, MapErrorToNSS(result)); | |
| 1966 transport_send_busy_ = false; | |
| 1967 OnSendComplete(result); | |
| 1968 LeaveFunction(""); | |
| 1969 } | |
| 1970 | |
| 1971 int SSLClientSocketNSS::BufferRecv() { | |
| 1972 if (transport_recv_busy_) return ERR_IO_PENDING; | |
| 1973 | |
| 1974 char* buf; | |
| 1975 int nb = memio_GetReadParams(nss_bufs_, &buf); | |
| 1976 EnterFunction(nb); | |
| 1977 int rv; | |
| 1978 if (!nb) { | |
| 1979 // buffer too full to read into, so no I/O possible at moment | |
| 1980 rv = ERR_IO_PENDING; | |
| 1981 } else { | |
| 1982 recv_buffer_ = new IOBuffer(nb); | |
| 1983 rv = transport_->socket()->Read( | |
| 1984 recv_buffer_, nb, | |
| 1985 base::Bind(&SSLClientSocketNSS::BufferRecvComplete, | |
| 1986 base::Unretained(this))); | |
| 1987 if (rv == ERR_IO_PENDING) { | |
| 1988 transport_recv_busy_ = true; | |
| 1989 } else { | |
| 1990 if (rv > 0) { | |
| 1991 memcpy(buf, recv_buffer_->data(), rv); | |
| 1992 } else if (rv == 0) { | |
| 1993 transport_recv_eof_ = true; | |
| 1994 } | |
| 1995 memio_PutReadResult(nss_bufs_, MapErrorToNSS(rv)); | |
| 1996 recv_buffer_ = NULL; | |
| 1997 } | |
| 1998 } | |
| 1999 LeaveFunction(rv); | |
| 2000 return rv; | |
| 2001 } | |
| 2002 | |
| 2003 void SSLClientSocketNSS::BufferRecvComplete(int result) { | |
| 2004 EnterFunction(result); | |
| 2005 if (result > 0) { | |
| 2006 char* buf; | |
| 2007 memio_GetReadParams(nss_bufs_, &buf); | |
| 2008 memcpy(buf, recv_buffer_->data(), result); | |
| 2009 } else if (result == 0) { | |
| 2010 transport_recv_eof_ = true; | |
| 2011 } | |
| 2012 recv_buffer_ = NULL; | |
| 2013 memio_PutReadResult(nss_bufs_, MapErrorToNSS(result)); | |
| 2014 transport_recv_busy_ = false; | |
| 2015 OnRecvComplete(result); | |
| 2016 LeaveFunction(""); | |
| 2017 } | |
| 2018 | |
| 2019 int SSLClientSocketNSS::HandleNSSError(PRErrorCode nss_error, | |
| 2020 bool handshake_error) { | |
| 2021 int net_error = handshake_error ? MapNSSHandshakeError(nss_error) : | |
| 2022 MapNSSError(nss_error); | |
| 2023 | |
| 2024 #if defined(OS_WIN) | |
| 2025 // On Windows, a handle to the HCRYPTPROV is cached in the X509Certificate | |
| 2026 // os_cert_handle() as an optimization. However, if the certificate | |
| 2027 // private key is stored on a smart card, and the smart card is removed, | |
| 2028 // the cached HCRYPTPROV will not be able to obtain the HCRYPTKEY again, | |
| 2029 // preventing client certificate authentication. Because the | |
| 2030 // X509Certificate may outlive the individual SSLClientSocketNSS, due to | |
| 2031 // caching in X509Certificate, this failure ends up preventing client | |
| 2032 // certificate authentication with the same certificate for all future | |
| 2033 // attempts, even after the smart card has been re-inserted. By setting | |
| 2034 // the CERT_KEY_PROV_HANDLE_PROP_ID to NULL, the cached HCRYPTPROV will | |
| 2035 // typically be freed. This allows a new HCRYPTPROV to be obtained from | |
| 2036 // the certificate on the next attempt, which should succeed if the smart | |
| 2037 // card has been re-inserted, or will typically prompt the user to | |
| 2038 // re-insert the smart card if not. | |
| 2039 if ((net_error == ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY || | |
| 2040 net_error == ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED) && | |
| 2041 ssl_config_.send_client_cert && ssl_config_.client_cert) { | |
| 2042 CertSetCertificateContextProperty( | |
| 2043 ssl_config_.client_cert->os_cert_handle(), | |
| 2044 CERT_KEY_PROV_HANDLE_PROP_ID, 0, NULL); | |
| 2045 } | |
| 2046 #endif | |
| 2047 | |
| 2048 return net_error; | |
| 2049 } | |
| 2050 | |
| 2051 // static | |
| 2052 // NSS calls this if an incoming certificate needs to be verified. | |
| 2053 // Do nothing but return SECSuccess. | |
| 2054 // This is called only in full handshake mode. | |
| 2055 // Peer certificate is retrieved in HandshakeCallback() later, which is called | |
| 2056 // in full handshake mode or in resumption handshake mode. | |
| 2057 SECStatus SSLClientSocketNSS::OwnAuthCertHandler(void* arg, | |
| 2058 PRFileDesc* socket, | |
| 2059 PRBool checksig, | |
| 2060 PRBool is_server) { | |
| 2061 #ifdef SSL_ENABLE_FALSE_START | |
| 2062 SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg); | |
| 2063 if (!that->server_cert_nss_) { | |
| 2064 // Only need to turn off False Start in the initial handshake. Also, it is | |
| 2065 // unsafe to call SSL_OptionSet in a renegotiation because the "first | |
| 2066 // handshake" lock isn't already held, which will result in an assertion | |
| 2067 // failure in the ssl_Get1stHandshakeLock call in SSL_OptionSet. | |
| 2068 PRBool npn; | |
| 2069 SECStatus rv = SSL_HandshakeNegotiatedExtension(socket, | |
| 2070 ssl_next_proto_nego_xtn, | |
| 2071 &npn); | |
| 2072 if (rv != SECSuccess || !npn) { | |
| 2073 // If the server doesn't support NPN, then we don't do False Start with | |
| 2074 // it. | |
| 2075 SSL_OptionSet(socket, SSL_ENABLE_FALSE_START, PR_FALSE); | |
| 2076 } | |
| 2077 } | |
| 2078 #endif | |
| 2079 | |
| 2080 // Tell NSS to not verify the certificate. | |
| 2081 return SECSuccess; | |
| 2082 } | |
| 2083 | |
| 2084 // static | |
| 2085 bool SSLClientSocketNSS::DomainBoundCertNegotiated(PRFileDesc* socket) { | |
| 2086 // TODO(wtc,mattm): this is temporary while DBC support is changed into | |
| 2087 // Channel ID. | |
| 2088 return false; | |
| 2089 } | |
| 2090 | |
| 2091 SECStatus SSLClientSocketNSS::DomainBoundClientAuthHandler( | |
| 2092 const SECItem* cert_types, | |
| 2093 CERTCertificate** result_certificate, | |
| 2094 SECKEYPrivateKey** result_private_key) { | |
| 2095 domain_bound_cert_xtn_negotiated_ = true; | |
| 2096 | |
| 2097 // We have negotiated the domain-bound certificate extension. | |
| 2098 std::string origin = "https://" + host_and_port_.ToString(); | |
| 2099 std::vector<uint8> requested_cert_types(cert_types->data, | |
| 2100 cert_types->data + cert_types->len); | |
| 2101 net_log_.BeginEvent(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, NULL); | |
| 2102 int error = server_bound_cert_service_->GetDomainBoundCert( | |
| 2103 origin, | |
| 2104 requested_cert_types, | |
| 2105 &domain_bound_cert_type_, | |
| 2106 &domain_bound_private_key_, | |
| 2107 &domain_bound_cert_, | |
| 2108 base::Bind(&SSLClientSocketNSS::OnHandshakeIOComplete, | |
| 2109 base::Unretained(this)), | |
| 2110 &domain_bound_cert_request_handle_); | |
| 2111 | |
| 2112 if (error == ERR_IO_PENDING) { | |
| 2113 // Asynchronous case. | |
| 2114 client_auth_cert_needed_ = true; | |
| 2115 return SECWouldBlock; | |
| 2116 } | |
| 2117 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_GET_DOMAIN_BOUND_CERT, | |
| 2118 error); | |
| 2119 | |
| 2120 SECStatus rv = SECSuccess; | |
| 2121 if (error == OK) { | |
| 2122 // Synchronous success. | |
| 2123 int result = ImportDBCertAndKey(result_certificate, | |
| 2124 result_private_key); | |
| 2125 if (result == OK) { | |
| 2126 set_domain_bound_cert_type(domain_bound_cert_type_); | |
| 2127 } else { | |
| 2128 rv = SECFailure; | |
| 2129 } | |
| 2130 } else { | |
| 2131 rv = SECFailure; // Synchronous failure. | |
| 2132 } | |
| 2133 | |
| 2134 int cert_count = (rv == SECSuccess) ? 1 : 0; | |
| 2135 net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2136 make_scoped_refptr(new NetLogIntegerParameter("cert_count", | |
| 2137 cert_count))); | |
| 2138 return rv; | |
| 2139 } | |
| 2140 | |
| 2141 #if defined(NSS_PLATFORM_CLIENT_AUTH) | |
| 2142 // static | |
| 2143 // NSS calls this if a client certificate is needed. | |
| 2144 SECStatus SSLClientSocketNSS::PlatformClientAuthHandler( | |
| 2145 void* arg, | |
| 2146 PRFileDesc* socket, | |
| 2147 CERTDistNames* ca_names, | |
| 2148 CERTCertList** result_certs, | |
| 2149 void** result_private_key, | |
| 2150 CERTCertificate** result_nss_certificate, | |
| 2151 SECKEYPrivateKey** result_nss_private_key) { | |
| 2152 SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg); | |
| 2153 | |
| 2154 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED, NULL); | |
| 2155 | |
| 2156 const SECItem* cert_types = SSL_GetRequestedClientCertificateTypes(socket); | |
| 2157 | |
| 2158 // Check if a domain-bound certificate is requested. | |
| 2159 if (DomainBoundCertNegotiated(socket)) { | |
| 2160 return that->DomainBoundClientAuthHandler( | |
| 2161 cert_types, result_nss_certificate, result_nss_private_key); | |
| 2162 } | |
| 2163 | |
| 2164 that->client_auth_cert_needed_ = !that->ssl_config_.send_client_cert; | |
| 2165 #if defined(OS_WIN) | |
| 2166 if (that->ssl_config_.send_client_cert) { | |
| 2167 if (that->ssl_config_.client_cert) { | |
| 2168 PCCERT_CONTEXT cert_context = | |
| 2169 that->ssl_config_.client_cert->os_cert_handle(); | |
| 2170 | |
| 2171 HCRYPTPROV_OR_NCRYPT_KEY_HANDLE crypt_prov = 0; | |
| 2172 DWORD key_spec = 0; | |
| 2173 BOOL must_free = FALSE; | |
| 2174 BOOL acquired_key = CryptAcquireCertificatePrivateKey( | |
| 2175 cert_context, CRYPT_ACQUIRE_CACHE_FLAG, NULL, | |
| 2176 &crypt_prov, &key_spec, &must_free); | |
| 2177 | |
| 2178 if (acquired_key) { | |
| 2179 // Since we passed CRYPT_ACQUIRE_CACHE_FLAG, |must_free| must be false | |
| 2180 // according to the MSDN documentation. | |
| 2181 CHECK_EQ(must_free, FALSE); | |
| 2182 DCHECK_NE(key_spec, CERT_NCRYPT_KEY_SPEC); | |
| 2183 | |
| 2184 SECItem der_cert; | |
| 2185 der_cert.type = siDERCertBuffer; | |
| 2186 der_cert.data = cert_context->pbCertEncoded; | |
| 2187 der_cert.len = cert_context->cbCertEncoded; | |
| 2188 | |
| 2189 // TODO(rsleevi): Error checking for NSS allocation errors. | |
| 2190 CERTCertDBHandle* db_handle = CERT_GetDefaultCertDB(); | |
| 2191 CERTCertificate* user_cert = CERT_NewTempCertificate( | |
| 2192 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 2193 if (!user_cert) { | |
| 2194 // Importing the certificate can fail for reasons including a serial | |
| 2195 // number collision. See crbug.com/97355. | |
| 2196 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2197 make_scoped_refptr(new NetLogIntegerParameter("cert_count", 0))); | |
| 2198 return SECFailure; | |
| 2199 } | |
| 2200 CERTCertList* cert_chain = CERT_NewCertList(); | |
| 2201 CERT_AddCertToListTail(cert_chain, user_cert); | |
| 2202 | |
| 2203 // Add the intermediates. | |
| 2204 X509Certificate::OSCertHandles intermediates = | |
| 2205 that->ssl_config_.client_cert->GetIntermediateCertificates(); | |
| 2206 for (X509Certificate::OSCertHandles::const_iterator it = | |
| 2207 intermediates.begin(); it != intermediates.end(); ++it) { | |
| 2208 der_cert.data = (*it)->pbCertEncoded; | |
| 2209 der_cert.len = (*it)->cbCertEncoded; | |
| 2210 | |
| 2211 CERTCertificate* intermediate = CERT_NewTempCertificate( | |
| 2212 db_handle, &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 2213 if (!intermediate) { | |
| 2214 CERT_DestroyCertList(cert_chain); | |
| 2215 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2216 make_scoped_refptr(new NetLogIntegerParameter("cert_count", | |
| 2217 0))); | |
| 2218 return SECFailure; | |
| 2219 } | |
| 2220 CERT_AddCertToListTail(cert_chain, intermediate); | |
| 2221 } | |
| 2222 PCERT_KEY_CONTEXT key_context = reinterpret_cast<PCERT_KEY_CONTEXT>( | |
| 2223 PORT_ZAlloc(sizeof(CERT_KEY_CONTEXT))); | |
| 2224 key_context->cbSize = sizeof(*key_context); | |
| 2225 // NSS will free this context when no longer in use, but the | |
| 2226 // |must_free| result from CryptAcquireCertificatePrivateKey was false | |
| 2227 // so we increment the refcount to negate NSS's future decrement. | |
| 2228 CryptContextAddRef(crypt_prov, NULL, 0); | |
| 2229 key_context->hCryptProv = crypt_prov; | |
| 2230 key_context->dwKeySpec = key_spec; | |
| 2231 *result_private_key = key_context; | |
| 2232 *result_certs = cert_chain; | |
| 2233 | |
| 2234 int cert_count = 1 + intermediates.size(); | |
| 2235 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2236 make_scoped_refptr(new NetLogIntegerParameter("cert_count", | |
| 2237 cert_count))); | |
| 2238 return SECSuccess; | |
| 2239 } | |
| 2240 LOG(WARNING) << "Client cert found without private key"; | |
| 2241 } | |
| 2242 // Send no client certificate. | |
| 2243 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2244 make_scoped_refptr(new NetLogIntegerParameter("cert_count", 0))); | |
| 2245 return SECFailure; | |
| 2246 } | |
| 2247 | |
| 2248 that->client_certs_.clear(); | |
| 2249 | |
| 2250 std::vector<CERT_NAME_BLOB> issuer_list(ca_names->nnames); | |
| 2251 for (int i = 0; i < ca_names->nnames; ++i) { | |
| 2252 issuer_list[i].cbData = ca_names->names[i].len; | |
| 2253 issuer_list[i].pbData = ca_names->names[i].data; | |
| 2254 } | |
| 2255 | |
| 2256 // Client certificates of the user are in the "MY" system certificate store. | |
| 2257 HCERTSTORE my_cert_store = CertOpenSystemStore(NULL, L"MY"); | |
| 2258 if (!my_cert_store) { | |
| 2259 LOG(ERROR) << "Could not open the \"MY\" system certificate store: " | |
| 2260 << GetLastError(); | |
| 2261 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2262 make_scoped_refptr(new NetLogIntegerParameter("cert_count", 0))); | |
| 2263 return SECFailure; | |
| 2264 } | |
| 2265 | |
| 2266 // Enumerate the client certificates. | |
| 2267 CERT_CHAIN_FIND_BY_ISSUER_PARA find_by_issuer_para; | |
| 2268 memset(&find_by_issuer_para, 0, sizeof(find_by_issuer_para)); | |
| 2269 find_by_issuer_para.cbSize = sizeof(find_by_issuer_para); | |
| 2270 find_by_issuer_para.pszUsageIdentifier = szOID_PKIX_KP_CLIENT_AUTH; | |
| 2271 find_by_issuer_para.cIssuer = ca_names->nnames; | |
| 2272 find_by_issuer_para.rgIssuer = ca_names->nnames ? &issuer_list[0] : NULL; | |
| 2273 find_by_issuer_para.pfnFindCallback = ClientCertFindCallback; | |
| 2274 | |
| 2275 PCCERT_CHAIN_CONTEXT chain_context = NULL; | |
| 2276 DWORD find_flags = CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG | | |
| 2277 CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG; | |
| 2278 | |
| 2279 for (;;) { | |
| 2280 // Find a certificate chain. | |
| 2281 chain_context = CertFindChainInStore(my_cert_store, | |
| 2282 X509_ASN_ENCODING, | |
| 2283 find_flags, | |
| 2284 CERT_CHAIN_FIND_BY_ISSUER, | |
| 2285 &find_by_issuer_para, | |
| 2286 chain_context); | |
| 2287 if (!chain_context) { | |
| 2288 DWORD err = GetLastError(); | |
| 2289 if (err != CRYPT_E_NOT_FOUND) | |
| 2290 DLOG(ERROR) << "CertFindChainInStore failed: " << err; | |
| 2291 break; | |
| 2292 } | |
| 2293 | |
| 2294 // Get the leaf certificate. | |
| 2295 PCCERT_CONTEXT cert_context = | |
| 2296 chain_context->rgpChain[0]->rgpElement[0]->pCertContext; | |
| 2297 // Create a copy the handle, so that we can close the "MY" certificate store | |
| 2298 // before returning from this function. | |
| 2299 PCCERT_CONTEXT cert_context2; | |
| 2300 BOOL ok = CertAddCertificateContextToStore(NULL, cert_context, | |
| 2301 CERT_STORE_ADD_USE_EXISTING, | |
| 2302 &cert_context2); | |
| 2303 if (!ok) { | |
| 2304 NOTREACHED(); | |
| 2305 continue; | |
| 2306 } | |
| 2307 | |
| 2308 // Copy the rest of the chain. Copying the chain stops gracefully if an | |
| 2309 // error is encountered, with the partial chain being used as the | |
| 2310 // intermediates, as opposed to failing to consider the client certificate | |
| 2311 // at all. | |
| 2312 net::X509Certificate::OSCertHandles intermediates; | |
| 2313 for (DWORD i = 1; i < chain_context->rgpChain[0]->cElement; i++) { | |
| 2314 PCCERT_CONTEXT intermediate_copy; | |
| 2315 ok = CertAddCertificateContextToStore( | |
| 2316 NULL, chain_context->rgpChain[0]->rgpElement[i]->pCertContext, | |
| 2317 CERT_STORE_ADD_USE_EXISTING, &intermediate_copy); | |
| 2318 if (!ok) { | |
| 2319 NOTREACHED(); | |
| 2320 break; | |
| 2321 } | |
| 2322 intermediates.push_back(intermediate_copy); | |
| 2323 } | |
| 2324 | |
| 2325 scoped_refptr<X509Certificate> cert = X509Certificate::CreateFromHandle( | |
| 2326 cert_context2, intermediates); | |
| 2327 that->client_certs_.push_back(cert); | |
| 2328 | |
| 2329 X509Certificate::FreeOSCertHandle(cert_context2); | |
| 2330 for (net::X509Certificate::OSCertHandles::iterator it = | |
| 2331 intermediates.begin(); it != intermediates.end(); ++it) { | |
| 2332 net::X509Certificate::FreeOSCertHandle(*it); | |
| 2333 } | |
| 2334 } | |
| 2335 | |
| 2336 BOOL ok = CertCloseStore(my_cert_store, CERT_CLOSE_STORE_CHECK_FLAG); | |
| 2337 DCHECK(ok); | |
| 2338 | |
| 2339 // Tell NSS to suspend the client authentication. We will then abort the | |
| 2340 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 2341 return SECWouldBlock; | |
| 2342 #elif defined(OS_MACOSX) | |
| 2343 if (that->ssl_config_.send_client_cert) { | |
| 2344 if (that->ssl_config_.client_cert) { | |
| 2345 OSStatus os_error = noErr; | |
| 2346 SecIdentityRef identity = NULL; | |
| 2347 SecKeyRef private_key = NULL; | |
| 2348 CFArrayRef chain = | |
| 2349 that->ssl_config_.client_cert->CreateClientCertificateChain(); | |
| 2350 if (chain) { | |
| 2351 identity = reinterpret_cast<SecIdentityRef>( | |
| 2352 const_cast<void*>(CFArrayGetValueAtIndex(chain, 0))); | |
| 2353 } | |
| 2354 if (identity) | |
| 2355 os_error = SecIdentityCopyPrivateKey(identity, &private_key); | |
| 2356 | |
| 2357 if (chain && identity && os_error == noErr) { | |
| 2358 // TODO(rsleevi): Error checking for NSS allocation errors. | |
| 2359 *result_certs = CERT_NewCertList(); | |
| 2360 *result_private_key = private_key; | |
| 2361 | |
| 2362 for (CFIndex i = 0; i < CFArrayGetCount(chain); ++i) { | |
| 2363 CSSM_DATA cert_data; | |
| 2364 SecCertificateRef cert_ref; | |
| 2365 if (i == 0) { | |
| 2366 cert_ref = that->ssl_config_.client_cert->os_cert_handle(); | |
| 2367 } else { | |
| 2368 cert_ref = reinterpret_cast<SecCertificateRef>( | |
| 2369 const_cast<void*>(CFArrayGetValueAtIndex(chain, i))); | |
| 2370 } | |
| 2371 os_error = SecCertificateGetData(cert_ref, &cert_data); | |
| 2372 if (os_error != noErr) | |
| 2373 break; | |
| 2374 | |
| 2375 SECItem der_cert; | |
| 2376 der_cert.type = siDERCertBuffer; | |
| 2377 der_cert.data = cert_data.Data; | |
| 2378 der_cert.len = cert_data.Length; | |
| 2379 CERTCertificate* nss_cert = CERT_NewTempCertificate( | |
| 2380 CERT_GetDefaultCertDB(), &der_cert, NULL, PR_FALSE, PR_TRUE); | |
| 2381 if (!nss_cert) { | |
| 2382 // In the event of an NSS error we make up an OS error and reuse | |
| 2383 // the error handling, below. | |
| 2384 os_error = errSecCreateChainFailed; | |
| 2385 break; | |
| 2386 } | |
| 2387 CERT_AddCertToListTail(*result_certs, nss_cert); | |
| 2388 } | |
| 2389 } | |
| 2390 if (os_error == noErr) { | |
| 2391 int cert_count = 0; | |
| 2392 if (chain) { | |
| 2393 cert_count = CFArrayGetCount(chain); | |
| 2394 CFRelease(chain); | |
| 2395 } | |
| 2396 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2397 make_scoped_refptr(new NetLogIntegerParameter("cert_count", | |
| 2398 cert_count))); | |
| 2399 return SECSuccess; | |
| 2400 } | |
| 2401 OSSTATUS_LOG(WARNING, os_error) | |
| 2402 << "Client cert found, but could not be used"; | |
| 2403 if (*result_certs) { | |
| 2404 CERT_DestroyCertList(*result_certs); | |
| 2405 *result_certs = NULL; | |
| 2406 } | |
| 2407 if (*result_private_key) | |
| 2408 *result_private_key = NULL; | |
| 2409 if (private_key) | |
| 2410 CFRelease(private_key); | |
| 2411 if (chain) | |
| 2412 CFRelease(chain); | |
| 2413 } | |
| 2414 // Send no client certificate. | |
| 2415 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2416 make_scoped_refptr(new NetLogIntegerParameter("cert_count", 0))); | |
| 2417 return SECFailure; | |
| 2418 } | |
| 2419 | |
| 2420 that->client_certs_.clear(); | |
| 2421 | |
| 2422 // First, get the cert issuer names allowed by the server. | |
| 2423 std::vector<CertPrincipal> valid_issuers; | |
| 2424 int n = ca_names->nnames; | |
| 2425 for (int i = 0; i < n; i++) { | |
| 2426 // Parse each name into a CertPrincipal object. | |
| 2427 CertPrincipal p; | |
| 2428 if (p.ParseDistinguishedName(ca_names->names[i].data, | |
| 2429 ca_names->names[i].len)) { | |
| 2430 valid_issuers.push_back(p); | |
| 2431 } | |
| 2432 } | |
| 2433 | |
| 2434 // Now get the available client certs whose issuers are allowed by the server. | |
| 2435 X509Certificate::GetSSLClientCertificates(that->host_and_port_.host(), | |
| 2436 valid_issuers, | |
| 2437 &that->client_certs_); | |
| 2438 | |
| 2439 // Tell NSS to suspend the client authentication. We will then abort the | |
| 2440 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 2441 return SECWouldBlock; | |
| 2442 #else | |
| 2443 return SECFailure; | |
| 2444 #endif | |
| 2445 } | |
| 2446 | |
| 2447 #else // NSS_PLATFORM_CLIENT_AUTH | |
| 2448 | |
| 2449 // static | |
| 2450 // NSS calls this if a client certificate is needed. | |
| 2451 // Based on Mozilla's NSS_GetClientAuthData. | |
| 2452 SECStatus SSLClientSocketNSS::ClientAuthHandler( | |
| 2453 void* arg, | |
| 2454 PRFileDesc* socket, | |
| 2455 CERTDistNames* ca_names, | |
| 2456 CERTCertificate** result_certificate, | |
| 2457 SECKEYPrivateKey** result_private_key) { | |
| 2458 SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg); | |
| 2459 | |
| 2460 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_REQUESTED, NULL); | |
| 2461 | |
| 2462 const SECItem* cert_types = SSL_GetRequestedClientCertificateTypes(socket); | |
| 2463 | |
| 2464 // Check if a domain-bound certificate is requested. | |
| 2465 if (DomainBoundCertNegotiated(socket)) { | |
| 2466 return that->DomainBoundClientAuthHandler( | |
| 2467 cert_types, result_certificate, result_private_key); | |
| 2468 } | |
| 2469 | |
| 2470 // Regular client certificate requested. | |
| 2471 that->client_auth_cert_needed_ = !that->ssl_config_.send_client_cert; | |
| 2472 void* wincx = SSL_RevealPinArg(socket); | |
| 2473 | |
| 2474 // Second pass: a client certificate should have been selected. | |
| 2475 if (that->ssl_config_.send_client_cert) { | |
| 2476 if (that->ssl_config_.client_cert) { | |
| 2477 CERTCertificate* cert = CERT_DupCertificate( | |
| 2478 that->ssl_config_.client_cert->os_cert_handle()); | |
| 2479 SECKEYPrivateKey* privkey = PK11_FindKeyByAnyCert(cert, wincx); | |
| 2480 if (privkey) { | |
| 2481 // TODO(jsorianopastor): We should wait for server certificate | |
| 2482 // verification before sending our credentials. See | |
| 2483 // http://crbug.com/13934. | |
| 2484 *result_certificate = cert; | |
| 2485 *result_private_key = privkey; | |
| 2486 // A cert_count of -1 means the number of certificates is unknown. | |
| 2487 // NSS will construct the certificate chain. | |
| 2488 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2489 make_scoped_refptr(new NetLogIntegerParameter("cert_count", -1))); | |
| 2490 return SECSuccess; | |
| 2491 } | |
| 2492 LOG(WARNING) << "Client cert found without private key"; | |
| 2493 } | |
| 2494 // Send no client certificate. | |
| 2495 that->net_log_.AddEvent(NetLog::TYPE_SSL_CLIENT_CERT_PROVIDED, | |
| 2496 make_scoped_refptr(new NetLogIntegerParameter("cert_count", 0))); | |
| 2497 return SECFailure; | |
| 2498 } | |
| 2499 | |
| 2500 // Iterate over all client certificates. | |
| 2501 CERTCertList* client_certs = CERT_FindUserCertsByUsage( | |
| 2502 CERT_GetDefaultCertDB(), certUsageSSLClient, | |
| 2503 PR_FALSE, PR_FALSE, wincx); | |
| 2504 if (client_certs) { | |
| 2505 for (CERTCertListNode* node = CERT_LIST_HEAD(client_certs); | |
| 2506 !CERT_LIST_END(node, client_certs); | |
| 2507 node = CERT_LIST_NEXT(node)) { | |
| 2508 // Only offer unexpired certificates. | |
| 2509 if (CERT_CheckCertValidTimes(node->cert, PR_Now(), PR_TRUE) != | |
| 2510 secCertTimeValid) | |
| 2511 continue; | |
| 2512 // Filter by issuer. | |
| 2513 // | |
| 2514 // TODO(davidben): This does a binary comparison of the DER-encoded | |
| 2515 // issuers. We should match according to RFC 5280 sec. 7.1. We should find | |
| 2516 // an appropriate NSS function or add one if needbe. | |
| 2517 if (ca_names->nnames && | |
| 2518 NSS_CmpCertChainWCANames(node->cert, ca_names) != SECSuccess) | |
| 2519 continue; | |
| 2520 X509Certificate* x509_cert = X509Certificate::CreateFromHandle( | |
| 2521 node->cert, net::X509Certificate::OSCertHandles()); | |
| 2522 that->client_certs_.push_back(x509_cert); | |
| 2523 } | |
| 2524 CERT_DestroyCertList(client_certs); | |
| 2525 } | |
| 2526 | |
| 2527 // Tell NSS to suspend the client authentication. We will then abort the | |
| 2528 // handshake by returning ERR_SSL_CLIENT_AUTH_CERT_NEEDED. | |
| 2529 return SECWouldBlock; | |
| 2530 } | |
| 2531 #endif // NSS_PLATFORM_CLIENT_AUTH | |
| 2532 | |
| 2533 void SSLClientSocketNSS::RecordDomainBoundCertSupport() const { | |
| 2534 PRBool last_handshake_resumed; | |
| 2535 SECStatus ok = SSL_HandshakeResumedSession(nss_fd_, &last_handshake_resumed); | |
| 2536 if (ok != SECSuccess || last_handshake_resumed) | |
| 2537 return; | |
| 2538 | |
| 2539 // Since this enum is used for a histogram, do not change or re-use values. | |
| 2540 enum { | |
| 2541 DISABLED = 0, | |
| 2542 CLIENT_ONLY = 1, | |
| 2543 CLIENT_AND_SERVER = 2, | |
| 2544 DOMAIN_BOUND_CERT_USAGE_MAX | |
| 2545 } supported = DISABLED; | |
| 2546 #ifdef SSL_ENABLE_OB_CERTS | |
| 2547 if (domain_bound_cert_xtn_negotiated_) | |
| 2548 supported = CLIENT_AND_SERVER; | |
| 2549 else if (ssl_config_.domain_bound_certs_enabled) | |
| 2550 supported = CLIENT_ONLY; | |
| 2551 #endif | |
| 2552 UMA_HISTOGRAM_ENUMERATION("DomainBoundCerts.Support", supported, | |
| 2553 DOMAIN_BOUND_CERT_USAGE_MAX); | |
| 2554 } | |
| 2555 | |
| 2556 // static | |
| 2557 // NSS calls this when handshake is completed. | |
| 2558 // After the SSL handshake is finished, use CertVerifier to verify | |
| 2559 // the saved server certificate. | |
| 2560 void SSLClientSocketNSS::HandshakeCallback(PRFileDesc* socket, | |
| 2561 void* arg) { | |
| 2562 SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg); | |
| 2563 | |
| 2564 that->handshake_callback_called_ = true; | |
| 2565 | |
| 2566 that->RecordDomainBoundCertSupport(); | |
| 2567 that->UpdateServerCert(); | |
| 2568 that->UpdateConnectionStatus(); | |
| 2569 } | |
| 2570 | |
| 2571 // NextProtoCallback is called by NSS during the handshake, if the server | |
| 2572 // supports NPN, to select a protocol from the list that the server offered. | |
| 2573 // See the comment in net/third_party/nss/ssl/ssl.h for the meanings of the | |
| 2574 // arguments. | |
| 2575 // static | |
| 2576 SECStatus | |
| 2577 SSLClientSocketNSS::NextProtoCallback(void* arg, | |
| 2578 PRFileDesc* nss_fd, | |
| 2579 const unsigned char* protos, | |
| 2580 unsigned int protos_len, | |
| 2581 unsigned char* proto_out, | |
| 2582 unsigned int* proto_out_len, | |
| 2583 unsigned int proto_max_len) { | |
| 2584 SSLClientSocketNSS* that = reinterpret_cast<SSLClientSocketNSS*>(arg); | |
| 2585 | |
| 2586 // For each protocol in server preference, see if we support it. | |
| 2587 for (unsigned int i = 0; i < protos_len; ) { | |
| 2588 const size_t len = protos[i]; | |
| 2589 for (std::vector<std::string>::const_iterator | |
| 2590 j = that->ssl_config_.next_protos.begin(); | |
| 2591 j != that->ssl_config_.next_protos.end(); j++) { | |
| 2592 // Having very long elements in the |next_protos| vector isn't a disaster | |
| 2593 // because they'll never be selected, but it does indicate an error | |
| 2594 // somewhere. | |
| 2595 DCHECK_LT(j->size(), 256u); | |
| 2596 | |
| 2597 if (j->size() == len && | |
| 2598 memcmp(&protos[i + 1], j->data(), len) == 0) { | |
| 2599 that->next_proto_status_ = kNextProtoNegotiated; | |
| 2600 that->next_proto_ = *j; | |
| 2601 break; | |
| 2602 } | |
| 2603 } | |
| 2604 | |
| 2605 if (that->next_proto_status_ == kNextProtoNegotiated) | |
| 2606 break; | |
| 2607 | |
| 2608 // NSS checks that the data in |protos| is well formed, so we know that | |
| 2609 // this doesn't cause us to jump off the end of the buffer. | |
| 2610 i += len + 1; | |
| 2611 } | |
| 2612 | |
| 2613 that->server_protos_.assign( | |
| 2614 reinterpret_cast<const char*>(protos), protos_len); | |
| 2615 | |
| 2616 // If we didn't find a protocol, we select the first one from our list. | |
| 2617 if (that->next_proto_status_ != kNextProtoNegotiated) { | |
| 2618 that->next_proto_status_ = kNextProtoNoOverlap; | |
| 2619 that->next_proto_ = that->ssl_config_.next_protos[0]; | |
| 2620 } | |
| 2621 | |
| 2622 if (that->next_proto_.size() > proto_max_len) { | |
| 2623 PORT_SetError(SEC_ERROR_OUTPUT_LEN); | |
| 2624 return SECFailure; | |
| 2625 } | |
| 2626 memcpy(proto_out, that->next_proto_.data(), that->next_proto_.size()); | |
| 2627 *proto_out_len = that->next_proto_.size(); | |
| 2628 return SECSuccess; | |
| 2629 } | |
| 2630 | |
| 2631 void SSLClientSocketNSS::EnsureThreadIdAssigned() const { | 3625 void SSLClientSocketNSS::EnsureThreadIdAssigned() const { |
| 2632 base::AutoLock auto_lock(lock_); | 3626 base::AutoLock auto_lock(lock_); |
| 2633 if (valid_thread_id_ != base::kInvalidThreadId) | 3627 if (valid_thread_id_ != base::kInvalidThreadId) |
| 2634 return; | 3628 return; |
| 2635 valid_thread_id_ = base::PlatformThread::CurrentId(); | 3629 valid_thread_id_ = base::PlatformThread::CurrentId(); |
| 2636 } | 3630 } |
| 2637 | 3631 |
| 2638 bool SSLClientSocketNSS::CalledOnValidThread() const { | 3632 bool SSLClientSocketNSS::CalledOnValidThread() const { |
| 2639 EnsureThreadIdAssigned(); | 3633 EnsureThreadIdAssigned(); |
| 2640 base::AutoLock auto_lock(lock_); | 3634 base::AutoLock auto_lock(lock_); |
| 2641 return valid_thread_id_ == base::PlatformThread::CurrentId(); | 3635 return valid_thread_id_ == base::PlatformThread::CurrentId(); |
| 2642 } | 3636 } |
| 2643 | 3637 |
| 2644 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const { | 3638 ServerBoundCertService* SSLClientSocketNSS::GetServerBoundCertService() const { |
| 2645 return server_bound_cert_service_; | 3639 return server_bound_cert_service_; |
| 2646 } | 3640 } |
| 2647 | 3641 |
| 2648 } // namespace net | 3642 } // namespace net |
| OLD | NEW |