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/ssl/ssl_connection_status_flags.h"
33 #include "net/ssl/ssl_info.h"
34 #include "net/test/cert_test_util.h"
35 #include "net/test/spawned_test_server/spawned_test_server.h"
36 #include "testing/gmock/include/gmock/gmock.h"
37 #include "testing/gtest/include/gtest/gtest.h"
38 #include "testing/platform_test.h"
40 #if !defined(USE_OPENSSL)
42 #include "crypto/nss_util.h"
44 #if !defined(CKM_AES_GCM)
45 #define CKM_AES_GCM 0x00001087
48 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
49 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
53 //-----------------------------------------------------------------------------
56 using testing::Return
;
63 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
64 // forwarding the Socket and StreamSocket interfaces to the underlying
66 // This is to provide a common base class for subclasses to override specific
67 // StreamSocket methods for testing, while still communicating with a 'real'
69 class WrappedStreamSocket
: public StreamSocket
{
71 explicit WrappedStreamSocket(scoped_ptr
<StreamSocket
> transport
)
72 : transport_(transport
.Pass()) {}
73 ~WrappedStreamSocket() override
{}
75 // StreamSocket implementation:
76 int Connect(const CompletionCallback
& callback
) override
{
77 return transport_
->Connect(callback
);
79 void Disconnect() override
{ transport_
->Disconnect(); }
80 bool IsConnected() const override
{ return transport_
->IsConnected(); }
81 bool IsConnectedAndIdle() const override
{
82 return transport_
->IsConnectedAndIdle();
84 int GetPeerAddress(IPEndPoint
* address
) const override
{
85 return transport_
->GetPeerAddress(address
);
87 int GetLocalAddress(IPEndPoint
* address
) const override
{
88 return transport_
->GetLocalAddress(address
);
90 const BoundNetLog
& NetLog() const override
{ return transport_
->NetLog(); }
91 void SetSubresourceSpeculation() override
{
92 transport_
->SetSubresourceSpeculation();
94 void SetOmniboxSpeculation() override
{ transport_
->SetOmniboxSpeculation(); }
95 bool WasEverUsed() const override
{ return transport_
->WasEverUsed(); }
96 bool UsingTCPFastOpen() const override
{
97 return transport_
->UsingTCPFastOpen();
99 bool WasNpnNegotiated() const override
{
100 return transport_
->WasNpnNegotiated();
102 NextProto
GetNegotiatedProtocol() const override
{
103 return transport_
->GetNegotiatedProtocol();
105 bool GetSSLInfo(SSLInfo
* ssl_info
) override
{
106 return transport_
->GetSSLInfo(ssl_info
);
109 // Socket implementation:
110 int Read(IOBuffer
* buf
,
112 const CompletionCallback
& callback
) override
{
113 return transport_
->Read(buf
, buf_len
, callback
);
115 int Write(IOBuffer
* buf
,
117 const CompletionCallback
& callback
) override
{
118 return transport_
->Write(buf
, buf_len
, callback
);
120 int SetReceiveBufferSize(int32 size
) override
{
121 return transport_
->SetReceiveBufferSize(size
);
123 int SetSendBufferSize(int32 size
) override
{
124 return transport_
->SetSendBufferSize(size
);
128 scoped_ptr
<StreamSocket
> transport_
;
131 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
132 // will ensure a certain amount of data is internally buffered before
133 // satisfying a Read() request. It exists to mimic OS-level internal
134 // buffering, but in a way to guarantee that X number of bytes will be
135 // returned to callers of Read(), regardless of how quickly the OS receives
136 // them from the TestServer.
137 class ReadBufferingStreamSocket
: public WrappedStreamSocket
{
139 explicit ReadBufferingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
140 ~ReadBufferingStreamSocket() override
{}
142 // Socket implementation:
143 int Read(IOBuffer
* buf
,
145 const CompletionCallback
& callback
) override
;
147 // Sets the internal buffer to |size|. This must not be greater than
148 // the largest value supplied to Read() - that is, it does not handle
149 // having "leftovers" at the end of Read().
150 // Each call to Read() will be prevented from completion until at least
151 // |size| data has been read.
152 // Set to 0 to turn off buffering, causing Read() to transparently
153 // read via the underlying transport.
154 void SetBufferSize(int size
);
163 int DoLoop(int result
);
165 int DoReadComplete(int result
);
166 void OnReadCompleted(int result
);
169 scoped_refptr
<GrowableIOBuffer
> read_buffer_
;
172 scoped_refptr
<IOBuffer
> user_read_buf_
;
173 CompletionCallback user_read_callback_
;
176 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
177 scoped_ptr
<StreamSocket
> transport
)
178 : WrappedStreamSocket(transport
.Pass()),
179 read_buffer_(new GrowableIOBuffer()),
182 void ReadBufferingStreamSocket::SetBufferSize(int size
) {
183 DCHECK(!user_read_buf_
.get());
185 read_buffer_
->SetCapacity(size
);
188 int ReadBufferingStreamSocket::Read(IOBuffer
* buf
,
190 const CompletionCallback
& callback
) {
191 if (buffer_size_
== 0)
192 return transport_
->Read(buf
, buf_len
, callback
);
194 if (buf_len
< buffer_size_
)
195 return ERR_UNEXPECTED
;
198 user_read_buf_
= buf
;
199 int result
= DoLoop(OK
);
200 if (result
== ERR_IO_PENDING
)
201 user_read_callback_
= callback
;
203 user_read_buf_
= NULL
;
207 int ReadBufferingStreamSocket::DoLoop(int result
) {
210 State current_state
= state_
;
212 switch (current_state
) {
216 case STATE_READ_COMPLETE
:
217 rv
= DoReadComplete(rv
);
221 NOTREACHED() << "Unexpected state: " << current_state
;
225 } while (rv
!= ERR_IO_PENDING
&& state_
!= STATE_NONE
);
229 int ReadBufferingStreamSocket::DoRead() {
230 state_
= STATE_READ_COMPLETE
;
232 transport_
->Read(read_buffer_
.get(),
233 read_buffer_
->RemainingCapacity(),
234 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted
,
235 base::Unretained(this)));
239 int ReadBufferingStreamSocket::DoReadComplete(int result
) {
244 read_buffer_
->set_offset(read_buffer_
->offset() + result
);
245 if (read_buffer_
->RemainingCapacity() > 0) {
250 memcpy(user_read_buf_
->data(),
251 read_buffer_
->StartOfBuffer(),
252 read_buffer_
->capacity());
253 read_buffer_
->set_offset(0);
254 return read_buffer_
->capacity();
257 void ReadBufferingStreamSocket::OnReadCompleted(int result
) {
258 result
= DoLoop(result
);
259 if (result
== ERR_IO_PENDING
)
262 user_read_buf_
= NULL
;
263 base::ResetAndReturn(&user_read_callback_
).Run(result
);
266 // Simulates synchronously receiving an error during Read() or Write()
267 class SynchronousErrorStreamSocket
: public WrappedStreamSocket
{
269 explicit SynchronousErrorStreamSocket(scoped_ptr
<StreamSocket
> transport
);
270 ~SynchronousErrorStreamSocket() override
{}
272 // Socket implementation:
273 int Read(IOBuffer
* buf
,
275 const CompletionCallback
& callback
) override
;
276 int Write(IOBuffer
* buf
,
278 const CompletionCallback
& callback
) override
;
280 // Sets the next Read() call and all future calls to return |error|.
281 // If there is already a pending asynchronous read, the configured error
282 // will not be returned until that asynchronous read has completed and Read()
284 void SetNextReadError(int error
) {
286 have_read_error_
= true;
287 pending_read_error_
= error
;
290 // Sets the next Write() call and all future calls to return |error|.
291 // If there is already a pending asynchronous write, the configured error
292 // will not be returned until that asynchronous write has completed and
293 // Write() is called again.
294 void SetNextWriteError(int error
) {
296 have_write_error_
= true;
297 pending_write_error_
= error
;
301 bool have_read_error_
;
302 int pending_read_error_
;
304 bool have_write_error_
;
305 int pending_write_error_
;
307 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket
);
310 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
311 scoped_ptr
<StreamSocket
> transport
)
312 : WrappedStreamSocket(transport
.Pass()),
313 have_read_error_(false),
314 pending_read_error_(OK
),
315 have_write_error_(false),
316 pending_write_error_(OK
) {}
318 int SynchronousErrorStreamSocket::Read(IOBuffer
* buf
,
320 const CompletionCallback
& callback
) {
321 if (have_read_error_
)
322 return pending_read_error_
;
323 return transport_
->Read(buf
, buf_len
, callback
);
326 int SynchronousErrorStreamSocket::Write(IOBuffer
* buf
,
328 const CompletionCallback
& callback
) {
329 if (have_write_error_
)
330 return pending_write_error_
;
331 return transport_
->Write(buf
, buf_len
, callback
);
334 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
335 // underlying transport needing to complete things asynchronously in a
336 // deterministic manner (e.g.: independent of the TestServer and the OS's
338 class FakeBlockingStreamSocket
: public WrappedStreamSocket
{
340 explicit FakeBlockingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
341 ~FakeBlockingStreamSocket() override
{}
343 // Socket implementation:
344 int Read(IOBuffer
* buf
,
346 const CompletionCallback
& callback
) override
;
347 int Write(IOBuffer
* buf
,
349 const CompletionCallback
& callback
) override
;
351 // Blocks read results on the socket. Reads will not complete until
352 // UnblockReadResult() has been called and a result is ready from the
353 // underlying transport. Note: if BlockReadResult() is called while there is a
354 // hanging asynchronous Read(), that Read is blocked.
355 void BlockReadResult();
356 void UnblockReadResult();
358 // Waits for the blocked Read() call to be complete at the underlying
360 void WaitForReadResult();
362 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
363 // underlying transport until UnblockWrite() has been called. Note: if there
364 // is a pending asynchronous write, it is NOT blocked. For purposes of
365 // blocking writes, data is considered to have reached the underlying
366 // transport as soon as Write() is called.
370 // Waits for the blocked Write() call to be scheduled.
374 // Handles completion from the underlying transport read.
375 void OnReadCompleted(int result
);
377 // True if read callbacks are blocked.
378 bool should_block_read_
;
380 // The user callback for the pending read call.
381 CompletionCallback pending_read_callback_
;
383 // The result for the blocked read callback, or ERR_IO_PENDING if not
385 int pending_read_result_
;
387 // WaitForReadResult() wait loop.
388 scoped_ptr
<base::RunLoop
> read_loop_
;
390 // True if write calls are blocked.
391 bool should_block_write_
;
393 // The buffer for the pending write, or NULL if not scheduled.
394 scoped_refptr
<IOBuffer
> pending_write_buf_
;
396 // The callback for the pending write call.
397 CompletionCallback pending_write_callback_
;
399 // The length for the pending write, or -1 if not scheduled.
400 int pending_write_len_
;
402 // WaitForWrite() wait loop.
403 scoped_ptr
<base::RunLoop
> write_loop_
;
406 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
407 scoped_ptr
<StreamSocket
> transport
)
408 : WrappedStreamSocket(transport
.Pass()),
409 should_block_read_(false),
410 pending_read_result_(ERR_IO_PENDING
),
411 should_block_write_(false),
412 pending_write_len_(-1) {}
414 int FakeBlockingStreamSocket::Read(IOBuffer
* buf
,
416 const CompletionCallback
& callback
) {
417 DCHECK(pending_read_callback_
.is_null());
418 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
419 DCHECK(!callback
.is_null());
421 int rv
= transport_
->Read(buf
, len
, base::Bind(
422 &FakeBlockingStreamSocket::OnReadCompleted
, base::Unretained(this)));
423 if (rv
== ERR_IO_PENDING
) {
424 // Save the callback to be called later.
425 pending_read_callback_
= callback
;
426 } else if (should_block_read_
) {
427 // Save the callback and read result to be called later.
428 pending_read_callback_
= callback
;
435 int FakeBlockingStreamSocket::Write(IOBuffer
* buf
,
437 const CompletionCallback
& callback
) {
441 if (!should_block_write_
)
442 return transport_
->Write(buf
, len
, callback
);
444 // Schedule the write, but do nothing.
445 DCHECK(!pending_write_buf_
.get());
446 DCHECK_EQ(-1, pending_write_len_
);
447 DCHECK(pending_write_callback_
.is_null());
448 DCHECK(!callback
.is_null());
449 pending_write_buf_
= buf
;
450 pending_write_len_
= len
;
451 pending_write_callback_
= callback
;
453 // Stop the write loop, if any.
456 return ERR_IO_PENDING
;
459 void FakeBlockingStreamSocket::BlockReadResult() {
460 DCHECK(!should_block_read_
);
461 should_block_read_
= true;
464 void FakeBlockingStreamSocket::UnblockReadResult() {
465 DCHECK(should_block_read_
);
466 should_block_read_
= false;
468 // If the operation is still pending in the underlying transport, immediately
469 // return - OnReadCompleted() will handle invoking the callback once the
470 // transport has completed.
471 if (pending_read_result_
== ERR_IO_PENDING
)
473 int result
= pending_read_result_
;
474 pending_read_result_
= ERR_IO_PENDING
;
475 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
478 void FakeBlockingStreamSocket::WaitForReadResult() {
479 DCHECK(should_block_read_
);
482 if (pending_read_result_
!= ERR_IO_PENDING
)
484 read_loop_
.reset(new base::RunLoop
);
487 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
490 void FakeBlockingStreamSocket::BlockWrite() {
491 DCHECK(!should_block_write_
);
492 should_block_write_
= true;
495 void FakeBlockingStreamSocket::UnblockWrite() {
496 DCHECK(should_block_write_
);
497 should_block_write_
= false;
499 // Do nothing if UnblockWrite() was called after BlockWrite(),
500 // without a Write() in between.
501 if (!pending_write_buf_
.get())
504 int rv
= transport_
->Write(
505 pending_write_buf_
.get(), pending_write_len_
, pending_write_callback_
);
506 pending_write_buf_
= NULL
;
507 pending_write_len_
= -1;
508 if (rv
== ERR_IO_PENDING
) {
509 pending_write_callback_
.Reset();
511 base::ResetAndReturn(&pending_write_callback_
).Run(rv
);
515 void FakeBlockingStreamSocket::WaitForWrite() {
516 DCHECK(should_block_write_
);
517 DCHECK(!write_loop_
);
519 if (pending_write_buf_
.get())
521 write_loop_
.reset(new base::RunLoop
);
524 DCHECK(pending_write_buf_
.get());
527 void FakeBlockingStreamSocket::OnReadCompleted(int result
) {
528 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
529 DCHECK(!pending_read_callback_
.is_null());
531 if (should_block_read_
) {
532 // Store the result so that the callback can be invoked once Unblock() is
534 pending_read_result_
= result
;
536 // Stop the WaitForReadResult() call if any.
540 // Either the Read() was never blocked or UnblockReadResult() was called
541 // before the Read() completed. Either way, run the callback.
542 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
546 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
547 // reads and writes on the socket.
548 class CountingStreamSocket
: public WrappedStreamSocket
{
550 explicit CountingStreamSocket(scoped_ptr
<StreamSocket
> transport
)
551 : WrappedStreamSocket(transport
.Pass()),
554 ~CountingStreamSocket() override
{}
556 // Socket implementation:
557 int Read(IOBuffer
* buf
,
559 const CompletionCallback
& callback
) override
{
561 return transport_
->Read(buf
, buf_len
, callback
);
563 int Write(IOBuffer
* buf
,
565 const CompletionCallback
& callback
) override
{
567 return transport_
->Write(buf
, buf_len
, callback
);
570 int read_count() const { return read_count_
; }
571 int write_count() const { return write_count_
; }
578 // CompletionCallback that will delete the associated StreamSocket when
579 // the callback is invoked.
580 class DeleteSocketCallback
: public TestCompletionCallbackBase
{
582 explicit DeleteSocketCallback(StreamSocket
* socket
)
584 callback_(base::Bind(&DeleteSocketCallback::OnComplete
,
585 base::Unretained(this))) {}
586 ~DeleteSocketCallback() override
{}
588 const CompletionCallback
& callback() const { return callback_
; }
591 void OnComplete(int result
) {
596 ADD_FAILURE() << "Deleting socket twice";
601 StreamSocket
* socket_
;
602 CompletionCallback callback_
;
604 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback
);
607 // A ChannelIDStore that always returns an error when asked for a
609 class FailingChannelIDStore
: public ChannelIDStore
{
610 int GetChannelID(const std::string
& server_identifier
,
611 base::Time
* expiration_time
,
612 std::string
* private_key_result
,
613 std::string
* cert_result
,
614 const GetChannelIDCallback
& callback
) override
{
615 return ERR_UNEXPECTED
;
617 void SetChannelID(const std::string
& server_identifier
,
618 base::Time creation_time
,
619 base::Time expiration_time
,
620 const std::string
& private_key
,
621 const std::string
& cert
) override
{}
622 void DeleteChannelID(const std::string
& server_identifier
,
623 const base::Closure
& completion_callback
) override
{}
624 void DeleteAllCreatedBetween(
625 base::Time delete_begin
,
626 base::Time delete_end
,
627 const base::Closure
& completion_callback
) override
{}
628 void DeleteAll(const base::Closure
& completion_callback
) override
{}
629 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
630 int GetChannelIDCount() override
{ return 0; }
631 void SetForceKeepSessionState() override
{}
634 // A ChannelIDStore that asynchronously returns an error when asked for a
636 class AsyncFailingChannelIDStore
: public ChannelIDStore
{
637 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 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 void DeleteChannelID(const std::string
& server_identifier
,
653 const base::Closure
& completion_callback
) override
{}
654 void DeleteAllCreatedBetween(
655 base::Time delete_begin
,
656 base::Time delete_end
,
657 const base::Closure
& completion_callback
) override
{}
658 void DeleteAll(const base::Closure
& completion_callback
) override
{}
659 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
660 int GetChannelIDCount() override
{ return 0; }
661 void SetForceKeepSessionState() override
{}
664 // A mock CTVerifier that records every call to Verify but doesn't verify
666 class MockCTVerifier
: public CTVerifier
{
668 MOCK_METHOD5(Verify
, int(X509Certificate
*,
672 const BoundNetLog
&));
675 class SSLClientSocketTest
: public PlatformTest
{
677 SSLClientSocketTest()
678 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
679 cert_verifier_(new MockCertVerifier
),
680 transport_security_state_(new TransportSecurityState
) {
681 cert_verifier_
->set_default_result(OK
);
682 context_
.cert_verifier
= cert_verifier_
.get();
683 context_
.transport_security_state
= transport_security_state_
.get();
687 // The address of the spawned test server, after calling StartTestServer().
688 const AddressList
& addr() const { return addr_
; }
690 // The SpawnedTestServer object, after calling StartTestServer().
691 const SpawnedTestServer
* test_server() const { return test_server_
.get(); }
693 void SetCTVerifier(CTVerifier
* ct_verifier
) {
694 context_
.cert_transparency_verifier
= ct_verifier
;
697 // Starts the test server with SSL configuration |ssl_options|. Returns true
699 bool StartTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
700 test_server_
.reset(new SpawnedTestServer(
701 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath()));
702 if (!test_server_
->Start()) {
703 LOG(ERROR
) << "Could not start SpawnedTestServer";
707 if (!test_server_
->GetAddressList(&addr_
)) {
708 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
714 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
715 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
716 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
717 if (!StartTestServer(ssl_options
))
720 transport_
.reset(new TCPClientSocket(addr_
, &log_
, NetLog::Source()));
721 int rv
= callback_
.GetResult(transport_
->Connect(callback_
.callback()));
723 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
729 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
730 scoped_ptr
<StreamSocket
> transport_socket
,
731 const HostPortPair
& host_and_port
,
732 const SSLConfig
& ssl_config
) {
733 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
734 connection
->SetSocket(transport_socket
.Pass());
735 return socket_factory_
->CreateSSLClientSocket(
736 connection
.Pass(), host_and_port
, ssl_config
, context_
);
739 // Create an SSLClientSocket object and use it to connect to a test
740 // server, then wait for connection results. This must be called after
741 // a successful ConnectToTestServer() call.
742 // |ssl_config| the SSL configuration to use.
743 // |result| will retrieve the ::Connect() result value.
744 // Returns true on success, false otherwise. Success means that the socket
745 // could be created and its Connect() was called, not that the connection
746 // itself was a success.
747 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
, int* result
) {
748 sock_
= CreateSSLClientSocket(
749 transport_
.Pass(), test_server_
->host_port_pair(), ssl_config
);
751 if (sock_
->IsConnected()) {
752 LOG(ERROR
) << "SSL Socket prematurely connected";
756 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
760 ClientSocketFactory
* socket_factory_
;
761 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
762 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
763 SSLClientSocketContext context_
;
764 scoped_ptr
<SSLClientSocket
> sock_
;
765 CapturingNetLog log_
;
768 scoped_ptr
<StreamSocket
> transport_
;
769 scoped_ptr
<SpawnedTestServer
> test_server_
;
770 TestCompletionCallback callback_
;
774 // Verifies the correctness of GetSSLCertRequestInfo.
775 class SSLClientSocketCertRequestInfoTest
: public SSLClientSocketTest
{
777 // Creates a test server with the given SSLOptions, connects to it and returns
778 // the SSLCertRequestInfo reported by the socket.
779 scoped_refptr
<SSLCertRequestInfo
> GetCertRequest(
780 SpawnedTestServer::SSLOptions ssl_options
) {
781 SpawnedTestServer
test_server(
782 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
783 if (!test_server
.Start())
787 if (!test_server
.GetAddressList(&addr
))
790 TestCompletionCallback callback
;
792 scoped_ptr
<StreamSocket
> transport(
793 new TCPClientSocket(addr
, &log
, NetLog::Source()));
794 int rv
= transport
->Connect(callback
.callback());
795 if (rv
== ERR_IO_PENDING
)
796 rv
= callback
.WaitForResult();
799 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
800 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
801 EXPECT_FALSE(sock
->IsConnected());
803 rv
= sock
->Connect(callback
.callback());
804 if (rv
== ERR_IO_PENDING
)
805 rv
= callback
.WaitForResult();
806 scoped_refptr
<SSLCertRequestInfo
> request_info
= new SSLCertRequestInfo();
807 sock
->GetSSLCertRequestInfo(request_info
.get());
809 EXPECT_FALSE(sock
->IsConnected());
811 test_server
.host_port_pair().Equals(request_info
->host_and_port
));
817 class SSLClientSocketFalseStartTest
: public SSLClientSocketTest
{
819 // Creates an SSLClientSocket with |client_config| attached to a
820 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
821 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
822 // so |*out_raw_transport| is a raw pointer.
824 // The client socket will begin a connect using |callback| but stop before the
825 // server's finished message is received. The finished message will be blocked
826 // in |*out_raw_transport|. To complete the handshake and successfully read
827 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
828 // the client successfully false started, |callback.WaitForResult()| will
829 // return OK without unblocking transport reads. But Read() will still block.)
831 // Must be called after StartTestServer is called.
832 void CreateAndConnectUntilServerFinishedReceived(
833 const SSLConfig
& client_config
,
834 TestCompletionCallback
* callback
,
835 FakeBlockingStreamSocket
** out_raw_transport
,
836 scoped_ptr
<SSLClientSocket
>* out_sock
) {
837 CHECK(test_server());
839 scoped_ptr
<StreamSocket
> real_transport(
840 new TCPClientSocket(addr(), NULL
, NetLog::Source()));
841 scoped_ptr
<FakeBlockingStreamSocket
> transport(
842 new FakeBlockingStreamSocket(real_transport
.Pass()));
843 int rv
= callback
->GetResult(transport
->Connect(callback
->callback()));
846 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
847 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
848 transport
.Pass(), test_server()->host_port_pair(), client_config
);
850 // Connect. Stop before the client processes the first server leg
851 // (ServerHello, etc.)
852 raw_transport
->BlockReadResult();
853 rv
= sock
->Connect(callback
->callback());
854 EXPECT_EQ(ERR_IO_PENDING
, rv
);
855 raw_transport
->WaitForReadResult();
857 // Release the ServerHello and wait for the client to write
858 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
859 // server's leg to complete, since it may span multiple reads.)
860 EXPECT_FALSE(callback
->have_result());
861 raw_transport
->BlockWrite();
862 raw_transport
->UnblockReadResult();
863 raw_transport
->WaitForWrite();
865 // And, finally, release that and block the next server leg
866 // (ChangeCipherSpec, Finished).
867 raw_transport
->BlockReadResult();
868 raw_transport
->UnblockWrite();
870 *out_raw_transport
= raw_transport
;
871 *out_sock
= sock
.Pass();
874 void TestFalseStart(const SpawnedTestServer::SSLOptions
& server_options
,
875 const SSLConfig
& client_config
,
876 bool expect_false_start
) {
877 ASSERT_TRUE(StartTestServer(server_options
));
879 TestCompletionCallback callback
;
880 FakeBlockingStreamSocket
* raw_transport
= NULL
;
881 scoped_ptr
<SSLClientSocket
> sock
;
882 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
883 client_config
, &callback
, &raw_transport
, &sock
));
885 if (expect_false_start
) {
886 // When False Starting, the handshake should complete before receiving the
887 // Change Cipher Spec and Finished messages.
889 // Note: callback.have_result() may not be true without waiting. The NSS
890 // state machine sometimes lives on a separate thread, so this thread may
891 // not yet have processed the signal that the handshake has completed.
892 int rv
= callback
.WaitForResult();
894 EXPECT_TRUE(sock
->IsConnected());
896 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
897 static const int kRequestTextSize
=
898 static_cast<int>(arraysize(request_text
) - 1);
899 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
900 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
902 // Write the request.
903 rv
= callback
.GetResult(sock
->Write(request_buffer
.get(),
905 callback
.callback()));
906 EXPECT_EQ(kRequestTextSize
, rv
);
908 // The read will hang; it's waiting for the peer to complete the
909 // handshake, and the handshake is still blocked.
910 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
911 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
913 // After releasing reads, the connection proceeds.
914 raw_transport
->UnblockReadResult();
915 rv
= callback
.GetResult(rv
);
918 // False Start is not enabled, so the handshake will not complete because
919 // the server second leg is blocked.
920 base::RunLoop().RunUntilIdle();
921 EXPECT_FALSE(callback
.have_result());
926 class SSLClientSocketChannelIDTest
: public SSLClientSocketTest
{
928 void EnableChannelID() {
929 channel_id_service_
.reset(
930 new ChannelIDService(new DefaultChannelIDStore(NULL
),
931 base::MessageLoopProxy::current()));
932 context_
.channel_id_service
= channel_id_service_
.get();
935 void EnableFailingChannelID() {
936 channel_id_service_
.reset(new ChannelIDService(
937 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
938 context_
.channel_id_service
= channel_id_service_
.get();
941 void EnableAsyncFailingChannelID() {
942 channel_id_service_
.reset(new ChannelIDService(
943 new AsyncFailingChannelIDStore(),
944 base::MessageLoopProxy::current()));
945 context_
.channel_id_service
= channel_id_service_
.get();
949 scoped_ptr
<ChannelIDService
> channel_id_service_
;
952 //-----------------------------------------------------------------------------
954 // LogContainsSSLConnectEndEvent returns true if the given index in the given
955 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
956 // merge the first application data record with the Finished message when false
957 // starting. However, in order to avoid the server timing out the handshake,
958 // they'll give up waiting for application data and send the Finished after a
959 // timeout. This means that an SSL connect end event may appear as a socket
961 static bool LogContainsSSLConnectEndEvent(
962 const CapturingNetLog::CapturedEntryList
& log
,
964 return LogContainsEndEvent(log
, i
, NetLog::TYPE_SSL_CONNECT
) ||
966 log
, i
, NetLog::TYPE_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
969 bool SupportsAESGCM() {
970 #if defined(USE_OPENSSL)
973 crypto::EnsureNSSInit();
974 return PK11_TokenExists(CKM_AES_GCM
) &&
975 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
);
981 TEST_F(SSLClientSocketTest
, Connect
) {
982 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
983 SpawnedTestServer::kLocalhost
,
985 ASSERT_TRUE(test_server
.Start());
988 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
990 TestCompletionCallback callback
;
992 scoped_ptr
<StreamSocket
> transport(
993 new TCPClientSocket(addr
, &log
, NetLog::Source()));
994 int rv
= transport
->Connect(callback
.callback());
995 if (rv
== ERR_IO_PENDING
)
996 rv
= callback
.WaitForResult();
999 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1000 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1002 EXPECT_FALSE(sock
->IsConnected());
1004 rv
= sock
->Connect(callback
.callback());
1006 CapturingNetLog::CapturedEntryList entries
;
1007 log
.GetEntries(&entries
);
1008 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1009 if (rv
== ERR_IO_PENDING
)
1010 rv
= callback
.WaitForResult();
1012 EXPECT_TRUE(sock
->IsConnected());
1013 log
.GetEntries(&entries
);
1014 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1017 EXPECT_FALSE(sock
->IsConnected());
1020 TEST_F(SSLClientSocketTest
, ConnectExpired
) {
1021 SpawnedTestServer::SSLOptions
ssl_options(
1022 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
1023 SpawnedTestServer
test_server(
1024 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1025 ASSERT_TRUE(test_server
.Start());
1027 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
1030 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1032 TestCompletionCallback callback
;
1033 CapturingNetLog log
;
1034 scoped_ptr
<StreamSocket
> transport(
1035 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1036 int rv
= transport
->Connect(callback
.callback());
1037 if (rv
== ERR_IO_PENDING
)
1038 rv
= callback
.WaitForResult();
1041 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1042 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1044 EXPECT_FALSE(sock
->IsConnected());
1046 rv
= sock
->Connect(callback
.callback());
1048 CapturingNetLog::CapturedEntryList entries
;
1049 log
.GetEntries(&entries
);
1050 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1051 if (rv
== ERR_IO_PENDING
)
1052 rv
= callback
.WaitForResult();
1054 EXPECT_EQ(ERR_CERT_DATE_INVALID
, rv
);
1056 // Rather than testing whether or not the underlying socket is connected,
1057 // test that the handshake has finished. This is because it may be
1058 // desirable to disconnect the socket before showing a user prompt, since
1059 // the user may take indefinitely long to respond.
1060 log
.GetEntries(&entries
);
1061 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1064 TEST_F(SSLClientSocketTest
, ConnectMismatched
) {
1065 SpawnedTestServer::SSLOptions
ssl_options(
1066 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
1067 SpawnedTestServer
test_server(
1068 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1069 ASSERT_TRUE(test_server
.Start());
1071 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
1074 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1076 TestCompletionCallback callback
;
1077 CapturingNetLog log
;
1078 scoped_ptr
<StreamSocket
> transport(
1079 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1080 int rv
= transport
->Connect(callback
.callback());
1081 if (rv
== ERR_IO_PENDING
)
1082 rv
= callback
.WaitForResult();
1085 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1086 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1088 EXPECT_FALSE(sock
->IsConnected());
1090 rv
= sock
->Connect(callback
.callback());
1092 CapturingNetLog::CapturedEntryList entries
;
1093 log
.GetEntries(&entries
);
1094 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1095 if (rv
== ERR_IO_PENDING
)
1096 rv
= callback
.WaitForResult();
1098 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
, rv
);
1100 // Rather than testing whether or not the underlying socket is connected,
1101 // test that the handshake has finished. This is because it may be
1102 // desirable to disconnect the socket before showing a user prompt, since
1103 // the user may take indefinitely long to respond.
1104 log
.GetEntries(&entries
);
1105 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1108 // Attempt to connect to a page which requests a client certificate. It should
1109 // return an error code on connect.
1110 TEST_F(SSLClientSocketTest
, ConnectClientAuthCertRequested
) {
1111 SpawnedTestServer::SSLOptions ssl_options
;
1112 ssl_options
.request_client_certificate
= true;
1113 SpawnedTestServer
test_server(
1114 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1115 ASSERT_TRUE(test_server
.Start());
1118 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1120 TestCompletionCallback callback
;
1121 CapturingNetLog log
;
1122 scoped_ptr
<StreamSocket
> transport(
1123 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1124 int rv
= transport
->Connect(callback
.callback());
1125 if (rv
== ERR_IO_PENDING
)
1126 rv
= callback
.WaitForResult();
1129 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1130 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1132 EXPECT_FALSE(sock
->IsConnected());
1134 rv
= sock
->Connect(callback
.callback());
1136 CapturingNetLog::CapturedEntryList entries
;
1137 log
.GetEntries(&entries
);
1138 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1139 if (rv
== ERR_IO_PENDING
)
1140 rv
= callback
.WaitForResult();
1142 log
.GetEntries(&entries
);
1143 // Because we prematurely kill the handshake at CertificateRequest,
1144 // the server may still send data (notably the ServerHelloDone)
1145 // after the error is returned. As a result, the SSL_CONNECT may not
1146 // be the last entry. See http://crbug.com/54445. We use
1147 // ExpectLogContainsSomewhere instead of
1148 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1149 // extra read instead of two. This occurs before the handshake ends,
1150 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1153 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1154 // fixed and we can respond to the first CertificateRequest
1155 // without closing the socket, add a unit test for sending the
1156 // certificate. This test may still be useful as we'll want to close
1157 // the socket on a timeout if the user takes a long time to pick a
1158 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1159 ExpectLogContainsSomewhere(
1160 entries
, 0, NetLog::TYPE_SSL_CONNECT
, NetLog::PHASE_END
);
1161 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
1162 EXPECT_FALSE(sock
->IsConnected());
1165 // Connect to a server requesting optional client authentication. Send it a
1166 // null certificate. It should allow the connection.
1168 // TODO(davidben): Also test providing an actual certificate.
1169 TEST_F(SSLClientSocketTest
, ConnectClientAuthSendNullCert
) {
1170 SpawnedTestServer::SSLOptions ssl_options
;
1171 ssl_options
.request_client_certificate
= true;
1172 SpawnedTestServer
test_server(
1173 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1174 ASSERT_TRUE(test_server
.Start());
1177 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1179 TestCompletionCallback callback
;
1180 CapturingNetLog log
;
1181 scoped_ptr
<StreamSocket
> transport(
1182 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1183 int rv
= transport
->Connect(callback
.callback());
1184 if (rv
== ERR_IO_PENDING
)
1185 rv
= callback
.WaitForResult();
1188 SSLConfig ssl_config
;
1189 ssl_config
.send_client_cert
= true;
1190 ssl_config
.client_cert
= NULL
;
1192 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1193 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1195 EXPECT_FALSE(sock
->IsConnected());
1197 // Our test server accepts certificate-less connections.
1198 // TODO(davidben): Add a test which requires them and verify the error.
1199 rv
= sock
->Connect(callback
.callback());
1201 CapturingNetLog::CapturedEntryList entries
;
1202 log
.GetEntries(&entries
);
1203 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1204 if (rv
== ERR_IO_PENDING
)
1205 rv
= callback
.WaitForResult();
1208 EXPECT_TRUE(sock
->IsConnected());
1209 log
.GetEntries(&entries
);
1210 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1212 // We responded to the server's certificate request with a Certificate
1213 // message with no client certificate in it. ssl_info.client_cert_sent
1214 // should be false in this case.
1216 sock
->GetSSLInfo(&ssl_info
);
1217 EXPECT_FALSE(ssl_info
.client_cert_sent
);
1220 EXPECT_FALSE(sock
->IsConnected());
1223 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1224 // - Server closes an SSL connection (with a close_notify alert message).
1225 // - Server closes the underlying TCP connection directly.
1226 // - Server sends data unexpectedly.
1228 // Tests that the socket can be read from successfully. Also test that a peer's
1229 // close_notify alert is successfully processed without error.
1230 TEST_F(SSLClientSocketTest
, Read
) {
1231 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1232 SpawnedTestServer::kLocalhost
,
1234 ASSERT_TRUE(test_server
.Start());
1237 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1239 TestCompletionCallback callback
;
1240 scoped_ptr
<StreamSocket
> transport(
1241 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1242 int rv
= transport
->Connect(callback
.callback());
1243 if (rv
== ERR_IO_PENDING
)
1244 rv
= callback
.WaitForResult();
1247 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1248 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1250 rv
= sock
->Connect(callback
.callback());
1251 if (rv
== ERR_IO_PENDING
)
1252 rv
= callback
.WaitForResult();
1254 EXPECT_TRUE(sock
->IsConnected());
1256 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1257 scoped_refptr
<IOBuffer
> request_buffer(
1258 new IOBuffer(arraysize(request_text
) - 1));
1259 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1262 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1263 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1265 if (rv
== ERR_IO_PENDING
)
1266 rv
= callback
.WaitForResult();
1267 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1269 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1271 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1272 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1274 if (rv
== ERR_IO_PENDING
)
1275 rv
= callback
.WaitForResult();
1282 // The peer should have cleanly closed the connection with a close_notify.
1286 // Tests that SSLClientSocket properly handles when the underlying transport
1287 // synchronously fails a transport read in during the handshake. The error code
1288 // should be preserved so SSLv3 fallback logic can condition on it.
1289 TEST_F(SSLClientSocketTest
, Connect_WithSynchronousError
) {
1290 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1291 SpawnedTestServer::kLocalhost
,
1293 ASSERT_TRUE(test_server
.Start());
1296 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1298 TestCompletionCallback callback
;
1299 scoped_ptr
<StreamSocket
> real_transport(
1300 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1301 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1302 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1303 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1306 // Disable TLS False Start to avoid handshake non-determinism.
1307 SSLConfig ssl_config
;
1308 ssl_config
.false_start_enabled
= false;
1310 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1311 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1312 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1314 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
1316 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1317 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1318 EXPECT_FALSE(sock
->IsConnected());
1321 // Tests that the SSLClientSocket properly handles when the underlying transport
1322 // synchronously returns an error code - such as if an intermediary terminates
1323 // the socket connection uncleanly.
1324 // This is a regression test for http://crbug.com/238536
1325 TEST_F(SSLClientSocketTest
, Read_WithSynchronousError
) {
1326 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1327 SpawnedTestServer::kLocalhost
,
1329 ASSERT_TRUE(test_server
.Start());
1332 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1334 TestCompletionCallback callback
;
1335 scoped_ptr
<StreamSocket
> real_transport(
1336 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1337 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1338 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1339 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1342 // Disable TLS False Start to avoid handshake non-determinism.
1343 SSLConfig ssl_config
;
1344 ssl_config
.false_start_enabled
= false;
1346 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1347 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1348 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1350 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1352 EXPECT_TRUE(sock
->IsConnected());
1354 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1355 static const int kRequestTextSize
=
1356 static_cast<int>(arraysize(request_text
) - 1);
1357 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1358 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1360 rv
= callback
.GetResult(
1361 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1362 EXPECT_EQ(kRequestTextSize
, rv
);
1364 // Simulate an unclean/forcible shutdown.
1365 raw_transport
->SetNextReadError(ERR_CONNECTION_RESET
);
1367 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1369 // Note: This test will hang if this bug has regressed. Simply checking that
1370 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1371 // result when using a dedicated task runner for NSS.
1372 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1373 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1376 // Tests that the SSLClientSocket properly handles when the underlying transport
1377 // asynchronously returns an error code while writing data - such as if an
1378 // intermediary terminates the socket connection uncleanly.
1379 // This is a regression test for http://crbug.com/249848
1380 TEST_F(SSLClientSocketTest
, Write_WithSynchronousError
) {
1381 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1382 SpawnedTestServer::kLocalhost
,
1384 ASSERT_TRUE(test_server
.Start());
1387 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1389 TestCompletionCallback callback
;
1390 scoped_ptr
<StreamSocket
> real_transport(
1391 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1392 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1393 // is retained in order to configure additional errors.
1394 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1395 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1396 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1397 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1398 new FakeBlockingStreamSocket(error_socket
.Pass()));
1399 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1400 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1403 // Disable TLS False Start to avoid handshake non-determinism.
1404 SSLConfig ssl_config
;
1405 ssl_config
.false_start_enabled
= false;
1407 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1408 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1410 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1412 EXPECT_TRUE(sock
->IsConnected());
1414 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1415 static const int kRequestTextSize
=
1416 static_cast<int>(arraysize(request_text
) - 1);
1417 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1418 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1420 // Simulate an unclean/forcible shutdown on the underlying socket.
1421 // However, simulate this error asynchronously.
1422 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1423 raw_transport
->BlockWrite();
1425 // This write should complete synchronously, because the TLS ciphertext
1426 // can be created and placed into the outgoing buffers independent of the
1427 // underlying transport.
1428 rv
= callback
.GetResult(
1429 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1430 EXPECT_EQ(kRequestTextSize
, rv
);
1432 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1434 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1435 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1437 // Now unblock the outgoing request, having it fail with the connection
1439 raw_transport
->UnblockWrite();
1441 // Note: This will cause an inifite loop if this bug has regressed. Simply
1442 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1443 // is a legitimate result when using a dedicated task runner for NSS.
1444 rv
= callback
.GetResult(rv
);
1445 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1448 // If there is a Write failure at the transport with no follow-up Read, although
1449 // the write error will not be returned to the client until a future Read or
1450 // Write operation, SSLClientSocket should not spin attempting to re-write on
1451 // the socket. This is a regression test for part of https://crbug.com/381160.
1452 TEST_F(SSLClientSocketTest
, Write_WithSynchronousErrorNoRead
) {
1453 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1454 SpawnedTestServer::kLocalhost
,
1456 ASSERT_TRUE(test_server
.Start());
1459 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1461 TestCompletionCallback callback
;
1462 scoped_ptr
<StreamSocket
> real_transport(
1463 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1464 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1465 // is retained in order to query them.
1466 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1467 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1468 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1469 scoped_ptr
<CountingStreamSocket
> counting_socket(
1470 new CountingStreamSocket(error_socket
.Pass()));
1471 CountingStreamSocket
* raw_counting_socket
= counting_socket
.get();
1472 int rv
= callback
.GetResult(counting_socket
->Connect(callback
.callback()));
1475 // Disable TLS False Start to avoid handshake non-determinism.
1476 SSLConfig ssl_config
;
1477 ssl_config
.false_start_enabled
= false;
1479 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1480 counting_socket
.Pass(), test_server
.host_port_pair(), ssl_config
));
1482 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1484 ASSERT_TRUE(sock
->IsConnected());
1486 // Simulate an unclean/forcible shutdown on the underlying socket.
1487 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1489 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1490 static const int kRequestTextSize
=
1491 static_cast<int>(arraysize(request_text
) - 1);
1492 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1493 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1495 // This write should complete synchronously, because the TLS ciphertext
1496 // can be created and placed into the outgoing buffers independent of the
1497 // underlying transport.
1498 rv
= callback
.GetResult(
1499 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1500 ASSERT_EQ(kRequestTextSize
, rv
);
1502 // Let the event loop spin for a little bit of time. Even on platforms where
1503 // pumping the state machine involve thread hops, there should be no further
1504 // writes on the transport socket.
1506 // TODO(davidben): Avoid the arbitrary timeout?
1507 int old_write_count
= raw_counting_socket
->write_count();
1509 base::MessageLoop::current()->PostDelayedTask(
1510 FROM_HERE
, loop
.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1512 EXPECT_EQ(old_write_count
, raw_counting_socket
->write_count());
1515 // Test the full duplex mode, with Read and Write pending at the same time.
1516 // This test also serves as a regression test for http://crbug.com/29815.
1517 TEST_F(SSLClientSocketTest
, Read_FullDuplex
) {
1518 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1519 SpawnedTestServer::kLocalhost
,
1521 ASSERT_TRUE(test_server
.Start());
1524 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1526 TestCompletionCallback callback
; // Used for everything except Write.
1528 scoped_ptr
<StreamSocket
> transport(
1529 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1530 int rv
= transport
->Connect(callback
.callback());
1531 if (rv
== ERR_IO_PENDING
)
1532 rv
= callback
.WaitForResult();
1535 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1536 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1538 rv
= sock
->Connect(callback
.callback());
1539 if (rv
== ERR_IO_PENDING
)
1540 rv
= callback
.WaitForResult();
1542 EXPECT_TRUE(sock
->IsConnected());
1544 // Issue a "hanging" Read first.
1545 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1546 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1547 // We haven't written the request, so there should be no response yet.
1548 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1550 // Write the request.
1551 // The request is padded with a User-Agent header to a size that causes the
1552 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1553 // This tests the fix for http://crbug.com/29815.
1554 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1555 for (int i
= 0; i
< 3770; ++i
)
1556 request_text
.push_back('*');
1557 request_text
.append("\r\n\r\n");
1558 scoped_refptr
<IOBuffer
> request_buffer(new StringIOBuffer(request_text
));
1560 TestCompletionCallback callback2
; // Used for Write only.
1562 request_buffer
.get(), request_text
.size(), callback2
.callback());
1563 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1565 if (rv
== ERR_IO_PENDING
)
1566 rv
= callback2
.WaitForResult();
1567 EXPECT_EQ(static_cast<int>(request_text
.size()), rv
);
1569 // Now get the Read result.
1570 rv
= callback
.WaitForResult();
1574 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1575 // mode when the underlying transport is blocked on sending data. When the
1576 // underlying transport completes due to an error, it should invoke both the
1577 // Read() and Write() callbacks. If the socket is deleted by the Read()
1578 // callback, the Write() callback should not be invoked.
1579 // Regression test for http://crbug.com/232633
1580 TEST_F(SSLClientSocketTest
, Read_DeleteWhilePendingFullDuplex
) {
1581 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1582 SpawnedTestServer::kLocalhost
,
1584 ASSERT_TRUE(test_server
.Start());
1587 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1589 TestCompletionCallback callback
;
1590 scoped_ptr
<StreamSocket
> real_transport(
1591 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1592 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1593 // is retained in order to configure additional errors.
1594 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1595 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1596 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1597 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1598 new FakeBlockingStreamSocket(error_socket
.Pass()));
1599 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1601 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1604 // Disable TLS False Start to avoid handshake non-determinism.
1605 SSLConfig ssl_config
;
1606 ssl_config
.false_start_enabled
= false;
1608 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
1609 transport
.Pass(), test_server
.host_port_pair(), ssl_config
);
1611 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1613 EXPECT_TRUE(sock
->IsConnected());
1615 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1616 request_text
.append(20 * 1024, '*');
1617 request_text
.append("\r\n\r\n");
1618 scoped_refptr
<DrainableIOBuffer
> request_buffer(new DrainableIOBuffer(
1619 new StringIOBuffer(request_text
), request_text
.size()));
1621 // Simulate errors being returned from the underlying Read() and Write() ...
1622 raw_error_socket
->SetNextReadError(ERR_CONNECTION_RESET
);
1623 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1624 // ... but have those errors returned asynchronously. Because the Write() will
1625 // return first, this will trigger the error.
1626 raw_transport
->BlockReadResult();
1627 raw_transport
->BlockWrite();
1629 // Enqueue a Read() before calling Write(), which should "hang" due to
1630 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1631 SSLClientSocket
* raw_sock
= sock
.get();
1632 DeleteSocketCallback
read_callback(sock
.release());
1633 scoped_refptr
<IOBuffer
> read_buf(new IOBuffer(4096));
1634 rv
= raw_sock
->Read(read_buf
.get(), 4096, read_callback
.callback());
1636 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1637 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1638 ASSERT_FALSE(read_callback
.have_result());
1640 #if !defined(USE_OPENSSL)
1641 // NSS follows a pattern where a call to PR_Write will only consume as
1642 // much data as it can encode into application data records before the
1643 // internal memio buffer is full, which should only fill if writing a large
1644 // amount of data and the underlying transport is blocked. Once this happens,
1645 // NSS will return (total size of all application data records it wrote) - 1,
1646 // with the caller expected to resume with the remaining unsent data.
1648 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1649 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1650 // get the socket in the state needed for the test below.
1652 // This is not needed for OpenSSL, because for OpenSSL,
1653 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1654 // SSLClientSocketOpenSSL::Write() will not return until all of
1655 // |request_buffer| has been written to the underlying BIO (although not
1656 // necessarily the underlying transport).
1657 rv
= callback
.GetResult(raw_sock
->Write(request_buffer
.get(),
1658 request_buffer
->BytesRemaining(),
1659 callback
.callback()));
1661 request_buffer
->DidConsume(rv
);
1663 // Guard to ensure that |request_buffer| was larger than all of the internal
1664 // buffers (transport, memio, NSS) along the way - otherwise the next call
1665 // to Write() will crash with an invalid buffer.
1666 ASSERT_LT(0, request_buffer
->BytesRemaining());
1669 // Attempt to write the remaining data. NSS will not be able to consume the
1670 // application data because the internal buffers are full, while OpenSSL will
1671 // return that its blocked because the underlying transport is blocked.
1672 rv
= raw_sock
->Write(request_buffer
.get(),
1673 request_buffer
->BytesRemaining(),
1674 callback
.callback());
1675 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1676 ASSERT_FALSE(callback
.have_result());
1678 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1679 // call the Read() callback, deleting the socket and thus aborting calling
1680 // the Write() callback.
1681 raw_transport
->UnblockWrite();
1683 rv
= read_callback
.WaitForResult();
1684 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1686 // The Write callback should not have been called.
1687 EXPECT_FALSE(callback
.have_result());
1690 // Tests that the SSLClientSocket does not crash if data is received on the
1691 // transport socket after a failing write. This can occur if we have a Write
1692 // error in a SPDY socket.
1693 // Regression test for http://crbug.com/335557
1694 TEST_F(SSLClientSocketTest
, Read_WithWriteError
) {
1695 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1696 SpawnedTestServer::kLocalhost
,
1698 ASSERT_TRUE(test_server
.Start());
1701 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1703 TestCompletionCallback callback
;
1704 scoped_ptr
<StreamSocket
> real_transport(
1705 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1706 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1707 // is retained in order to configure additional errors.
1708 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1709 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1710 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1711 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1712 new FakeBlockingStreamSocket(error_socket
.Pass()));
1713 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1715 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1718 // Disable TLS False Start to avoid handshake non-determinism.
1719 SSLConfig ssl_config
;
1720 ssl_config
.false_start_enabled
= false;
1722 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1723 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1725 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1727 EXPECT_TRUE(sock
->IsConnected());
1729 // Send a request so there is something to read from the socket.
1730 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1731 static const int kRequestTextSize
=
1732 static_cast<int>(arraysize(request_text
) - 1);
1733 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1734 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1736 rv
= callback
.GetResult(
1737 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1738 EXPECT_EQ(kRequestTextSize
, rv
);
1740 // Start a hanging read.
1741 TestCompletionCallback read_callback
;
1742 raw_transport
->BlockReadResult();
1743 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1744 rv
= sock
->Read(buf
.get(), 4096, read_callback
.callback());
1745 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1747 // Perform another write, but have it fail. Write a request larger than the
1748 // internal socket buffers so that the request hits the underlying transport
1749 // socket and detects the error.
1750 std::string long_request_text
=
1751 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1752 long_request_text
.append(20 * 1024, '*');
1753 long_request_text
.append("\r\n\r\n");
1754 scoped_refptr
<DrainableIOBuffer
> long_request_buffer(new DrainableIOBuffer(
1755 new StringIOBuffer(long_request_text
), long_request_text
.size()));
1757 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1759 // Write as much data as possible until hitting an error. This is necessary
1760 // for NSS. PR_Write will only consume as much data as it can encode into
1761 // application data records before the internal memio buffer is full, which
1762 // should only fill if writing a large amount of data and the underlying
1763 // transport is blocked. Once this happens, NSS will return (total size of all
1764 // application data records it wrote) - 1, with the caller expected to resume
1765 // with the remaining unsent data.
1767 rv
= callback
.GetResult(sock
->Write(long_request_buffer
.get(),
1768 long_request_buffer
->BytesRemaining(),
1769 callback
.callback()));
1771 long_request_buffer
->DidConsume(rv
);
1772 // Abort if the entire buffer is ever consumed.
1773 ASSERT_LT(0, long_request_buffer
->BytesRemaining());
1777 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1779 // Release the read.
1780 raw_transport
->UnblockReadResult();
1781 rv
= read_callback
.WaitForResult();
1783 #if defined(USE_OPENSSL)
1784 // Should still read bytes despite the write error.
1787 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1788 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1789 // the write error stops future reads.
1790 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1794 // Tests that SSLClientSocket fails the handshake if the underlying
1795 // transport is cleanly closed.
1796 TEST_F(SSLClientSocketTest
, Connect_WithZeroReturn
) {
1797 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1798 SpawnedTestServer::kLocalhost
,
1800 ASSERT_TRUE(test_server
.Start());
1803 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1805 TestCompletionCallback callback
;
1806 scoped_ptr
<StreamSocket
> real_transport(
1807 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1808 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1809 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1810 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1813 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1814 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1815 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1817 raw_transport
->SetNextReadError(0);
1819 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1820 EXPECT_EQ(ERR_CONNECTION_CLOSED
, rv
);
1821 EXPECT_FALSE(sock
->IsConnected());
1824 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1825 // is cleanly closed, but the peer does not send close_notify.
1826 // This is a regression test for https://crbug.com/422246
1827 TEST_F(SSLClientSocketTest
, Read_WithZeroReturn
) {
1828 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1829 SpawnedTestServer::kLocalhost
,
1831 ASSERT_TRUE(test_server
.Start());
1834 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1836 TestCompletionCallback callback
;
1837 scoped_ptr
<StreamSocket
> real_transport(
1838 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1839 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1840 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1841 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1844 // Disable TLS False Start to ensure the handshake has completed.
1845 SSLConfig ssl_config
;
1846 ssl_config
.false_start_enabled
= false;
1848 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1849 scoped_ptr
<SSLClientSocket
> sock(
1850 CreateSSLClientSocket(transport
.Pass(),
1851 test_server
.host_port_pair(),
1854 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1856 EXPECT_TRUE(sock
->IsConnected());
1858 raw_transport
->SetNextReadError(0);
1859 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1860 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1864 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1865 // underlying socket is cleanly closed asynchronously.
1866 // This is a regression test for https://crbug.com/422246
1867 TEST_F(SSLClientSocketTest
, Read_WithAsyncZeroReturn
) {
1868 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1869 SpawnedTestServer::kLocalhost
,
1871 ASSERT_TRUE(test_server
.Start());
1874 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1876 TestCompletionCallback callback
;
1877 scoped_ptr
<StreamSocket
> real_transport(
1878 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1879 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1880 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1881 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1882 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1883 new FakeBlockingStreamSocket(error_socket
.Pass()));
1884 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1885 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1888 // Disable TLS False Start to ensure the handshake has completed.
1889 SSLConfig ssl_config
;
1890 ssl_config
.false_start_enabled
= false;
1892 scoped_ptr
<SSLClientSocket
> sock(
1893 CreateSSLClientSocket(transport
.Pass(),
1894 test_server
.host_port_pair(),
1897 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1899 EXPECT_TRUE(sock
->IsConnected());
1901 raw_error_socket
->SetNextReadError(0);
1902 raw_transport
->BlockReadResult();
1903 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1904 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1905 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1907 raw_transport
->UnblockReadResult();
1908 rv
= callback
.GetResult(rv
);
1912 // Tests that fatal alerts from the peer are processed. This is a regression
1913 // test for https://crbug.com/466303.
1914 TEST_F(SSLClientSocketTest
, Read_WithFatalAlert
) {
1915 SpawnedTestServer::SSLOptions ssl_options
;
1916 ssl_options
.alert_after_handshake
= true;
1917 ASSERT_TRUE(StartTestServer(ssl_options
));
1919 SSLConfig ssl_config
;
1920 TestCompletionCallback callback
;
1921 scoped_ptr
<StreamSocket
> transport(
1922 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
1923 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
1924 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1925 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
1926 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
1928 // Receive the fatal alert.
1929 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1930 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, callback
.GetResult(sock
->Read(
1931 buf
.get(), 4096, callback
.callback())));
1934 TEST_F(SSLClientSocketTest
, Read_SmallChunks
) {
1935 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1936 SpawnedTestServer::kLocalhost
,
1938 ASSERT_TRUE(test_server
.Start());
1941 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1943 TestCompletionCallback callback
;
1944 scoped_ptr
<StreamSocket
> transport(
1945 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1946 int rv
= transport
->Connect(callback
.callback());
1947 if (rv
== ERR_IO_PENDING
)
1948 rv
= callback
.WaitForResult();
1951 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1952 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1954 rv
= sock
->Connect(callback
.callback());
1955 if (rv
== ERR_IO_PENDING
)
1956 rv
= callback
.WaitForResult();
1959 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1960 scoped_refptr
<IOBuffer
> request_buffer(
1961 new IOBuffer(arraysize(request_text
) - 1));
1962 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1965 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1966 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1968 if (rv
== ERR_IO_PENDING
)
1969 rv
= callback
.WaitForResult();
1970 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1972 scoped_refptr
<IOBuffer
> buf(new IOBuffer(1));
1974 rv
= sock
->Read(buf
.get(), 1, callback
.callback());
1975 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1977 if (rv
== ERR_IO_PENDING
)
1978 rv
= callback
.WaitForResult();
1986 TEST_F(SSLClientSocketTest
, Read_ManySmallRecords
) {
1987 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1988 SpawnedTestServer::kLocalhost
,
1990 ASSERT_TRUE(test_server
.Start());
1993 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1995 TestCompletionCallback callback
;
1997 scoped_ptr
<StreamSocket
> real_transport(
1998 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1999 scoped_ptr
<ReadBufferingStreamSocket
> transport(
2000 new ReadBufferingStreamSocket(real_transport
.Pass()));
2001 ReadBufferingStreamSocket
* raw_transport
= transport
.get();
2002 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2005 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2006 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2008 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2010 ASSERT_TRUE(sock
->IsConnected());
2012 const char request_text
[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
2013 scoped_refptr
<IOBuffer
> request_buffer(
2014 new IOBuffer(arraysize(request_text
) - 1));
2015 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2017 rv
= callback
.GetResult(sock
->Write(
2018 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback()));
2020 ASSERT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2022 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2023 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2024 // of SSL data is buffered first. The 15K of buffered data is made up of
2025 // many smaller SSL records (the TestServer writes along 1350 byte
2026 // plaintext boundaries), although there may also be a few records that are
2027 // smaller or larger, due to timing and SSL False Start.
2028 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2029 // the SSLClientSocket implementation, and larger than the minimum amount
2030 // of ciphertext necessary to contain the 8K of plaintext requested below.
2031 raw_transport
->SetBufferSize(15000);
2033 scoped_refptr
<IOBuffer
> buffer(new IOBuffer(8192));
2034 rv
= callback
.GetResult(sock
->Read(buffer
.get(), 8192, callback
.callback()));
2035 ASSERT_EQ(rv
, 8192);
2038 TEST_F(SSLClientSocketTest
, Read_Interrupted
) {
2039 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2040 SpawnedTestServer::kLocalhost
,
2042 ASSERT_TRUE(test_server
.Start());
2045 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2047 TestCompletionCallback callback
;
2048 scoped_ptr
<StreamSocket
> transport(
2049 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2050 int rv
= transport
->Connect(callback
.callback());
2051 if (rv
== ERR_IO_PENDING
)
2052 rv
= callback
.WaitForResult();
2055 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2056 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2058 rv
= sock
->Connect(callback
.callback());
2059 if (rv
== ERR_IO_PENDING
)
2060 rv
= callback
.WaitForResult();
2063 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2064 scoped_refptr
<IOBuffer
> request_buffer(
2065 new IOBuffer(arraysize(request_text
) - 1));
2066 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2069 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2070 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2072 if (rv
== ERR_IO_PENDING
)
2073 rv
= callback
.WaitForResult();
2074 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2076 // Do a partial read and then exit. This test should not crash!
2077 scoped_refptr
<IOBuffer
> buf(new IOBuffer(512));
2078 rv
= sock
->Read(buf
.get(), 512, callback
.callback());
2079 EXPECT_TRUE(rv
> 0 || rv
== ERR_IO_PENDING
);
2081 if (rv
== ERR_IO_PENDING
)
2082 rv
= callback
.WaitForResult();
2087 TEST_F(SSLClientSocketTest
, Read_FullLogging
) {
2088 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2089 SpawnedTestServer::kLocalhost
,
2091 ASSERT_TRUE(test_server
.Start());
2094 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2096 TestCompletionCallback callback
;
2097 CapturingNetLog log
;
2098 log
.SetLogLevel(NetLog::LOG_ALL
);
2099 scoped_ptr
<StreamSocket
> transport(
2100 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2101 int rv
= transport
->Connect(callback
.callback());
2102 if (rv
== ERR_IO_PENDING
)
2103 rv
= callback
.WaitForResult();
2106 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2107 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2109 rv
= sock
->Connect(callback
.callback());
2110 if (rv
== ERR_IO_PENDING
)
2111 rv
= callback
.WaitForResult();
2113 EXPECT_TRUE(sock
->IsConnected());
2115 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2116 scoped_refptr
<IOBuffer
> request_buffer(
2117 new IOBuffer(arraysize(request_text
) - 1));
2118 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2121 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2122 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2124 if (rv
== ERR_IO_PENDING
)
2125 rv
= callback
.WaitForResult();
2126 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2128 CapturingNetLog::CapturedEntryList entries
;
2129 log
.GetEntries(&entries
);
2130 size_t last_index
= ExpectLogContainsSomewhereAfter(
2131 entries
, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
2133 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
2135 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
2136 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2138 if (rv
== ERR_IO_PENDING
)
2139 rv
= callback
.WaitForResult();
2145 log
.GetEntries(&entries
);
2147 ExpectLogContainsSomewhereAfter(entries
,
2149 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
2150 NetLog::PHASE_NONE
);
2154 // Regression test for http://crbug.com/42538
2155 TEST_F(SSLClientSocketTest
, PrematureApplicationData
) {
2156 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2157 SpawnedTestServer::kLocalhost
,
2159 ASSERT_TRUE(test_server
.Start());
2162 TestCompletionCallback callback
;
2164 static const unsigned char application_data
[] = {
2165 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2166 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2167 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2168 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2169 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2170 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2171 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2172 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2173 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2176 // All reads and writes complete synchronously (async=false).
2177 MockRead data_reads
[] = {
2178 MockRead(SYNCHRONOUS
,
2179 reinterpret_cast<const char*>(application_data
),
2180 arraysize(application_data
)),
2181 MockRead(SYNCHRONOUS
, OK
), };
2183 StaticSocketDataProvider
data(data_reads
, arraysize(data_reads
), NULL
, 0);
2185 scoped_ptr
<StreamSocket
> transport(
2186 new MockTCPClientSocket(addr
, NULL
, &data
));
2187 int rv
= transport
->Connect(callback
.callback());
2188 if (rv
== ERR_IO_PENDING
)
2189 rv
= callback
.WaitForResult();
2192 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2193 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2195 rv
= sock
->Connect(callback
.callback());
2196 if (rv
== ERR_IO_PENDING
)
2197 rv
= callback
.WaitForResult();
2198 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, rv
);
2201 TEST_F(SSLClientSocketTest
, CipherSuiteDisables
) {
2202 // Rather than exhaustively disabling every RC4 ciphersuite defined at
2203 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
2204 // only disabling those cipher suites that the test server actually
2206 const uint16 kCiphersToDisable
[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
2209 SpawnedTestServer::SSLOptions ssl_options
;
2210 // Enable only RC4 on the test server.
2211 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
2212 SpawnedTestServer
test_server(
2213 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2214 ASSERT_TRUE(test_server
.Start());
2217 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2219 TestCompletionCallback callback
;
2220 CapturingNetLog log
;
2221 scoped_ptr
<StreamSocket
> transport(
2222 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2223 int rv
= transport
->Connect(callback
.callback());
2224 if (rv
== ERR_IO_PENDING
)
2225 rv
= callback
.WaitForResult();
2228 SSLConfig ssl_config
;
2229 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2230 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2232 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2233 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2235 EXPECT_FALSE(sock
->IsConnected());
2237 rv
= sock
->Connect(callback
.callback());
2238 CapturingNetLog::CapturedEntryList entries
;
2239 log
.GetEntries(&entries
);
2240 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2242 // NSS has special handling that maps a handshake_failure alert received
2243 // immediately after a client_hello to be a mismatched cipher suite error,
2244 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
2245 // Secure Transport (OS X), the handshake_failure is bubbled up without any
2246 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
2247 // indicates that no cipher suite was negotiated with the test server.
2248 if (rv
== ERR_IO_PENDING
)
2249 rv
= callback
.WaitForResult();
2250 EXPECT_TRUE(rv
== ERR_SSL_VERSION_OR_CIPHER_MISMATCH
||
2251 rv
== ERR_SSL_PROTOCOL_ERROR
);
2252 // The exact ordering differs between SSLClientSocketNSS (which issues an
2253 // extra read) and SSLClientSocketMac (which does not). Just make sure the
2254 // error appears somewhere in the log.
2255 log
.GetEntries(&entries
);
2256 ExpectLogContainsSomewhere(
2257 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2259 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2260 // the socket when it encounters an error, whereas other implementations
2261 // leave it connected.
2262 // Because this an error that the test server is mutually aware of, as opposed
2263 // to being an error such as a certificate name mismatch, which is
2264 // client-only, the exact index of the SSL connect end depends on how
2265 // quickly the test server closes the underlying socket. If the test server
2266 // closes before the IO message loop pumps messages, there may be a 0-byte
2267 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2268 // result, the SSL connect end event will be the second-to-last entry,
2269 // rather than the last entry.
2270 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1) ||
2271 LogContainsSSLConnectEndEvent(entries
, -2));
2274 // When creating an SSLClientSocket, it is allowed to pass in a
2275 // ClientSocketHandle that is not obtained from a client socket pool.
2276 // Here we verify that such a simple ClientSocketHandle, not associated with any
2277 // client socket pool, can be destroyed safely.
2278 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2279 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2280 SpawnedTestServer::kLocalhost
,
2282 ASSERT_TRUE(test_server
.Start());
2285 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2287 TestCompletionCallback callback
;
2288 scoped_ptr
<StreamSocket
> transport(
2289 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2290 int rv
= transport
->Connect(callback
.callback());
2291 if (rv
== ERR_IO_PENDING
)
2292 rv
= callback
.WaitForResult();
2295 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2296 socket_handle
->SetSocket(transport
.Pass());
2298 scoped_ptr
<SSLClientSocket
> sock(socket_factory_
->CreateSSLClientSocket(
2299 socket_handle
.Pass(), test_server
.host_port_pair(), SSLConfig(),
2302 EXPECT_FALSE(sock
->IsConnected());
2303 rv
= sock
->Connect(callback
.callback());
2304 if (rv
== ERR_IO_PENDING
)
2305 rv
= callback
.WaitForResult();
2309 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2310 // code and different keying label results in different keying material.
2311 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2312 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2313 SpawnedTestServer::kLocalhost
,
2315 ASSERT_TRUE(test_server
.Start());
2318 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2320 TestCompletionCallback callback
;
2322 scoped_ptr
<StreamSocket
> transport(
2323 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2324 int rv
= transport
->Connect(callback
.callback());
2325 if (rv
== ERR_IO_PENDING
)
2326 rv
= callback
.WaitForResult();
2329 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2330 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2332 rv
= sock
->Connect(callback
.callback());
2333 if (rv
== ERR_IO_PENDING
)
2334 rv
= callback
.WaitForResult();
2336 EXPECT_TRUE(sock
->IsConnected());
2338 const int kKeyingMaterialSize
= 32;
2339 const char kKeyingLabel1
[] = "client-socket-test-1";
2340 const char kKeyingContext
[] = "";
2341 unsigned char client_out1
[kKeyingMaterialSize
];
2342 memset(client_out1
, 0, sizeof(client_out1
));
2343 rv
= sock
->ExportKeyingMaterial(
2344 kKeyingLabel1
, false, kKeyingContext
, client_out1
, sizeof(client_out1
));
2347 const char kKeyingLabel2
[] = "client-socket-test-2";
2348 unsigned char client_out2
[kKeyingMaterialSize
];
2349 memset(client_out2
, 0, sizeof(client_out2
));
2350 rv
= sock
->ExportKeyingMaterial(
2351 kKeyingLabel2
, false, kKeyingContext
, client_out2
, sizeof(client_out2
));
2353 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2356 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2357 // explicit NSS initialization.
2358 TEST(SSLClientSocket
, ClearSessionCache
) {
2359 SSLClientSocket::ClearSessionCache();
2362 TEST(SSLClientSocket
, SerializeNextProtos
) {
2363 NextProtoVector next_protos
;
2364 next_protos
.push_back(kProtoHTTP11
);
2365 next_protos
.push_back(kProtoSPDY31
);
2366 static std::vector
<uint8_t> serialized
=
2367 SSLClientSocket::SerializeNextProtos(next_protos
, true);
2368 ASSERT_EQ(18u, serialized
.size());
2369 EXPECT_EQ(8, serialized
[0]); // length("http/1.1")
2370 EXPECT_EQ('h', serialized
[1]);
2371 EXPECT_EQ('t', serialized
[2]);
2372 EXPECT_EQ('t', serialized
[3]);
2373 EXPECT_EQ('p', serialized
[4]);
2374 EXPECT_EQ('/', serialized
[5]);
2375 EXPECT_EQ('1', serialized
[6]);
2376 EXPECT_EQ('.', serialized
[7]);
2377 EXPECT_EQ('1', serialized
[8]);
2378 EXPECT_EQ(8, serialized
[9]); // length("spdy/3.1")
2379 EXPECT_EQ('s', serialized
[10]);
2380 EXPECT_EQ('p', serialized
[11]);
2381 EXPECT_EQ('d', serialized
[12]);
2382 EXPECT_EQ('y', serialized
[13]);
2383 EXPECT_EQ('/', serialized
[14]);
2384 EXPECT_EQ('3', serialized
[15]);
2385 EXPECT_EQ('.', serialized
[16]);
2386 EXPECT_EQ('1', serialized
[17]);
2389 // Test that the server certificates are properly retrieved from the underlying
2391 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2392 // The connection does not have to be successful.
2393 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2395 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2396 // This makes the server present redundant-server-chain.pem, which contains
2397 // intermediate certificates.
2398 SpawnedTestServer::SSLOptions
ssl_options(
2399 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2400 SpawnedTestServer
test_server(
2401 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2402 ASSERT_TRUE(test_server
.Start());
2405 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2407 TestCompletionCallback callback
;
2408 scoped_ptr
<StreamSocket
> transport(
2409 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2410 int rv
= transport
->Connect(callback
.callback());
2411 rv
= callback
.GetResult(rv
);
2414 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2415 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2416 EXPECT_FALSE(sock
->IsConnected());
2417 rv
= sock
->Connect(callback
.callback());
2418 rv
= callback
.GetResult(rv
);
2420 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2421 EXPECT_TRUE(sock
->IsConnected());
2423 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2424 // certs from redundant-server-chain.pem.
2425 CertificateList server_certs
=
2426 CreateCertificateListFromFile(GetTestCertsDirectory(),
2427 "redundant-server-chain.pem",
2428 X509Certificate::FORMAT_AUTO
);
2430 // Get the server certificate as received client side.
2431 scoped_refptr
<X509Certificate
> server_certificate
=
2432 sock
->GetUnverifiedServerCertificateChain();
2434 // Get the intermediates as received client side.
2435 const X509Certificate::OSCertHandles
& server_intermediates
=
2436 server_certificate
->GetIntermediateCertificates();
2438 // Check that the unverified server certificate chain is properly retrieved
2439 // from the underlying ssl stack.
2440 ASSERT_EQ(4U, server_certs
.size());
2442 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2443 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2445 ASSERT_EQ(3U, server_intermediates
.size());
2447 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2448 server_certs
[1]->os_cert_handle()));
2449 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2450 server_certs
[2]->os_cert_handle()));
2451 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2452 server_certs
[3]->os_cert_handle()));
2455 EXPECT_FALSE(sock
->IsConnected());
2458 // This tests that SSLInfo contains a properly re-constructed certificate
2459 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2460 // verified, not the chain as served by the server. (They may be different.)
2462 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2463 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2464 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2465 // a self-signed root. Such a situation can occur when a new root (C2) is
2466 // cross-certified by an old root (D) and has two different versions of its
2467 // floating around. Servers may supply C2 as an intermediate, but the
2468 // SSLClientSocket should return the chain that was verified, from
2469 // verify_result, instead.
2470 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2471 // By default, cause the CertVerifier to treat all certificates as
2473 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2475 // We will expect SSLInfo to ultimately contain this chain.
2476 CertificateList certs
=
2477 CreateCertificateListFromFile(GetTestCertsDirectory(),
2478 "redundant-validated-chain.pem",
2479 X509Certificate::FORMAT_AUTO
);
2480 ASSERT_EQ(3U, certs
.size());
2482 X509Certificate::OSCertHandles temp_intermediates
;
2483 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2484 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2486 CertVerifyResult verify_result
;
2487 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2488 certs
[0]->os_cert_handle(), temp_intermediates
);
2490 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2491 // rather than A->B->C.
2492 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2494 // Load and install the root for the validated chain.
2495 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2496 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2497 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
2498 ScopedTestRoot
scoped_root(root_cert
.get());
2500 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2501 SpawnedTestServer::SSLOptions
ssl_options(
2502 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2503 SpawnedTestServer
test_server(
2504 SpawnedTestServer::TYPE_HTTPS
,
2506 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2507 ASSERT_TRUE(test_server
.Start());
2510 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2512 TestCompletionCallback callback
;
2513 CapturingNetLog log
;
2514 scoped_ptr
<StreamSocket
> transport(
2515 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2516 int rv
= transport
->Connect(callback
.callback());
2517 if (rv
== ERR_IO_PENDING
)
2518 rv
= callback
.WaitForResult();
2521 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2522 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2523 EXPECT_FALSE(sock
->IsConnected());
2524 rv
= sock
->Connect(callback
.callback());
2526 CapturingNetLog::CapturedEntryList entries
;
2527 log
.GetEntries(&entries
);
2528 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2529 if (rv
== ERR_IO_PENDING
)
2530 rv
= callback
.WaitForResult();
2533 EXPECT_TRUE(sock
->IsConnected());
2534 log
.GetEntries(&entries
);
2535 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2538 sock
->GetSSLInfo(&ssl_info
);
2540 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2542 const X509Certificate::OSCertHandles
& intermediates
=
2543 ssl_info
.cert
->GetIntermediateCertificates();
2544 ASSERT_EQ(2U, intermediates
.size());
2545 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2546 certs
[0]->os_cert_handle()));
2547 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2548 certs
[1]->os_cert_handle()));
2549 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2550 certs
[2]->os_cert_handle()));
2553 EXPECT_FALSE(sock
->IsConnected());
2556 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2557 SpawnedTestServer::SSLOptions ssl_options
;
2558 ssl_options
.request_client_certificate
= true;
2559 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2560 ASSERT_TRUE(request_info
.get());
2561 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2564 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2565 const base::FilePath::CharType kThawteFile
[] =
2566 FILE_PATH_LITERAL("thawte.single.pem");
2567 const unsigned char kThawteDN
[] = {
2568 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2569 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2570 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2571 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2572 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2573 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2574 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2575 const size_t kThawteLen
= sizeof(kThawteDN
);
2577 const base::FilePath::CharType kDiginotarFile
[] =
2578 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2579 const unsigned char kDiginotarDN
[] = {
2580 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2581 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2582 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2583 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2584 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2585 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2586 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2587 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2589 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2591 SpawnedTestServer::SSLOptions ssl_options
;
2592 ssl_options
.request_client_certificate
= true;
2593 ssl_options
.client_authorities
.push_back(
2594 GetTestClientCertsDirectory().Append(kThawteFile
));
2595 ssl_options
.client_authorities
.push_back(
2596 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2597 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2598 ASSERT_TRUE(request_info
.get());
2599 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2600 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2601 request_info
->cert_authorities
[0]);
2603 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2604 request_info
->cert_authorities
[1]);
2607 // cert_key_types is currently only populated on OpenSSL.
2608 #if defined(USE_OPENSSL)
2609 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2610 SpawnedTestServer::SSLOptions ssl_options
;
2611 ssl_options
.request_client_certificate
= true;
2612 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2613 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2614 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2615 ASSERT_TRUE(request_info
.get());
2616 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2617 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2618 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2620 #endif // defined(USE_OPENSSL)
2622 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2623 SpawnedTestServer::SSLOptions ssl_options
;
2624 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2626 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
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
, &log_
, NetLog::Source()));
2637 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2640 SSLConfig ssl_config
;
2641 ssl_config
.signed_cert_timestamps_enabled
= true;
2643 MockCTVerifier ct_verifier
;
2644 SetCTVerifier(&ct_verifier
);
2646 // Check that the SCT list is extracted as expected.
2647 EXPECT_CALL(ct_verifier
, Verify(_
, "", "test", _
, _
)).WillRepeatedly(
2648 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2650 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2651 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2652 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2655 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2660 bool IsValidOCSPResponse(const base::StringPiece
& input
) {
2661 base::StringPiece ocsp_response
= input
;
2662 base::StringPiece sequence
, response_status
, response_bytes
;
2663 return asn1::GetElement(&ocsp_response
, asn1::kSEQUENCE
, &sequence
) &&
2664 ocsp_response
.empty() &&
2665 asn1::GetElement(&sequence
, asn1::kENUMERATED
, &response_status
) &&
2666 asn1::GetElement(&sequence
,
2667 asn1::kContextSpecific
| asn1::kConstructed
| 0,
2668 &response_status
) &&
2674 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2675 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2676 SpawnedTestServer::SSLOptions ssl_options
;
2677 ssl_options
.staple_ocsp_response
= true;
2678 // The test server currently only knows how to generate OCSP responses
2679 // for a freshly minted certificate.
2680 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2682 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2685 ASSERT_TRUE(test_server
.Start());
2688 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2690 TestCompletionCallback callback
;
2691 scoped_ptr
<StreamSocket
> transport(
2692 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2693 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2696 SSLConfig ssl_config
;
2697 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2698 // Certificate Transparency verification regardless of whether the platform
2699 // is able to process the OCSP status itself.
2700 ssl_config
.signed_cert_timestamps_enabled
= true;
2702 MockCTVerifier ct_verifier
;
2703 SetCTVerifier(&ct_verifier
);
2705 // Check that the OCSP response is extracted and well-formed. It should be the
2706 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2707 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2708 // particular, it should not include the overall two-byte length prefix from
2710 EXPECT_CALL(ct_verifier
,
2711 Verify(_
, Truly(IsValidOCSPResponse
), "", _
, _
)).WillRepeatedly(
2712 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2714 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2715 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2716 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2719 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2722 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2723 SpawnedTestServer::SSLOptions ssl_options
;
2724 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2726 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2729 ASSERT_TRUE(test_server
.Start());
2732 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2734 TestCompletionCallback callback
;
2735 scoped_ptr
<StreamSocket
> transport(
2736 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2737 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2740 SSLConfig ssl_config
;
2741 ssl_config
.signed_cert_timestamps_enabled
= false;
2743 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2744 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2745 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2748 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2751 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2752 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2753 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2754 SpawnedTestServer::kLocalhost
,
2756 ASSERT_TRUE(test_server
.Start());
2759 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2761 TestCompletionCallback callback
;
2762 scoped_ptr
<StreamSocket
> transport(
2763 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2764 int rv
= transport
->Connect(callback
.callback());
2765 if (rv
== ERR_IO_PENDING
)
2766 rv
= callback
.WaitForResult();
2769 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2770 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2772 rv
= sock
->Connect(callback
.callback());
2773 if (rv
== ERR_IO_PENDING
)
2774 rv
= callback
.WaitForResult();
2777 // The socket was just connected. It should be idle because it is speaking
2778 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2780 EXPECT_TRUE(sock
->IsConnected());
2781 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2782 EXPECT_FALSE(sock
->WasEverUsed());
2784 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2785 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2786 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2787 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2789 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2790 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2792 if (rv
== ERR_IO_PENDING
)
2793 rv
= callback
.WaitForResult();
2794 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2796 // The socket has now been used.
2797 EXPECT_TRUE(sock
->WasEverUsed());
2799 // TODO(davidben): Read one byte to ensure the test server has responded and
2800 // then assert IsConnectedAndIdle is false. This currently doesn't work
2801 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2802 // SSL implementation's internal buffers. Either call PR_Available and
2803 // SSL_pending, although the former isn't actually implemented or perhaps
2804 // attempt to read one byte extra.
2807 // Tests that session caches are sharded by max_version.
2808 TEST_F(SSLClientSocketTest
, FallbackShardSessionCache
) {
2809 SpawnedTestServer::SSLOptions ssl_options
;
2810 ASSERT_TRUE(StartTestServer(ssl_options
));
2812 // Prepare a normal and fallback SSL config.
2813 SSLConfig ssl_config
;
2814 SSLConfig fallback_ssl_config
;
2815 fallback_ssl_config
.version_max
= SSL_PROTOCOL_VERSION_TLS1
;
2816 fallback_ssl_config
.version_fallback
= true;
2818 // Connect with a fallback config from the test server to add an entry to the
2820 TestCompletionCallback callback
;
2821 scoped_ptr
<StreamSocket
> transport(
2822 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2823 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2824 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2825 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
));
2826 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2828 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2829 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2830 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2831 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2833 // A non-fallback connection needs a full handshake.
2834 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2835 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2836 sock
= CreateSSLClientSocket(transport
.Pass(),
2837 test_server()->host_port_pair(), ssl_config
);
2838 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2839 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2840 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2841 // This does not check for equality because TLS 1.2 support is conditional on
2842 // system NSS features.
2843 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2844 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2846 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2847 // 1.2, the above test would not be sufficient to prove the session caches are
2848 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2849 // attempt to resume with two more connections.
2851 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2852 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2853 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2854 sock
= CreateSSLClientSocket(transport
.Pass(),
2855 test_server()->host_port_pair(), ssl_config
);
2856 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2857 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2858 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2859 // This does not check for equality because TLS 1.2 support is conditional on
2860 // system NSS features.
2861 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2862 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2864 // The fallback connection still resumes from its session cache. It cannot
2865 // offer the > TLS 1.0 session, so this must have been the session from the
2866 // first fallback connection.
2867 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2868 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2869 sock
= CreateSSLClientSocket(
2870 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
);
2871 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2872 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2873 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2874 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2875 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2878 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
2879 if (!SupportsAESGCM()) {
2880 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2884 // False Start requires NPN/ALPN, perfect forward secrecy, and an AEAD.
2885 SpawnedTestServer::SSLOptions server_options
;
2886 server_options
.key_exchanges
=
2887 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2888 server_options
.bulk_ciphers
=
2889 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2890 server_options
.enable_npn
= true;
2891 SSLConfig client_config
;
2892 client_config
.next_protos
.push_back(kProtoHTTP11
);
2893 ASSERT_NO_FATAL_FAILURE(
2894 TestFalseStart(server_options
, client_config
, true));
2897 // Test that False Start is disabled without NPN.
2898 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
2899 if (!SupportsAESGCM()) {
2900 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2904 SpawnedTestServer::SSLOptions server_options
;
2905 server_options
.key_exchanges
=
2906 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2907 server_options
.bulk_ciphers
=
2908 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2909 SSLConfig client_config
;
2910 client_config
.next_protos
.clear();
2911 ASSERT_NO_FATAL_FAILURE(
2912 TestFalseStart(server_options
, client_config
, false));
2915 // Test that False Start is disabled without perfect forward secrecy.
2916 TEST_F(SSLClientSocketFalseStartTest
, NoForwardSecrecy
) {
2917 if (!SupportsAESGCM()) {
2918 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2922 SpawnedTestServer::SSLOptions server_options
;
2923 server_options
.key_exchanges
=
2924 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
2925 server_options
.bulk_ciphers
=
2926 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2927 server_options
.enable_npn
= true;
2928 SSLConfig client_config
;
2929 client_config
.next_protos
.push_back(kProtoHTTP11
);
2930 ASSERT_NO_FATAL_FAILURE(
2931 TestFalseStart(server_options
, client_config
, false));
2934 // Test that False Start is disabled without an AEAD.
2935 TEST_F(SSLClientSocketFalseStartTest
, NoAEAD
) {
2936 SpawnedTestServer::SSLOptions server_options
;
2937 server_options
.key_exchanges
=
2938 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2939 server_options
.bulk_ciphers
=
2940 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
2941 server_options
.enable_npn
= true;
2942 SSLConfig client_config
;
2943 client_config
.next_protos
.push_back(kProtoHTTP11
);
2944 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
2947 // Test that sessions are resumable after receiving the server Finished message.
2948 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
2949 if (!SupportsAESGCM()) {
2950 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2955 SpawnedTestServer::SSLOptions server_options
;
2956 server_options
.key_exchanges
=
2957 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2958 server_options
.bulk_ciphers
=
2959 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2960 server_options
.enable_npn
= true;
2961 SSLConfig client_config
;
2962 client_config
.next_protos
.push_back(kProtoHTTP11
);
2964 // Let a full handshake complete with False Start.
2965 ASSERT_NO_FATAL_FAILURE(
2966 TestFalseStart(server_options
, client_config
, true));
2968 // Make a second connection.
2969 TestCompletionCallback callback
;
2970 scoped_ptr
<StreamSocket
> transport2(
2971 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2972 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
2973 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
2974 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
2975 ASSERT_TRUE(sock2
.get());
2976 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
2978 // It should resume the session.
2980 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
2981 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2984 // Test that sessions are not resumable before receiving the server Finished
2986 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinish
) {
2987 if (!SupportsAESGCM()) {
2988 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2993 SpawnedTestServer::SSLOptions server_options
;
2994 server_options
.key_exchanges
=
2995 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
2996 server_options
.bulk_ciphers
=
2997 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2998 server_options
.enable_npn
= true;
2999 ASSERT_TRUE(StartTestServer(server_options
));
3001 SSLConfig client_config
;
3002 client_config
.next_protos
.push_back(kProtoHTTP11
);
3004 // Start a handshake up to the server Finished message.
3005 TestCompletionCallback callback
;
3006 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3007 scoped_ptr
<SSLClientSocket
> sock1
;
3008 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3009 client_config
, &callback
, &raw_transport1
, &sock1
));
3010 // Although raw_transport1 has the server Finished blocked, the handshake
3012 EXPECT_EQ(OK
, callback
.WaitForResult());
3014 // Continue to block the client (|sock1|) from processing the Finished
3015 // message, but allow it to arrive on the socket. This ensures that, from the
3016 // server's point of view, it has completed the handshake and added the
3017 // session to its session cache.
3019 // The actual read on |sock1| will not complete until the Finished message is
3020 // processed; however, pump the underlying transport so that it is read from
3021 // the socket. This still has the potential to race, but is generally unlikely
3022 // due to socket buffer sizes.
3023 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3024 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3025 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3026 raw_transport1
->WaitForReadResult();
3028 // Drop the old socket. This is needed because the Python test server can't
3029 // service two sockets in parallel.
3032 // Start a second connection.
3033 scoped_ptr
<StreamSocket
> transport2(
3034 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3035 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3036 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3037 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3038 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3040 // No session resumption because the first connection never received a server
3041 // Finished message.
3043 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3044 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3047 // Connect to a server using channel id. It should allow the connection.
3048 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
3049 SpawnedTestServer::SSLOptions ssl_options
;
3051 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3054 SSLConfig ssl_config
;
3055 ssl_config
.channel_id_enabled
= true;
3058 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3061 EXPECT_TRUE(sock_
->IsConnected());
3062 EXPECT_TRUE(sock_
->WasChannelIDSent());
3064 sock_
->Disconnect();
3065 EXPECT_FALSE(sock_
->IsConnected());
3068 // Connect to a server using Channel ID but failing to look up the Channel
3069 // ID. It should fail.
3070 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
3071 SpawnedTestServer::SSLOptions ssl_options
;
3073 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3075 EnableFailingChannelID();
3076 SSLConfig ssl_config
;
3077 ssl_config
.channel_id_enabled
= true;
3080 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3082 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3083 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3084 // error codes for now.
3085 // http://crbug.com/373670
3087 EXPECT_FALSE(sock_
->IsConnected());
3090 // Connect to a server using Channel ID but asynchronously failing to look up
3091 // the Channel ID. It should fail.
3092 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
3093 SpawnedTestServer::SSLOptions ssl_options
;
3095 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3097 EnableAsyncFailingChannelID();
3098 SSLConfig ssl_config
;
3099 ssl_config
.channel_id_enabled
= true;
3102 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3104 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
3105 EXPECT_FALSE(sock_
->IsConnected());