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(Error 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(Error 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 TEST_F(SSLClientSocketTest
, Read_SmallChunks
) {
1831 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1832 SpawnedTestServer::kLocalhost
,
1834 ASSERT_TRUE(test_server
.Start());
1837 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1839 TestCompletionCallback callback
;
1840 scoped_ptr
<StreamSocket
> transport(
1841 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1842 int rv
= transport
->Connect(callback
.callback());
1843 if (rv
== ERR_IO_PENDING
)
1844 rv
= callback
.WaitForResult();
1847 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1848 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1850 rv
= sock
->Connect(callback
.callback());
1851 if (rv
== ERR_IO_PENDING
)
1852 rv
= callback
.WaitForResult();
1855 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1856 scoped_refptr
<IOBuffer
> request_buffer(
1857 new IOBuffer(arraysize(request_text
) - 1));
1858 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1861 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1862 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1864 if (rv
== ERR_IO_PENDING
)
1865 rv
= callback
.WaitForResult();
1866 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1868 scoped_refptr
<IOBuffer
> buf(new IOBuffer(1));
1870 rv
= sock
->Read(buf
.get(), 1, callback
.callback());
1871 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1873 if (rv
== ERR_IO_PENDING
)
1874 rv
= callback
.WaitForResult();
1882 TEST_F(SSLClientSocketTest
, Read_ManySmallRecords
) {
1883 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1884 SpawnedTestServer::kLocalhost
,
1886 ASSERT_TRUE(test_server
.Start());
1889 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1891 TestCompletionCallback callback
;
1893 scoped_ptr
<StreamSocket
> real_transport(
1894 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1895 scoped_ptr
<ReadBufferingStreamSocket
> transport(
1896 new ReadBufferingStreamSocket(real_transport
.Pass()));
1897 ReadBufferingStreamSocket
* raw_transport
= transport
.get();
1898 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1901 scoped_ptr
<SSLClientSocket
> sock(
1902 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
1903 test_server
.host_port_pair(),
1904 kDefaultSSLConfig
));
1906 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1908 ASSERT_TRUE(sock
->IsConnected());
1910 const char request_text
[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1911 scoped_refptr
<IOBuffer
> request_buffer(
1912 new IOBuffer(arraysize(request_text
) - 1));
1913 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1915 rv
= callback
.GetResult(sock
->Write(
1916 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback()));
1918 ASSERT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1920 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1921 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1922 // of SSL data is buffered first. The 15K of buffered data is made up of
1923 // many smaller SSL records (the TestServer writes along 1350 byte
1924 // plaintext boundaries), although there may also be a few records that are
1925 // smaller or larger, due to timing and SSL False Start.
1926 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1927 // the SSLClientSocket implementation, and larger than the minimum amount
1928 // of ciphertext necessary to contain the 8K of plaintext requested below.
1929 raw_transport
->SetBufferSize(15000);
1931 scoped_refptr
<IOBuffer
> buffer(new IOBuffer(8192));
1932 rv
= callback
.GetResult(sock
->Read(buffer
.get(), 8192, callback
.callback()));
1933 ASSERT_EQ(rv
, 8192);
1936 TEST_F(SSLClientSocketTest
, Read_Interrupted
) {
1937 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1938 SpawnedTestServer::kLocalhost
,
1940 ASSERT_TRUE(test_server
.Start());
1943 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1945 TestCompletionCallback callback
;
1946 scoped_ptr
<StreamSocket
> transport(
1947 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1948 int rv
= transport
->Connect(callback
.callback());
1949 if (rv
== ERR_IO_PENDING
)
1950 rv
= callback
.WaitForResult();
1953 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1954 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
1956 rv
= sock
->Connect(callback
.callback());
1957 if (rv
== ERR_IO_PENDING
)
1958 rv
= callback
.WaitForResult();
1961 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1962 scoped_refptr
<IOBuffer
> request_buffer(
1963 new IOBuffer(arraysize(request_text
) - 1));
1964 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1967 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1968 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1970 if (rv
== ERR_IO_PENDING
)
1971 rv
= callback
.WaitForResult();
1972 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1974 // Do a partial read and then exit. This test should not crash!
1975 scoped_refptr
<IOBuffer
> buf(new IOBuffer(512));
1976 rv
= sock
->Read(buf
.get(), 512, callback
.callback());
1977 EXPECT_TRUE(rv
> 0 || rv
== ERR_IO_PENDING
);
1979 if (rv
== ERR_IO_PENDING
)
1980 rv
= callback
.WaitForResult();
1985 TEST_F(SSLClientSocketTest
, Read_FullLogging
) {
1986 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1987 SpawnedTestServer::kLocalhost
,
1989 ASSERT_TRUE(test_server
.Start());
1992 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1994 TestCompletionCallback callback
;
1995 CapturingNetLog log
;
1996 log
.SetLogLevel(NetLog::LOG_ALL
);
1997 scoped_ptr
<StreamSocket
> transport(
1998 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1999 int rv
= transport
->Connect(callback
.callback());
2000 if (rv
== ERR_IO_PENDING
)
2001 rv
= callback
.WaitForResult();
2004 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2005 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2007 rv
= sock
->Connect(callback
.callback());
2008 if (rv
== ERR_IO_PENDING
)
2009 rv
= callback
.WaitForResult();
2011 EXPECT_TRUE(sock
->IsConnected());
2013 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2014 scoped_refptr
<IOBuffer
> request_buffer(
2015 new IOBuffer(arraysize(request_text
) - 1));
2016 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2019 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2020 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2022 if (rv
== ERR_IO_PENDING
)
2023 rv
= callback
.WaitForResult();
2024 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2026 CapturingNetLog::CapturedEntryList entries
;
2027 log
.GetEntries(&entries
);
2028 size_t last_index
= ExpectLogContainsSomewhereAfter(
2029 entries
, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
2031 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
2033 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
2034 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2036 if (rv
== ERR_IO_PENDING
)
2037 rv
= callback
.WaitForResult();
2043 log
.GetEntries(&entries
);
2045 ExpectLogContainsSomewhereAfter(entries
,
2047 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
2048 NetLog::PHASE_NONE
);
2052 // Regression test for http://crbug.com/42538
2053 TEST_F(SSLClientSocketTest
, PrematureApplicationData
) {
2054 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2055 SpawnedTestServer::kLocalhost
,
2057 ASSERT_TRUE(test_server
.Start());
2060 TestCompletionCallback callback
;
2062 static const unsigned char application_data
[] = {
2063 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2064 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2065 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2066 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2067 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2068 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2069 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2070 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2071 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2074 // All reads and writes complete synchronously (async=false).
2075 MockRead data_reads
[] = {
2076 MockRead(SYNCHRONOUS
,
2077 reinterpret_cast<const char*>(application_data
),
2078 arraysize(application_data
)),
2079 MockRead(SYNCHRONOUS
, OK
), };
2081 StaticSocketDataProvider
data(data_reads
, arraysize(data_reads
), NULL
, 0);
2083 scoped_ptr
<StreamSocket
> transport(
2084 new MockTCPClientSocket(addr
, NULL
, &data
));
2085 int rv
= transport
->Connect(callback
.callback());
2086 if (rv
== ERR_IO_PENDING
)
2087 rv
= callback
.WaitForResult();
2090 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2091 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2093 rv
= sock
->Connect(callback
.callback());
2094 if (rv
== ERR_IO_PENDING
)
2095 rv
= callback
.WaitForResult();
2096 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, rv
);
2099 TEST_F(SSLClientSocketTest
, CipherSuiteDisables
) {
2100 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2101 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2102 // only disabling those cipher suites that the test server actually
2104 const uint16 kCiphersToDisable
[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2107 SpawnedTestServer::SSLOptions ssl_options
;
2108 // Enable only RC4 on the test server.
2109 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
2110 SpawnedTestServer
test_server(
2111 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2112 ASSERT_TRUE(test_server
.Start());
2115 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2117 TestCompletionCallback callback
;
2118 CapturingNetLog log
;
2119 scoped_ptr
<StreamSocket
> transport(
2120 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2121 int rv
= transport
->Connect(callback
.callback());
2122 if (rv
== ERR_IO_PENDING
)
2123 rv
= callback
.WaitForResult();
2126 SSLConfig ssl_config
;
2127 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2128 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2130 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2131 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2133 EXPECT_FALSE(sock
->IsConnected());
2135 rv
= sock
->Connect(callback
.callback());
2136 CapturingNetLog::CapturedEntryList entries
;
2137 log
.GetEntries(&entries
);
2138 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2140 // NSS has special handling that maps a handshake_failure alert received
2141 // immediately after a client_hello to be a mismatched cipher suite error,
2142 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2143 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2144 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2145 // indicates that no cipher suite was negotiated with the test server.
2146 if (rv
== ERR_IO_PENDING
)
2147 rv
= callback
.WaitForResult();
2148 EXPECT_TRUE(rv
== ERR_SSL_VERSION_OR_CIPHER_MISMATCH
||
2149 rv
== ERR_SSL_PROTOCOL_ERROR
);
2150 // The exact ordering differs between SSLClientSocketNSS (which issues an
2151 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2152 // error appears somewhere in the log.
2153 log
.GetEntries(&entries
);
2154 ExpectLogContainsSomewhere(
2155 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2157 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2158 // the socket when it encounters an error, whereas other implementations
2159 // leave it connected.
2160 // Because this an error that the test server is mutually aware of, as opposed
2161 // to being an error such as a certificate name mismatch, which is
2162 // client-only, the exact index of the SSL connect end depends on how
2163 // quickly the test server closes the underlying socket. If the test server
2164 // closes before the IO message loop pumps messages, there may be a 0-byte
2165 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2166 // result, the SSL connect end event will be the second-to-last entry,
2167 // rather than the last entry.
2168 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1) ||
2169 LogContainsSSLConnectEndEvent(entries
, -2));
2172 // When creating an SSLClientSocket, it is allowed to pass in a
2173 // ClientSocketHandle that is not obtained from a client socket pool.
2174 // Here we verify that such a simple ClientSocketHandle, not associated with any
2175 // client socket pool, can be destroyed safely.
2176 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2177 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2178 SpawnedTestServer::kLocalhost
,
2180 ASSERT_TRUE(test_server
.Start());
2183 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2185 TestCompletionCallback callback
;
2186 scoped_ptr
<StreamSocket
> transport(
2187 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2188 int rv
= transport
->Connect(callback
.callback());
2189 if (rv
== ERR_IO_PENDING
)
2190 rv
= callback
.WaitForResult();
2193 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2194 socket_handle
->SetSocket(transport
.Pass());
2196 scoped_ptr
<SSLClientSocket
> sock(
2197 socket_factory_
->CreateSSLClientSocket(socket_handle
.Pass(),
2198 test_server
.host_port_pair(),
2202 EXPECT_FALSE(sock
->IsConnected());
2203 rv
= sock
->Connect(callback
.callback());
2204 if (rv
== ERR_IO_PENDING
)
2205 rv
= callback
.WaitForResult();
2209 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2210 // code and different keying label results in different keying material.
2211 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2212 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2213 SpawnedTestServer::kLocalhost
,
2215 ASSERT_TRUE(test_server
.Start());
2218 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2220 TestCompletionCallback callback
;
2222 scoped_ptr
<StreamSocket
> transport(
2223 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2224 int rv
= transport
->Connect(callback
.callback());
2225 if (rv
== ERR_IO_PENDING
)
2226 rv
= callback
.WaitForResult();
2229 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2230 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2232 rv
= sock
->Connect(callback
.callback());
2233 if (rv
== ERR_IO_PENDING
)
2234 rv
= callback
.WaitForResult();
2236 EXPECT_TRUE(sock
->IsConnected());
2238 const int kKeyingMaterialSize
= 32;
2239 const char* kKeyingLabel1
= "client-socket-test-1";
2240 const char* kKeyingContext
= "";
2241 unsigned char client_out1
[kKeyingMaterialSize
];
2242 memset(client_out1
, 0, sizeof(client_out1
));
2243 rv
= sock
->ExportKeyingMaterial(
2244 kKeyingLabel1
, false, kKeyingContext
, client_out1
, sizeof(client_out1
));
2247 const char* kKeyingLabel2
= "client-socket-test-2";
2248 unsigned char client_out2
[kKeyingMaterialSize
];
2249 memset(client_out2
, 0, sizeof(client_out2
));
2250 rv
= sock
->ExportKeyingMaterial(
2251 kKeyingLabel2
, false, kKeyingContext
, client_out2
, sizeof(client_out2
));
2253 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2256 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2257 // explicit NSS initialization.
2258 TEST(SSLClientSocket
, ClearSessionCache
) {
2259 SSLClientSocket::ClearSessionCache();
2262 // Test that the server certificates are properly retrieved from the underlying
2264 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2265 // The connection does not have to be successful.
2266 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2268 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2269 // This makes the server present redundant-server-chain.pem, which contains
2270 // intermediate certificates.
2271 SpawnedTestServer::SSLOptions
ssl_options(
2272 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2273 SpawnedTestServer
test_server(
2274 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2275 ASSERT_TRUE(test_server
.Start());
2278 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2280 TestCompletionCallback callback
;
2281 scoped_ptr
<StreamSocket
> transport(
2282 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2283 int rv
= transport
->Connect(callback
.callback());
2284 rv
= callback
.GetResult(rv
);
2287 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2288 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2289 EXPECT_FALSE(sock
->IsConnected());
2290 rv
= sock
->Connect(callback
.callback());
2291 rv
= callback
.GetResult(rv
);
2293 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2294 EXPECT_TRUE(sock
->IsConnected());
2296 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2297 // certs from redundant-server-chain.pem.
2298 CertificateList server_certs
=
2299 CreateCertificateListFromFile(GetTestCertsDirectory(),
2300 "redundant-server-chain.pem",
2301 X509Certificate::FORMAT_AUTO
);
2303 // Get the server certificate as received client side.
2304 scoped_refptr
<X509Certificate
> server_certificate
=
2305 sock
->GetUnverifiedServerCertificateChain();
2307 // Get the intermediates as received client side.
2308 const X509Certificate::OSCertHandles
& server_intermediates
=
2309 server_certificate
->GetIntermediateCertificates();
2311 // Check that the unverified server certificate chain is properly retrieved
2312 // from the underlying ssl stack.
2313 ASSERT_EQ(4U, server_certs
.size());
2315 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2316 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2318 ASSERT_EQ(3U, server_intermediates
.size());
2320 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2321 server_certs
[1]->os_cert_handle()));
2322 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2323 server_certs
[2]->os_cert_handle()));
2324 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2325 server_certs
[3]->os_cert_handle()));
2328 EXPECT_FALSE(sock
->IsConnected());
2331 // This tests that SSLInfo contains a properly re-constructed certificate
2332 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2333 // verified, not the chain as served by the server. (They may be different.)
2335 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2336 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2337 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2338 // a self-signed root. Such a situation can occur when a new root (C2) is
2339 // cross-certified by an old root (D) and has two different versions of its
2340 // floating around. Servers may supply C2 as an intermediate, but the
2341 // SSLClientSocket should return the chain that was verified, from
2342 // verify_result, instead.
2343 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2344 // By default, cause the CertVerifier to treat all certificates as
2346 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2348 // We will expect SSLInfo to ultimately contain this chain.
2349 CertificateList certs
=
2350 CreateCertificateListFromFile(GetTestCertsDirectory(),
2351 "redundant-validated-chain.pem",
2352 X509Certificate::FORMAT_AUTO
);
2353 ASSERT_EQ(3U, certs
.size());
2355 X509Certificate::OSCertHandles temp_intermediates
;
2356 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2357 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2359 CertVerifyResult verify_result
;
2360 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2361 certs
[0]->os_cert_handle(), temp_intermediates
);
2363 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2364 // rather than A->B->C.
2365 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2367 // Load and install the root for the validated chain.
2368 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2369 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2370 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
2371 ScopedTestRoot
scoped_root(root_cert
.get());
2373 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2374 SpawnedTestServer::SSLOptions
ssl_options(
2375 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2376 SpawnedTestServer
test_server(
2377 SpawnedTestServer::TYPE_HTTPS
,
2379 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2380 ASSERT_TRUE(test_server
.Start());
2383 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2385 TestCompletionCallback callback
;
2386 CapturingNetLog log
;
2387 scoped_ptr
<StreamSocket
> transport(
2388 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2389 int rv
= transport
->Connect(callback
.callback());
2390 if (rv
== ERR_IO_PENDING
)
2391 rv
= callback
.WaitForResult();
2394 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2395 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2396 EXPECT_FALSE(sock
->IsConnected());
2397 rv
= sock
->Connect(callback
.callback());
2399 CapturingNetLog::CapturedEntryList entries
;
2400 log
.GetEntries(&entries
);
2401 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2402 if (rv
== ERR_IO_PENDING
)
2403 rv
= callback
.WaitForResult();
2406 EXPECT_TRUE(sock
->IsConnected());
2407 log
.GetEntries(&entries
);
2408 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2411 sock
->GetSSLInfo(&ssl_info
);
2413 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2415 const X509Certificate::OSCertHandles
& intermediates
=
2416 ssl_info
.cert
->GetIntermediateCertificates();
2417 ASSERT_EQ(2U, intermediates
.size());
2418 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2419 certs
[0]->os_cert_handle()));
2420 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2421 certs
[1]->os_cert_handle()));
2422 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2423 certs
[2]->os_cert_handle()));
2426 EXPECT_FALSE(sock
->IsConnected());
2429 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2430 SpawnedTestServer::SSLOptions ssl_options
;
2431 ssl_options
.request_client_certificate
= true;
2432 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2433 ASSERT_TRUE(request_info
.get());
2434 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2437 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2438 const base::FilePath::CharType kThawteFile
[] =
2439 FILE_PATH_LITERAL("thawte.single.pem");
2440 const unsigned char kThawteDN
[] = {
2441 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2442 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2443 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2444 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2445 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2446 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2447 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2448 const size_t kThawteLen
= sizeof(kThawteDN
);
2450 const base::FilePath::CharType kDiginotarFile
[] =
2451 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2452 const unsigned char kDiginotarDN
[] = {
2453 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2454 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2455 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2456 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2457 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2458 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2459 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2460 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2462 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2464 SpawnedTestServer::SSLOptions ssl_options
;
2465 ssl_options
.request_client_certificate
= true;
2466 ssl_options
.client_authorities
.push_back(
2467 GetTestClientCertsDirectory().Append(kThawteFile
));
2468 ssl_options
.client_authorities
.push_back(
2469 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2470 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2471 ASSERT_TRUE(request_info
.get());
2472 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2473 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2474 request_info
->cert_authorities
[0]);
2476 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2477 request_info
->cert_authorities
[1]);
2480 // cert_key_types is currently only populated on OpenSSL.
2481 #if defined(USE_OPENSSL)
2482 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2483 SpawnedTestServer::SSLOptions ssl_options
;
2484 ssl_options
.request_client_certificate
= true;
2485 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2486 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2487 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2488 ASSERT_TRUE(request_info
.get());
2489 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2490 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2491 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2493 #endif // defined(USE_OPENSSL)
2495 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2496 SpawnedTestServer::SSLOptions ssl_options
;
2497 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2499 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2502 ASSERT_TRUE(test_server
.Start());
2505 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2507 TestCompletionCallback callback
;
2508 scoped_ptr
<StreamSocket
> transport(
2509 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2510 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2513 SSLConfig ssl_config
;
2514 ssl_config
.signed_cert_timestamps_enabled
= true;
2516 MockCTVerifier ct_verifier
;
2517 SetCTVerifier(&ct_verifier
);
2519 // Check that the SCT list is extracted as expected.
2520 EXPECT_CALL(ct_verifier
, Verify(_
, "", "test", _
, _
)).WillRepeatedly(
2521 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2523 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2524 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2525 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2528 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2533 bool IsValidOCSPResponse(const base::StringPiece
& input
) {
2534 base::StringPiece ocsp_response
= input
;
2535 base::StringPiece sequence
, response_status
, response_bytes
;
2536 return asn1::GetElement(&ocsp_response
, asn1::kSEQUENCE
, &sequence
) &&
2537 ocsp_response
.empty() &&
2538 asn1::GetElement(&sequence
, asn1::kENUMERATED
, &response_status
) &&
2539 asn1::GetElement(&sequence
,
2540 asn1::kContextSpecific
| asn1::kConstructed
| 0,
2541 &response_status
) &&
2547 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2548 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2549 SpawnedTestServer::SSLOptions ssl_options
;
2550 ssl_options
.staple_ocsp_response
= true;
2551 // The test server currently only knows how to generate OCSP responses
2552 // for a freshly minted certificate.
2553 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2555 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2558 ASSERT_TRUE(test_server
.Start());
2561 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2563 TestCompletionCallback callback
;
2564 scoped_ptr
<StreamSocket
> transport(
2565 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2566 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2569 SSLConfig ssl_config
;
2570 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2571 // Certificate Transparency verification regardless of whether the platform
2572 // is able to process the OCSP status itself.
2573 ssl_config
.signed_cert_timestamps_enabled
= true;
2575 MockCTVerifier ct_verifier
;
2576 SetCTVerifier(&ct_verifier
);
2578 // Check that the OCSP response is extracted and well-formed. It should be the
2579 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2580 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2581 // particular, it should not include the overall two-byte length prefix from
2583 EXPECT_CALL(ct_verifier
,
2584 Verify(_
, Truly(IsValidOCSPResponse
), "", _
, _
)).WillRepeatedly(
2585 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2587 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2588 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2589 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2592 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2595 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2596 SpawnedTestServer::SSLOptions ssl_options
;
2597 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2599 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2602 ASSERT_TRUE(test_server
.Start());
2605 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2607 TestCompletionCallback callback
;
2608 scoped_ptr
<StreamSocket
> transport(
2609 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2610 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2613 SSLConfig ssl_config
;
2614 ssl_config
.signed_cert_timestamps_enabled
= false;
2616 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2617 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2618 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2621 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2624 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2625 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2626 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2627 SpawnedTestServer::kLocalhost
,
2629 ASSERT_TRUE(test_server
.Start());
2632 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2634 TestCompletionCallback callback
;
2635 scoped_ptr
<StreamSocket
> transport(
2636 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2637 int rv
= transport
->Connect(callback
.callback());
2638 if (rv
== ERR_IO_PENDING
)
2639 rv
= callback
.WaitForResult();
2642 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2643 transport
.Pass(), test_server
.host_port_pair(), kDefaultSSLConfig
));
2645 rv
= sock
->Connect(callback
.callback());
2646 if (rv
== ERR_IO_PENDING
)
2647 rv
= callback
.WaitForResult();
2650 // The socket was just connected. It should be idle because it is speaking
2651 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2653 EXPECT_TRUE(sock
->IsConnected());
2654 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2655 EXPECT_FALSE(sock
->WasEverUsed());
2657 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2658 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2659 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2660 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2662 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2663 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2665 if (rv
== ERR_IO_PENDING
)
2666 rv
= callback
.WaitForResult();
2667 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2669 // The socket has now been used.
2670 EXPECT_TRUE(sock
->WasEverUsed());
2672 // TODO(davidben): Read one byte to ensure the test server has responded and
2673 // then assert IsConnectedAndIdle is false. This currently doesn't work
2674 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2675 // SSL implementation's internal buffers. Either call PR_Available and
2676 // SSL_pending, although the former isn't actually implemented or perhaps
2677 // attempt to read one byte extra.
2680 #if defined(USE_OPENSSL)
2682 TEST_F(SSLClientSocketTest
, HandshakeCallbackIsRun_WithFailure
) {
2683 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2684 SpawnedTestServer::kLocalhost
,
2686 ASSERT_TRUE(test_server
.Start());
2689 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2691 TestCompletionCallback callback
;
2692 scoped_ptr
<StreamSocket
> real_transport(
2693 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2694 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
2695 new SynchronousErrorStreamSocket(real_transport
.Pass()));
2696 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2699 // Disable TLS False Start to avoid handshake non-determinism.
2700 SSLConfig ssl_config
;
2701 ssl_config
.false_start_enabled
= false;
2703 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
2704 scoped_ptr
<SSLClientSocket
> sock(
2705 CreateSSLClientSocket(transport
.PassAs
<StreamSocket
>(),
2706 test_server
.host_port_pair(),
2709 sock
->SetHandshakeCompletionCallback(base::Bind(
2710 &SSLClientSocketTest::RecordCompletedHandshake
, base::Unretained(this)));
2712 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
2714 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2715 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
2716 EXPECT_FALSE(sock
->IsConnected());
2718 EXPECT_TRUE(ran_handshake_completion_callback_
);
2721 // Tests that the completion callback is run when an SSL connection
2722 // completes successfully.
2723 TEST_F(SSLClientSocketTest
, HandshakeCallbackIsRun_WithSuccess
) {
2724 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2725 SpawnedTestServer::kLocalhost
,
2727 ASSERT_TRUE(test_server
.Start());
2730 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2732 scoped_ptr
<StreamSocket
> transport(
2733 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2735 TestCompletionCallback callback
;
2736 int rv
= transport
->Connect(callback
.callback());
2737 if (rv
== ERR_IO_PENDING
)
2738 rv
= callback
.WaitForResult();
2741 SSLConfig ssl_config
= kDefaultSSLConfig
;
2742 ssl_config
.false_start_enabled
= false;
2744 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2745 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2747 sock
->SetHandshakeCompletionCallback(base::Bind(
2748 &SSLClientSocketTest::RecordCompletedHandshake
, base::Unretained(this)));
2750 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2753 EXPECT_TRUE(sock
->IsConnected());
2754 EXPECT_TRUE(ran_handshake_completion_callback_
);
2757 // Tests that the completion callback is run with a server that doesn't cache
2759 TEST_F(SSLClientSocketTest
, HandshakeCallbackIsRun_WithDisabledSessionCache
) {
2760 SpawnedTestServer::SSLOptions ssl_options
;
2761 ssl_options
.disable_session_cache
= true;
2762 SpawnedTestServer
test_server(
2763 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2764 ASSERT_TRUE(test_server
.Start());
2767 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2769 scoped_ptr
<StreamSocket
> transport(
2770 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2772 TestCompletionCallback callback
;
2773 int rv
= transport
->Connect(callback
.callback());
2774 if (rv
== ERR_IO_PENDING
)
2775 rv
= callback
.WaitForResult();
2778 SSLConfig ssl_config
= kDefaultSSLConfig
;
2779 ssl_config
.false_start_enabled
= false;
2781 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2782 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2784 sock
->SetHandshakeCompletionCallback(base::Bind(
2785 &SSLClientSocketTest::RecordCompletedHandshake
, base::Unretained(this)));
2787 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2790 EXPECT_TRUE(sock
->IsConnected());
2791 EXPECT_TRUE(ran_handshake_completion_callback_
);
2794 TEST_F(SSLClientSocketFalseStartTest
,
2795 HandshakeCallbackIsRun_WithFalseStartFailure
) {
2796 // False Start requires NPN and a forward-secret cipher suite.
2797 SpawnedTestServer::SSLOptions server_options
;
2798 server_options
.key_exchanges
=
2799 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2800 server_options
.enable_npn
= true;
2801 SSLConfig client_config
;
2802 client_config
.next_protos
.push_back("http/1.1");
2803 monitor_handshake_callback_
= true;
2804 fail_handshake_after_false_start_
= true;
2805 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, true));
2806 ASSERT_TRUE(ran_handshake_completion_callback_
);
2809 TEST_F(SSLClientSocketFalseStartTest
,
2810 HandshakeCallbackIsRun_WithFalseStartSuccess
) {
2811 // False Start requires NPN and a forward-secret cipher suite.
2812 SpawnedTestServer::SSLOptions server_options
;
2813 server_options
.key_exchanges
=
2814 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2815 server_options
.enable_npn
= true;
2816 SSLConfig client_config
;
2817 client_config
.next_protos
.push_back("http/1.1");
2818 monitor_handshake_callback_
= true;
2819 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, true));
2820 ASSERT_TRUE(ran_handshake_completion_callback_
);
2822 #endif // defined(USE_OPENSSL)
2824 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
2825 // False Start requires NPN and a forward-secret cipher suite.
2826 SpawnedTestServer::SSLOptions server_options
;
2827 server_options
.key_exchanges
=
2828 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2829 server_options
.enable_npn
= true;
2830 SSLConfig client_config
;
2831 client_config
.next_protos
.push_back("http/1.1");
2832 ASSERT_NO_FATAL_FAILURE(
2833 TestFalseStart(server_options
, client_config
, true));
2836 // Test that False Start is disabled without NPN.
2837 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
2838 SpawnedTestServer::SSLOptions server_options
;
2839 server_options
.key_exchanges
=
2840 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2841 SSLConfig client_config
;
2842 client_config
.next_protos
.clear();
2843 ASSERT_NO_FATAL_FAILURE(
2844 TestFalseStart(server_options
, client_config
, false));
2847 // Test that False Start is disabled without a forward-secret cipher suite.
2848 TEST_F(SSLClientSocketFalseStartTest
, NoForwardSecrecy
) {
2849 SpawnedTestServer::SSLOptions server_options
;
2850 server_options
.key_exchanges
=
2851 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
2852 server_options
.enable_npn
= true;
2853 SSLConfig client_config
;
2854 client_config
.next_protos
.push_back("http/1.1");
2855 ASSERT_NO_FATAL_FAILURE(
2856 TestFalseStart(server_options
, client_config
, false));
2859 // Test that sessions are resumable after receiving the server Finished message.
2860 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
2862 SpawnedTestServer::SSLOptions server_options
;
2863 server_options
.key_exchanges
=
2864 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2865 server_options
.enable_npn
= true;
2866 SSLConfig client_config
;
2867 client_config
.next_protos
.push_back("http/1.1");
2869 // Let a full handshake complete with False Start.
2870 ASSERT_NO_FATAL_FAILURE(
2871 TestFalseStart(server_options
, client_config
, true));
2873 // Make a second connection.
2874 TestCompletionCallback callback
;
2875 scoped_ptr
<StreamSocket
> transport2(
2876 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2877 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
2878 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
2879 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
2880 ASSERT_TRUE(sock2
.get());
2881 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
2883 // It should resume the session.
2885 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
2886 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2889 // Test that sessions are not resumable before receiving the server Finished
2891 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinish
) {
2893 SpawnedTestServer::SSLOptions server_options
;
2894 server_options
.key_exchanges
=
2895 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2896 server_options
.enable_npn
= true;
2897 ASSERT_TRUE(StartTestServer(server_options
));
2899 SSLConfig client_config
;
2900 client_config
.next_protos
.push_back("http/1.1");
2902 // Start a handshake up to the server Finished message.
2903 TestCompletionCallback callback
;
2904 FakeBlockingStreamSocket
* raw_transport1
;
2905 scoped_ptr
<SSLClientSocket
> sock1
;
2906 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
2907 client_config
, &callback
, &raw_transport1
, &sock1
));
2908 // Although raw_transport1 has the server Finished blocked, the handshake
2910 EXPECT_EQ(OK
, callback
.WaitForResult());
2912 // Drop the old socket. This is needed because the Python test server can't
2913 // service two sockets in parallel.
2916 // Start a second connection.
2917 scoped_ptr
<StreamSocket
> transport2(
2918 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2919 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
2920 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
2921 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
2922 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
2924 // No session resumption because the first connection never received a server
2925 // Finished message.
2927 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
2928 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2931 // Connect to a server using channel id. It should allow the connection.
2932 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
2933 SpawnedTestServer::SSLOptions ssl_options
;
2935 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2938 SSLConfig ssl_config
= kDefaultSSLConfig
;
2939 ssl_config
.channel_id_enabled
= true;
2942 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2945 EXPECT_TRUE(sock_
->IsConnected());
2946 EXPECT_TRUE(sock_
->WasChannelIDSent());
2948 sock_
->Disconnect();
2949 EXPECT_FALSE(sock_
->IsConnected());
2952 // Connect to a server using Channel ID but failing to look up the Channel
2953 // ID. It should fail.
2954 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
2955 SpawnedTestServer::SSLOptions ssl_options
;
2957 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2959 EnableFailingChannelID();
2960 SSLConfig ssl_config
= kDefaultSSLConfig
;
2961 ssl_config
.channel_id_enabled
= true;
2964 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2966 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
2967 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
2968 // error codes for now.
2969 // http://crbug.com/373670
2971 EXPECT_FALSE(sock_
->IsConnected());
2974 // Connect to a server using Channel ID but asynchronously failing to look up
2975 // the Channel ID. It should fail.
2976 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
2977 SpawnedTestServer::SSLOptions ssl_options
;
2979 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
2981 EnableAsyncFailingChannelID();
2982 SSLConfig ssl_config
= kDefaultSSLConfig
;
2983 ssl_config
.channel_id_enabled
= true;
2986 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
2988 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
2989 EXPECT_FALSE(sock_
->IsConnected());