1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "net/socket/ssl_client_socket.h" 6 7 #include "base/callback_helpers.h" 8 #include "base/memory/ref_counted.h" 9 #include "base/run_loop.h" 10 #include "base/time/time.h" 11 #include "net/base/address_list.h" 12 #include "net/base/io_buffer.h" 13 #include "net/base/net_errors.h" 14 #include "net/base/net_log.h" 15 #include "net/base/net_log_unittest.h" 16 #include "net/base/test_completion_callback.h" 17 #include "net/base/test_data_directory.h" 18 #include "net/cert/mock_cert_verifier.h" 19 #include "net/cert/test_root_certs.h" 20 #include "net/dns/host_resolver.h" 21 #include "net/http/transport_security_state.h" 22 #include "net/socket/client_socket_factory.h" 23 #include "net/socket/client_socket_handle.h" 24 #include "net/socket/socket_test_util.h" 25 #include "net/socket/tcp_client_socket.h" 26 #include "net/ssl/default_server_bound_cert_store.h" 27 #include "net/ssl/ssl_cert_request_info.h" 28 #include "net/ssl/ssl_config_service.h" 29 #include "net/test/cert_test_util.h" 30 #include "net/test/spawned_test_server/spawned_test_server.h" 31 #include "testing/gtest/include/gtest/gtest.h" 32 #include "testing/platform_test.h" 33 34 //----------------------------------------------------------------------------- 35 36 namespace net { 37 38 namespace { 39 40 const SSLConfig kDefaultSSLConfig; 41 42 // WrappedStreamSocket is a base class that wraps an existing StreamSocket, 43 // forwarding the Socket and StreamSocket interfaces to the underlying 44 // transport. 45 // This is to provide a common base class for subclasses to override specific 46 // StreamSocket methods for testing, while still communicating with a 'real' 47 // StreamSocket. 48 class WrappedStreamSocket : public StreamSocket { 49 public: 50 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport) 51 : transport_(transport.Pass()) {} 52 virtual ~WrappedStreamSocket() {} 53 54 // StreamSocket implementation: 55 virtual int Connect(const CompletionCallback& callback) OVERRIDE { 56 return transport_->Connect(callback); 57 } 58 virtual void Disconnect() OVERRIDE { transport_->Disconnect(); } 59 virtual bool IsConnected() const OVERRIDE { 60 return transport_->IsConnected(); 61 } 62 virtual bool IsConnectedAndIdle() const OVERRIDE { 63 return transport_->IsConnectedAndIdle(); 64 } 65 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE { 66 return transport_->GetPeerAddress(address); 67 } 68 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE { 69 return transport_->GetLocalAddress(address); 70 } 71 virtual const BoundNetLog& NetLog() const OVERRIDE { 72 return transport_->NetLog(); 73 } 74 virtual void SetSubresourceSpeculation() OVERRIDE { 75 transport_->SetSubresourceSpeculation(); 76 } 77 virtual void SetOmniboxSpeculation() OVERRIDE { 78 transport_->SetOmniboxSpeculation(); 79 } 80 virtual bool WasEverUsed() const OVERRIDE { 81 return transport_->WasEverUsed(); 82 } 83 virtual bool UsingTCPFastOpen() const OVERRIDE { 84 return transport_->UsingTCPFastOpen(); 85 } 86 virtual bool WasNpnNegotiated() const OVERRIDE { 87 return transport_->WasNpnNegotiated(); 88 } 89 virtual NextProto GetNegotiatedProtocol() const OVERRIDE { 90 return transport_->GetNegotiatedProtocol(); 91 } 92 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE { 93 return transport_->GetSSLInfo(ssl_info); 94 } 95 96 // Socket implementation: 97 virtual int Read(IOBuffer* buf, 98 int buf_len, 99 const CompletionCallback& callback) OVERRIDE { 100 return transport_->Read(buf, buf_len, callback); 101 } 102 virtual int Write(IOBuffer* buf, 103 int buf_len, 104 const CompletionCallback& callback) OVERRIDE { 105 return transport_->Write(buf, buf_len, callback); 106 } 107 virtual int SetReceiveBufferSize(int32 size) OVERRIDE { 108 return transport_->SetReceiveBufferSize(size); 109 } 110 virtual int SetSendBufferSize(int32 size) OVERRIDE { 111 return transport_->SetSendBufferSize(size); 112 } 113 114 protected: 115 scoped_ptr<StreamSocket> transport_; 116 }; 117 118 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that 119 // will ensure a certain amount of data is internally buffered before 120 // satisfying a Read() request. It exists to mimic OS-level internal 121 // buffering, but in a way to guarantee that X number of bytes will be 122 // returned to callers of Read(), regardless of how quickly the OS receives 123 // them from the TestServer. 124 class ReadBufferingStreamSocket : public WrappedStreamSocket { 125 public: 126 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport); 127 virtual ~ReadBufferingStreamSocket() {} 128 129 // Socket implementation: 130 virtual int Read(IOBuffer* buf, 131 int buf_len, 132 const CompletionCallback& callback) OVERRIDE; 133 134 // Sets the internal buffer to |size|. This must not be greater than 135 // the largest value supplied to Read() - that is, it does not handle 136 // having "leftovers" at the end of Read(). 137 // Each call to Read() will be prevented from completion until at least 138 // |size| data has been read. 139 // Set to 0 to turn off buffering, causing Read() to transparently 140 // read via the underlying transport. 141 void SetBufferSize(int size); 142 143 private: 144 enum State { 145 STATE_NONE, 146 STATE_READ, 147 STATE_READ_COMPLETE, 148 }; 149 150 int DoLoop(int result); 151 int DoRead(); 152 int DoReadComplete(int result); 153 void OnReadCompleted(int result); 154 155 State state_; 156 scoped_refptr<GrowableIOBuffer> read_buffer_; 157 int buffer_size_; 158 159 scoped_refptr<IOBuffer> user_read_buf_; 160 CompletionCallback user_read_callback_; 161 }; 162 163 ReadBufferingStreamSocket::ReadBufferingStreamSocket( 164 scoped_ptr<StreamSocket> transport) 165 : WrappedStreamSocket(transport.Pass()), 166 read_buffer_(new GrowableIOBuffer()), 167 buffer_size_(0) {} 168 169 void ReadBufferingStreamSocket::SetBufferSize(int size) { 170 DCHECK(!user_read_buf_.get()); 171 buffer_size_ = size; 172 read_buffer_->SetCapacity(size); 173 } 174 175 int ReadBufferingStreamSocket::Read(IOBuffer* buf, 176 int buf_len, 177 const CompletionCallback& callback) { 178 if (buffer_size_ == 0) 179 return transport_->Read(buf, buf_len, callback); 180 181 if (buf_len < buffer_size_) 182 return ERR_UNEXPECTED; 183 184 state_ = STATE_READ; 185 user_read_buf_ = buf; 186 int result = DoLoop(OK); 187 if (result == ERR_IO_PENDING) 188 user_read_callback_ = callback; 189 else 190 user_read_buf_ = NULL; 191 return result; 192 } 193 194 int ReadBufferingStreamSocket::DoLoop(int result) { 195 int rv = result; 196 do { 197 State current_state = state_; 198 state_ = STATE_NONE; 199 switch (current_state) { 200 case STATE_READ: 201 rv = DoRead(); 202 break; 203 case STATE_READ_COMPLETE: 204 rv = DoReadComplete(rv); 205 break; 206 case STATE_NONE: 207 default: 208 NOTREACHED() << "Unexpected state: " << current_state; 209 rv = ERR_UNEXPECTED; 210 break; 211 } 212 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE); 213 return rv; 214 } 215 216 int ReadBufferingStreamSocket::DoRead() { 217 state_ = STATE_READ_COMPLETE; 218 int rv = 219 transport_->Read(read_buffer_.get(), 220 read_buffer_->RemainingCapacity(), 221 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted, 222 base::Unretained(this))); 223 return rv; 224 } 225 226 int ReadBufferingStreamSocket::DoReadComplete(int result) { 227 state_ = STATE_NONE; 228 if (result <= 0) 229 return result; 230 231 read_buffer_->set_offset(read_buffer_->offset() + result); 232 if (read_buffer_->RemainingCapacity() > 0) { 233 state_ = STATE_READ; 234 return OK; 235 } 236 237 memcpy(user_read_buf_->data(), 238 read_buffer_->StartOfBuffer(), 239 read_buffer_->capacity()); 240 read_buffer_->set_offset(0); 241 return read_buffer_->capacity(); 242 } 243 244 void ReadBufferingStreamSocket::OnReadCompleted(int result) { 245 result = DoLoop(result); 246 if (result == ERR_IO_PENDING) 247 return; 248 249 user_read_buf_ = NULL; 250 base::ResetAndReturn(&user_read_callback_).Run(result); 251 } 252 253 // Simulates synchronously receiving an error during Read() or Write() 254 class SynchronousErrorStreamSocket : public WrappedStreamSocket { 255 public: 256 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport); 257 virtual ~SynchronousErrorStreamSocket() {} 258 259 // Socket implementation: 260 virtual int Read(IOBuffer* buf, 261 int buf_len, 262 const CompletionCallback& callback) OVERRIDE; 263 virtual int Write(IOBuffer* buf, 264 int buf_len, 265 const CompletionCallback& callback) OVERRIDE; 266 267 // Sets the next Read() call and all future calls to return |error|. 268 // If there is already a pending asynchronous read, the configured error 269 // will not be returned until that asynchronous read has completed and Read() 270 // is called again. 271 void SetNextReadError(Error error) { 272 DCHECK_GE(0, error); 273 have_read_error_ = true; 274 pending_read_error_ = error; 275 } 276 277 // Sets the next Write() call and all future calls to return |error|. 278 // If there is already a pending asynchronous write, the configured error 279 // will not be returned until that asynchronous write has completed and 280 // Write() is called again. 281 void SetNextWriteError(Error error) { 282 DCHECK_GE(0, error); 283 have_write_error_ = true; 284 pending_write_error_ = error; 285 } 286 287 private: 288 bool have_read_error_; 289 int pending_read_error_; 290 291 bool have_write_error_; 292 int pending_write_error_; 293 294 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket); 295 }; 296 297 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket( 298 scoped_ptr<StreamSocket> transport) 299 : WrappedStreamSocket(transport.Pass()), 300 have_read_error_(false), 301 pending_read_error_(OK), 302 have_write_error_(false), 303 pending_write_error_(OK) {} 304 305 int SynchronousErrorStreamSocket::Read(IOBuffer* buf, 306 int buf_len, 307 const CompletionCallback& callback) { 308 if (have_read_error_) 309 return pending_read_error_; 310 return transport_->Read(buf, buf_len, callback); 311 } 312 313 int SynchronousErrorStreamSocket::Write(IOBuffer* buf, 314 int buf_len, 315 const CompletionCallback& callback) { 316 if (have_write_error_) 317 return pending_write_error_; 318 return transport_->Write(buf, buf_len, callback); 319 } 320 321 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the 322 // underlying transport needing to complete things asynchronously in a 323 // deterministic manner (e.g.: independent of the TestServer and the OS's 324 // semantics). 325 class FakeBlockingStreamSocket : public WrappedStreamSocket { 326 public: 327 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport); 328 virtual ~FakeBlockingStreamSocket() {} 329 330 // Socket implementation: 331 virtual int Read(IOBuffer* buf, 332 int buf_len, 333 const CompletionCallback& callback) OVERRIDE; 334 virtual int Write(IOBuffer* buf, 335 int buf_len, 336 const CompletionCallback& callback) OVERRIDE; 337 338 // Blocks read results on the socket. Reads will not complete until 339 // UnblockReadResult() has been called and a result is ready from the 340 // underlying transport. Note: if BlockReadResult() is called while there is a 341 // hanging asynchronous Read(), that Read is blocked. 342 void BlockReadResult(); 343 void UnblockReadResult(); 344 345 // Waits for the blocked Read() call to be complete at the underlying 346 // transport. 347 void WaitForReadResult(); 348 349 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the 350 // underlying transport until UnblockWrite() has been called. Note: if there 351 // is a pending asynchronous write, it is NOT blocked. For purposes of 352 // blocking writes, data is considered to have reached the underlying 353 // transport as soon as Write() is called. 354 void BlockWrite(); 355 void UnblockWrite(); 356 357 // Waits for the blocked Write() call to be scheduled. 358 void WaitForWrite(); 359 360 private: 361 // Handles completion from the underlying transport read. 362 void OnReadCompleted(int result); 363 364 // True if read callbacks are blocked. 365 bool should_block_read_; 366 367 // The user callback for the pending read call. 368 CompletionCallback pending_read_callback_; 369 370 // The result for the blocked read callback, or ERR_IO_PENDING if not 371 // completed. 372 int pending_read_result_; 373 374 // WaitForReadResult() wait loop. 375 scoped_ptr<base::RunLoop> read_loop_; 376 377 // True if write calls are blocked. 378 bool should_block_write_; 379 380 // The buffer for the pending write, or NULL if not scheduled. 381 scoped_refptr<IOBuffer> pending_write_buf_; 382 383 // The callback for the pending write call. 384 CompletionCallback pending_write_callback_; 385 386 // The length for the pending write, or -1 if not scheduled. 387 int pending_write_len_; 388 389 // WaitForWrite() wait loop. 390 scoped_ptr<base::RunLoop> write_loop_; 391 }; 392 393 FakeBlockingStreamSocket::FakeBlockingStreamSocket( 394 scoped_ptr<StreamSocket> transport) 395 : WrappedStreamSocket(transport.Pass()), 396 should_block_read_(false), 397 pending_read_result_(ERR_IO_PENDING), 398 should_block_write_(false), 399 pending_write_len_(-1) {} 400 401 int FakeBlockingStreamSocket::Read(IOBuffer* buf, 402 int len, 403 const CompletionCallback& callback) { 404 DCHECK(pending_read_callback_.is_null()); 405 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_); 406 DCHECK(!callback.is_null()); 407 408 int rv = transport_->Read(buf, len, base::Bind( 409 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this))); 410 if (rv == ERR_IO_PENDING) { 411 // Save the callback to be called later. 412 pending_read_callback_ = callback; 413 } else if (should_block_read_) { 414 // Save the callback and read result to be called later. 415 pending_read_callback_ = callback; 416 OnReadCompleted(rv); 417 rv = ERR_IO_PENDING; 418 } 419 return rv; 420 } 421 422 int FakeBlockingStreamSocket::Write(IOBuffer* buf, 423 int len, 424 const CompletionCallback& callback) { 425 DCHECK(buf); 426 DCHECK_LE(0, len); 427 428 if (!should_block_write_) 429 return transport_->Write(buf, len, callback); 430 431 // Schedule the write, but do nothing. 432 DCHECK(!pending_write_buf_); 433 DCHECK_EQ(-1, pending_write_len_); 434 DCHECK(pending_write_callback_.is_null()); 435 DCHECK(!callback.is_null()); 436 pending_write_buf_ = buf; 437 pending_write_len_ = len; 438 pending_write_callback_ = callback; 439 440 // Stop the write loop, if any. 441 if (write_loop_) 442 write_loop_->Quit(); 443 return ERR_IO_PENDING; 444 } 445 446 void FakeBlockingStreamSocket::BlockReadResult() { 447 DCHECK(!should_block_read_); 448 should_block_read_ = true; 449 } 450 451 void FakeBlockingStreamSocket::UnblockReadResult() { 452 DCHECK(should_block_read_); 453 should_block_read_ = false; 454 455 // If the operation is still pending in the underlying transport, immediately 456 // return - OnReadCompleted() will handle invoking the callback once the 457 // transport has completed. 458 if (pending_read_result_ == ERR_IO_PENDING) 459 return; 460 int result = pending_read_result_; 461 pending_read_result_ = ERR_IO_PENDING; 462 base::ResetAndReturn(&pending_read_callback_).Run(result); 463 } 464 465 void FakeBlockingStreamSocket::WaitForReadResult() { 466 DCHECK(should_block_read_); 467 DCHECK(!read_loop_); 468 469 if (pending_read_result_ != ERR_IO_PENDING) 470 return; 471 read_loop_.reset(new base::RunLoop); 472 read_loop_->Run(); 473 read_loop_.reset(); 474 DCHECK_NE(ERR_IO_PENDING, pending_read_result_); 475 } 476 477 void FakeBlockingStreamSocket::BlockWrite() { 478 DCHECK(!should_block_write_); 479 should_block_write_ = true; 480 } 481 482 void FakeBlockingStreamSocket::UnblockWrite() { 483 DCHECK(should_block_write_); 484 should_block_write_ = false; 485 486 // Do nothing if UnblockWrite() was called after BlockWrite(), 487 // without a Write() in between. 488 if (!pending_write_buf_) 489 return; 490 491 int rv = transport_->Write(pending_write_buf_, pending_write_len_, 492 pending_write_callback_); 493 pending_write_buf_ = NULL; 494 pending_write_len_ = -1; 495 if (rv == ERR_IO_PENDING) { 496 pending_write_callback_.Reset(); 497 } else { 498 base::ResetAndReturn(&pending_write_callback_).Run(rv); 499 } 500 } 501 502 void FakeBlockingStreamSocket::WaitForWrite() { 503 DCHECK(should_block_write_); 504 DCHECK(!write_loop_); 505 506 if (pending_write_buf_) 507 return; 508 write_loop_.reset(new base::RunLoop); 509 write_loop_->Run(); 510 write_loop_.reset(); 511 DCHECK(pending_write_buf_); 512 } 513 514 void FakeBlockingStreamSocket::OnReadCompleted(int result) { 515 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_); 516 DCHECK(!pending_read_callback_.is_null()); 517 518 if (should_block_read_) { 519 // Store the result so that the callback can be invoked once Unblock() is 520 // called. 521 pending_read_result_ = result; 522 523 // Stop the WaitForReadResult() call if any. 524 if (read_loop_) 525 read_loop_->Quit(); 526 } else { 527 // Either the Read() was never blocked or UnblockReadResult() was called 528 // before the Read() completed. Either way, run the callback. 529 base::ResetAndReturn(&pending_read_callback_).Run(result); 530 } 531 } 532 533 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of 534 // reads and writes on the socket. 535 class CountingStreamSocket : public WrappedStreamSocket { 536 public: 537 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport) 538 : WrappedStreamSocket(transport.Pass()), 539 read_count_(0), 540 write_count_(0) {} 541 virtual ~CountingStreamSocket() {} 542 543 // Socket implementation: 544 virtual int Read(IOBuffer* buf, 545 int buf_len, 546 const CompletionCallback& callback) OVERRIDE { 547 read_count_++; 548 return transport_->Read(buf, buf_len, callback); 549 } 550 virtual int Write(IOBuffer* buf, 551 int buf_len, 552 const CompletionCallback& callback) OVERRIDE { 553 write_count_++; 554 return transport_->Write(buf, buf_len, callback); 555 } 556 557 int read_count() const { return read_count_; } 558 int write_count() const { return write_count_; } 559 560 private: 561 int read_count_; 562 int write_count_; 563 }; 564 565 // CompletionCallback that will delete the associated StreamSocket when 566 // the callback is invoked. 567 class DeleteSocketCallback : public TestCompletionCallbackBase { 568 public: 569 explicit DeleteSocketCallback(StreamSocket* socket) 570 : socket_(socket), 571 callback_(base::Bind(&DeleteSocketCallback::OnComplete, 572 base::Unretained(this))) {} 573 virtual ~DeleteSocketCallback() {} 574 575 const CompletionCallback& callback() const { return callback_; } 576 577 private: 578 void OnComplete(int result) { 579 if (socket_) { 580 delete socket_; 581 socket_ = NULL; 582 } else { 583 ADD_FAILURE() << "Deleting socket twice"; 584 } 585 SetResult(result); 586 } 587 588 StreamSocket* socket_; 589 CompletionCallback callback_; 590 591 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback); 592 }; 593 594 // A ServerBoundCertStore that always returns an error when asked for a 595 // certificate. 596 class FailingServerBoundCertStore : public ServerBoundCertStore { 597 virtual int GetServerBoundCert(const std::string& server_identifier, 598 base::Time* expiration_time, 599 std::string* private_key_result, 600 std::string* cert_result, 601 const GetCertCallback& callback) OVERRIDE { 602 return ERR_UNEXPECTED; 603 } 604 virtual void SetServerBoundCert(const std::string& server_identifier, 605 base::Time creation_time, 606 base::Time expiration_time, 607 const std::string& private_key, 608 const std::string& cert) OVERRIDE {} 609 virtual void DeleteServerBoundCert(const std::string& server_identifier, 610 const base::Closure& completion_callback) 611 OVERRIDE {} 612 virtual void DeleteAllCreatedBetween(base::Time delete_begin, 613 base::Time delete_end, 614 const base::Closure& completion_callback) 615 OVERRIDE {} 616 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {} 617 virtual void GetAllServerBoundCerts(const GetCertListCallback& callback) 618 OVERRIDE {} 619 virtual int GetCertCount() OVERRIDE { return 0; } 620 virtual void SetForceKeepSessionState() OVERRIDE {} 621 }; 622 623 class SSLClientSocketTest : public PlatformTest { 624 public: 625 SSLClientSocketTest() 626 : socket_factory_(ClientSocketFactory::GetDefaultFactory()), 627 cert_verifier_(new MockCertVerifier), 628 transport_security_state_(new TransportSecurityState) { 629 cert_verifier_->set_default_result(OK); 630 context_.cert_verifier = cert_verifier_.get(); 631 context_.transport_security_state = transport_security_state_.get(); 632 } 633 634 protected: 635 // The address of the spawned test server, after calling StartTestServer(). 636 const AddressList& addr() const { return addr_; } 637 638 // The SpawnedTestServer object, after calling StartTestServer(). 639 const SpawnedTestServer* test_server() const { return test_server_.get(); } 640 641 // Starts the test server with SSL configuration |ssl_options|. Returns true 642 // on success. 643 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) { 644 test_server_.reset(new SpawnedTestServer( 645 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath())); 646 if (!test_server_->Start()) { 647 LOG(ERROR) << "Could not start SpawnedTestServer"; 648 return false; 649 } 650 651 if (!test_server_->GetAddressList(&addr_)) { 652 LOG(ERROR) << "Could not get SpawnedTestServer address list"; 653 return false; 654 } 655 return true; 656 } 657 658 // Sets up a TCP connection to a HTTPS server. To actually do the SSL 659 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below. 660 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) { 661 if (!StartTestServer(ssl_options)) 662 return false; 663 664 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source())); 665 int rv = callback_.GetResult(transport_->Connect(callback_.callback())); 666 if (rv != OK) { 667 LOG(ERROR) << "Could not connect to SpawnedTestServer"; 668 return false; 669 } 670 return true; 671 } 672 673 scoped_ptr<SSLClientSocket> CreateSSLClientSocket( 674 scoped_ptr<StreamSocket> transport_socket, 675 const HostPortPair& host_and_port, 676 const SSLConfig& ssl_config) { 677 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle); 678 connection->SetSocket(transport_socket.Pass()); 679 return socket_factory_->CreateSSLClientSocket( 680 connection.Pass(), host_and_port, ssl_config, context_); 681 } 682 683 // Create an SSLClientSocket object and use it to connect to a test 684 // server, then wait for connection results. This must be called after 685 // a successful ConnectToTestServer() call. 686 // |ssl_config| the SSL configuration to use. 687 // |result| will retrieve the ::Connect() result value. 688 // Returns true on success, false otherwise. Success means that the socket 689 // could be created and its Connect() was called, not that the connection 690 // itself was a success. 691 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) { 692 sock_ = CreateSSLClientSocket( 693 transport_.Pass(), test_server_->host_port_pair(), ssl_config); 694 695 if (sock_->IsConnected()) { 696 LOG(ERROR) << "SSL Socket prematurely connected"; 697 return false; 698 } 699 700 *result = callback_.GetResult(sock_->Connect(callback_.callback())); 701 return true; 702 } 703 704 ClientSocketFactory* socket_factory_; 705 scoped_ptr<MockCertVerifier> cert_verifier_; 706 scoped_ptr<TransportSecurityState> transport_security_state_; 707 SSLClientSocketContext context_; 708 scoped_ptr<SSLClientSocket> sock_; 709 CapturingNetLog log_; 710 711 private: 712 scoped_ptr<StreamSocket> transport_; 713 scoped_ptr<SpawnedTestServer> test_server_; 714 TestCompletionCallback callback_; 715 AddressList addr_; 716 }; 717 718 // Verifies the correctness of GetSSLCertRequestInfo. 719 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest { 720 protected: 721 // Creates a test server with the given SSLOptions, connects to it and returns 722 // the SSLCertRequestInfo reported by the socket. 723 scoped_refptr<SSLCertRequestInfo> GetCertRequest( 724 SpawnedTestServer::SSLOptions ssl_options) { 725 SpawnedTestServer test_server( 726 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 727 if (!test_server.Start()) 728 return NULL; 729 730 AddressList addr; 731 if (!test_server.GetAddressList(&addr)) 732 return NULL; 733 734 TestCompletionCallback callback; 735 CapturingNetLog log; 736 scoped_ptr<StreamSocket> transport( 737 new TCPClientSocket(addr, &log, NetLog::Source())); 738 int rv = transport->Connect(callback.callback()); 739 if (rv == ERR_IO_PENDING) 740 rv = callback.WaitForResult(); 741 EXPECT_EQ(OK, rv); 742 743 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 744 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 745 EXPECT_FALSE(sock->IsConnected()); 746 747 rv = sock->Connect(callback.callback()); 748 if (rv == ERR_IO_PENDING) 749 rv = callback.WaitForResult(); 750 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo(); 751 sock->GetSSLCertRequestInfo(request_info.get()); 752 sock->Disconnect(); 753 EXPECT_FALSE(sock->IsConnected()); 754 EXPECT_TRUE( 755 test_server.host_port_pair().Equals(request_info->host_and_port)); 756 757 return request_info; 758 } 759 }; 760 761 class SSLClientSocketFalseStartTest : public SSLClientSocketTest { 762 protected: 763 // Creates an SSLClientSocket with |client_config| attached to a 764 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and 765 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket, 766 // so |*out_raw_transport| is a raw pointer. 767 // 768 // The client socket will begin a connect using |callback| but stop before the 769 // server's finished message is received. The finished message will be blocked 770 // in |*out_raw_transport|. To complete the handshake and successfully read 771 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if 772 // the client successfully false started, |callback.WaitForResult()| will 773 // return OK without unblocking transport reads. But Read() will still block.) 774 // 775 // Must be called after StartTestServer is called. 776 void CreateAndConnectUntilServerFinishedReceived( 777 const SSLConfig& client_config, 778 TestCompletionCallback* callback, 779 FakeBlockingStreamSocket** out_raw_transport, 780 scoped_ptr<SSLClientSocket>* out_sock) { 781 CHECK(test_server()); 782 783 scoped_ptr<StreamSocket> real_transport( 784 new TCPClientSocket(addr(), NULL, NetLog::Source())); 785 scoped_ptr<FakeBlockingStreamSocket> transport( 786 new FakeBlockingStreamSocket(real_transport.Pass())); 787 int rv = callback->GetResult(transport->Connect(callback->callback())); 788 EXPECT_EQ(OK, rv); 789 790 FakeBlockingStreamSocket* raw_transport = transport.get(); 791 scoped_ptr<SSLClientSocket> sock = 792 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 793 test_server()->host_port_pair(), 794 client_config); 795 796 // Connect. Stop before the client processes the first server leg 797 // (ServerHello, etc.) 798 raw_transport->BlockReadResult(); 799 rv = sock->Connect(callback->callback()); 800 EXPECT_EQ(ERR_IO_PENDING, rv); 801 raw_transport->WaitForReadResult(); 802 803 // Release the ServerHello and wait for the client to write 804 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the 805 // server's leg to complete, since it may span multiple reads.) 806 EXPECT_FALSE(callback->have_result()); 807 raw_transport->BlockWrite(); 808 raw_transport->UnblockReadResult(); 809 raw_transport->WaitForWrite(); 810 811 // And, finally, release that and block the next server leg 812 // (ChangeCipherSpec, Finished). 813 raw_transport->BlockReadResult(); 814 raw_transport->UnblockWrite(); 815 816 *out_raw_transport = raw_transport; 817 *out_sock = sock.Pass(); 818 } 819 820 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options, 821 const SSLConfig& client_config, 822 bool expect_false_start) { 823 ASSERT_TRUE(StartTestServer(server_options)); 824 825 TestCompletionCallback callback; 826 FakeBlockingStreamSocket* raw_transport = NULL; 827 scoped_ptr<SSLClientSocket> sock; 828 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived( 829 client_config, &callback, &raw_transport, &sock)); 830 831 if (expect_false_start) { 832 // When False Starting, the handshake should complete before receiving the 833 // Change Cipher Spec and Finished messages. 834 // 835 // Note: callback.have_result() may not be true without waiting. The NSS 836 // state machine sometimes lives on a separate thread, so this thread may 837 // not yet have processed the signal that the handshake has completed. 838 int rv = callback.WaitForResult(); 839 EXPECT_EQ(OK, rv); 840 EXPECT_TRUE(sock->IsConnected()); 841 842 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 843 static const int kRequestTextSize = 844 static_cast<int>(arraysize(request_text) - 1); 845 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); 846 memcpy(request_buffer->data(), request_text, kRequestTextSize); 847 848 // Write the request. 849 rv = callback.GetResult(sock->Write(request_buffer.get(), 850 kRequestTextSize, 851 callback.callback())); 852 EXPECT_EQ(kRequestTextSize, rv); 853 854 // The read will hang; it's waiting for the peer to complete the 855 // handshake, and the handshake is still blocked. 856 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 857 rv = sock->Read(buf.get(), 4096, callback.callback()); 858 859 // After releasing reads, the connection proceeds. 860 raw_transport->UnblockReadResult(); 861 rv = callback.GetResult(rv); 862 EXPECT_LT(0, rv); 863 } else { 864 // False Start is not enabled, so the handshake will not complete because 865 // the server second leg is blocked. 866 base::RunLoop().RunUntilIdle(); 867 EXPECT_FALSE(callback.have_result()); 868 } 869 } 870 }; 871 872 class SSLClientSocketChannelIDTest : public SSLClientSocketTest { 873 protected: 874 void EnableChannelID() { 875 cert_service_.reset( 876 new ServerBoundCertService(new DefaultServerBoundCertStore(NULL), 877 base::MessageLoopProxy::current())); 878 context_.server_bound_cert_service = cert_service_.get(); 879 } 880 881 void EnableFailingChannelID() { 882 cert_service_.reset(new ServerBoundCertService( 883 new FailingServerBoundCertStore(), base::MessageLoopProxy::current())); 884 context_.server_bound_cert_service = cert_service_.get(); 885 } 886 887 private: 888 scoped_ptr<ServerBoundCertService> cert_service_; 889 }; 890 891 //----------------------------------------------------------------------------- 892 893 // LogContainsSSLConnectEndEvent returns true if the given index in the given 894 // log is an SSL connect end event. The NSS sockets will cork in an attempt to 895 // merge the first application data record with the Finished message when false 896 // starting. However, in order to avoid the server timing out the handshake, 897 // they'll give up waiting for application data and send the Finished after a 898 // timeout. This means that an SSL connect end event may appear as a socket 899 // write. 900 static bool LogContainsSSLConnectEndEvent( 901 const CapturingNetLog::CapturedEntryList& log, 902 int i) { 903 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) || 904 LogContainsEvent( 905 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE); 906 } 907 908 } // namespace 909 910 TEST_F(SSLClientSocketTest, Connect) { 911 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 912 SpawnedTestServer::kLocalhost, 913 base::FilePath()); 914 ASSERT_TRUE(test_server.Start()); 915 916 AddressList addr; 917 ASSERT_TRUE(test_server.GetAddressList(&addr)); 918 919 TestCompletionCallback callback; 920 CapturingNetLog log; 921 scoped_ptr<StreamSocket> transport( 922 new TCPClientSocket(addr, &log, NetLog::Source())); 923 int rv = transport->Connect(callback.callback()); 924 if (rv == ERR_IO_PENDING) 925 rv = callback.WaitForResult(); 926 EXPECT_EQ(OK, rv); 927 928 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 929 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 930 931 EXPECT_FALSE(sock->IsConnected()); 932 933 rv = sock->Connect(callback.callback()); 934 935 CapturingNetLog::CapturedEntryList entries; 936 log.GetEntries(&entries); 937 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 938 if (rv == ERR_IO_PENDING) 939 rv = callback.WaitForResult(); 940 EXPECT_EQ(OK, rv); 941 EXPECT_TRUE(sock->IsConnected()); 942 log.GetEntries(&entries); 943 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 944 945 sock->Disconnect(); 946 EXPECT_FALSE(sock->IsConnected()); 947 } 948 949 TEST_F(SSLClientSocketTest, ConnectExpired) { 950 SpawnedTestServer::SSLOptions ssl_options( 951 SpawnedTestServer::SSLOptions::CERT_EXPIRED); 952 SpawnedTestServer test_server( 953 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 954 ASSERT_TRUE(test_server.Start()); 955 956 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID); 957 958 AddressList addr; 959 ASSERT_TRUE(test_server.GetAddressList(&addr)); 960 961 TestCompletionCallback callback; 962 CapturingNetLog log; 963 scoped_ptr<StreamSocket> transport( 964 new TCPClientSocket(addr, &log, NetLog::Source())); 965 int rv = transport->Connect(callback.callback()); 966 if (rv == ERR_IO_PENDING) 967 rv = callback.WaitForResult(); 968 EXPECT_EQ(OK, rv); 969 970 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 971 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 972 973 EXPECT_FALSE(sock->IsConnected()); 974 975 rv = sock->Connect(callback.callback()); 976 977 CapturingNetLog::CapturedEntryList entries; 978 log.GetEntries(&entries); 979 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 980 if (rv == ERR_IO_PENDING) 981 rv = callback.WaitForResult(); 982 983 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv); 984 985 // Rather than testing whether or not the underlying socket is connected, 986 // test that the handshake has finished. This is because it may be 987 // desirable to disconnect the socket before showing a user prompt, since 988 // the user may take indefinitely long to respond. 989 log.GetEntries(&entries); 990 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 991 } 992 993 TEST_F(SSLClientSocketTest, ConnectMismatched) { 994 SpawnedTestServer::SSLOptions ssl_options( 995 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); 996 SpawnedTestServer test_server( 997 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 998 ASSERT_TRUE(test_server.Start()); 999 1000 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID); 1001 1002 AddressList addr; 1003 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1004 1005 TestCompletionCallback callback; 1006 CapturingNetLog log; 1007 scoped_ptr<StreamSocket> transport( 1008 new TCPClientSocket(addr, &log, NetLog::Source())); 1009 int rv = transport->Connect(callback.callback()); 1010 if (rv == ERR_IO_PENDING) 1011 rv = callback.WaitForResult(); 1012 EXPECT_EQ(OK, rv); 1013 1014 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1015 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1016 1017 EXPECT_FALSE(sock->IsConnected()); 1018 1019 rv = sock->Connect(callback.callback()); 1020 1021 CapturingNetLog::CapturedEntryList entries; 1022 log.GetEntries(&entries); 1023 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 1024 if (rv == ERR_IO_PENDING) 1025 rv = callback.WaitForResult(); 1026 1027 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv); 1028 1029 // Rather than testing whether or not the underlying socket is connected, 1030 // test that the handshake has finished. This is because it may be 1031 // desirable to disconnect the socket before showing a user prompt, since 1032 // the user may take indefinitely long to respond. 1033 log.GetEntries(&entries); 1034 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 1035 } 1036 1037 // Attempt to connect to a page which requests a client certificate. It should 1038 // return an error code on connect. 1039 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) { 1040 SpawnedTestServer::SSLOptions ssl_options; 1041 ssl_options.request_client_certificate = true; 1042 SpawnedTestServer test_server( 1043 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 1044 ASSERT_TRUE(test_server.Start()); 1045 1046 AddressList addr; 1047 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1048 1049 TestCompletionCallback callback; 1050 CapturingNetLog log; 1051 scoped_ptr<StreamSocket> transport( 1052 new TCPClientSocket(addr, &log, NetLog::Source())); 1053 int rv = transport->Connect(callback.callback()); 1054 if (rv == ERR_IO_PENDING) 1055 rv = callback.WaitForResult(); 1056 EXPECT_EQ(OK, rv); 1057 1058 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1059 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1060 1061 EXPECT_FALSE(sock->IsConnected()); 1062 1063 rv = sock->Connect(callback.callback()); 1064 1065 CapturingNetLog::CapturedEntryList entries; 1066 log.GetEntries(&entries); 1067 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 1068 if (rv == ERR_IO_PENDING) 1069 rv = callback.WaitForResult(); 1070 1071 log.GetEntries(&entries); 1072 // Because we prematurely kill the handshake at CertificateRequest, 1073 // the server may still send data (notably the ServerHelloDone) 1074 // after the error is returned. As a result, the SSL_CONNECT may not 1075 // be the last entry. See http://crbug.com/54445. We use 1076 // ExpectLogContainsSomewhere instead of 1077 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one 1078 // extra read instead of two. This occurs before the handshake ends, 1079 // so the corking logic of LogContainsSSLConnectEndEvent isn't 1080 // necessary. 1081 // 1082 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is 1083 // fixed and we can respond to the first CertificateRequest 1084 // without closing the socket, add a unit test for sending the 1085 // certificate. This test may still be useful as we'll want to close 1086 // the socket on a timeout if the user takes a long time to pick a 1087 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832 1088 ExpectLogContainsSomewhere( 1089 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END); 1090 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv); 1091 EXPECT_FALSE(sock->IsConnected()); 1092 } 1093 1094 // Connect to a server requesting optional client authentication. Send it a 1095 // null certificate. It should allow the connection. 1096 // 1097 // TODO(davidben): Also test providing an actual certificate. 1098 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) { 1099 SpawnedTestServer::SSLOptions ssl_options; 1100 ssl_options.request_client_certificate = true; 1101 SpawnedTestServer test_server( 1102 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 1103 ASSERT_TRUE(test_server.Start()); 1104 1105 AddressList addr; 1106 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1107 1108 TestCompletionCallback callback; 1109 CapturingNetLog log; 1110 scoped_ptr<StreamSocket> transport( 1111 new TCPClientSocket(addr, &log, NetLog::Source())); 1112 int rv = transport->Connect(callback.callback()); 1113 if (rv == ERR_IO_PENDING) 1114 rv = callback.WaitForResult(); 1115 EXPECT_EQ(OK, rv); 1116 1117 SSLConfig ssl_config = kDefaultSSLConfig; 1118 ssl_config.send_client_cert = true; 1119 ssl_config.client_cert = NULL; 1120 1121 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1122 transport.Pass(), test_server.host_port_pair(), ssl_config)); 1123 1124 EXPECT_FALSE(sock->IsConnected()); 1125 1126 // Our test server accepts certificate-less connections. 1127 // TODO(davidben): Add a test which requires them and verify the error. 1128 rv = sock->Connect(callback.callback()); 1129 1130 CapturingNetLog::CapturedEntryList entries; 1131 log.GetEntries(&entries); 1132 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 1133 if (rv == ERR_IO_PENDING) 1134 rv = callback.WaitForResult(); 1135 1136 EXPECT_EQ(OK, rv); 1137 EXPECT_TRUE(sock->IsConnected()); 1138 log.GetEntries(&entries); 1139 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 1140 1141 // We responded to the server's certificate request with a Certificate 1142 // message with no client certificate in it. ssl_info.client_cert_sent 1143 // should be false in this case. 1144 SSLInfo ssl_info; 1145 sock->GetSSLInfo(&ssl_info); 1146 EXPECT_FALSE(ssl_info.client_cert_sent); 1147 1148 sock->Disconnect(); 1149 EXPECT_FALSE(sock->IsConnected()); 1150 } 1151 1152 // TODO(wtc): Add unit tests for IsConnectedAndIdle: 1153 // - Server closes an SSL connection (with a close_notify alert message). 1154 // - Server closes the underlying TCP connection directly. 1155 // - Server sends data unexpectedly. 1156 1157 TEST_F(SSLClientSocketTest, Read) { 1158 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1159 SpawnedTestServer::kLocalhost, 1160 base::FilePath()); 1161 ASSERT_TRUE(test_server.Start()); 1162 1163 AddressList addr; 1164 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1165 1166 TestCompletionCallback callback; 1167 scoped_ptr<StreamSocket> transport( 1168 new TCPClientSocket(addr, NULL, NetLog::Source())); 1169 int rv = transport->Connect(callback.callback()); 1170 if (rv == ERR_IO_PENDING) 1171 rv = callback.WaitForResult(); 1172 EXPECT_EQ(OK, rv); 1173 1174 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1175 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1176 1177 rv = sock->Connect(callback.callback()); 1178 if (rv == ERR_IO_PENDING) 1179 rv = callback.WaitForResult(); 1180 EXPECT_EQ(OK, rv); 1181 EXPECT_TRUE(sock->IsConnected()); 1182 1183 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1184 scoped_refptr<IOBuffer> request_buffer( 1185 new IOBuffer(arraysize(request_text) - 1)); 1186 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); 1187 1188 rv = sock->Write( 1189 request_buffer.get(), arraysize(request_text) - 1, callback.callback()); 1190 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1191 1192 if (rv == ERR_IO_PENDING) 1193 rv = callback.WaitForResult(); 1194 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); 1195 1196 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1197 for (;;) { 1198 rv = sock->Read(buf.get(), 4096, callback.callback()); 1199 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1200 1201 if (rv == ERR_IO_PENDING) 1202 rv = callback.WaitForResult(); 1203 1204 EXPECT_GE(rv, 0); 1205 if (rv <= 0) 1206 break; 1207 } 1208 } 1209 1210 // Tests that the SSLClientSocket properly handles when the underlying transport 1211 // synchronously returns an error code - such as if an intermediary terminates 1212 // the socket connection uncleanly. 1213 // This is a regression test for http://crbug.com/238536 1214 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) { 1215 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1216 SpawnedTestServer::kLocalhost, 1217 base::FilePath()); 1218 ASSERT_TRUE(test_server.Start()); 1219 1220 AddressList addr; 1221 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1222 1223 TestCompletionCallback callback; 1224 scoped_ptr<StreamSocket> real_transport( 1225 new TCPClientSocket(addr, NULL, NetLog::Source())); 1226 scoped_ptr<SynchronousErrorStreamSocket> transport( 1227 new SynchronousErrorStreamSocket(real_transport.Pass())); 1228 int rv = callback.GetResult(transport->Connect(callback.callback())); 1229 EXPECT_EQ(OK, rv); 1230 1231 // Disable TLS False Start to avoid handshake non-determinism. 1232 SSLConfig ssl_config; 1233 ssl_config.false_start_enabled = false; 1234 1235 SynchronousErrorStreamSocket* raw_transport = transport.get(); 1236 scoped_ptr<SSLClientSocket> sock( 1237 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 1238 test_server.host_port_pair(), 1239 ssl_config)); 1240 1241 rv = callback.GetResult(sock->Connect(callback.callback())); 1242 EXPECT_EQ(OK, rv); 1243 EXPECT_TRUE(sock->IsConnected()); 1244 1245 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1246 static const int kRequestTextSize = 1247 static_cast<int>(arraysize(request_text) - 1); 1248 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); 1249 memcpy(request_buffer->data(), request_text, kRequestTextSize); 1250 1251 rv = callback.GetResult( 1252 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback())); 1253 EXPECT_EQ(kRequestTextSize, rv); 1254 1255 // Simulate an unclean/forcible shutdown. 1256 raw_transport->SetNextReadError(ERR_CONNECTION_RESET); 1257 1258 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1259 1260 // Note: This test will hang if this bug has regressed. Simply checking that 1261 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate 1262 // result when using a dedicated task runner for NSS. 1263 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback())); 1264 1265 #if !defined(USE_OPENSSL) 1266 // SSLClientSocketNSS records the error exactly 1267 EXPECT_EQ(ERR_CONNECTION_RESET, rv); 1268 #else 1269 // SSLClientSocketOpenSSL treats any errors as a simple EOF. 1270 EXPECT_EQ(0, rv); 1271 #endif 1272 } 1273 1274 // Tests that the SSLClientSocket properly handles when the underlying transport 1275 // asynchronously returns an error code while writing data - such as if an 1276 // intermediary terminates the socket connection uncleanly. 1277 // This is a regression test for http://crbug.com/249848 1278 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) { 1279 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1280 SpawnedTestServer::kLocalhost, 1281 base::FilePath()); 1282 ASSERT_TRUE(test_server.Start()); 1283 1284 AddressList addr; 1285 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1286 1287 TestCompletionCallback callback; 1288 scoped_ptr<StreamSocket> real_transport( 1289 new TCPClientSocket(addr, NULL, NetLog::Source())); 1290 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer 1291 // is retained in order to configure additional errors. 1292 scoped_ptr<SynchronousErrorStreamSocket> error_socket( 1293 new SynchronousErrorStreamSocket(real_transport.Pass())); 1294 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); 1295 scoped_ptr<FakeBlockingStreamSocket> transport( 1296 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>())); 1297 FakeBlockingStreamSocket* raw_transport = transport.get(); 1298 int rv = callback.GetResult(transport->Connect(callback.callback())); 1299 EXPECT_EQ(OK, rv); 1300 1301 // Disable TLS False Start to avoid handshake non-determinism. 1302 SSLConfig ssl_config; 1303 ssl_config.false_start_enabled = false; 1304 1305 scoped_ptr<SSLClientSocket> sock( 1306 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 1307 test_server.host_port_pair(), 1308 ssl_config)); 1309 1310 rv = callback.GetResult(sock->Connect(callback.callback())); 1311 EXPECT_EQ(OK, rv); 1312 EXPECT_TRUE(sock->IsConnected()); 1313 1314 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1315 static const int kRequestTextSize = 1316 static_cast<int>(arraysize(request_text) - 1); 1317 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); 1318 memcpy(request_buffer->data(), request_text, kRequestTextSize); 1319 1320 // Simulate an unclean/forcible shutdown on the underlying socket. 1321 // However, simulate this error asynchronously. 1322 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); 1323 raw_transport->BlockWrite(); 1324 1325 // This write should complete synchronously, because the TLS ciphertext 1326 // can be created and placed into the outgoing buffers independent of the 1327 // underlying transport. 1328 rv = callback.GetResult( 1329 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback())); 1330 EXPECT_EQ(kRequestTextSize, rv); 1331 1332 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1333 1334 rv = sock->Read(buf.get(), 4096, callback.callback()); 1335 EXPECT_EQ(ERR_IO_PENDING, rv); 1336 1337 // Now unblock the outgoing request, having it fail with the connection 1338 // being reset. 1339 raw_transport->UnblockWrite(); 1340 1341 // Note: This will cause an inifite loop if this bug has regressed. Simply 1342 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING 1343 // is a legitimate result when using a dedicated task runner for NSS. 1344 rv = callback.GetResult(rv); 1345 1346 #if !defined(USE_OPENSSL) 1347 // SSLClientSocketNSS records the error exactly 1348 EXPECT_EQ(ERR_CONNECTION_RESET, rv); 1349 #else 1350 // SSLClientSocketOpenSSL treats any errors as a simple EOF. 1351 EXPECT_EQ(0, rv); 1352 #endif 1353 } 1354 1355 // If there is a Write failure at the transport with no follow-up Read, although 1356 // the write error will not be returned to the client until a future Read or 1357 // Write operation, SSLClientSocket should not spin attempting to re-write on 1358 // the socket. This is a regression test for part of https://crbug.com/381160. 1359 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) { 1360 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1361 SpawnedTestServer::kLocalhost, 1362 base::FilePath()); 1363 ASSERT_TRUE(test_server.Start()); 1364 1365 AddressList addr; 1366 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1367 1368 TestCompletionCallback callback; 1369 scoped_ptr<StreamSocket> real_transport( 1370 new TCPClientSocket(addr, NULL, NetLog::Source())); 1371 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer 1372 // is retained in order to query them. 1373 scoped_ptr<SynchronousErrorStreamSocket> error_socket( 1374 new SynchronousErrorStreamSocket(real_transport.Pass())); 1375 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); 1376 scoped_ptr<CountingStreamSocket> counting_socket( 1377 new CountingStreamSocket(error_socket.PassAs<StreamSocket>())); 1378 CountingStreamSocket* raw_counting_socket = counting_socket.get(); 1379 int rv = callback.GetResult(counting_socket->Connect(callback.callback())); 1380 ASSERT_EQ(OK, rv); 1381 1382 // Disable TLS False Start to avoid handshake non-determinism. 1383 SSLConfig ssl_config; 1384 ssl_config.false_start_enabled = false; 1385 1386 scoped_ptr<SSLClientSocket> sock( 1387 CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(), 1388 test_server.host_port_pair(), 1389 ssl_config)); 1390 1391 rv = callback.GetResult(sock->Connect(callback.callback())); 1392 ASSERT_EQ(OK, rv); 1393 ASSERT_TRUE(sock->IsConnected()); 1394 1395 // Simulate an unclean/forcible shutdown on the underlying socket. 1396 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); 1397 1398 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1399 static const int kRequestTextSize = 1400 static_cast<int>(arraysize(request_text) - 1); 1401 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); 1402 memcpy(request_buffer->data(), request_text, kRequestTextSize); 1403 1404 // This write should complete synchronously, because the TLS ciphertext 1405 // can be created and placed into the outgoing buffers independent of the 1406 // underlying transport. 1407 rv = callback.GetResult( 1408 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback())); 1409 ASSERT_EQ(kRequestTextSize, rv); 1410 1411 // Let the event loop spin for a little bit of time. Even on platforms where 1412 // pumping the state machine involve thread hops, there should be no further 1413 // writes on the transport socket. 1414 // 1415 // TODO(davidben): Avoid the arbitrary timeout? 1416 int old_write_count = raw_counting_socket->write_count(); 1417 base::RunLoop loop; 1418 base::MessageLoop::current()->PostDelayedTask( 1419 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100)); 1420 loop.Run(); 1421 EXPECT_EQ(old_write_count, raw_counting_socket->write_count()); 1422 } 1423 1424 // Test the full duplex mode, with Read and Write pending at the same time. 1425 // This test also serves as a regression test for http://crbug.com/29815. 1426 TEST_F(SSLClientSocketTest, Read_FullDuplex) { 1427 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1428 SpawnedTestServer::kLocalhost, 1429 base::FilePath()); 1430 ASSERT_TRUE(test_server.Start()); 1431 1432 AddressList addr; 1433 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1434 1435 TestCompletionCallback callback; // Used for everything except Write. 1436 1437 scoped_ptr<StreamSocket> transport( 1438 new TCPClientSocket(addr, NULL, NetLog::Source())); 1439 int rv = transport->Connect(callback.callback()); 1440 if (rv == ERR_IO_PENDING) 1441 rv = callback.WaitForResult(); 1442 EXPECT_EQ(OK, rv); 1443 1444 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1445 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1446 1447 rv = sock->Connect(callback.callback()); 1448 if (rv == ERR_IO_PENDING) 1449 rv = callback.WaitForResult(); 1450 EXPECT_EQ(OK, rv); 1451 EXPECT_TRUE(sock->IsConnected()); 1452 1453 // Issue a "hanging" Read first. 1454 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1455 rv = sock->Read(buf.get(), 4096, callback.callback()); 1456 // We haven't written the request, so there should be no response yet. 1457 ASSERT_EQ(ERR_IO_PENDING, rv); 1458 1459 // Write the request. 1460 // The request is padded with a User-Agent header to a size that causes the 1461 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around. 1462 // This tests the fix for http://crbug.com/29815. 1463 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name "; 1464 for (int i = 0; i < 3770; ++i) 1465 request_text.push_back('*'); 1466 request_text.append("\r\n\r\n"); 1467 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text)); 1468 1469 TestCompletionCallback callback2; // Used for Write only. 1470 rv = sock->Write( 1471 request_buffer.get(), request_text.size(), callback2.callback()); 1472 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1473 1474 if (rv == ERR_IO_PENDING) 1475 rv = callback2.WaitForResult(); 1476 EXPECT_EQ(static_cast<int>(request_text.size()), rv); 1477 1478 // Now get the Read result. 1479 rv = callback.WaitForResult(); 1480 EXPECT_GT(rv, 0); 1481 } 1482 1483 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex 1484 // mode when the underlying transport is blocked on sending data. When the 1485 // underlying transport completes due to an error, it should invoke both the 1486 // Read() and Write() callbacks. If the socket is deleted by the Read() 1487 // callback, the Write() callback should not be invoked. 1488 // Regression test for http://crbug.com/232633 1489 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) { 1490 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1491 SpawnedTestServer::kLocalhost, 1492 base::FilePath()); 1493 ASSERT_TRUE(test_server.Start()); 1494 1495 AddressList addr; 1496 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1497 1498 TestCompletionCallback callback; 1499 scoped_ptr<StreamSocket> real_transport( 1500 new TCPClientSocket(addr, NULL, NetLog::Source())); 1501 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer 1502 // is retained in order to configure additional errors. 1503 scoped_ptr<SynchronousErrorStreamSocket> error_socket( 1504 new SynchronousErrorStreamSocket(real_transport.Pass())); 1505 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); 1506 scoped_ptr<FakeBlockingStreamSocket> transport( 1507 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>())); 1508 FakeBlockingStreamSocket* raw_transport = transport.get(); 1509 1510 int rv = callback.GetResult(transport->Connect(callback.callback())); 1511 EXPECT_EQ(OK, rv); 1512 1513 // Disable TLS False Start to avoid handshake non-determinism. 1514 SSLConfig ssl_config; 1515 ssl_config.false_start_enabled = false; 1516 1517 scoped_ptr<SSLClientSocket> sock = 1518 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 1519 test_server.host_port_pair(), 1520 ssl_config); 1521 1522 rv = callback.GetResult(sock->Connect(callback.callback())); 1523 EXPECT_EQ(OK, rv); 1524 EXPECT_TRUE(sock->IsConnected()); 1525 1526 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name "; 1527 request_text.append(20 * 1024, '*'); 1528 request_text.append("\r\n\r\n"); 1529 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer( 1530 new StringIOBuffer(request_text), request_text.size())); 1531 1532 // Simulate errors being returned from the underlying Read() and Write() ... 1533 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET); 1534 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); 1535 // ... but have those errors returned asynchronously. Because the Write() will 1536 // return first, this will trigger the error. 1537 raw_transport->BlockReadResult(); 1538 raw_transport->BlockWrite(); 1539 1540 // Enqueue a Read() before calling Write(), which should "hang" due to 1541 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return. 1542 SSLClientSocket* raw_sock = sock.get(); 1543 DeleteSocketCallback read_callback(sock.release()); 1544 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096)); 1545 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback()); 1546 1547 // Ensure things didn't complete synchronously, otherwise |sock| is invalid. 1548 ASSERT_EQ(ERR_IO_PENDING, rv); 1549 ASSERT_FALSE(read_callback.have_result()); 1550 1551 #if !defined(USE_OPENSSL) 1552 // NSS follows a pattern where a call to PR_Write will only consume as 1553 // much data as it can encode into application data records before the 1554 // internal memio buffer is full, which should only fill if writing a large 1555 // amount of data and the underlying transport is blocked. Once this happens, 1556 // NSS will return (total size of all application data records it wrote) - 1, 1557 // with the caller expected to resume with the remaining unsent data. 1558 // 1559 // This causes SSLClientSocketNSS::Write to return that it wrote some data 1560 // before it will return ERR_IO_PENDING, so make an extra call to Write() to 1561 // get the socket in the state needed for the test below. 1562 // 1563 // This is not needed for OpenSSL, because for OpenSSL, 1564 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus 1565 // SSLClientSocketOpenSSL::Write() will not return until all of 1566 // |request_buffer| has been written to the underlying BIO (although not 1567 // necessarily the underlying transport). 1568 rv = callback.GetResult(raw_sock->Write(request_buffer.get(), 1569 request_buffer->BytesRemaining(), 1570 callback.callback())); 1571 ASSERT_LT(0, rv); 1572 request_buffer->DidConsume(rv); 1573 1574 // Guard to ensure that |request_buffer| was larger than all of the internal 1575 // buffers (transport, memio, NSS) along the way - otherwise the next call 1576 // to Write() will crash with an invalid buffer. 1577 ASSERT_LT(0, request_buffer->BytesRemaining()); 1578 #endif 1579 1580 // Attempt to write the remaining data. NSS will not be able to consume the 1581 // application data because the internal buffers are full, while OpenSSL will 1582 // return that its blocked because the underlying transport is blocked. 1583 rv = raw_sock->Write(request_buffer.get(), 1584 request_buffer->BytesRemaining(), 1585 callback.callback()); 1586 ASSERT_EQ(ERR_IO_PENDING, rv); 1587 ASSERT_FALSE(callback.have_result()); 1588 1589 // Now unblock Write(), which will invoke OnSendComplete and (eventually) 1590 // call the Read() callback, deleting the socket and thus aborting calling 1591 // the Write() callback. 1592 raw_transport->UnblockWrite(); 1593 1594 rv = read_callback.WaitForResult(); 1595 1596 #if !defined(USE_OPENSSL) 1597 // NSS records the error exactly. 1598 EXPECT_EQ(ERR_CONNECTION_RESET, rv); 1599 #else 1600 // OpenSSL treats any errors as a simple EOF. 1601 EXPECT_EQ(0, rv); 1602 #endif 1603 1604 // The Write callback should not have been called. 1605 EXPECT_FALSE(callback.have_result()); 1606 } 1607 1608 // Tests that the SSLClientSocket does not crash if data is received on the 1609 // transport socket after a failing write. This can occur if we have a Write 1610 // error in a SPDY socket. 1611 // Regression test for http://crbug.com/335557 1612 TEST_F(SSLClientSocketTest, Read_WithWriteError) { 1613 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1614 SpawnedTestServer::kLocalhost, 1615 base::FilePath()); 1616 ASSERT_TRUE(test_server.Start()); 1617 1618 AddressList addr; 1619 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1620 1621 TestCompletionCallback callback; 1622 scoped_ptr<StreamSocket> real_transport( 1623 new TCPClientSocket(addr, NULL, NetLog::Source())); 1624 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer 1625 // is retained in order to configure additional errors. 1626 scoped_ptr<SynchronousErrorStreamSocket> error_socket( 1627 new SynchronousErrorStreamSocket(real_transport.Pass())); 1628 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get(); 1629 scoped_ptr<FakeBlockingStreamSocket> transport( 1630 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>())); 1631 FakeBlockingStreamSocket* raw_transport = transport.get(); 1632 1633 int rv = callback.GetResult(transport->Connect(callback.callback())); 1634 EXPECT_EQ(OK, rv); 1635 1636 // Disable TLS False Start to avoid handshake non-determinism. 1637 SSLConfig ssl_config; 1638 ssl_config.false_start_enabled = false; 1639 1640 scoped_ptr<SSLClientSocket> sock( 1641 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 1642 test_server.host_port_pair(), 1643 ssl_config)); 1644 1645 rv = callback.GetResult(sock->Connect(callback.callback())); 1646 EXPECT_EQ(OK, rv); 1647 EXPECT_TRUE(sock->IsConnected()); 1648 1649 // Send a request so there is something to read from the socket. 1650 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1651 static const int kRequestTextSize = 1652 static_cast<int>(arraysize(request_text) - 1); 1653 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize)); 1654 memcpy(request_buffer->data(), request_text, kRequestTextSize); 1655 1656 rv = callback.GetResult( 1657 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback())); 1658 EXPECT_EQ(kRequestTextSize, rv); 1659 1660 // Start a hanging read. 1661 TestCompletionCallback read_callback; 1662 raw_transport->BlockReadResult(); 1663 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1664 rv = sock->Read(buf.get(), 4096, read_callback.callback()); 1665 EXPECT_EQ(ERR_IO_PENDING, rv); 1666 1667 // Perform another write, but have it fail. Write a request larger than the 1668 // internal socket buffers so that the request hits the underlying transport 1669 // socket and detects the error. 1670 std::string long_request_text = 1671 "GET / HTTP/1.1\r\nUser-Agent: long browser name "; 1672 long_request_text.append(20 * 1024, '*'); 1673 long_request_text.append("\r\n\r\n"); 1674 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer( 1675 new StringIOBuffer(long_request_text), long_request_text.size())); 1676 1677 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET); 1678 1679 // Write as much data as possible until hitting an error. This is necessary 1680 // for NSS. PR_Write will only consume as much data as it can encode into 1681 // application data records before the internal memio buffer is full, which 1682 // should only fill if writing a large amount of data and the underlying 1683 // transport is blocked. Once this happens, NSS will return (total size of all 1684 // application data records it wrote) - 1, with the caller expected to resume 1685 // with the remaining unsent data. 1686 do { 1687 rv = callback.GetResult(sock->Write(long_request_buffer.get(), 1688 long_request_buffer->BytesRemaining(), 1689 callback.callback())); 1690 if (rv > 0) { 1691 long_request_buffer->DidConsume(rv); 1692 // Abort if the entire buffer is ever consumed. 1693 ASSERT_LT(0, long_request_buffer->BytesRemaining()); 1694 } 1695 } while (rv > 0); 1696 1697 #if !defined(USE_OPENSSL) 1698 // NSS records the error exactly. 1699 EXPECT_EQ(ERR_CONNECTION_RESET, rv); 1700 #else 1701 // OpenSSL treats the reset as a generic protocol error. 1702 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv); 1703 #endif 1704 1705 // Release the read. Some bytes should go through. 1706 raw_transport->UnblockReadResult(); 1707 rv = read_callback.WaitForResult(); 1708 1709 // Per the fix for http://crbug.com/249848, write failures currently break 1710 // reads. Change this assertion if they're changed to not collide. 1711 EXPECT_EQ(ERR_CONNECTION_RESET, rv); 1712 } 1713 1714 TEST_F(SSLClientSocketTest, Read_SmallChunks) { 1715 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1716 SpawnedTestServer::kLocalhost, 1717 base::FilePath()); 1718 ASSERT_TRUE(test_server.Start()); 1719 1720 AddressList addr; 1721 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1722 1723 TestCompletionCallback callback; 1724 scoped_ptr<StreamSocket> transport( 1725 new TCPClientSocket(addr, NULL, NetLog::Source())); 1726 int rv = transport->Connect(callback.callback()); 1727 if (rv == ERR_IO_PENDING) 1728 rv = callback.WaitForResult(); 1729 EXPECT_EQ(OK, rv); 1730 1731 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1732 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1733 1734 rv = sock->Connect(callback.callback()); 1735 if (rv == ERR_IO_PENDING) 1736 rv = callback.WaitForResult(); 1737 EXPECT_EQ(OK, rv); 1738 1739 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1740 scoped_refptr<IOBuffer> request_buffer( 1741 new IOBuffer(arraysize(request_text) - 1)); 1742 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); 1743 1744 rv = sock->Write( 1745 request_buffer.get(), arraysize(request_text) - 1, callback.callback()); 1746 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1747 1748 if (rv == ERR_IO_PENDING) 1749 rv = callback.WaitForResult(); 1750 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); 1751 1752 scoped_refptr<IOBuffer> buf(new IOBuffer(1)); 1753 for (;;) { 1754 rv = sock->Read(buf.get(), 1, callback.callback()); 1755 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1756 1757 if (rv == ERR_IO_PENDING) 1758 rv = callback.WaitForResult(); 1759 1760 EXPECT_GE(rv, 0); 1761 if (rv <= 0) 1762 break; 1763 } 1764 } 1765 1766 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) { 1767 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1768 SpawnedTestServer::kLocalhost, 1769 base::FilePath()); 1770 ASSERT_TRUE(test_server.Start()); 1771 1772 AddressList addr; 1773 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1774 1775 TestCompletionCallback callback; 1776 1777 scoped_ptr<StreamSocket> real_transport( 1778 new TCPClientSocket(addr, NULL, NetLog::Source())); 1779 scoped_ptr<ReadBufferingStreamSocket> transport( 1780 new ReadBufferingStreamSocket(real_transport.Pass())); 1781 ReadBufferingStreamSocket* raw_transport = transport.get(); 1782 int rv = callback.GetResult(transport->Connect(callback.callback())); 1783 ASSERT_EQ(OK, rv); 1784 1785 scoped_ptr<SSLClientSocket> sock( 1786 CreateSSLClientSocket(transport.PassAs<StreamSocket>(), 1787 test_server.host_port_pair(), 1788 kDefaultSSLConfig)); 1789 1790 rv = callback.GetResult(sock->Connect(callback.callback())); 1791 ASSERT_EQ(OK, rv); 1792 ASSERT_TRUE(sock->IsConnected()); 1793 1794 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n"; 1795 scoped_refptr<IOBuffer> request_buffer( 1796 new IOBuffer(arraysize(request_text) - 1)); 1797 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); 1798 1799 rv = callback.GetResult(sock->Write( 1800 request_buffer.get(), arraysize(request_text) - 1, callback.callback())); 1801 ASSERT_GT(rv, 0); 1802 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); 1803 1804 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of 1805 // data (the max SSL record size) at a time. Ensure that at least 15K worth 1806 // of SSL data is buffered first. The 15K of buffered data is made up of 1807 // many smaller SSL records (the TestServer writes along 1350 byte 1808 // plaintext boundaries), although there may also be a few records that are 1809 // smaller or larger, due to timing and SSL False Start. 1810 // 15K was chosen because 15K is smaller than the 17K (max) read issued by 1811 // the SSLClientSocket implementation, and larger than the minimum amount 1812 // of ciphertext necessary to contain the 8K of plaintext requested below. 1813 raw_transport->SetBufferSize(15000); 1814 1815 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192)); 1816 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback())); 1817 ASSERT_EQ(rv, 8192); 1818 } 1819 1820 TEST_F(SSLClientSocketTest, Read_Interrupted) { 1821 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1822 SpawnedTestServer::kLocalhost, 1823 base::FilePath()); 1824 ASSERT_TRUE(test_server.Start()); 1825 1826 AddressList addr; 1827 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1828 1829 TestCompletionCallback callback; 1830 scoped_ptr<StreamSocket> transport( 1831 new TCPClientSocket(addr, NULL, NetLog::Source())); 1832 int rv = transport->Connect(callback.callback()); 1833 if (rv == ERR_IO_PENDING) 1834 rv = callback.WaitForResult(); 1835 EXPECT_EQ(OK, rv); 1836 1837 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1838 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1839 1840 rv = sock->Connect(callback.callback()); 1841 if (rv == ERR_IO_PENDING) 1842 rv = callback.WaitForResult(); 1843 EXPECT_EQ(OK, rv); 1844 1845 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1846 scoped_refptr<IOBuffer> request_buffer( 1847 new IOBuffer(arraysize(request_text) - 1)); 1848 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); 1849 1850 rv = sock->Write( 1851 request_buffer.get(), arraysize(request_text) - 1, callback.callback()); 1852 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1853 1854 if (rv == ERR_IO_PENDING) 1855 rv = callback.WaitForResult(); 1856 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); 1857 1858 // Do a partial read and then exit. This test should not crash! 1859 scoped_refptr<IOBuffer> buf(new IOBuffer(512)); 1860 rv = sock->Read(buf.get(), 512, callback.callback()); 1861 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING); 1862 1863 if (rv == ERR_IO_PENDING) 1864 rv = callback.WaitForResult(); 1865 1866 EXPECT_GT(rv, 0); 1867 } 1868 1869 TEST_F(SSLClientSocketTest, Read_FullLogging) { 1870 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1871 SpawnedTestServer::kLocalhost, 1872 base::FilePath()); 1873 ASSERT_TRUE(test_server.Start()); 1874 1875 AddressList addr; 1876 ASSERT_TRUE(test_server.GetAddressList(&addr)); 1877 1878 TestCompletionCallback callback; 1879 CapturingNetLog log; 1880 log.SetLogLevel(NetLog::LOG_ALL); 1881 scoped_ptr<StreamSocket> transport( 1882 new TCPClientSocket(addr, &log, NetLog::Source())); 1883 int rv = transport->Connect(callback.callback()); 1884 if (rv == ERR_IO_PENDING) 1885 rv = callback.WaitForResult(); 1886 EXPECT_EQ(OK, rv); 1887 1888 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1889 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1890 1891 rv = sock->Connect(callback.callback()); 1892 if (rv == ERR_IO_PENDING) 1893 rv = callback.WaitForResult(); 1894 EXPECT_EQ(OK, rv); 1895 EXPECT_TRUE(sock->IsConnected()); 1896 1897 const char request_text[] = "GET / HTTP/1.0\r\n\r\n"; 1898 scoped_refptr<IOBuffer> request_buffer( 1899 new IOBuffer(arraysize(request_text) - 1)); 1900 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1); 1901 1902 rv = sock->Write( 1903 request_buffer.get(), arraysize(request_text) - 1, callback.callback()); 1904 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1905 1906 if (rv == ERR_IO_PENDING) 1907 rv = callback.WaitForResult(); 1908 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv); 1909 1910 CapturingNetLog::CapturedEntryList entries; 1911 log.GetEntries(&entries); 1912 size_t last_index = ExpectLogContainsSomewhereAfter( 1913 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE); 1914 1915 scoped_refptr<IOBuffer> buf(new IOBuffer(4096)); 1916 for (;;) { 1917 rv = sock->Read(buf.get(), 4096, callback.callback()); 1918 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 1919 1920 if (rv == ERR_IO_PENDING) 1921 rv = callback.WaitForResult(); 1922 1923 EXPECT_GE(rv, 0); 1924 if (rv <= 0) 1925 break; 1926 1927 log.GetEntries(&entries); 1928 last_index = 1929 ExpectLogContainsSomewhereAfter(entries, 1930 last_index + 1, 1931 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED, 1932 NetLog::PHASE_NONE); 1933 } 1934 } 1935 1936 // Regression test for http://crbug.com/42538 1937 TEST_F(SSLClientSocketTest, PrematureApplicationData) { 1938 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 1939 SpawnedTestServer::kLocalhost, 1940 base::FilePath()); 1941 ASSERT_TRUE(test_server.Start()); 1942 1943 AddressList addr; 1944 TestCompletionCallback callback; 1945 1946 static const unsigned char application_data[] = { 1947 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b, 1948 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46, 1949 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6, 1950 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36, 1951 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d, 1952 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f, 1953 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57, 1954 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82, 1955 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 1956 0x0a}; 1957 1958 // All reads and writes complete synchronously (async=false). 1959 MockRead data_reads[] = { 1960 MockRead(SYNCHRONOUS, 1961 reinterpret_cast<const char*>(application_data), 1962 arraysize(application_data)), 1963 MockRead(SYNCHRONOUS, OK), }; 1964 1965 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0); 1966 1967 scoped_ptr<StreamSocket> transport( 1968 new MockTCPClientSocket(addr, NULL, &data)); 1969 int rv = transport->Connect(callback.callback()); 1970 if (rv == ERR_IO_PENDING) 1971 rv = callback.WaitForResult(); 1972 EXPECT_EQ(OK, rv); 1973 1974 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 1975 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 1976 1977 rv = sock->Connect(callback.callback()); 1978 if (rv == ERR_IO_PENDING) 1979 rv = callback.WaitForResult(); 1980 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv); 1981 } 1982 1983 TEST_F(SSLClientSocketTest, CipherSuiteDisables) { 1984 // Rather than exhaustively disabling every RC4 ciphersuite defined at 1985 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, 1986 // only disabling those cipher suites that the test server actually 1987 // implements. 1988 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA 1989 }; 1990 1991 SpawnedTestServer::SSLOptions ssl_options; 1992 // Enable only RC4 on the test server. 1993 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4; 1994 SpawnedTestServer test_server( 1995 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 1996 ASSERT_TRUE(test_server.Start()); 1997 1998 AddressList addr; 1999 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2000 2001 TestCompletionCallback callback; 2002 CapturingNetLog log; 2003 scoped_ptr<StreamSocket> transport( 2004 new TCPClientSocket(addr, &log, NetLog::Source())); 2005 int rv = transport->Connect(callback.callback()); 2006 if (rv == ERR_IO_PENDING) 2007 rv = callback.WaitForResult(); 2008 EXPECT_EQ(OK, rv); 2009 2010 SSLConfig ssl_config; 2011 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i) 2012 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]); 2013 2014 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2015 transport.Pass(), test_server.host_port_pair(), ssl_config)); 2016 2017 EXPECT_FALSE(sock->IsConnected()); 2018 2019 rv = sock->Connect(callback.callback()); 2020 CapturingNetLog::CapturedEntryList entries; 2021 log.GetEntries(&entries); 2022 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 2023 2024 // NSS has special handling that maps a handshake_failure alert received 2025 // immediately after a client_hello to be a mismatched cipher suite error, 2026 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or 2027 // Secure Transport (OS X), the handshake_failure is bubbled up without any 2028 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure 2029 // indicates that no cipher suite was negotiated with the test server. 2030 if (rv == ERR_IO_PENDING) 2031 rv = callback.WaitForResult(); 2032 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH || 2033 rv == ERR_SSL_PROTOCOL_ERROR); 2034 // The exact ordering differs between SSLClientSocketNSS (which issues an 2035 // extra read) and SSLClientSocketMac (which does not). Just make sure the 2036 // error appears somewhere in the log. 2037 log.GetEntries(&entries); 2038 ExpectLogContainsSomewhere( 2039 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE); 2040 2041 // We cannot test sock->IsConnected(), as the NSS implementation disconnects 2042 // the socket when it encounters an error, whereas other implementations 2043 // leave it connected. 2044 // Because this an error that the test server is mutually aware of, as opposed 2045 // to being an error such as a certificate name mismatch, which is 2046 // client-only, the exact index of the SSL connect end depends on how 2047 // quickly the test server closes the underlying socket. If the test server 2048 // closes before the IO message loop pumps messages, there may be a 0-byte 2049 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a 2050 // result, the SSL connect end event will be the second-to-last entry, 2051 // rather than the last entry. 2052 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) || 2053 LogContainsSSLConnectEndEvent(entries, -2)); 2054 } 2055 2056 // When creating an SSLClientSocket, it is allowed to pass in a 2057 // ClientSocketHandle that is not obtained from a client socket pool. 2058 // Here we verify that such a simple ClientSocketHandle, not associated with any 2059 // client socket pool, can be destroyed safely. 2060 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) { 2061 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2062 SpawnedTestServer::kLocalhost, 2063 base::FilePath()); 2064 ASSERT_TRUE(test_server.Start()); 2065 2066 AddressList addr; 2067 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2068 2069 TestCompletionCallback callback; 2070 scoped_ptr<StreamSocket> transport( 2071 new TCPClientSocket(addr, NULL, NetLog::Source())); 2072 int rv = transport->Connect(callback.callback()); 2073 if (rv == ERR_IO_PENDING) 2074 rv = callback.WaitForResult(); 2075 EXPECT_EQ(OK, rv); 2076 2077 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle()); 2078 socket_handle->SetSocket(transport.Pass()); 2079 2080 scoped_ptr<SSLClientSocket> sock( 2081 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(), 2082 test_server.host_port_pair(), 2083 kDefaultSSLConfig, 2084 context_)); 2085 2086 EXPECT_FALSE(sock->IsConnected()); 2087 rv = sock->Connect(callback.callback()); 2088 if (rv == ERR_IO_PENDING) 2089 rv = callback.WaitForResult(); 2090 EXPECT_EQ(OK, rv); 2091 } 2092 2093 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success 2094 // code and different keying label results in different keying material. 2095 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) { 2096 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2097 SpawnedTestServer::kLocalhost, 2098 base::FilePath()); 2099 ASSERT_TRUE(test_server.Start()); 2100 2101 AddressList addr; 2102 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2103 2104 TestCompletionCallback callback; 2105 2106 scoped_ptr<StreamSocket> transport( 2107 new TCPClientSocket(addr, NULL, NetLog::Source())); 2108 int rv = transport->Connect(callback.callback()); 2109 if (rv == ERR_IO_PENDING) 2110 rv = callback.WaitForResult(); 2111 EXPECT_EQ(OK, rv); 2112 2113 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2114 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 2115 2116 rv = sock->Connect(callback.callback()); 2117 if (rv == ERR_IO_PENDING) 2118 rv = callback.WaitForResult(); 2119 EXPECT_EQ(OK, rv); 2120 EXPECT_TRUE(sock->IsConnected()); 2121 2122 const int kKeyingMaterialSize = 32; 2123 const char* kKeyingLabel1 = "client-socket-test-1"; 2124 const char* kKeyingContext = ""; 2125 unsigned char client_out1[kKeyingMaterialSize]; 2126 memset(client_out1, 0, sizeof(client_out1)); 2127 rv = sock->ExportKeyingMaterial( 2128 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1)); 2129 EXPECT_EQ(rv, OK); 2130 2131 const char* kKeyingLabel2 = "client-socket-test-2"; 2132 unsigned char client_out2[kKeyingMaterialSize]; 2133 memset(client_out2, 0, sizeof(client_out2)); 2134 rv = sock->ExportKeyingMaterial( 2135 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2)); 2136 EXPECT_EQ(rv, OK); 2137 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0); 2138 } 2139 2140 // Verifies that SSLClientSocket::ClearSessionCache can be called without 2141 // explicit NSS initialization. 2142 TEST(SSLClientSocket, ClearSessionCache) { 2143 SSLClientSocket::ClearSessionCache(); 2144 } 2145 2146 // Test that the server certificates are properly retrieved from the underlying 2147 // SSL stack. 2148 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) { 2149 // The connection does not have to be successful. 2150 cert_verifier_->set_default_result(ERR_CERT_INVALID); 2151 2152 // Set up a test server with CERT_CHAIN_WRONG_ROOT. 2153 // This makes the server present redundant-server-chain.pem, which contains 2154 // intermediate certificates. 2155 SpawnedTestServer::SSLOptions ssl_options( 2156 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT); 2157 SpawnedTestServer test_server( 2158 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()); 2159 ASSERT_TRUE(test_server.Start()); 2160 2161 AddressList addr; 2162 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2163 2164 TestCompletionCallback callback; 2165 scoped_ptr<StreamSocket> transport( 2166 new TCPClientSocket(addr, NULL, NetLog::Source())); 2167 int rv = transport->Connect(callback.callback()); 2168 rv = callback.GetResult(rv); 2169 EXPECT_EQ(OK, rv); 2170 2171 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2172 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 2173 EXPECT_FALSE(sock->IsConnected()); 2174 rv = sock->Connect(callback.callback()); 2175 rv = callback.GetResult(rv); 2176 2177 EXPECT_EQ(ERR_CERT_INVALID, rv); 2178 EXPECT_TRUE(sock->IsConnected()); 2179 2180 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present 2181 // certs from redundant-server-chain.pem. 2182 CertificateList server_certs = 2183 CreateCertificateListFromFile(GetTestCertsDirectory(), 2184 "redundant-server-chain.pem", 2185 X509Certificate::FORMAT_AUTO); 2186 2187 // Get the server certificate as received client side. 2188 scoped_refptr<X509Certificate> server_certificate = 2189 sock->GetUnverifiedServerCertificateChain(); 2190 2191 // Get the intermediates as received client side. 2192 const X509Certificate::OSCertHandles& server_intermediates = 2193 server_certificate->GetIntermediateCertificates(); 2194 2195 // Check that the unverified server certificate chain is properly retrieved 2196 // from the underlying ssl stack. 2197 ASSERT_EQ(4U, server_certs.size()); 2198 2199 EXPECT_TRUE(X509Certificate::IsSameOSCert( 2200 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle())); 2201 2202 ASSERT_EQ(3U, server_intermediates.size()); 2203 2204 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0], 2205 server_certs[1]->os_cert_handle())); 2206 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1], 2207 server_certs[2]->os_cert_handle())); 2208 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2], 2209 server_certs[3]->os_cert_handle())); 2210 2211 sock->Disconnect(); 2212 EXPECT_FALSE(sock->IsConnected()); 2213 } 2214 2215 // This tests that SSLInfo contains a properly re-constructed certificate 2216 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as 2217 // verified, not the chain as served by the server. (They may be different.) 2218 // 2219 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A 2220 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem 2221 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but 2222 // a self-signed root. Such a situation can occur when a new root (C2) is 2223 // cross-certified by an old root (D) and has two different versions of its 2224 // floating around. Servers may supply C2 as an intermediate, but the 2225 // SSLClientSocket should return the chain that was verified, from 2226 // verify_result, instead. 2227 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) { 2228 // By default, cause the CertVerifier to treat all certificates as 2229 // expired. 2230 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID); 2231 2232 // We will expect SSLInfo to ultimately contain this chain. 2233 CertificateList certs = 2234 CreateCertificateListFromFile(GetTestCertsDirectory(), 2235 "redundant-validated-chain.pem", 2236 X509Certificate::FORMAT_AUTO); 2237 ASSERT_EQ(3U, certs.size()); 2238 2239 X509Certificate::OSCertHandles temp_intermediates; 2240 temp_intermediates.push_back(certs[1]->os_cert_handle()); 2241 temp_intermediates.push_back(certs[2]->os_cert_handle()); 2242 2243 CertVerifyResult verify_result; 2244 verify_result.verified_cert = X509Certificate::CreateFromHandle( 2245 certs[0]->os_cert_handle(), temp_intermediates); 2246 2247 // Add a rule that maps the server cert (A) to the chain of A->B->C2 2248 // rather than A->B->C. 2249 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK); 2250 2251 // Load and install the root for the validated chain. 2252 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile( 2253 GetTestCertsDirectory(), "redundant-validated-chain-root.pem"); 2254 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert); 2255 ScopedTestRoot scoped_root(root_cert.get()); 2256 2257 // Set up a test server with CERT_CHAIN_WRONG_ROOT. 2258 SpawnedTestServer::SSLOptions ssl_options( 2259 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT); 2260 SpawnedTestServer test_server( 2261 SpawnedTestServer::TYPE_HTTPS, 2262 ssl_options, 2263 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 2264 ASSERT_TRUE(test_server.Start()); 2265 2266 AddressList addr; 2267 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2268 2269 TestCompletionCallback callback; 2270 CapturingNetLog log; 2271 scoped_ptr<StreamSocket> transport( 2272 new TCPClientSocket(addr, &log, NetLog::Source())); 2273 int rv = transport->Connect(callback.callback()); 2274 if (rv == ERR_IO_PENDING) 2275 rv = callback.WaitForResult(); 2276 EXPECT_EQ(OK, rv); 2277 2278 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2279 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 2280 EXPECT_FALSE(sock->IsConnected()); 2281 rv = sock->Connect(callback.callback()); 2282 2283 CapturingNetLog::CapturedEntryList entries; 2284 log.GetEntries(&entries); 2285 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 2286 if (rv == ERR_IO_PENDING) 2287 rv = callback.WaitForResult(); 2288 2289 EXPECT_EQ(OK, rv); 2290 EXPECT_TRUE(sock->IsConnected()); 2291 log.GetEntries(&entries); 2292 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 2293 2294 SSLInfo ssl_info; 2295 sock->GetSSLInfo(&ssl_info); 2296 2297 // Verify that SSLInfo contains the corrected re-constructed chain A -> B 2298 // -> C2. 2299 const X509Certificate::OSCertHandles& intermediates = 2300 ssl_info.cert->GetIntermediateCertificates(); 2301 ASSERT_EQ(2U, intermediates.size()); 2302 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(), 2303 certs[0]->os_cert_handle())); 2304 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0], 2305 certs[1]->os_cert_handle())); 2306 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1], 2307 certs[2]->os_cert_handle())); 2308 2309 sock->Disconnect(); 2310 EXPECT_FALSE(sock->IsConnected()); 2311 } 2312 2313 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) { 2314 SpawnedTestServer::SSLOptions ssl_options; 2315 ssl_options.request_client_certificate = true; 2316 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options); 2317 ASSERT_TRUE(request_info.get()); 2318 EXPECT_EQ(0u, request_info->cert_authorities.size()); 2319 } 2320 2321 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) { 2322 const base::FilePath::CharType kThawteFile[] = 2323 FILE_PATH_LITERAL("thawte.single.pem"); 2324 const unsigned char kThawteDN[] = { 2325 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 2326 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a, 2327 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e, 2328 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79, 2329 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 2330 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 2331 0x53, 0x47, 0x43, 0x20, 0x43, 0x41}; 2332 const size_t kThawteLen = sizeof(kThawteDN); 2333 2334 const base::FilePath::CharType kDiginotarFile[] = 2335 FILE_PATH_LITERAL("diginotar_root_ca.pem"); 2336 const unsigned char kDiginotarDN[] = { 2337 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 2338 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a, 2339 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31, 2340 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69, 2341 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74, 2342 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 2343 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f, 2344 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e, 2345 0x6c}; 2346 const size_t kDiginotarLen = sizeof(kDiginotarDN); 2347 2348 SpawnedTestServer::SSLOptions ssl_options; 2349 ssl_options.request_client_certificate = true; 2350 ssl_options.client_authorities.push_back( 2351 GetTestClientCertsDirectory().Append(kThawteFile)); 2352 ssl_options.client_authorities.push_back( 2353 GetTestClientCertsDirectory().Append(kDiginotarFile)); 2354 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options); 2355 ASSERT_TRUE(request_info.get()); 2356 ASSERT_EQ(2u, request_info->cert_authorities.size()); 2357 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen), 2358 request_info->cert_authorities[0]); 2359 EXPECT_EQ( 2360 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen), 2361 request_info->cert_authorities[1]); 2362 } 2363 2364 // cert_key_types is currently only populated on OpenSSL. 2365 #if defined(USE_OPENSSL) 2366 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) { 2367 SpawnedTestServer::SSLOptions ssl_options; 2368 ssl_options.request_client_certificate = true; 2369 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN); 2370 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN); 2371 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options); 2372 ASSERT_TRUE(request_info.get()); 2373 ASSERT_EQ(2u, request_info->cert_key_types.size()); 2374 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]); 2375 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]); 2376 } 2377 #endif // defined(USE_OPENSSL) 2378 2379 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) { 2380 SpawnedTestServer::SSLOptions ssl_options; 2381 ssl_options.signed_cert_timestamps_tls_ext = "test"; 2382 2383 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2384 ssl_options, 2385 base::FilePath()); 2386 ASSERT_TRUE(test_server.Start()); 2387 2388 AddressList addr; 2389 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2390 2391 TestCompletionCallback callback; 2392 CapturingNetLog log; 2393 scoped_ptr<StreamSocket> transport( 2394 new TCPClientSocket(addr, &log, NetLog::Source())); 2395 int rv = transport->Connect(callback.callback()); 2396 if (rv == ERR_IO_PENDING) 2397 rv = callback.WaitForResult(); 2398 EXPECT_EQ(OK, rv); 2399 2400 SSLConfig ssl_config; 2401 ssl_config.signed_cert_timestamps_enabled = true; 2402 2403 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2404 transport.Pass(), test_server.host_port_pair(), ssl_config)); 2405 2406 EXPECT_FALSE(sock->IsConnected()); 2407 2408 rv = sock->Connect(callback.callback()); 2409 2410 CapturingNetLog::CapturedEntryList entries; 2411 log.GetEntries(&entries); 2412 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 2413 if (rv == ERR_IO_PENDING) 2414 rv = callback.WaitForResult(); 2415 EXPECT_EQ(OK, rv); 2416 EXPECT_TRUE(sock->IsConnected()); 2417 log.GetEntries(&entries); 2418 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 2419 2420 #if !defined(USE_OPENSSL) 2421 EXPECT_TRUE(sock->signed_cert_timestamps_received_); 2422 #else 2423 // Enabling CT for OpenSSL is currently a noop. 2424 EXPECT_FALSE(sock->signed_cert_timestamps_received_); 2425 #endif 2426 2427 sock->Disconnect(); 2428 EXPECT_FALSE(sock->IsConnected()); 2429 } 2430 2431 // Test that enabling Signed Certificate Timestamps enables OCSP stapling. 2432 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) { 2433 SpawnedTestServer::SSLOptions ssl_options; 2434 ssl_options.staple_ocsp_response = true; 2435 // The test server currently only knows how to generate OCSP responses 2436 // for a freshly minted certificate. 2437 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO; 2438 2439 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2440 ssl_options, 2441 base::FilePath()); 2442 ASSERT_TRUE(test_server.Start()); 2443 2444 AddressList addr; 2445 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2446 2447 TestCompletionCallback callback; 2448 CapturingNetLog log; 2449 scoped_ptr<StreamSocket> transport( 2450 new TCPClientSocket(addr, &log, NetLog::Source())); 2451 int rv = transport->Connect(callback.callback()); 2452 if (rv == ERR_IO_PENDING) 2453 rv = callback.WaitForResult(); 2454 EXPECT_EQ(OK, rv); 2455 2456 SSLConfig ssl_config; 2457 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for 2458 // Certificate Transparency verification regardless of whether the platform 2459 // is able to process the OCSP status itself. 2460 ssl_config.signed_cert_timestamps_enabled = true; 2461 2462 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2463 transport.Pass(), test_server.host_port_pair(), ssl_config)); 2464 2465 EXPECT_FALSE(sock->IsConnected()); 2466 2467 rv = sock->Connect(callback.callback()); 2468 2469 CapturingNetLog::CapturedEntryList entries; 2470 log.GetEntries(&entries); 2471 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 2472 if (rv == ERR_IO_PENDING) 2473 rv = callback.WaitForResult(); 2474 EXPECT_EQ(OK, rv); 2475 EXPECT_TRUE(sock->IsConnected()); 2476 log.GetEntries(&entries); 2477 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 2478 2479 #if !defined(USE_OPENSSL) 2480 EXPECT_TRUE(sock->stapled_ocsp_response_received_); 2481 #else 2482 // OCSP stapling isn't currently supported in the OpenSSL socket. 2483 EXPECT_FALSE(sock->stapled_ocsp_response_received_); 2484 #endif 2485 2486 sock->Disconnect(); 2487 EXPECT_FALSE(sock->IsConnected()); 2488 } 2489 2490 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) { 2491 SpawnedTestServer::SSLOptions ssl_options; 2492 ssl_options.signed_cert_timestamps_tls_ext = "test"; 2493 2494 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2495 ssl_options, 2496 base::FilePath()); 2497 ASSERT_TRUE(test_server.Start()); 2498 2499 AddressList addr; 2500 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2501 2502 TestCompletionCallback callback; 2503 CapturingNetLog log; 2504 scoped_ptr<StreamSocket> transport( 2505 new TCPClientSocket(addr, &log, NetLog::Source())); 2506 int rv = transport->Connect(callback.callback()); 2507 if (rv == ERR_IO_PENDING) 2508 rv = callback.WaitForResult(); 2509 EXPECT_EQ(OK, rv); 2510 2511 SSLConfig ssl_config; 2512 ssl_config.signed_cert_timestamps_enabled = false; 2513 2514 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2515 transport.Pass(), test_server.host_port_pair(), ssl_config)); 2516 2517 EXPECT_FALSE(sock->IsConnected()); 2518 2519 rv = sock->Connect(callback.callback()); 2520 2521 CapturingNetLog::CapturedEntryList entries; 2522 log.GetEntries(&entries); 2523 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT)); 2524 if (rv == ERR_IO_PENDING) 2525 rv = callback.WaitForResult(); 2526 EXPECT_EQ(OK, rv); 2527 EXPECT_TRUE(sock->IsConnected()); 2528 log.GetEntries(&entries); 2529 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1)); 2530 2531 EXPECT_FALSE(sock->signed_cert_timestamps_received_); 2532 2533 sock->Disconnect(); 2534 EXPECT_FALSE(sock->IsConnected()); 2535 } 2536 2537 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected. 2538 TEST_F(SSLClientSocketTest, ReuseStates) { 2539 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, 2540 SpawnedTestServer::kLocalhost, 2541 base::FilePath()); 2542 ASSERT_TRUE(test_server.Start()); 2543 2544 AddressList addr; 2545 ASSERT_TRUE(test_server.GetAddressList(&addr)); 2546 2547 TestCompletionCallback callback; 2548 scoped_ptr<StreamSocket> transport( 2549 new TCPClientSocket(addr, NULL, NetLog::Source())); 2550 int rv = transport->Connect(callback.callback()); 2551 if (rv == ERR_IO_PENDING) 2552 rv = callback.WaitForResult(); 2553 EXPECT_EQ(OK, rv); 2554 2555 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket( 2556 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig)); 2557 2558 rv = sock->Connect(callback.callback()); 2559 if (rv == ERR_IO_PENDING) 2560 rv = callback.WaitForResult(); 2561 EXPECT_EQ(OK, rv); 2562 2563 // The socket was just connected. It should be idle because it is speaking 2564 // HTTP. Although the transport has been used for the handshake, WasEverUsed() 2565 // returns false. 2566 EXPECT_TRUE(sock->IsConnected()); 2567 EXPECT_TRUE(sock->IsConnectedAndIdle()); 2568 EXPECT_FALSE(sock->WasEverUsed()); 2569 2570 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n"; 2571 const size_t kRequestLen = arraysize(kRequestText) - 1; 2572 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen)); 2573 memcpy(request_buffer->data(), kRequestText, kRequestLen); 2574 2575 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback()); 2576 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING); 2577 2578 if (rv == ERR_IO_PENDING) 2579 rv = callback.WaitForResult(); 2580 EXPECT_EQ(static_cast<int>(kRequestLen), rv); 2581 2582 // The socket has now been used. 2583 EXPECT_TRUE(sock->WasEverUsed()); 2584 2585 // TODO(davidben): Read one byte to ensure the test server has responded and 2586 // then assert IsConnectedAndIdle is false. This currently doesn't work 2587 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their 2588 // SSL implementation's internal buffers. Either call PR_Available and 2589 // SSL_pending, although the former isn't actually implemented or perhaps 2590 // attempt to read one byte extra. 2591 } 2592 2593 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) { 2594 // False Start requires NPN and a forward-secret cipher suite. 2595 SpawnedTestServer::SSLOptions server_options; 2596 server_options.key_exchanges = 2597 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; 2598 server_options.enable_npn = true; 2599 SSLConfig client_config; 2600 client_config.next_protos.push_back("http/1.1"); 2601 ASSERT_NO_FATAL_FAILURE( 2602 TestFalseStart(server_options, client_config, true)); 2603 } 2604 2605 // Test that False Start is disabled without NPN. 2606 TEST_F(SSLClientSocketFalseStartTest, NoNPN) { 2607 SpawnedTestServer::SSLOptions server_options; 2608 server_options.key_exchanges = 2609 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; 2610 SSLConfig client_config; 2611 client_config.next_protos.clear(); 2612 ASSERT_NO_FATAL_FAILURE( 2613 TestFalseStart(server_options, client_config, false)); 2614 } 2615 2616 // Test that False Start is disabled without a forward-secret cipher suite. 2617 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) { 2618 SpawnedTestServer::SSLOptions server_options; 2619 server_options.key_exchanges = 2620 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA; 2621 server_options.enable_npn = true; 2622 SSLConfig client_config; 2623 client_config.next_protos.push_back("http/1.1"); 2624 ASSERT_NO_FATAL_FAILURE( 2625 TestFalseStart(server_options, client_config, false)); 2626 } 2627 2628 // Test that sessions are resumable after receiving the server Finished message. 2629 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) { 2630 // Start a server. 2631 SpawnedTestServer::SSLOptions server_options; 2632 server_options.key_exchanges = 2633 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; 2634 server_options.enable_npn = true; 2635 SSLConfig client_config; 2636 client_config.next_protos.push_back("http/1.1"); 2637 2638 // Let a full handshake complete with False Start. 2639 ASSERT_NO_FATAL_FAILURE( 2640 TestFalseStart(server_options, client_config, true)); 2641 2642 // Make a second connection. 2643 TestCompletionCallback callback; 2644 scoped_ptr<StreamSocket> transport2( 2645 new TCPClientSocket(addr(), &log_, NetLog::Source())); 2646 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback()))); 2647 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket( 2648 transport2.Pass(), test_server()->host_port_pair(), client_config); 2649 ASSERT_TRUE(sock2.get()); 2650 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback()))); 2651 2652 // It should resume the session. 2653 SSLInfo ssl_info; 2654 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info)); 2655 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type); 2656 } 2657 2658 // Test that sessions are not resumable before receiving the server Finished 2659 // message. 2660 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) { 2661 // Start a server. 2662 SpawnedTestServer::SSLOptions server_options; 2663 server_options.key_exchanges = 2664 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA; 2665 server_options.enable_npn = true; 2666 ASSERT_TRUE(StartTestServer(server_options)); 2667 2668 SSLConfig client_config; 2669 client_config.next_protos.push_back("http/1.1"); 2670 2671 // Start a handshake up to the server Finished message. 2672 TestCompletionCallback callback; 2673 FakeBlockingStreamSocket* raw_transport1; 2674 scoped_ptr<SSLClientSocket> sock1; 2675 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived( 2676 client_config, &callback, &raw_transport1, &sock1)); 2677 // Although raw_transport1 has the server Finished blocked, the handshake 2678 // still completes. 2679 EXPECT_EQ(OK, callback.WaitForResult()); 2680 2681 // Drop the old socket. This is needed because the Python test server can't 2682 // service two sockets in parallel. 2683 sock1.reset(); 2684 2685 // Start a second connection. 2686 scoped_ptr<StreamSocket> transport2( 2687 new TCPClientSocket(addr(), &log_, NetLog::Source())); 2688 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback()))); 2689 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket( 2690 transport2.Pass(), test_server()->host_port_pair(), client_config); 2691 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback()))); 2692 2693 // No session resumption because the first connection never received a server 2694 // Finished message. 2695 SSLInfo ssl_info; 2696 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info)); 2697 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type); 2698 } 2699 2700 // Connect to a server using channel id. It should allow the connection. 2701 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) { 2702 SpawnedTestServer::SSLOptions ssl_options; 2703 2704 ASSERT_TRUE(ConnectToTestServer(ssl_options)); 2705 2706 EnableChannelID(); 2707 SSLConfig ssl_config = kDefaultSSLConfig; 2708 ssl_config.channel_id_enabled = true; 2709 2710 int rv; 2711 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); 2712 2713 EXPECT_EQ(OK, rv); 2714 EXPECT_TRUE(sock_->IsConnected()); 2715 EXPECT_TRUE(sock_->WasChannelIDSent()); 2716 2717 sock_->Disconnect(); 2718 EXPECT_FALSE(sock_->IsConnected()); 2719 } 2720 2721 // Connect to a server using channel id but without sending a key. It should 2722 // fail. 2723 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) { 2724 SpawnedTestServer::SSLOptions ssl_options; 2725 2726 ASSERT_TRUE(ConnectToTestServer(ssl_options)); 2727 2728 EnableFailingChannelID(); 2729 SSLConfig ssl_config = kDefaultSSLConfig; 2730 ssl_config.channel_id_enabled = true; 2731 2732 int rv; 2733 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv)); 2734 2735 // TODO(haavardm (at) opera.com): Due to differences in threading, Linux returns 2736 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all 2737 // error codes for now. 2738 // http://crbug.com/373670 2739 EXPECT_NE(OK, rv); 2740 EXPECT_FALSE(sock_->IsConnected()); 2741 } 2742 2743 } // namespace net 2744