1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/ssl_client_socket.h"
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/asn1_util.h"
19 #include "net/cert/ct_verifier.h"
20 #include "net/cert/mock_cert_verifier.h"
21 #include "net/cert/test_root_certs.h"
22 #include "net/dns/host_resolver.h"
23 #include "net/http/transport_security_state.h"
24 #include "net/socket/client_socket_factory.h"
25 #include "net/socket/client_socket_handle.h"
26 #include "net/socket/socket_test_util.h"
27 #include "net/socket/tcp_client_socket.h"
28 #include "net/ssl/channel_id_service.h"
29 #include "net/ssl/default_channel_id_store.h"
30 #include "net/ssl/ssl_cert_request_info.h"
31 #include "net/ssl/ssl_config_service.h"
32 #include "net/test/cert_test_util.h"
33 #include "net/test/spawned_test_server/spawned_test_server.h"
34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gtest/include/gtest/gtest.h"
36 #include "testing/platform_test.h"
38 //-----------------------------------------------------------------------------
41 using testing::Return;
48 const SSLConfig kDefaultSSLConfig;
50 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
51 // forwarding the Socket and StreamSocket interfaces to the underlying
53 // This is to provide a common base class for subclasses to override specific
54 // StreamSocket methods for testing, while still communicating with a 'real'
56 class WrappedStreamSocket : public StreamSocket {
58 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
59 : transport_(transport.Pass()) {}
60 virtual ~WrappedStreamSocket() {}
62 // StreamSocket implementation:
63 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
64 return transport_->Connect(callback);
66 virtual void Disconnect() OVERRIDE { transport_->Disconnect(); }
67 virtual bool IsConnected() const OVERRIDE {
68 return transport_->IsConnected();
70 virtual bool IsConnectedAndIdle() const OVERRIDE {
71 return transport_->IsConnectedAndIdle();
73 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
74 return transport_->GetPeerAddress(address);
76 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
77 return transport_->GetLocalAddress(address);
79 virtual const BoundNetLog& NetLog() const OVERRIDE {
80 return transport_->NetLog();
82 virtual void SetSubresourceSpeculation() OVERRIDE {
83 transport_->SetSubresourceSpeculation();
85 virtual void SetOmniboxSpeculation() OVERRIDE {
86 transport_->SetOmniboxSpeculation();
88 virtual bool WasEverUsed() const OVERRIDE {
89 return transport_->WasEverUsed();
91 virtual bool UsingTCPFastOpen() const OVERRIDE {
92 return transport_->UsingTCPFastOpen();
94 virtual bool WasNpnNegotiated() const OVERRIDE {
95 return transport_->WasNpnNegotiated();
97 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
98 return transport_->GetNegotiatedProtocol();
100 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
101 return transport_->GetSSLInfo(ssl_info);
104 // Socket implementation:
105 virtual int Read(IOBuffer* buf,
107 const CompletionCallback& callback) OVERRIDE {
108 return transport_->Read(buf, buf_len, callback);
110 virtual int Write(IOBuffer* buf,
112 const CompletionCallback& callback) OVERRIDE {
113 return transport_->Write(buf, buf_len, callback);
115 virtual int SetReceiveBufferSize(int32 size) OVERRIDE {
116 return transport_->SetReceiveBufferSize(size);
118 virtual int SetSendBufferSize(int32 size) OVERRIDE {
119 return transport_->SetSendBufferSize(size);
123 scoped_ptr<StreamSocket> transport_;
126 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
127 // will ensure a certain amount of data is internally buffered before
128 // satisfying a Read() request. It exists to mimic OS-level internal
129 // buffering, but in a way to guarantee that X number of bytes will be
130 // returned to callers of Read(), regardless of how quickly the OS receives
131 // them from the TestServer.
132 class ReadBufferingStreamSocket : public WrappedStreamSocket {
134 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
135 virtual ~ReadBufferingStreamSocket() {}
137 // Socket implementation:
138 virtual int Read(IOBuffer* buf,
140 const CompletionCallback& callback) OVERRIDE;
142 // Sets the internal buffer to |size|. This must not be greater than
143 // the largest value supplied to Read() - that is, it does not handle
144 // having "leftovers" at the end of Read().
145 // Each call to Read() will be prevented from completion until at least
146 // |size| data has been read.
147 // Set to 0 to turn off buffering, causing Read() to transparently
148 // read via the underlying transport.
149 void SetBufferSize(int size);
158 int DoLoop(int result);
160 int DoReadComplete(int result);
161 void OnReadCompleted(int result);
164 scoped_refptr<GrowableIOBuffer> read_buffer_;
167 scoped_refptr<IOBuffer> user_read_buf_;
168 CompletionCallback user_read_callback_;
171 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
172 scoped_ptr<StreamSocket> transport)
173 : WrappedStreamSocket(transport.Pass()),
174 read_buffer_(new GrowableIOBuffer()),
177 void ReadBufferingStreamSocket::SetBufferSize(int size) {
178 DCHECK(!user_read_buf_.get());
180 read_buffer_->SetCapacity(size);
183 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
185 const CompletionCallback& callback) {
186 if (buffer_size_ == 0)
187 return transport_->Read(buf, buf_len, callback);
189 if (buf_len < buffer_size_)
190 return ERR_UNEXPECTED;
193 user_read_buf_ = buf;
194 int result = DoLoop(OK);
195 if (result == ERR_IO_PENDING)
196 user_read_callback_ = callback;
198 user_read_buf_ = NULL;
202 int ReadBufferingStreamSocket::DoLoop(int result) {
205 State current_state = state_;
207 switch (current_state) {
211 case STATE_READ_COMPLETE:
212 rv = DoReadComplete(rv);
216 NOTREACHED() << "Unexpected state: " << current_state;
220 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
224 int ReadBufferingStreamSocket::DoRead() {
225 state_ = STATE_READ_COMPLETE;
227 transport_->Read(read_buffer_.get(),
228 read_buffer_->RemainingCapacity(),
229 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
230 base::Unretained(this)));
234 int ReadBufferingStreamSocket::DoReadComplete(int result) {
239 read_buffer_->set_offset(read_buffer_->offset() + result);
240 if (read_buffer_->RemainingCapacity() > 0) {
245 memcpy(user_read_buf_->data(),
246 read_buffer_->StartOfBuffer(),
247 read_buffer_->capacity());
248 read_buffer_->set_offset(0);
249 return read_buffer_->capacity();
252 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
253 result = DoLoop(result);
254 if (result == ERR_IO_PENDING)
257 user_read_buf_ = NULL;
258 base::ResetAndReturn(&user_read_callback_).Run(result);
261 // Simulates synchronously receiving an error during Read() or Write()
262 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
264 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
265 virtual ~SynchronousErrorStreamSocket() {}
267 // Socket implementation:
268 virtual int Read(IOBuffer* buf,
270 const CompletionCallback& callback) OVERRIDE;
271 virtual int Write(IOBuffer* buf,
273 const CompletionCallback& callback) OVERRIDE;
275 // Sets the next Read() call and all future calls to return |error|.
276 // If there is already a pending asynchronous read, the configured error
277 // will not be returned until that asynchronous read has completed and Read()
279 void SetNextReadError(int error) {
281 have_read_error_ = true;
282 pending_read_error_ = error;
285 // Sets the next Write() call and all future calls to return |error|.
286 // If there is already a pending asynchronous write, the configured error
287 // will not be returned until that asynchronous write has completed and
288 // Write() is called again.
289 void SetNextWriteError(int error) {
291 have_write_error_ = true;
292 pending_write_error_ = error;
296 bool have_read_error_;
297 int pending_read_error_;
299 bool have_write_error_;
300 int pending_write_error_;
302 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
305 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
306 scoped_ptr<StreamSocket> transport)
307 : WrappedStreamSocket(transport.Pass()),
308 have_read_error_(false),
309 pending_read_error_(OK),
310 have_write_error_(false),
311 pending_write_error_(OK) {}
313 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
315 const CompletionCallback& callback) {
316 if (have_read_error_)
317 return pending_read_error_;
318 return transport_->Read(buf, buf_len, callback);
321 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
323 const CompletionCallback& callback) {
324 if (have_write_error_)
325 return pending_write_error_;
326 return transport_->Write(buf, buf_len, callback);
329 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
330 // underlying transport needing to complete things asynchronously in a
331 // deterministic manner (e.g.: independent of the TestServer and the OS's
333 class FakeBlockingStreamSocket : public WrappedStreamSocket {
335 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
336 virtual ~FakeBlockingStreamSocket() {}
338 // Socket implementation:
339 virtual int Read(IOBuffer* buf,
341 const CompletionCallback& callback) OVERRIDE;
342 virtual int Write(IOBuffer* buf,
344 const CompletionCallback& callback) OVERRIDE;
346 // Blocks read results on the socket. Reads will not complete until
347 // UnblockReadResult() has been called and a result is ready from the
348 // underlying transport. Note: if BlockReadResult() is called while there is a
349 // hanging asynchronous Read(), that Read is blocked.
350 void BlockReadResult();
351 void UnblockReadResult();
353 // Waits for the blocked Read() call to be complete at the underlying
355 void WaitForReadResult();
357 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
358 // underlying transport until UnblockWrite() has been called. Note: if there
359 // is a pending asynchronous write, it is NOT blocked. For purposes of
360 // blocking writes, data is considered to have reached the underlying
361 // transport as soon as Write() is called.
365 // Waits for the blocked Write() call to be scheduled.
368 // Returns the wrapped stream socket.
369 StreamSocket* transport() { return transport_.get(); }
372 // Handles completion from the underlying transport read.
373 void OnReadCompleted(int result);
375 // True if read callbacks are blocked.
376 bool should_block_read_;
378 // The user callback for the pending read call.
379 CompletionCallback pending_read_callback_;
381 // The result for the blocked read callback, or ERR_IO_PENDING if not
383 int pending_read_result_;
385 // WaitForReadResult() wait loop.
386 scoped_ptr<base::RunLoop> read_loop_;
388 // True if write calls are blocked.
389 bool should_block_write_;
391 // The buffer for the pending write, or NULL if not scheduled.
392 scoped_refptr<IOBuffer> pending_write_buf_;
394 // The callback for the pending write call.
395 CompletionCallback pending_write_callback_;
397 // The length for the pending write, or -1 if not scheduled.
398 int pending_write_len_;
400 // WaitForWrite() wait loop.
401 scoped_ptr<base::RunLoop> write_loop_;
404 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
405 scoped_ptr<StreamSocket> transport)
406 : WrappedStreamSocket(transport.Pass()),
407 should_block_read_(false),
408 pending_read_result_(ERR_IO_PENDING),
409 should_block_write_(false),
410 pending_write_len_(-1) {}
412 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
414 const CompletionCallback& callback) {
415 DCHECK(pending_read_callback_.is_null());
416 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
417 DCHECK(!callback.is_null());
419 int rv = transport_->Read(buf, len, base::Bind(
420 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
421 if (rv == ERR_IO_PENDING) {
422 // Save the callback to be called later.
423 pending_read_callback_ = callback;
424 } else if (should_block_read_) {
425 // Save the callback and read result to be called later.
426 pending_read_callback_ = callback;
433 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
435 const CompletionCallback& callback) {
439 if (!should_block_write_)
440 return transport_->Write(buf, len, callback);
442 // Schedule the write, but do nothing.
443 DCHECK(!pending_write_buf_.get());
444 DCHECK_EQ(-1, pending_write_len_);
445 DCHECK(pending_write_callback_.is_null());
446 DCHECK(!callback.is_null());
447 pending_write_buf_ = buf;
448 pending_write_len_ = len;
449 pending_write_callback_ = callback;
451 // Stop the write loop, if any.
454 return ERR_IO_PENDING;
457 void FakeBlockingStreamSocket::BlockReadResult() {
458 DCHECK(!should_block_read_);
459 should_block_read_ = true;
462 void FakeBlockingStreamSocket::UnblockReadResult() {
463 DCHECK(should_block_read_);
464 should_block_read_ = false;
466 // If the operation is still pending in the underlying transport, immediately
467 // return - OnReadCompleted() will handle invoking the callback once the
468 // transport has completed.
469 if (pending_read_result_ == ERR_IO_PENDING)
471 int result = pending_read_result_;
472 pending_read_result_ = ERR_IO_PENDING;
473 base::ResetAndReturn(&pending_read_callback_).Run(result);
476 void FakeBlockingStreamSocket::WaitForReadResult() {
477 DCHECK(should_block_read_);
480 if (pending_read_result_ != ERR_IO_PENDING)
482 read_loop_.reset(new base::RunLoop);
485 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
488 void FakeBlockingStreamSocket::BlockWrite() {
489 DCHECK(!should_block_write_);
490 should_block_write_ = true;
493 void FakeBlockingStreamSocket::UnblockWrite() {
494 DCHECK(should_block_write_);
495 should_block_write_ = false;
497 // Do nothing if UnblockWrite() was called after BlockWrite(),
498 // without a Write() in between.
499 if (!pending_write_buf_.get())
502 int rv = transport_->Write(
503 pending_write_buf_.get(), pending_write_len_, pending_write_callback_);
504 pending_write_buf_ = NULL;
505 pending_write_len_ = -1;
506 if (rv == ERR_IO_PENDING) {
507 pending_write_callback_.Reset();
509 base::ResetAndReturn(&pending_write_callback_).Run(rv);
513 void FakeBlockingStreamSocket::WaitForWrite() {
514 DCHECK(should_block_write_);
515 DCHECK(!write_loop_);
517 if (pending_write_buf_.get())
519 write_loop_.reset(new base::RunLoop);
522 DCHECK(pending_write_buf_.get());
525 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
526 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
527 DCHECK(!pending_read_callback_.is_null());
529 if (should_block_read_) {
530 // Store the result so that the callback can be invoked once Unblock() is
532 pending_read_result_ = result;
534 // Stop the WaitForReadResult() call if any.
538 // Either the Read() was never blocked or UnblockReadResult() was called
539 // before the Read() completed. Either way, run the callback.
540 base::ResetAndReturn(&pending_read_callback_).Run(result);
544 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
545 // reads and writes on the socket.
546 class CountingStreamSocket : public WrappedStreamSocket {
548 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
549 : WrappedStreamSocket(transport.Pass()),
552 virtual ~CountingStreamSocket() {}
554 // Socket implementation:
555 virtual int Read(IOBuffer* buf,
557 const CompletionCallback& callback) OVERRIDE {
559 return transport_->Read(buf, buf_len, callback);
561 virtual int Write(IOBuffer* buf,
563 const CompletionCallback& callback) OVERRIDE {
565 return transport_->Write(buf, buf_len, callback);
568 int read_count() const { return read_count_; }
569 int write_count() const { return write_count_; }
576 // CompletionCallback that will delete the associated StreamSocket when
577 // the callback is invoked.
578 class DeleteSocketCallback : public TestCompletionCallbackBase {
580 explicit DeleteSocketCallback(StreamSocket* socket)
582 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
583 base::Unretained(this))) {}
584 virtual ~DeleteSocketCallback() {}
586 const CompletionCallback& callback() const { return callback_; }
589 void OnComplete(int result) {
594 ADD_FAILURE() << "Deleting socket twice";
599 StreamSocket* socket_;
600 CompletionCallback callback_;
602 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
605 // A ChannelIDStore that always returns an error when asked for a
607 class FailingChannelIDStore : public ChannelIDStore {
608 virtual int GetChannelID(const std::string& server_identifier,
609 base::Time* expiration_time,
610 std::string* private_key_result,
611 std::string* cert_result,
612 const GetChannelIDCallback& callback) OVERRIDE {
613 return ERR_UNEXPECTED;
615 virtual void SetChannelID(const std::string& server_identifier,
616 base::Time creation_time,
617 base::Time expiration_time,
618 const std::string& private_key,
619 const std::string& cert) OVERRIDE {}
620 virtual void DeleteChannelID(const std::string& server_identifier,
621 const base::Closure& completion_callback)
623 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
624 base::Time delete_end,
625 const base::Closure& completion_callback)
627 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
628 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
630 virtual int GetChannelIDCount() OVERRIDE { return 0; }
631 virtual void SetForceKeepSessionState() OVERRIDE {}
634 // A ChannelIDStore that asynchronously returns an error when asked for a
636 class AsyncFailingChannelIDStore : public ChannelIDStore {
637 virtual int GetChannelID(const std::string& server_identifier,
638 base::Time* expiration_time,
639 std::string* private_key_result,
640 std::string* cert_result,
641 const GetChannelIDCallback& callback) OVERRIDE {
642 base::MessageLoop::current()->PostTask(
643 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
644 server_identifier, base::Time(), "", ""));
645 return ERR_IO_PENDING;
647 virtual void SetChannelID(const std::string& server_identifier,
648 base::Time creation_time,
649 base::Time expiration_time,
650 const std::string& private_key,
651 const std::string& cert) OVERRIDE {}
652 virtual void DeleteChannelID(const std::string& server_identifier,
653 const base::Closure& completion_callback)
655 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
656 base::Time delete_end,
657 const base::Closure& completion_callback)
659 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
660 virtual void GetAllChannelIDs(const GetChannelIDListCallback& callback)
662 virtual int GetChannelIDCount() OVERRIDE { return 0; }
663 virtual void SetForceKeepSessionState() OVERRIDE {}
666 // A mock CTVerifier that records every call to Verify but doesn't verify
668 class MockCTVerifier : public CTVerifier {
670 MOCK_METHOD5(Verify, int(X509Certificate*,
674 const BoundNetLog&));
677 class SSLClientSocketTest : public PlatformTest {
679 SSLClientSocketTest()
680 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
681 cert_verifier_(new MockCertVerifier),
682 transport_security_state_(new TransportSecurityState),
683 ran_handshake_completion_callback_(false) {
684 cert_verifier_->set_default_result(OK);
685 context_.cert_verifier = cert_verifier_.get();
686 context_.transport_security_state = transport_security_state_.get();
689 void RecordCompletedHandshake() { ran_handshake_completion_callback_ = true; }
692 // The address of the spawned test server, after calling StartTestServer().
693 const AddressList& addr() const { return addr_; }
695 // The SpawnedTestServer object, after calling StartTestServer().
696 const SpawnedTestServer* test_server() const { return test_server_.get(); }
698 void SetCTVerifier(CTVerifier* ct_verifier) {
699 context_.cert_transparency_verifier = ct_verifier;
702 // Starts the test server with SSL configuration |ssl_options|. Returns true
704 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
705 test_server_.reset(new SpawnedTestServer(
706 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
707 if (!test_server_->Start()) {
708 LOG(ERROR) << "Could not start SpawnedTestServer";
712 if (!test_server_->GetAddressList(&addr_)) {
713 LOG(ERROR) << "Could not get SpawnedTestServer address list";
719 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
720 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
721 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
722 if (!StartTestServer(ssl_options))
725 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
726 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
728 LOG(ERROR) << "Could not connect to SpawnedTestServer";
734 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
735 scoped_ptr<StreamSocket> transport_socket,
736 const HostPortPair& host_and_port,
737 const SSLConfig& ssl_config) {
738 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
739 connection->SetSocket(transport_socket.Pass());
740 return socket_factory_->CreateSSLClientSocket(
741 connection.Pass(), host_and_port, ssl_config, context_);
744 // Create an SSLClientSocket object and use it to connect to a test
745 // server, then wait for connection results. This must be called after
746 // a successful ConnectToTestServer() call.
747 // |ssl_config| the SSL configuration to use.
748 // |result| will retrieve the ::Connect() result value.
749 // Returns true on success, false otherwise. Success means that the socket
750 // could be created and its Connect() was called, not that the connection
751 // itself was a success.
752 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
753 sock_ = CreateSSLClientSocket(
754 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
756 if (sock_->IsConnected()) {
757 LOG(ERROR) << "SSL Socket prematurely connected";
761 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
765 ClientSocketFactory* socket_factory_;
766 scoped_ptr<MockCertVerifier> cert_verifier_;
767 scoped_ptr<TransportSecurityState> transport_security_state_;
768 SSLClientSocketContext context_;
769 scoped_ptr<SSLClientSocket> sock_;
770 CapturingNetLog log_;
771 bool ran_handshake_completion_callback_;
774 scoped_ptr<StreamSocket> transport_;
775 scoped_ptr<SpawnedTestServer> test_server_;
776 TestCompletionCallback callback_;
780 // Verifies the correctness of GetSSLCertRequestInfo.
781 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
783 // Creates a test server with the given SSLOptions, connects to it and returns
784 // the SSLCertRequestInfo reported by the socket.
785 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
786 SpawnedTestServer::SSLOptions ssl_options) {
787 SpawnedTestServer test_server(
788 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
789 if (!test_server.Start())
793 if (!test_server.GetAddressList(&addr))
796 TestCompletionCallback callback;
798 scoped_ptr<StreamSocket> transport(
799 new TCPClientSocket(addr, &log, NetLog::Source()));
800 int rv = transport->Connect(callback.callback());
801 if (rv == ERR_IO_PENDING)
802 rv = callback.WaitForResult();
805 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
806 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
807 EXPECT_FALSE(sock->IsConnected());
809 rv = sock->Connect(callback.callback());
810 if (rv == ERR_IO_PENDING)
811 rv = callback.WaitForResult();
812 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
813 sock->GetSSLCertRequestInfo(request_info.get());
815 EXPECT_FALSE(sock->IsConnected());
817 test_server.host_port_pair().Equals(request_info->host_and_port));
823 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
825 SSLClientSocketFalseStartTest()
826 : monitor_handshake_callback_(false),
827 fail_handshake_after_false_start_(false) {}
830 // Creates an SSLClientSocket with |client_config| attached to a
831 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
832 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
833 // so |*out_raw_transport| is a raw pointer.
835 // The client socket will begin a connect using |callback| but stop before the
836 // server's finished message is received. The finished message will be blocked
837 // in |*out_raw_transport|. To complete the handshake and successfully read
838 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
839 // the client successfully false started, |callback.WaitForResult()| will
840 // return OK without unblocking transport reads. But Read() will still block.)
842 // Must be called after StartTestServer is called.
843 void CreateAndConnectUntilServerFinishedReceived(
844 const SSLConfig& client_config,
845 TestCompletionCallback* callback,
846 FakeBlockingStreamSocket** out_raw_transport,
847 scoped_ptr<SSLClientSocket>* out_sock) {
848 CHECK(test_server());
850 scoped_ptr<StreamSocket> real_transport(scoped_ptr<StreamSocket>(
851 new TCPClientSocket(addr(), NULL, NetLog::Source())));
852 real_transport.reset(
853 new SynchronousErrorStreamSocket(real_transport.Pass()));
855 scoped_ptr<FakeBlockingStreamSocket> transport(
856 new FakeBlockingStreamSocket(real_transport.Pass()));
857 int rv = callback->GetResult(transport->Connect(callback->callback()));
860 FakeBlockingStreamSocket* raw_transport = transport.get();
861 scoped_ptr<SSLClientSocket> sock =
862 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
863 test_server()->host_port_pair(),
866 if (monitor_handshake_callback_) {
867 sock->SetHandshakeCompletionCallback(
868 base::Bind(&SSLClientSocketTest::RecordCompletedHandshake,
869 base::Unretained(this)));
872 // Connect. Stop before the client processes the first server leg
873 // (ServerHello, etc.)
874 raw_transport->BlockReadResult();
875 rv = sock->Connect(callback->callback());
876 EXPECT_EQ(ERR_IO_PENDING, rv);
877 raw_transport->WaitForReadResult();
879 // Release the ServerHello and wait for the client to write
880 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
881 // server's leg to complete, since it may span multiple reads.)
882 EXPECT_FALSE(callback->have_result());
883 raw_transport->BlockWrite();
884 raw_transport->UnblockReadResult();
885 raw_transport->WaitForWrite();
887 if (fail_handshake_after_false_start_) {
888 SynchronousErrorStreamSocket* error_socket =
889 static_cast<SynchronousErrorStreamSocket*>(
890 raw_transport->transport());
891 error_socket->SetNextReadError(ERR_CONNECTION_RESET);
893 // And, finally, release that and block the next server leg
894 // (ChangeCipherSpec, Finished).
895 raw_transport->BlockReadResult();
896 raw_transport->UnblockWrite();
898 *out_raw_transport = raw_transport;
899 *out_sock = sock.Pass();
902 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
903 const SSLConfig& client_config,
904 bool expect_false_start) {
905 ASSERT_TRUE(StartTestServer(server_options));
907 TestCompletionCallback callback;
908 FakeBlockingStreamSocket* raw_transport = NULL;
909 scoped_ptr<SSLClientSocket> sock;
911 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
912 client_config, &callback, &raw_transport, &sock));
914 if (expect_false_start) {
915 // When False Starting, the handshake should complete before receiving the
916 // Change Cipher Spec and Finished messages.
918 // Note: callback.have_result() may not be true without waiting. The NSS
919 // state machine sometimes lives on a separate thread, so this thread may
920 // not yet have processed the signal that the handshake has completed.
921 int rv = callback.WaitForResult();
923 EXPECT_TRUE(sock->IsConnected());
925 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
926 static const int kRequestTextSize =
927 static_cast<int>(arraysize(request_text) - 1);
928 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
929 memcpy(request_buffer->data(), request_text, kRequestTextSize);
931 // Write the request.
932 rv = callback.GetResult(sock->Write(request_buffer.get(),
934 callback.callback()));
935 EXPECT_EQ(kRequestTextSize, rv);
937 // The read will hang; it's waiting for the peer to complete the
938 // handshake, and the handshake is still blocked.
939 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
940 rv = sock->Read(buf.get(), 4096, callback.callback());
942 // After releasing reads, the connection proceeds.
943 raw_transport->UnblockReadResult();
944 rv = callback.GetResult(rv);
945 if (fail_handshake_after_false_start_)
946 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
950 // False Start is not enabled, so the handshake will not complete because
951 // the server second leg is blocked.
952 base::RunLoop().RunUntilIdle();
953 EXPECT_FALSE(callback.have_result());
957 // Indicates that the socket's handshake completion callback should
959 bool monitor_handshake_callback_;
960 // Indicates that this test's handshake should fail after the client
961 // "finished" message is sent.
962 bool fail_handshake_after_false_start_;
965 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
967 void EnableChannelID() {
968 channel_id_service_.reset(
969 new ChannelIDService(new DefaultChannelIDStore(NULL),
970 base::MessageLoopProxy::current()));
971 context_.channel_id_service = channel_id_service_.get();
974 void EnableFailingChannelID() {
975 channel_id_service_.reset(new ChannelIDService(
976 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
977 context_.channel_id_service = channel_id_service_.get();
980 void EnableAsyncFailingChannelID() {
981 channel_id_service_.reset(new ChannelIDService(
982 new AsyncFailingChannelIDStore(),
983 base::MessageLoopProxy::current()));
984 context_.channel_id_service = channel_id_service_.get();
988 scoped_ptr<ChannelIDService> channel_id_service_;
991 //-----------------------------------------------------------------------------
993 // LogContainsSSLConnectEndEvent returns true if the given index in the given
994 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
995 // merge the first application data record with the Finished message when false
996 // starting. However, in order to avoid the server timing out the handshake,
997 // they'll give up waiting for application data and send the Finished after a
998 // timeout. This means that an SSL connect end event may appear as a socket
1000 static bool LogContainsSSLConnectEndEvent(
1001 const CapturingNetLog::CapturedEntryList& log,
1003 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
1005 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1010 TEST_F(SSLClientSocketTest, Connect) {
1011 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1012 SpawnedTestServer::kLocalhost,
1014 ASSERT_TRUE(test_server.Start());
1017 ASSERT_TRUE(test_server.GetAddressList(&addr));
1019 TestCompletionCallback callback;
1020 CapturingNetLog log;
1021 scoped_ptr<StreamSocket> transport(
1022 new TCPClientSocket(addr, &log, NetLog::Source()));
1023 int rv = transport->Connect(callback.callback());
1024 if (rv == ERR_IO_PENDING)
1025 rv = callback.WaitForResult();
1028 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1029 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1031 EXPECT_FALSE(sock->IsConnected());
1033 rv = sock->Connect(callback.callback());
1035 CapturingNetLog::CapturedEntryList entries;
1036 log.GetEntries(&entries);
1037 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1038 if (rv == ERR_IO_PENDING)
1039 rv = callback.WaitForResult();
1041 EXPECT_TRUE(sock->IsConnected());
1042 log.GetEntries(&entries);
1043 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1046 EXPECT_FALSE(sock->IsConnected());
1049 TEST_F(SSLClientSocketTest, ConnectExpired) {
1050 SpawnedTestServer::SSLOptions ssl_options(
1051 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
1052 SpawnedTestServer test_server(
1053 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1054 ASSERT_TRUE(test_server.Start());
1056 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1059 ASSERT_TRUE(test_server.GetAddressList(&addr));
1061 TestCompletionCallback callback;
1062 CapturingNetLog log;
1063 scoped_ptr<StreamSocket> transport(
1064 new TCPClientSocket(addr, &log, NetLog::Source()));
1065 int rv = transport->Connect(callback.callback());
1066 if (rv == ERR_IO_PENDING)
1067 rv = callback.WaitForResult();
1070 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1071 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1073 EXPECT_FALSE(sock->IsConnected());
1075 rv = sock->Connect(callback.callback());
1077 CapturingNetLog::CapturedEntryList entries;
1078 log.GetEntries(&entries);
1079 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1080 if (rv == ERR_IO_PENDING)
1081 rv = callback.WaitForResult();
1083 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1085 // Rather than testing whether or not the underlying socket is connected,
1086 // test that the handshake has finished. This is because it may be
1087 // desirable to disconnect the socket before showing a user prompt, since
1088 // the user may take indefinitely long to respond.
1089 log.GetEntries(&entries);
1090 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1093 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1094 SpawnedTestServer::SSLOptions ssl_options(
1095 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1096 SpawnedTestServer test_server(
1097 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1098 ASSERT_TRUE(test_server.Start());
1100 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1103 ASSERT_TRUE(test_server.GetAddressList(&addr));
1105 TestCompletionCallback callback;
1106 CapturingNetLog log;
1107 scoped_ptr<StreamSocket> transport(
1108 new TCPClientSocket(addr, &log, NetLog::Source()));
1109 int rv = transport->Connect(callback.callback());
1110 if (rv == ERR_IO_PENDING)
1111 rv = callback.WaitForResult();
1114 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1115 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1117 EXPECT_FALSE(sock->IsConnected());
1119 rv = sock->Connect(callback.callback());
1121 CapturingNetLog::CapturedEntryList entries;
1122 log.GetEntries(&entries);
1123 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1124 if (rv == ERR_IO_PENDING)
1125 rv = callback.WaitForResult();
1127 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1129 // Rather than testing whether or not the underlying socket is connected,
1130 // test that the handshake has finished. This is because it may be
1131 // desirable to disconnect the socket before showing a user prompt, since
1132 // the user may take indefinitely long to respond.
1133 log.GetEntries(&entries);
1134 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1137 // Attempt to connect to a page which requests a client certificate. It should
1138 // return an error code on connect.
1139 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1140 SpawnedTestServer::SSLOptions ssl_options;
1141 ssl_options.request_client_certificate = true;
1142 SpawnedTestServer test_server(
1143 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1144 ASSERT_TRUE(test_server.Start());
1147 ASSERT_TRUE(test_server.GetAddressList(&addr));
1149 TestCompletionCallback callback;
1150 CapturingNetLog log;
1151 scoped_ptr<StreamSocket> transport(
1152 new TCPClientSocket(addr, &log, NetLog::Source()));
1153 int rv = transport->Connect(callback.callback());
1154 if (rv == ERR_IO_PENDING)
1155 rv = callback.WaitForResult();
1158 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1159 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1161 EXPECT_FALSE(sock->IsConnected());
1163 rv = sock->Connect(callback.callback());
1165 CapturingNetLog::CapturedEntryList entries;
1166 log.GetEntries(&entries);
1167 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1168 if (rv == ERR_IO_PENDING)
1169 rv = callback.WaitForResult();
1171 log.GetEntries(&entries);
1172 // Because we prematurely kill the handshake at CertificateRequest,
1173 // the server may still send data (notably the ServerHelloDone)
1174 // after the error is returned. As a result, the SSL_CONNECT may not
1175 // be the last entry. See http://crbug.com/54445. We use
1176 // ExpectLogContainsSomewhere instead of
1177 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1178 // extra read instead of two. This occurs before the handshake ends,
1179 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1182 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1183 // fixed and we can respond to the first CertificateRequest
1184 // without closing the socket, add a unit test for sending the
1185 // certificate. This test may still be useful as we'll want to close
1186 // the socket on a timeout if the user takes a long time to pick a
1187 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1188 ExpectLogContainsSomewhere(
1189 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1190 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1191 EXPECT_FALSE(sock->IsConnected());
1194 // Connect to a server requesting optional client authentication. Send it a
1195 // null certificate. It should allow the connection.
1197 // TODO(davidben): Also test providing an actual certificate.
1198 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1199 SpawnedTestServer::SSLOptions ssl_options;
1200 ssl_options.request_client_certificate = true;
1201 SpawnedTestServer test_server(
1202 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1203 ASSERT_TRUE(test_server.Start());
1206 ASSERT_TRUE(test_server.GetAddressList(&addr));
1208 TestCompletionCallback callback;
1209 CapturingNetLog log;
1210 scoped_ptr<StreamSocket> transport(
1211 new TCPClientSocket(addr, &log, NetLog::Source()));
1212 int rv = transport->Connect(callback.callback());
1213 if (rv == ERR_IO_PENDING)
1214 rv = callback.WaitForResult();
1217 SSLConfig ssl_config = kDefaultSSLConfig;
1218 ssl_config.send_client_cert = true;
1219 ssl_config.client_cert = NULL;
1221 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1222 transport.Pass(), test_server.host_port_pair(), ssl_config));
1224 EXPECT_FALSE(sock->IsConnected());
1226 // Our test server accepts certificate-less connections.
1227 // TODO(davidben): Add a test which requires them and verify the error.
1228 rv = sock->Connect(callback.callback());
1230 CapturingNetLog::CapturedEntryList entries;
1231 log.GetEntries(&entries);
1232 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1233 if (rv == ERR_IO_PENDING)
1234 rv = callback.WaitForResult();
1237 EXPECT_TRUE(sock->IsConnected());
1238 log.GetEntries(&entries);
1239 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1241 // We responded to the server's certificate request with a Certificate
1242 // message with no client certificate in it. ssl_info.client_cert_sent
1243 // should be false in this case.
1245 sock->GetSSLInfo(&ssl_info);
1246 EXPECT_FALSE(ssl_info.client_cert_sent);
1249 EXPECT_FALSE(sock->IsConnected());
1252 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1253 // - Server closes an SSL connection (with a close_notify alert message).
1254 // - Server closes the underlying TCP connection directly.
1255 // - Server sends data unexpectedly.
1257 TEST_F(SSLClientSocketTest, Read) {
1258 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1259 SpawnedTestServer::kLocalhost,
1261 ASSERT_TRUE(test_server.Start());
1264 ASSERT_TRUE(test_server.GetAddressList(&addr));
1266 TestCompletionCallback callback;
1267 scoped_ptr<StreamSocket> transport(
1268 new TCPClientSocket(addr, NULL, NetLog::Source()));
1269 int rv = transport->Connect(callback.callback());
1270 if (rv == ERR_IO_PENDING)
1271 rv = callback.WaitForResult();
1274 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1275 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1277 rv = sock->Connect(callback.callback());
1278 if (rv == ERR_IO_PENDING)
1279 rv = callback.WaitForResult();
1281 EXPECT_TRUE(sock->IsConnected());
1283 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1284 scoped_refptr<IOBuffer> request_buffer(
1285 new IOBuffer(arraysize(request_text) - 1));
1286 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1289 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1290 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1292 if (rv == ERR_IO_PENDING)
1293 rv = callback.WaitForResult();
1294 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1296 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1298 rv = sock->Read(buf.get(), 4096, callback.callback());
1299 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1301 if (rv == ERR_IO_PENDING)
1302 rv = callback.WaitForResult();
1310 // Tests that SSLClientSocket properly handles when the underlying transport
1311 // synchronously fails a transport read in during the handshake. The error code
1312 // should be preserved so SSLv3 fallback logic can condition on it.
1313 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1314 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1315 SpawnedTestServer::kLocalhost,
1317 ASSERT_TRUE(test_server.Start());
1320 ASSERT_TRUE(test_server.GetAddressList(&addr));
1322 TestCompletionCallback callback;
1323 scoped_ptr<StreamSocket> real_transport(
1324 new TCPClientSocket(addr, NULL, NetLog::Source()));
1325 scoped_ptr<SynchronousErrorStreamSocket> transport(
1326 new SynchronousErrorStreamSocket(real_transport.Pass()));
1327 int rv = callback.GetResult(transport->Connect(callback.callback()));
1330 // Disable TLS False Start to avoid handshake non-determinism.
1331 SSLConfig ssl_config;
1332 ssl_config.false_start_enabled = false;
1334 SynchronousErrorStreamSocket* raw_transport = transport.get();
1335 scoped_ptr<SSLClientSocket> sock(
1336 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1337 test_server.host_port_pair(),
1340 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1342 rv = callback.GetResult(sock->Connect(callback.callback()));
1343 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1344 EXPECT_FALSE(sock->IsConnected());
1347 // Tests that the SSLClientSocket properly handles when the underlying transport
1348 // synchronously returns an error code - such as if an intermediary terminates
1349 // the socket connection uncleanly.
1350 // This is a regression test for http://crbug.com/238536
1351 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1352 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1353 SpawnedTestServer::kLocalhost,
1355 ASSERT_TRUE(test_server.Start());
1358 ASSERT_TRUE(test_server.GetAddressList(&addr));
1360 TestCompletionCallback callback;
1361 scoped_ptr<StreamSocket> real_transport(
1362 new TCPClientSocket(addr, NULL, NetLog::Source()));
1363 scoped_ptr<SynchronousErrorStreamSocket> transport(
1364 new SynchronousErrorStreamSocket(real_transport.Pass()));
1365 int rv = callback.GetResult(transport->Connect(callback.callback()));
1368 // Disable TLS False Start to avoid handshake non-determinism.
1369 SSLConfig ssl_config;
1370 ssl_config.false_start_enabled = false;
1372 SynchronousErrorStreamSocket* raw_transport = transport.get();
1373 scoped_ptr<SSLClientSocket> sock(
1374 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1375 test_server.host_port_pair(),
1378 rv = callback.GetResult(sock->Connect(callback.callback()));
1380 EXPECT_TRUE(sock->IsConnected());
1382 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1383 static const int kRequestTextSize =
1384 static_cast<int>(arraysize(request_text) - 1);
1385 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1386 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1388 rv = callback.GetResult(
1389 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1390 EXPECT_EQ(kRequestTextSize, rv);
1392 // Simulate an unclean/forcible shutdown.
1393 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1395 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1397 // Note: This test will hang if this bug has regressed. Simply checking that
1398 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1399 // result when using a dedicated task runner for NSS.
1400 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1401 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1404 // Tests that the SSLClientSocket properly handles when the underlying transport
1405 // asynchronously returns an error code while writing data - such as if an
1406 // intermediary terminates the socket connection uncleanly.
1407 // This is a regression test for http://crbug.com/249848
1408 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1409 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1410 SpawnedTestServer::kLocalhost,
1412 ASSERT_TRUE(test_server.Start());
1415 ASSERT_TRUE(test_server.GetAddressList(&addr));
1417 TestCompletionCallback callback;
1418 scoped_ptr<StreamSocket> real_transport(
1419 new TCPClientSocket(addr, NULL, NetLog::Source()));
1420 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1421 // is retained in order to configure additional errors.
1422 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1423 new SynchronousErrorStreamSocket(real_transport.Pass()));
1424 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1425 scoped_ptr<FakeBlockingStreamSocket> transport(
1426 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1427 FakeBlockingStreamSocket* raw_transport = transport.get();
1428 int rv = callback.GetResult(transport->Connect(callback.callback()));
1431 // Disable TLS False Start to avoid handshake non-determinism.
1432 SSLConfig ssl_config;
1433 ssl_config.false_start_enabled = false;
1435 scoped_ptr<SSLClientSocket> sock(
1436 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1437 test_server.host_port_pair(),
1440 rv = callback.GetResult(sock->Connect(callback.callback()));
1442 EXPECT_TRUE(sock->IsConnected());
1444 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1445 static const int kRequestTextSize =
1446 static_cast<int>(arraysize(request_text) - 1);
1447 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1448 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1450 // Simulate an unclean/forcible shutdown on the underlying socket.
1451 // However, simulate this error asynchronously.
1452 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1453 raw_transport->BlockWrite();
1455 // This write should complete synchronously, because the TLS ciphertext
1456 // can be created and placed into the outgoing buffers independent of the
1457 // underlying transport.
1458 rv = callback.GetResult(
1459 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1460 EXPECT_EQ(kRequestTextSize, rv);
1462 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1464 rv = sock->Read(buf.get(), 4096, callback.callback());
1465 EXPECT_EQ(ERR_IO_PENDING, rv);
1467 // Now unblock the outgoing request, having it fail with the connection
1469 raw_transport->UnblockWrite();
1471 // Note: This will cause an inifite loop if this bug has regressed. Simply
1472 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1473 // is a legitimate result when using a dedicated task runner for NSS.
1474 rv = callback.GetResult(rv);
1475 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1478 // If there is a Write failure at the transport with no follow-up Read, although
1479 // the write error will not be returned to the client until a future Read or
1480 // Write operation, SSLClientSocket should not spin attempting to re-write on
1481 // the socket. This is a regression test for part of https://crbug.com/381160.
1482 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1483 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1484 SpawnedTestServer::kLocalhost,
1486 ASSERT_TRUE(test_server.Start());
1489 ASSERT_TRUE(test_server.GetAddressList(&addr));
1491 TestCompletionCallback callback;
1492 scoped_ptr<StreamSocket> real_transport(
1493 new TCPClientSocket(addr, NULL, NetLog::Source()));
1494 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1495 // is retained in order to query them.
1496 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1497 new SynchronousErrorStreamSocket(real_transport.Pass()));
1498 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1499 scoped_ptr<CountingStreamSocket> counting_socket(
1500 new CountingStreamSocket(error_socket.PassAs<StreamSocket>()));
1501 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1502 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1505 // Disable TLS False Start to avoid handshake non-determinism.
1506 SSLConfig ssl_config;
1507 ssl_config.false_start_enabled = false;
1509 scoped_ptr<SSLClientSocket> sock(
1510 CreateSSLClientSocket(counting_socket.PassAs<StreamSocket>(),
1511 test_server.host_port_pair(),
1514 rv = callback.GetResult(sock->Connect(callback.callback()));
1516 ASSERT_TRUE(sock->IsConnected());
1518 // Simulate an unclean/forcible shutdown on the underlying socket.
1519 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1521 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1522 static const int kRequestTextSize =
1523 static_cast<int>(arraysize(request_text) - 1);
1524 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1525 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1527 // This write should complete synchronously, because the TLS ciphertext
1528 // can be created and placed into the outgoing buffers independent of the
1529 // underlying transport.
1530 rv = callback.GetResult(
1531 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1532 ASSERT_EQ(kRequestTextSize, rv);
1534 // Let the event loop spin for a little bit of time. Even on platforms where
1535 // pumping the state machine involve thread hops, there should be no further
1536 // writes on the transport socket.
1538 // TODO(davidben): Avoid the arbitrary timeout?
1539 int old_write_count = raw_counting_socket->write_count();
1541 base::MessageLoop::current()->PostDelayedTask(
1542 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1544 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1547 // Test the full duplex mode, with Read and Write pending at the same time.
1548 // This test also serves as a regression test for http://crbug.com/29815.
1549 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1550 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1551 SpawnedTestServer::kLocalhost,
1553 ASSERT_TRUE(test_server.Start());
1556 ASSERT_TRUE(test_server.GetAddressList(&addr));
1558 TestCompletionCallback callback; // Used for everything except Write.
1560 scoped_ptr<StreamSocket> transport(
1561 new TCPClientSocket(addr, NULL, NetLog::Source()));
1562 int rv = transport->Connect(callback.callback());
1563 if (rv == ERR_IO_PENDING)
1564 rv = callback.WaitForResult();
1567 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1568 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1570 rv = sock->Connect(callback.callback());
1571 if (rv == ERR_IO_PENDING)
1572 rv = callback.WaitForResult();
1574 EXPECT_TRUE(sock->IsConnected());
1576 // Issue a "hanging" Read first.
1577 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1578 rv = sock->Read(buf.get(), 4096, callback.callback());
1579 // We haven't written the request, so there should be no response yet.
1580 ASSERT_EQ(ERR_IO_PENDING, rv);
1582 // Write the request.
1583 // The request is padded with a User-Agent header to a size that causes the
1584 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1585 // This tests the fix for http://crbug.com/29815.
1586 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1587 for (int i = 0; i < 3770; ++i)
1588 request_text.push_back('*');
1589 request_text.append("\r\n\r\n");
1590 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1592 TestCompletionCallback callback2; // Used for Write only.
1594 request_buffer.get(), request_text.size(), callback2.callback());
1595 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1597 if (rv == ERR_IO_PENDING)
1598 rv = callback2.WaitForResult();
1599 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1601 // Now get the Read result.
1602 rv = callback.WaitForResult();
1606 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1607 // mode when the underlying transport is blocked on sending data. When the
1608 // underlying transport completes due to an error, it should invoke both the
1609 // Read() and Write() callbacks. If the socket is deleted by the Read()
1610 // callback, the Write() callback should not be invoked.
1611 // Regression test for http://crbug.com/232633
1612 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1613 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1614 SpawnedTestServer::kLocalhost,
1616 ASSERT_TRUE(test_server.Start());
1619 ASSERT_TRUE(test_server.GetAddressList(&addr));
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();
1633 int rv = callback.GetResult(transport->Connect(callback.callback()));
1636 // Disable TLS False Start to avoid handshake non-determinism.
1637 SSLConfig ssl_config;
1638 ssl_config.false_start_enabled = false;
1640 scoped_ptr<SSLClientSocket> sock =
1641 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1642 test_server.host_port_pair(),
1645 rv = callback.GetResult(sock->Connect(callback.callback()));
1647 EXPECT_TRUE(sock->IsConnected());
1649 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1650 request_text.append(20 * 1024, '*');
1651 request_text.append("\r\n\r\n");
1652 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1653 new StringIOBuffer(request_text), request_text.size()));
1655 // Simulate errors being returned from the underlying Read() and Write() ...
1656 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1657 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1658 // ... but have those errors returned asynchronously. Because the Write() will
1659 // return first, this will trigger the error.
1660 raw_transport->BlockReadResult();
1661 raw_transport->BlockWrite();
1663 // Enqueue a Read() before calling Write(), which should "hang" due to
1664 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1665 SSLClientSocket* raw_sock = sock.get();
1666 DeleteSocketCallback read_callback(sock.release());
1667 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1668 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1670 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1671 ASSERT_EQ(ERR_IO_PENDING, rv);
1672 ASSERT_FALSE(read_callback.have_result());
1674 #if !defined(USE_OPENSSL)
1675 // NSS follows a pattern where a call to PR_Write will only consume as
1676 // much data as it can encode into application data records before the
1677 // internal memio buffer is full, which should only fill if writing a large
1678 // amount of data and the underlying transport is blocked. Once this happens,
1679 // NSS will return (total size of all application data records it wrote) - 1,
1680 // with the caller expected to resume with the remaining unsent data.
1682 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1683 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1684 // get the socket in the state needed for the test below.
1686 // This is not needed for OpenSSL, because for OpenSSL,
1687 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1688 // SSLClientSocketOpenSSL::Write() will not return until all of
1689 // |request_buffer| has been written to the underlying BIO (although not
1690 // necessarily the underlying transport).
1691 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1692 request_buffer->BytesRemaining(),
1693 callback.callback()));
1695 request_buffer->DidConsume(rv);
1697 // Guard to ensure that |request_buffer| was larger than all of the internal
1698 // buffers (transport, memio, NSS) along the way - otherwise the next call
1699 // to Write() will crash with an invalid buffer.
1700 ASSERT_LT(0, request_buffer->BytesRemaining());
1703 // Attempt to write the remaining data. NSS will not be able to consume the
1704 // application data because the internal buffers are full, while OpenSSL will
1705 // return that its blocked because the underlying transport is blocked.
1706 rv = raw_sock->Write(request_buffer.get(),
1707 request_buffer->BytesRemaining(),
1708 callback.callback());
1709 ASSERT_EQ(ERR_IO_PENDING, rv);
1710 ASSERT_FALSE(callback.have_result());
1712 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1713 // call the Read() callback, deleting the socket and thus aborting calling
1714 // the Write() callback.
1715 raw_transport->UnblockWrite();
1717 rv = read_callback.WaitForResult();
1718 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1720 // The Write callback should not have been called.
1721 EXPECT_FALSE(callback.have_result());
1724 // Tests that the SSLClientSocket does not crash if data is received on the
1725 // transport socket after a failing write. This can occur if we have a Write
1726 // error in a SPDY socket.
1727 // Regression test for http://crbug.com/335557
1728 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1729 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1730 SpawnedTestServer::kLocalhost,
1732 ASSERT_TRUE(test_server.Start());
1735 ASSERT_TRUE(test_server.GetAddressList(&addr));
1737 TestCompletionCallback callback;
1738 scoped_ptr<StreamSocket> real_transport(
1739 new TCPClientSocket(addr, NULL, NetLog::Source()));
1740 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1741 // is retained in order to configure additional errors.
1742 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1743 new SynchronousErrorStreamSocket(real_transport.Pass()));
1744 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1745 scoped_ptr<FakeBlockingStreamSocket> transport(
1746 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1747 FakeBlockingStreamSocket* raw_transport = transport.get();
1749 int rv = callback.GetResult(transport->Connect(callback.callback()));
1752 // Disable TLS False Start to avoid handshake non-determinism.
1753 SSLConfig ssl_config;
1754 ssl_config.false_start_enabled = false;
1756 scoped_ptr<SSLClientSocket> sock(
1757 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1758 test_server.host_port_pair(),
1761 rv = callback.GetResult(sock->Connect(callback.callback()));
1763 EXPECT_TRUE(sock->IsConnected());
1765 // Send a request so there is something to read from the socket.
1766 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1767 static const int kRequestTextSize =
1768 static_cast<int>(arraysize(request_text) - 1);
1769 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1770 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1772 rv = callback.GetResult(
1773 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1774 EXPECT_EQ(kRequestTextSize, rv);
1776 // Start a hanging read.
1777 TestCompletionCallback read_callback;
1778 raw_transport->BlockReadResult();
1779 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1780 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1781 EXPECT_EQ(ERR_IO_PENDING, rv);
1783 // Perform another write, but have it fail. Write a request larger than the
1784 // internal socket buffers so that the request hits the underlying transport
1785 // socket and detects the error.
1786 std::string long_request_text =
1787 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1788 long_request_text.append(20 * 1024, '*');
1789 long_request_text.append("\r\n\r\n");
1790 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1791 new StringIOBuffer(long_request_text), long_request_text.size()));
1793 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1795 // Write as much data as possible until hitting an error. This is necessary
1796 // for NSS. PR_Write will only consume as much data as it can encode into
1797 // application data records before the internal memio buffer is full, which
1798 // should only fill if writing a large amount of data and the underlying
1799 // transport is blocked. Once this happens, NSS will return (total size of all
1800 // application data records it wrote) - 1, with the caller expected to resume
1801 // with the remaining unsent data.
1803 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1804 long_request_buffer->BytesRemaining(),
1805 callback.callback()));
1807 long_request_buffer->DidConsume(rv);
1808 // Abort if the entire buffer is ever consumed.
1809 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1813 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1815 // Release the read.
1816 raw_transport->UnblockReadResult();
1817 rv = read_callback.WaitForResult();
1819 #if defined(USE_OPENSSL)
1820 // Should still read bytes despite the write error.
1823 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1824 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1825 // the write error stops future reads.
1826 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1830 // Tests that SSLClientSocket fails the handshake if the underlying
1831 // transport is cleanly closed.
1832 TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
1833 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1834 SpawnedTestServer::kLocalhost,
1836 ASSERT_TRUE(test_server.Start());
1839 ASSERT_TRUE(test_server.GetAddressList(&addr));
1841 TestCompletionCallback callback;
1842 scoped_ptr<StreamSocket> real_transport(
1843 new TCPClientSocket(addr, NULL, NetLog::Source()));
1844 scoped_ptr<SynchronousErrorStreamSocket> transport(
1845 new SynchronousErrorStreamSocket(real_transport.Pass()));
1846 int rv = callback.GetResult(transport->Connect(callback.callback()));
1849 SynchronousErrorStreamSocket* raw_transport = transport.get();
1850 scoped_ptr<SSLClientSocket> sock(
1851 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1852 test_server.host_port_pair(),
1853 kDefaultSSLConfig));
1855 raw_transport->SetNextReadError(0);
1857 rv = callback.GetResult(sock->Connect(callback.callback()));
1858 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
1859 EXPECT_FALSE(sock->IsConnected());
1862 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1863 // underlying socket is cleanly closed.
1864 // This is a regression test for https://crbug.com/422246
1865 TEST_F(SSLClientSocketTest, Read_WithZeroReturn) {
1866 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1867 SpawnedTestServer::kLocalhost,
1869 ASSERT_TRUE(test_server.Start());
1872 ASSERT_TRUE(test_server.GetAddressList(&addr));
1874 TestCompletionCallback callback;
1875 scoped_ptr<StreamSocket> real_transport(
1876 new TCPClientSocket(addr, NULL, NetLog::Source()));
1877 scoped_ptr<SynchronousErrorStreamSocket> transport(
1878 new SynchronousErrorStreamSocket(real_transport.Pass()));
1879 int rv = callback.GetResult(transport->Connect(callback.callback()));
1882 // Disable TLS False Start to ensure the handshake has completed.
1883 SSLConfig ssl_config;
1884 ssl_config.false_start_enabled = false;
1886 SynchronousErrorStreamSocket* raw_transport = transport.get();
1887 scoped_ptr<SSLClientSocket> sock(
1888 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1889 test_server.host_port_pair(),
1892 rv = callback.GetResult(sock->Connect(callback.callback()));
1894 EXPECT_TRUE(sock->IsConnected());
1896 raw_transport->SetNextReadError(0);
1897 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1898 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1902 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1903 // underlying socket is cleanly closed asynchronously.
1904 // This is a regression test for https://crbug.com/422246
1905 TEST_F(SSLClientSocketTest, Read_WithAsyncZeroReturn) {
1906 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1907 SpawnedTestServer::kLocalhost,
1909 ASSERT_TRUE(test_server.Start());
1912 ASSERT_TRUE(test_server.GetAddressList(&addr));
1914 TestCompletionCallback callback;
1915 scoped_ptr<StreamSocket> real_transport(
1916 new TCPClientSocket(addr, NULL, NetLog::Source()));
1917 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1918 new SynchronousErrorStreamSocket(real_transport.Pass()));
1919 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1920 scoped_ptr<FakeBlockingStreamSocket> transport(
1921 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1922 FakeBlockingStreamSocket* raw_transport = transport.get();
1923 int rv = callback.GetResult(transport->Connect(callback.callback()));
1926 // Disable TLS False Start to ensure the handshake has completed.
1927 SSLConfig ssl_config;
1928 ssl_config.false_start_enabled = false;
1930 scoped_ptr<SSLClientSocket> sock(
1931 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1932 test_server.host_port_pair(),
1935 rv = callback.GetResult(sock->Connect(callback.callback()));
1937 EXPECT_TRUE(sock->IsConnected());
1939 raw_error_socket->SetNextReadError(0);
1940 raw_transport->BlockReadResult();
1941 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1942 rv = sock->Read(buf.get(), 4096, callback.callback());
1943 EXPECT_EQ(ERR_IO_PENDING, rv);
1945 raw_transport->UnblockReadResult();
1946 rv = callback.GetResult(rv);
1950 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1951 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1952 SpawnedTestServer::kLocalhost,
1954 ASSERT_TRUE(test_server.Start());
1957 ASSERT_TRUE(test_server.GetAddressList(&addr));
1959 TestCompletionCallback callback;
1960 scoped_ptr<StreamSocket> transport(
1961 new TCPClientSocket(addr, NULL, NetLog::Source()));
1962 int rv = transport->Connect(callback.callback());
1963 if (rv == ERR_IO_PENDING)
1964 rv = callback.WaitForResult();
1967 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1968 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1970 rv = sock->Connect(callback.callback());
1971 if (rv == ERR_IO_PENDING)
1972 rv = callback.WaitForResult();
1975 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1976 scoped_refptr<IOBuffer> request_buffer(
1977 new IOBuffer(arraysize(request_text) - 1));
1978 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1981 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1982 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1984 if (rv == ERR_IO_PENDING)
1985 rv = callback.WaitForResult();
1986 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1988 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1990 rv = sock->Read(buf.get(), 1, callback.callback());
1991 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1993 if (rv == ERR_IO_PENDING)
1994 rv = callback.WaitForResult();
2002 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
2003 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2004 SpawnedTestServer::kLocalhost,
2006 ASSERT_TRUE(test_server.Start());
2009 ASSERT_TRUE(test_server.GetAddressList(&addr));
2011 TestCompletionCallback callback;
2013 scoped_ptr<StreamSocket> real_transport(
2014 new TCPClientSocket(addr, NULL, NetLog::Source()));
2015 scoped_ptr<ReadBufferingStreamSocket> transport(
2016 new ReadBufferingStreamSocket(real_transport.Pass()));
2017 ReadBufferingStreamSocket* raw_transport = transport.get();
2018 int rv = callback.GetResult(transport->Connect(callback.callback()));
2021 scoped_ptr<SSLClientSocket> sock(
2022 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
2023 test_server.host_port_pair(),
2024 kDefaultSSLConfig));
2026 rv = callback.GetResult(sock->Connect(callback.callback()));
2028 ASSERT_TRUE(sock->IsConnected());
2030 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
2031 scoped_refptr<IOBuffer> request_buffer(
2032 new IOBuffer(arraysize(request_text) - 1));
2033 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2035 rv = callback.GetResult(sock->Write(
2036 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
2038 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2040 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2041 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2042 // of SSL data is buffered first. The 15K of buffered data is made up of
2043 // many smaller SSL records (the TestServer writes along 1350 byte
2044 // plaintext boundaries), although there may also be a few records that are
2045 // smaller or larger, due to timing and SSL False Start.
2046 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2047 // the SSLClientSocket implementation, and larger than the minimum amount
2048 // of ciphertext necessary to contain the 8K of plaintext requested below.
2049 raw_transport->SetBufferSize(15000);
2051 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
2052 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
2053 ASSERT_EQ(rv, 8192);
2056 TEST_F(SSLClientSocketTest, Read_Interrupted) {
2057 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2058 SpawnedTestServer::kLocalhost,
2060 ASSERT_TRUE(test_server.Start());
2063 ASSERT_TRUE(test_server.GetAddressList(&addr));
2065 TestCompletionCallback callback;
2066 scoped_ptr<StreamSocket> transport(
2067 new TCPClientSocket(addr, NULL, NetLog::Source()));
2068 int rv = transport->Connect(callback.callback());
2069 if (rv == ERR_IO_PENDING)
2070 rv = callback.WaitForResult();
2073 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2074 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2076 rv = sock->Connect(callback.callback());
2077 if (rv == ERR_IO_PENDING)
2078 rv = callback.WaitForResult();
2081 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2082 scoped_refptr<IOBuffer> request_buffer(
2083 new IOBuffer(arraysize(request_text) - 1));
2084 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2087 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2088 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2090 if (rv == ERR_IO_PENDING)
2091 rv = callback.WaitForResult();
2092 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2094 // Do a partial read and then exit. This test should not crash!
2095 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
2096 rv = sock->Read(buf.get(), 512, callback.callback());
2097 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
2099 if (rv == ERR_IO_PENDING)
2100 rv = callback.WaitForResult();
2105 TEST_F(SSLClientSocketTest, Read_FullLogging) {
2106 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2107 SpawnedTestServer::kLocalhost,
2109 ASSERT_TRUE(test_server.Start());
2112 ASSERT_TRUE(test_server.GetAddressList(&addr));
2114 TestCompletionCallback callback;
2115 CapturingNetLog log;
2116 log.SetLogLevel(NetLog::LOG_ALL);
2117 scoped_ptr<StreamSocket> transport(
2118 new TCPClientSocket(addr, &log, NetLog::Source()));
2119 int rv = transport->Connect(callback.callback());
2120 if (rv == ERR_IO_PENDING)
2121 rv = callback.WaitForResult();
2124 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2125 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2127 rv = sock->Connect(callback.callback());
2128 if (rv == ERR_IO_PENDING)
2129 rv = callback.WaitForResult();
2131 EXPECT_TRUE(sock->IsConnected());
2133 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2134 scoped_refptr<IOBuffer> request_buffer(
2135 new IOBuffer(arraysize(request_text) - 1));
2136 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2139 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2140 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2142 if (rv == ERR_IO_PENDING)
2143 rv = callback.WaitForResult();
2144 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2146 CapturingNetLog::CapturedEntryList entries;
2147 log.GetEntries(&entries);
2148 size_t last_index = ExpectLogContainsSomewhereAfter(
2149 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2151 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2153 rv = sock->Read(buf.get(), 4096, callback.callback());
2154 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2156 if (rv == ERR_IO_PENDING)
2157 rv = callback.WaitForResult();
2163 log.GetEntries(&entries);
2165 ExpectLogContainsSomewhereAfter(entries,
2167 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2168 NetLog::PHASE_NONE);
2172 // Regression test for http://crbug.com/42538
2173 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2174 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2175 SpawnedTestServer::kLocalhost,
2177 ASSERT_TRUE(test_server.Start());
2180 TestCompletionCallback callback;
2182 static const unsigned char application_data[] = {
2183 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2184 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2185 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2186 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2187 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2188 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2189 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2190 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2191 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2194 // All reads and writes complete synchronously (async=false).
2195 MockRead data_reads[] = {
2196 MockRead(SYNCHRONOUS,
2197 reinterpret_cast<const char*>(application_data),
2198 arraysize(application_data)),
2199 MockRead(SYNCHRONOUS, OK), };
2201 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2203 scoped_ptr<StreamSocket> transport(
2204 new MockTCPClientSocket(addr, NULL, &data));
2205 int rv = transport->Connect(callback.callback());
2206 if (rv == ERR_IO_PENDING)
2207 rv = callback.WaitForResult();
2210 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2211 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2213 rv = sock->Connect(callback.callback());
2214 if (rv == ERR_IO_PENDING)
2215 rv = callback.WaitForResult();
2216 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2219 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2220 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2221 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2222 // only disabling those cipher suites that the test server actually
2224 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2227 SpawnedTestServer::SSLOptions ssl_options;
2228 // Enable only RC4 on the test server.
2229 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
2230 SpawnedTestServer test_server(
2231 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2232 ASSERT_TRUE(test_server.Start());
2235 ASSERT_TRUE(test_server.GetAddressList(&addr));
2237 TestCompletionCallback callback;
2238 CapturingNetLog log;
2239 scoped_ptr<StreamSocket> transport(
2240 new TCPClientSocket(addr, &log, NetLog::Source()));
2241 int rv = transport->Connect(callback.callback());
2242 if (rv == ERR_IO_PENDING)
2243 rv = callback.WaitForResult();
2246 SSLConfig ssl_config;
2247 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2248 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2250 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2251 transport.Pass(), test_server.host_port_pair(), ssl_config));
2253 EXPECT_FALSE(sock->IsConnected());
2255 rv = sock->Connect(callback.callback());
2256 CapturingNetLog::CapturedEntryList entries;
2257 log.GetEntries(&entries);
2258 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2260 // NSS has special handling that maps a handshake_failure alert received
2261 // immediately after a client_hello to be a mismatched cipher suite error,
2262 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2263 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2264 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2265 // indicates that no cipher suite was negotiated with the test server.
2266 if (rv == ERR_IO_PENDING)
2267 rv = callback.WaitForResult();
2268 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
2269 rv == ERR_SSL_PROTOCOL_ERROR);
2270 // The exact ordering differs between SSLClientSocketNSS (which issues an
2271 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2272 // error appears somewhere in the log.
2273 log.GetEntries(&entries);
2274 ExpectLogContainsSomewhere(
2275 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2277 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2278 // the socket when it encounters an error, whereas other implementations
2279 // leave it connected.
2280 // Because this an error that the test server is mutually aware of, as opposed
2281 // to being an error such as a certificate name mismatch, which is
2282 // client-only, the exact index of the SSL connect end depends on how
2283 // quickly the test server closes the underlying socket. If the test server
2284 // closes before the IO message loop pumps messages, there may be a 0-byte
2285 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2286 // result, the SSL connect end event will be the second-to-last entry,
2287 // rather than the last entry.
2288 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2289 LogContainsSSLConnectEndEvent(entries, -2));
2292 // When creating an SSLClientSocket, it is allowed to pass in a
2293 // ClientSocketHandle that is not obtained from a client socket pool.
2294 // Here we verify that such a simple ClientSocketHandle, not associated with any
2295 // client socket pool, can be destroyed safely.
2296 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2297 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2298 SpawnedTestServer::kLocalhost,
2300 ASSERT_TRUE(test_server.Start());
2303 ASSERT_TRUE(test_server.GetAddressList(&addr));
2305 TestCompletionCallback callback;
2306 scoped_ptr<StreamSocket> transport(
2307 new TCPClientSocket(addr, NULL, NetLog::Source()));
2308 int rv = transport->Connect(callback.callback());
2309 if (rv == ERR_IO_PENDING)
2310 rv = callback.WaitForResult();
2313 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2314 socket_handle->SetSocket(transport.Pass());
2316 scoped_ptr<SSLClientSocket> sock(
2317 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
2318 test_server.host_port_pair(),
2322 EXPECT_FALSE(sock->IsConnected());
2323 rv = sock->Connect(callback.callback());
2324 if (rv == ERR_IO_PENDING)
2325 rv = callback.WaitForResult();
2329 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2330 // code and different keying label results in different keying material.
2331 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2332 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2333 SpawnedTestServer::kLocalhost,
2335 ASSERT_TRUE(test_server.Start());
2338 ASSERT_TRUE(test_server.GetAddressList(&addr));
2340 TestCompletionCallback callback;
2342 scoped_ptr<StreamSocket> transport(
2343 new TCPClientSocket(addr, NULL, NetLog::Source()));
2344 int rv = transport->Connect(callback.callback());
2345 if (rv == ERR_IO_PENDING)
2346 rv = callback.WaitForResult();
2349 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2350 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2352 rv = sock->Connect(callback.callback());
2353 if (rv == ERR_IO_PENDING)
2354 rv = callback.WaitForResult();
2356 EXPECT_TRUE(sock->IsConnected());
2358 const int kKeyingMaterialSize = 32;
2359 const char* kKeyingLabel1 = "client-socket-test-1";
2360 const char* kKeyingContext = "";
2361 unsigned char client_out1[kKeyingMaterialSize];
2362 memset(client_out1, 0, sizeof(client_out1));
2363 rv = sock->ExportKeyingMaterial(
2364 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
2367 const char* kKeyingLabel2 = "client-socket-test-2";
2368 unsigned char client_out2[kKeyingMaterialSize];
2369 memset(client_out2, 0, sizeof(client_out2));
2370 rv = sock->ExportKeyingMaterial(
2371 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
2373 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2376 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2377 // explicit NSS initialization.
2378 TEST(SSLClientSocket, ClearSessionCache) {
2379 SSLClientSocket::ClearSessionCache();
2382 // Test that the server certificates are properly retrieved from the underlying
2384 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2385 // The connection does not have to be successful.
2386 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2388 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2389 // This makes the server present redundant-server-chain.pem, which contains
2390 // intermediate certificates.
2391 SpawnedTestServer::SSLOptions ssl_options(
2392 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2393 SpawnedTestServer test_server(
2394 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2395 ASSERT_TRUE(test_server.Start());
2398 ASSERT_TRUE(test_server.GetAddressList(&addr));
2400 TestCompletionCallback callback;
2401 scoped_ptr<StreamSocket> transport(
2402 new TCPClientSocket(addr, NULL, NetLog::Source()));
2403 int rv = transport->Connect(callback.callback());
2404 rv = callback.GetResult(rv);
2407 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2408 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2409 EXPECT_FALSE(sock->IsConnected());
2410 rv = sock->Connect(callback.callback());
2411 rv = callback.GetResult(rv);
2413 EXPECT_EQ(ERR_CERT_INVALID, rv);
2414 EXPECT_TRUE(sock->IsConnected());
2416 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2417 // certs from redundant-server-chain.pem.
2418 CertificateList server_certs =
2419 CreateCertificateListFromFile(GetTestCertsDirectory(),
2420 "redundant-server-chain.pem",
2421 X509Certificate::FORMAT_AUTO);
2423 // Get the server certificate as received client side.
2424 scoped_refptr<X509Certificate> server_certificate =
2425 sock->GetUnverifiedServerCertificateChain();
2427 // Get the intermediates as received client side.
2428 const X509Certificate::OSCertHandles& server_intermediates =
2429 server_certificate->GetIntermediateCertificates();
2431 // Check that the unverified server certificate chain is properly retrieved
2432 // from the underlying ssl stack.
2433 ASSERT_EQ(4U, server_certs.size());
2435 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2436 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2438 ASSERT_EQ(3U, server_intermediates.size());
2440 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2441 server_certs[1]->os_cert_handle()));
2442 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2443 server_certs[2]->os_cert_handle()));
2444 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2445 server_certs[3]->os_cert_handle()));
2448 EXPECT_FALSE(sock->IsConnected());
2451 // This tests that SSLInfo contains a properly re-constructed certificate
2452 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2453 // verified, not the chain as served by the server. (They may be different.)
2455 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2456 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2457 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2458 // a self-signed root. Such a situation can occur when a new root (C2) is
2459 // cross-certified by an old root (D) and has two different versions of its
2460 // floating around. Servers may supply C2 as an intermediate, but the
2461 // SSLClientSocket should return the chain that was verified, from
2462 // verify_result, instead.
2463 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2464 // By default, cause the CertVerifier to treat all certificates as
2466 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2468 // We will expect SSLInfo to ultimately contain this chain.
2469 CertificateList certs =
2470 CreateCertificateListFromFile(GetTestCertsDirectory(),
2471 "redundant-validated-chain.pem",
2472 X509Certificate::FORMAT_AUTO);
2473 ASSERT_EQ(3U, certs.size());
2475 X509Certificate::OSCertHandles temp_intermediates;
2476 temp_intermediates.push_back(certs[1]->os_cert_handle());
2477 temp_intermediates.push_back(certs[2]->os_cert_handle());
2479 CertVerifyResult verify_result;
2480 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2481 certs[0]->os_cert_handle(), temp_intermediates);
2483 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2484 // rather than A->B->C.
2485 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2487 // Load and install the root for the validated chain.
2488 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2489 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2490 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2491 ScopedTestRoot scoped_root(root_cert.get());
2493 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2494 SpawnedTestServer::SSLOptions ssl_options(
2495 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2496 SpawnedTestServer test_server(
2497 SpawnedTestServer::TYPE_HTTPS,
2499 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2500 ASSERT_TRUE(test_server.Start());
2503 ASSERT_TRUE(test_server.GetAddressList(&addr));
2505 TestCompletionCallback callback;
2506 CapturingNetLog log;
2507 scoped_ptr<StreamSocket> transport(
2508 new TCPClientSocket(addr, &log, NetLog::Source()));
2509 int rv = transport->Connect(callback.callback());
2510 if (rv == ERR_IO_PENDING)
2511 rv = callback.WaitForResult();
2514 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2515 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2516 EXPECT_FALSE(sock->IsConnected());
2517 rv = sock->Connect(callback.callback());
2519 CapturingNetLog::CapturedEntryList entries;
2520 log.GetEntries(&entries);
2521 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2522 if (rv == ERR_IO_PENDING)
2523 rv = callback.WaitForResult();
2526 EXPECT_TRUE(sock->IsConnected());
2527 log.GetEntries(&entries);
2528 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2531 sock->GetSSLInfo(&ssl_info);
2533 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2535 const X509Certificate::OSCertHandles& intermediates =
2536 ssl_info.cert->GetIntermediateCertificates();
2537 ASSERT_EQ(2U, intermediates.size());
2538 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2539 certs[0]->os_cert_handle()));
2540 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2541 certs[1]->os_cert_handle()));
2542 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2543 certs[2]->os_cert_handle()));
2546 EXPECT_FALSE(sock->IsConnected());
2549 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2550 SpawnedTestServer::SSLOptions ssl_options;
2551 ssl_options.request_client_certificate = true;
2552 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2553 ASSERT_TRUE(request_info.get());
2554 EXPECT_EQ(0u, request_info->cert_authorities.size());
2557 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2558 const base::FilePath::CharType kThawteFile[] =
2559 FILE_PATH_LITERAL("thawte.single.pem");
2560 const unsigned char kThawteDN[] = {
2561 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2562 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2563 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2564 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2565 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2566 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2567 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2568 const size_t kThawteLen = sizeof(kThawteDN);
2570 const base::FilePath::CharType kDiginotarFile[] =
2571 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2572 const unsigned char kDiginotarDN[] = {
2573 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2574 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2575 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2576 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2577 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2578 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2579 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2580 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2582 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2584 SpawnedTestServer::SSLOptions ssl_options;
2585 ssl_options.request_client_certificate = true;
2586 ssl_options.client_authorities.push_back(
2587 GetTestClientCertsDirectory().Append(kThawteFile));
2588 ssl_options.client_authorities.push_back(
2589 GetTestClientCertsDirectory().Append(kDiginotarFile));
2590 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2591 ASSERT_TRUE(request_info.get());
2592 ASSERT_EQ(2u, request_info->cert_authorities.size());
2593 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2594 request_info->cert_authorities[0]);
2596 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2597 request_info->cert_authorities[1]);
2600 // cert_key_types is currently only populated on OpenSSL.
2601 #if defined(USE_OPENSSL)
2602 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2603 SpawnedTestServer::SSLOptions ssl_options;
2604 ssl_options.request_client_certificate = true;
2605 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2606 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2607 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2608 ASSERT_TRUE(request_info.get());
2609 ASSERT_EQ(2u, request_info->cert_key_types.size());
2610 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2611 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2613 #endif // defined(USE_OPENSSL)
2615 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2616 SpawnedTestServer::SSLOptions ssl_options;
2617 ssl_options.signed_cert_timestamps_tls_ext = "test";
2619 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2622 ASSERT_TRUE(test_server.Start());
2625 ASSERT_TRUE(test_server.GetAddressList(&addr));
2627 TestCompletionCallback callback;
2628 scoped_ptr<StreamSocket> transport(
2629 new TCPClientSocket(addr, &log_, NetLog::Source()));
2630 int rv = callback.GetResult(transport->Connect(callback.callback()));
2633 SSLConfig ssl_config;
2634 ssl_config.signed_cert_timestamps_enabled = true;
2636 MockCTVerifier ct_verifier;
2637 SetCTVerifier(&ct_verifier);
2639 // Check that the SCT list is extracted as expected.
2640 EXPECT_CALL(ct_verifier, Verify(_, "", "test", _, _)).WillRepeatedly(
2641 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2643 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2644 transport.Pass(), test_server.host_port_pair(), ssl_config));
2645 rv = callback.GetResult(sock->Connect(callback.callback()));
2648 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2653 bool IsValidOCSPResponse(const base::StringPiece& input) {
2654 base::StringPiece ocsp_response = input;
2655 base::StringPiece sequence, response_status, response_bytes;
2656 return asn1::GetElement(&ocsp_response, asn1::kSEQUENCE, &sequence) &&
2657 ocsp_response.empty() &&
2658 asn1::GetElement(&sequence, asn1::kENUMERATED, &response_status) &&
2659 asn1::GetElement(&sequence,
2660 asn1::kContextSpecific | asn1::kConstructed | 0,
2661 &response_status) &&
2667 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2668 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2669 SpawnedTestServer::SSLOptions ssl_options;
2670 ssl_options.staple_ocsp_response = true;
2671 // The test server currently only knows how to generate OCSP responses
2672 // for a freshly minted certificate.
2673 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2675 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2678 ASSERT_TRUE(test_server.Start());
2681 ASSERT_TRUE(test_server.GetAddressList(&addr));
2683 TestCompletionCallback callback;
2684 scoped_ptr<StreamSocket> transport(
2685 new TCPClientSocket(addr, &log_, NetLog::Source()));
2686 int rv = callback.GetResult(transport->Connect(callback.callback()));
2689 SSLConfig ssl_config;
2690 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2691 // Certificate Transparency verification regardless of whether the platform
2692 // is able to process the OCSP status itself.
2693 ssl_config.signed_cert_timestamps_enabled = true;
2695 MockCTVerifier ct_verifier;
2696 SetCTVerifier(&ct_verifier);
2698 // Check that the OCSP response is extracted and well-formed. It should be the
2699 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2700 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2701 // particular, it should not include the overall two-byte length prefix from
2703 EXPECT_CALL(ct_verifier,
2704 Verify(_, Truly(IsValidOCSPResponse), "", _, _)).WillRepeatedly(
2705 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2707 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2708 transport.Pass(), test_server.host_port_pair(), ssl_config));
2709 rv = callback.GetResult(sock->Connect(callback.callback()));
2712 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2715 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2716 SpawnedTestServer::SSLOptions ssl_options;
2717 ssl_options.signed_cert_timestamps_tls_ext = "test";
2719 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2722 ASSERT_TRUE(test_server.Start());
2725 ASSERT_TRUE(test_server.GetAddressList(&addr));
2727 TestCompletionCallback callback;
2728 scoped_ptr<StreamSocket> transport(
2729 new TCPClientSocket(addr, &log_, NetLog::Source()));
2730 int rv = callback.GetResult(transport->Connect(callback.callback()));
2733 SSLConfig ssl_config;
2734 ssl_config.signed_cert_timestamps_enabled = false;
2736 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2737 transport.Pass(), test_server.host_port_pair(), ssl_config));
2738 rv = callback.GetResult(sock->Connect(callback.callback()));
2741 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2744 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2745 TEST_F(SSLClientSocketTest, ReuseStates) {
2746 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2747 SpawnedTestServer::kLocalhost,
2749 ASSERT_TRUE(test_server.Start());
2752 ASSERT_TRUE(test_server.GetAddressList(&addr));
2754 TestCompletionCallback callback;
2755 scoped_ptr<StreamSocket> transport(
2756 new TCPClientSocket(addr, NULL, NetLog::Source()));
2757 int rv = transport->Connect(callback.callback());
2758 if (rv == ERR_IO_PENDING)
2759 rv = callback.WaitForResult();
2762 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2763 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2765 rv = sock->Connect(callback.callback());
2766 if (rv == ERR_IO_PENDING)
2767 rv = callback.WaitForResult();
2770 // The socket was just connected. It should be idle because it is speaking
2771 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2773 EXPECT_TRUE(sock->IsConnected());
2774 EXPECT_TRUE(sock->IsConnectedAndIdle());
2775 EXPECT_FALSE(sock->WasEverUsed());
2777 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2778 const size_t kRequestLen = arraysize(kRequestText) - 1;
2779 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2780 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2782 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2783 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2785 if (rv == ERR_IO_PENDING)
2786 rv = callback.WaitForResult();
2787 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2789 // The socket has now been used.
2790 EXPECT_TRUE(sock->WasEverUsed());
2792 // TODO(davidben): Read one byte to ensure the test server has responded and
2793 // then assert IsConnectedAndIdle is false. This currently doesn't work
2794 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2795 // SSL implementation's internal buffers. Either call PR_Available and
2796 // SSL_pending, although the former isn't actually implemented or perhaps
2797 // attempt to read one byte extra.
2800 #if defined(USE_OPENSSL)
2802 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithFailure) {
2803 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2804 SpawnedTestServer::kLocalhost,
2806 ASSERT_TRUE(test_server.Start());
2809 ASSERT_TRUE(test_server.GetAddressList(&addr));
2811 TestCompletionCallback callback;
2812 scoped_ptr<StreamSocket> real_transport(
2813 new TCPClientSocket(addr, NULL, NetLog::Source()));
2814 scoped_ptr<SynchronousErrorStreamSocket> transport(
2815 new SynchronousErrorStreamSocket(real_transport.Pass()));
2816 int rv = callback.GetResult(transport->Connect(callback.callback()));
2819 // Disable TLS False Start to avoid handshake non-determinism.
2820 SSLConfig ssl_config;
2821 ssl_config.false_start_enabled = false;
2823 SynchronousErrorStreamSocket* raw_transport = transport.get();
2824 scoped_ptr<SSLClientSocket> sock(
2825 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
2826 test_server.host_port_pair(),
2829 sock->SetHandshakeCompletionCallback(base::Bind(
2830 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2832 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
2834 rv = callback.GetResult(sock->Connect(callback.callback()));
2835 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
2836 EXPECT_FALSE(sock->IsConnected());
2838 EXPECT_TRUE(ran_handshake_completion_callback_);
2841 // Tests that the completion callback is run when an SSL connection
2842 // completes successfully.
2843 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithSuccess) {
2844 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2845 SpawnedTestServer::kLocalhost,
2847 ASSERT_TRUE(test_server.Start());
2850 ASSERT_TRUE(test_server.GetAddressList(&addr));
2852 scoped_ptr<StreamSocket> transport(
2853 new TCPClientSocket(addr, NULL, NetLog::Source()));
2855 TestCompletionCallback callback;
2856 int rv = transport->Connect(callback.callback());
2857 if (rv == ERR_IO_PENDING)
2858 rv = callback.WaitForResult();
2861 SSLConfig ssl_config = kDefaultSSLConfig;
2862 ssl_config.false_start_enabled = false;
2864 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2865 transport.Pass(), test_server.host_port_pair(), ssl_config));
2867 sock->SetHandshakeCompletionCallback(base::Bind(
2868 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2870 rv = callback.GetResult(sock->Connect(callback.callback()));
2873 EXPECT_TRUE(sock->IsConnected());
2874 EXPECT_TRUE(ran_handshake_completion_callback_);
2877 // Tests that the completion callback is run with a server that doesn't cache
2879 TEST_F(SSLClientSocketTest, HandshakeCallbackIsRun_WithDisabledSessionCache) {
2880 SpawnedTestServer::SSLOptions ssl_options;
2881 ssl_options.disable_session_cache = true;
2882 SpawnedTestServer test_server(
2883 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2884 ASSERT_TRUE(test_server.Start());
2887 ASSERT_TRUE(test_server.GetAddressList(&addr));
2889 scoped_ptr<StreamSocket> transport(
2890 new TCPClientSocket(addr, NULL, NetLog::Source()));
2892 TestCompletionCallback callback;
2893 int rv = transport->Connect(callback.callback());
2894 if (rv == ERR_IO_PENDING)
2895 rv = callback.WaitForResult();
2898 SSLConfig ssl_config = kDefaultSSLConfig;
2899 ssl_config.false_start_enabled = false;
2901 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2902 transport.Pass(), test_server.host_port_pair(), ssl_config));
2904 sock->SetHandshakeCompletionCallback(base::Bind(
2905 &SSLClientSocketTest::RecordCompletedHandshake, base::Unretained(this)));
2907 rv = callback.GetResult(sock->Connect(callback.callback()));
2910 EXPECT_TRUE(sock->IsConnected());
2911 EXPECT_TRUE(ran_handshake_completion_callback_);
2914 TEST_F(SSLClientSocketFalseStartTest,
2915 HandshakeCallbackIsRun_WithFalseStartFailure) {
2916 // False Start requires NPN and a forward-secret cipher suite.
2917 SpawnedTestServer::SSLOptions server_options;
2918 server_options.key_exchanges =
2919 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2920 server_options.enable_npn = true;
2921 SSLConfig client_config;
2922 client_config.next_protos.push_back("http/1.1");
2923 monitor_handshake_callback_ = true;
2924 fail_handshake_after_false_start_ = true;
2925 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2926 ASSERT_TRUE(ran_handshake_completion_callback_);
2929 TEST_F(SSLClientSocketFalseStartTest,
2930 HandshakeCallbackIsRun_WithFalseStartSuccess) {
2931 // False Start requires NPN and a forward-secret cipher suite.
2932 SpawnedTestServer::SSLOptions server_options;
2933 server_options.key_exchanges =
2934 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2935 server_options.enable_npn = true;
2936 SSLConfig client_config;
2937 client_config.next_protos.push_back("http/1.1");
2938 monitor_handshake_callback_ = true;
2939 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, true));
2940 ASSERT_TRUE(ran_handshake_completion_callback_);
2942 #endif // defined(USE_OPENSSL)
2944 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
2945 // False Start requires NPN and a forward-secret cipher suite.
2946 SpawnedTestServer::SSLOptions server_options;
2947 server_options.key_exchanges =
2948 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2949 server_options.enable_npn = true;
2950 SSLConfig client_config;
2951 client_config.next_protos.push_back("http/1.1");
2952 ASSERT_NO_FATAL_FAILURE(
2953 TestFalseStart(server_options, client_config, true));
2956 // Test that False Start is disabled without NPN.
2957 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
2958 SpawnedTestServer::SSLOptions server_options;
2959 server_options.key_exchanges =
2960 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2961 SSLConfig client_config;
2962 client_config.next_protos.clear();
2963 ASSERT_NO_FATAL_FAILURE(
2964 TestFalseStart(server_options, client_config, false));
2967 // Test that False Start is disabled without a forward-secret cipher suite.
2968 TEST_F(SSLClientSocketFalseStartTest, NoForwardSecrecy) {
2969 SpawnedTestServer::SSLOptions server_options;
2970 server_options.key_exchanges =
2971 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
2972 server_options.enable_npn = true;
2973 SSLConfig client_config;
2974 client_config.next_protos.push_back("http/1.1");
2975 ASSERT_NO_FATAL_FAILURE(
2976 TestFalseStart(server_options, client_config, false));
2979 // Test that sessions are resumable after receiving the server Finished message.
2980 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
2982 SpawnedTestServer::SSLOptions server_options;
2983 server_options.key_exchanges =
2984 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
2985 server_options.enable_npn = true;
2986 SSLConfig client_config;
2987 client_config.next_protos.push_back("http/1.1");
2989 // Let a full handshake complete with False Start.
2990 ASSERT_NO_FATAL_FAILURE(
2991 TestFalseStart(server_options, client_config, true));
2993 // Make a second connection.
2994 TestCompletionCallback callback;
2995 scoped_ptr<StreamSocket> transport2(
2996 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2997 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
2998 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
2999 transport2.Pass(), test_server()->host_port_pair(), client_config);
3000 ASSERT_TRUE(sock2.get());
3001 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3003 // It should resume the session.
3005 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3006 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3009 // Test that sessions are not resumable before receiving the server Finished
3011 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinish) {
3013 SpawnedTestServer::SSLOptions server_options;
3014 server_options.key_exchanges =
3015 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
3016 server_options.enable_npn = true;
3017 ASSERT_TRUE(StartTestServer(server_options));
3019 SSLConfig client_config;
3020 client_config.next_protos.push_back("http/1.1");
3022 // Start a handshake up to the server Finished message.
3023 TestCompletionCallback callback;
3024 FakeBlockingStreamSocket* raw_transport1;
3025 scoped_ptr<SSLClientSocket> sock1;
3026 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3027 client_config, &callback, &raw_transport1, &sock1));
3028 // Although raw_transport1 has the server Finished blocked, the handshake
3030 EXPECT_EQ(OK, callback.WaitForResult());
3032 // Drop the old socket. This is needed because the Python test server can't
3033 // service two sockets in parallel.
3036 // Start a second connection.
3037 scoped_ptr<StreamSocket> transport2(
3038 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3039 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3040 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3041 transport2.Pass(), test_server()->host_port_pair(), client_config);
3042 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3044 // No session resumption because the first connection never received a server
3045 // Finished message.
3047 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3048 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3051 // Connect to a server using channel id. It should allow the connection.
3052 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
3053 SpawnedTestServer::SSLOptions ssl_options;
3055 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3058 SSLConfig ssl_config = kDefaultSSLConfig;
3059 ssl_config.channel_id_enabled = true;
3062 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3065 EXPECT_TRUE(sock_->IsConnected());
3066 EXPECT_TRUE(sock_->WasChannelIDSent());
3068 sock_->Disconnect();
3069 EXPECT_FALSE(sock_->IsConnected());
3072 // Connect to a server using Channel ID but failing to look up the Channel
3073 // ID. It should fail.
3074 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
3075 SpawnedTestServer::SSLOptions ssl_options;
3077 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3079 EnableFailingChannelID();
3080 SSLConfig ssl_config = kDefaultSSLConfig;
3081 ssl_config.channel_id_enabled = true;
3084 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3086 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3087 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3088 // error codes for now.
3089 // http://crbug.com/373670
3091 EXPECT_FALSE(sock_->IsConnected());
3094 // Connect to a server using Channel ID but asynchronously failing to look up
3095 // the Channel ID. It should fail.
3096 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
3097 SpawnedTestServer::SSLOptions ssl_options;
3099 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3101 EnableAsyncFailingChannelID();
3102 SSLConfig ssl_config = kDefaultSSLConfig;
3103 ssl_config.channel_id_enabled = true;
3106 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3108 EXPECT_EQ(ERR_UNEXPECTED, rv);
3109 EXPECT_FALSE(sock_->IsConnected());