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/test_completion_callback.h"
15 #include "net/base/test_data_directory.h"
16 #include "net/cert/asn1_util.h"
17 #include "net/cert/ct_verifier.h"
18 #include "net/cert/mock_cert_verifier.h"
19 #include "net/cert/test_root_certs.h"
20 #include "net/dns/host_resolver.h"
21 #include "net/http/transport_security_state.h"
22 #include "net/log/net_log.h"
23 #include "net/log/net_log_unittest.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 AES_128_CBC ciphersuite defined at
2203 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2204 // disabling those cipher suites that the test server actually implements.
2205 const uint16 kCiphersToDisable
[] = {
2206 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2207 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2208 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2211 SpawnedTestServer::SSLOptions ssl_options
;
2212 // Enable only AES_128_CBC on the test server.
2213 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
2214 SpawnedTestServer
test_server(
2215 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2216 ASSERT_TRUE(test_server
.Start());
2219 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2221 TestCompletionCallback callback
;
2222 CapturingNetLog log
;
2223 scoped_ptr
<StreamSocket
> transport(
2224 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2225 int rv
= transport
->Connect(callback
.callback());
2226 if (rv
== ERR_IO_PENDING
)
2227 rv
= callback
.WaitForResult();
2230 SSLConfig ssl_config
;
2231 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2232 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2234 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2235 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2237 EXPECT_FALSE(sock
->IsConnected());
2239 rv
= sock
->Connect(callback
.callback());
2240 CapturingNetLog::CapturedEntryList entries
;
2241 log
.GetEntries(&entries
);
2242 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2244 if (rv
== ERR_IO_PENDING
)
2245 rv
= callback
.WaitForResult();
2246 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
, rv
);
2247 // The exact ordering depends no whether an extra read is issued. Just check
2248 // the error is somewhere in the log.
2249 log
.GetEntries(&entries
);
2250 ExpectLogContainsSomewhere(
2251 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2253 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2254 // the socket when it encounters an error, whereas other implementations
2255 // leave it connected.
2256 // Because this an error that the test server is mutually aware of, as opposed
2257 // to being an error such as a certificate name mismatch, which is
2258 // client-only, the exact index of the SSL connect end depends on how
2259 // quickly the test server closes the underlying socket. If the test server
2260 // closes before the IO message loop pumps messages, there may be a 0-byte
2261 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2262 // result, the SSL connect end event will be the second-to-last entry,
2263 // rather than the last entry.
2264 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1) ||
2265 LogContainsSSLConnectEndEvent(entries
, -2));
2268 // When creating an SSLClientSocket, it is allowed to pass in a
2269 // ClientSocketHandle that is not obtained from a client socket pool.
2270 // Here we verify that such a simple ClientSocketHandle, not associated with any
2271 // client socket pool, can be destroyed safely.
2272 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2273 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2274 SpawnedTestServer::kLocalhost
,
2276 ASSERT_TRUE(test_server
.Start());
2279 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2281 TestCompletionCallback callback
;
2282 scoped_ptr
<StreamSocket
> transport(
2283 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2284 int rv
= transport
->Connect(callback
.callback());
2285 if (rv
== ERR_IO_PENDING
)
2286 rv
= callback
.WaitForResult();
2289 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2290 socket_handle
->SetSocket(transport
.Pass());
2292 scoped_ptr
<SSLClientSocket
> sock(socket_factory_
->CreateSSLClientSocket(
2293 socket_handle
.Pass(), test_server
.host_port_pair(), SSLConfig(),
2296 EXPECT_FALSE(sock
->IsConnected());
2297 rv
= sock
->Connect(callback
.callback());
2298 if (rv
== ERR_IO_PENDING
)
2299 rv
= callback
.WaitForResult();
2303 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2304 // code and different keying label results in different keying material.
2305 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2306 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2307 SpawnedTestServer::kLocalhost
,
2309 ASSERT_TRUE(test_server
.Start());
2312 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2314 TestCompletionCallback callback
;
2316 scoped_ptr
<StreamSocket
> transport(
2317 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2318 int rv
= transport
->Connect(callback
.callback());
2319 if (rv
== ERR_IO_PENDING
)
2320 rv
= callback
.WaitForResult();
2323 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2324 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2326 rv
= sock
->Connect(callback
.callback());
2327 if (rv
== ERR_IO_PENDING
)
2328 rv
= callback
.WaitForResult();
2330 EXPECT_TRUE(sock
->IsConnected());
2332 const int kKeyingMaterialSize
= 32;
2333 const char kKeyingLabel1
[] = "client-socket-test-1";
2334 const char kKeyingContext1
[] = "";
2335 unsigned char client_out1
[kKeyingMaterialSize
];
2336 memset(client_out1
, 0, sizeof(client_out1
));
2337 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, false, kKeyingContext1
,
2338 client_out1
, sizeof(client_out1
));
2341 const char kKeyingLabel2
[] = "client-socket-test-2";
2342 unsigned char client_out2
[kKeyingMaterialSize
];
2343 memset(client_out2
, 0, sizeof(client_out2
));
2344 rv
= sock
->ExportKeyingMaterial(kKeyingLabel2
, false, kKeyingContext1
,
2345 client_out2
, sizeof(client_out2
));
2347 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2349 const char kKeyingContext2
[] = "context";
2350 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext2
,
2351 client_out2
, sizeof(client_out2
));
2353 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2355 // Using an empty context should give different key material from not using a
2357 memset(client_out2
, 0, sizeof(client_out2
));
2358 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext1
,
2359 client_out2
, sizeof(client_out2
));
2361 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2364 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2365 // explicit NSS initialization.
2366 TEST(SSLClientSocket
, ClearSessionCache
) {
2367 SSLClientSocket::ClearSessionCache();
2370 TEST(SSLClientSocket
, SerializeNextProtos
) {
2371 NextProtoVector next_protos
;
2372 next_protos
.push_back(kProtoHTTP11
);
2373 next_protos
.push_back(kProtoSPDY31
);
2374 static std::vector
<uint8_t> serialized
=
2375 SSLClientSocket::SerializeNextProtos(next_protos
, true);
2376 ASSERT_EQ(18u, serialized
.size());
2377 EXPECT_EQ(8, serialized
[0]); // length("http/1.1")
2378 EXPECT_EQ('h', serialized
[1]);
2379 EXPECT_EQ('t', serialized
[2]);
2380 EXPECT_EQ('t', serialized
[3]);
2381 EXPECT_EQ('p', serialized
[4]);
2382 EXPECT_EQ('/', serialized
[5]);
2383 EXPECT_EQ('1', serialized
[6]);
2384 EXPECT_EQ('.', serialized
[7]);
2385 EXPECT_EQ('1', serialized
[8]);
2386 EXPECT_EQ(8, serialized
[9]); // length("spdy/3.1")
2387 EXPECT_EQ('s', serialized
[10]);
2388 EXPECT_EQ('p', serialized
[11]);
2389 EXPECT_EQ('d', serialized
[12]);
2390 EXPECT_EQ('y', serialized
[13]);
2391 EXPECT_EQ('/', serialized
[14]);
2392 EXPECT_EQ('3', serialized
[15]);
2393 EXPECT_EQ('.', serialized
[16]);
2394 EXPECT_EQ('1', serialized
[17]);
2397 // Test that the server certificates are properly retrieved from the underlying
2399 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2400 // The connection does not have to be successful.
2401 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2403 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2404 // This makes the server present redundant-server-chain.pem, which contains
2405 // intermediate certificates.
2406 SpawnedTestServer::SSLOptions
ssl_options(
2407 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2408 SpawnedTestServer
test_server(
2409 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2410 ASSERT_TRUE(test_server
.Start());
2413 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2415 TestCompletionCallback callback
;
2416 scoped_ptr
<StreamSocket
> transport(
2417 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2418 int rv
= transport
->Connect(callback
.callback());
2419 rv
= callback
.GetResult(rv
);
2422 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2423 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2424 EXPECT_FALSE(sock
->IsConnected());
2425 rv
= sock
->Connect(callback
.callback());
2426 rv
= callback
.GetResult(rv
);
2428 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2429 EXPECT_TRUE(sock
->IsConnected());
2431 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2432 // certs from redundant-server-chain.pem.
2433 CertificateList server_certs
=
2434 CreateCertificateListFromFile(GetTestCertsDirectory(),
2435 "redundant-server-chain.pem",
2436 X509Certificate::FORMAT_AUTO
);
2438 // Get the server certificate as received client side.
2439 scoped_refptr
<X509Certificate
> server_certificate
=
2440 sock
->GetUnverifiedServerCertificateChain();
2442 // Get the intermediates as received client side.
2443 const X509Certificate::OSCertHandles
& server_intermediates
=
2444 server_certificate
->GetIntermediateCertificates();
2446 // Check that the unverified server certificate chain is properly retrieved
2447 // from the underlying ssl stack.
2448 ASSERT_EQ(4U, server_certs
.size());
2450 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2451 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2453 ASSERT_EQ(3U, server_intermediates
.size());
2455 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2456 server_certs
[1]->os_cert_handle()));
2457 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2458 server_certs
[2]->os_cert_handle()));
2459 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2460 server_certs
[3]->os_cert_handle()));
2463 EXPECT_FALSE(sock
->IsConnected());
2466 // This tests that SSLInfo contains a properly re-constructed certificate
2467 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2468 // verified, not the chain as served by the server. (They may be different.)
2470 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2471 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2472 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2473 // a self-signed root. Such a situation can occur when a new root (C2) is
2474 // cross-certified by an old root (D) and has two different versions of its
2475 // floating around. Servers may supply C2 as an intermediate, but the
2476 // SSLClientSocket should return the chain that was verified, from
2477 // verify_result, instead.
2478 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2479 // By default, cause the CertVerifier to treat all certificates as
2481 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2483 // We will expect SSLInfo to ultimately contain this chain.
2484 CertificateList certs
=
2485 CreateCertificateListFromFile(GetTestCertsDirectory(),
2486 "redundant-validated-chain.pem",
2487 X509Certificate::FORMAT_AUTO
);
2488 ASSERT_EQ(3U, certs
.size());
2490 X509Certificate::OSCertHandles temp_intermediates
;
2491 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2492 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2494 CertVerifyResult verify_result
;
2495 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2496 certs
[0]->os_cert_handle(), temp_intermediates
);
2498 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2499 // rather than A->B->C.
2500 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2502 // Load and install the root for the validated chain.
2503 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2504 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2505 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
2506 ScopedTestRoot
scoped_root(root_cert
.get());
2508 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2509 SpawnedTestServer::SSLOptions
ssl_options(
2510 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2511 SpawnedTestServer
test_server(
2512 SpawnedTestServer::TYPE_HTTPS
,
2514 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2515 ASSERT_TRUE(test_server
.Start());
2518 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2520 TestCompletionCallback callback
;
2521 CapturingNetLog log
;
2522 scoped_ptr
<StreamSocket
> transport(
2523 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2524 int rv
= transport
->Connect(callback
.callback());
2525 if (rv
== ERR_IO_PENDING
)
2526 rv
= callback
.WaitForResult();
2529 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2530 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2531 EXPECT_FALSE(sock
->IsConnected());
2532 rv
= sock
->Connect(callback
.callback());
2534 CapturingNetLog::CapturedEntryList entries
;
2535 log
.GetEntries(&entries
);
2536 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2537 if (rv
== ERR_IO_PENDING
)
2538 rv
= callback
.WaitForResult();
2541 EXPECT_TRUE(sock
->IsConnected());
2542 log
.GetEntries(&entries
);
2543 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2546 sock
->GetSSLInfo(&ssl_info
);
2548 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2550 const X509Certificate::OSCertHandles
& intermediates
=
2551 ssl_info
.cert
->GetIntermediateCertificates();
2552 ASSERT_EQ(2U, intermediates
.size());
2553 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2554 certs
[0]->os_cert_handle()));
2555 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2556 certs
[1]->os_cert_handle()));
2557 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2558 certs
[2]->os_cert_handle()));
2561 EXPECT_FALSE(sock
->IsConnected());
2564 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2565 SpawnedTestServer::SSLOptions ssl_options
;
2566 ssl_options
.request_client_certificate
= true;
2567 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2568 ASSERT_TRUE(request_info
.get());
2569 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2572 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2573 const base::FilePath::CharType kThawteFile
[] =
2574 FILE_PATH_LITERAL("thawte.single.pem");
2575 const unsigned char kThawteDN
[] = {
2576 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2577 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2578 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2579 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2580 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2581 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2582 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2583 const size_t kThawteLen
= sizeof(kThawteDN
);
2585 const base::FilePath::CharType kDiginotarFile
[] =
2586 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2587 const unsigned char kDiginotarDN
[] = {
2588 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2589 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2590 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2591 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2592 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2593 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2594 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2595 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2597 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2599 SpawnedTestServer::SSLOptions ssl_options
;
2600 ssl_options
.request_client_certificate
= true;
2601 ssl_options
.client_authorities
.push_back(
2602 GetTestClientCertsDirectory().Append(kThawteFile
));
2603 ssl_options
.client_authorities
.push_back(
2604 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2605 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2606 ASSERT_TRUE(request_info
.get());
2607 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2608 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2609 request_info
->cert_authorities
[0]);
2611 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2612 request_info
->cert_authorities
[1]);
2615 // cert_key_types is currently only populated on OpenSSL.
2616 #if defined(USE_OPENSSL)
2617 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2618 SpawnedTestServer::SSLOptions ssl_options
;
2619 ssl_options
.request_client_certificate
= true;
2620 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2621 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2622 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2623 ASSERT_TRUE(request_info
.get());
2624 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2625 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2626 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2628 #endif // defined(USE_OPENSSL)
2630 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2631 SpawnedTestServer::SSLOptions ssl_options
;
2632 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2634 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2637 ASSERT_TRUE(test_server
.Start());
2640 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2642 TestCompletionCallback callback
;
2643 scoped_ptr
<StreamSocket
> transport(
2644 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2645 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2648 SSLConfig ssl_config
;
2649 ssl_config
.signed_cert_timestamps_enabled
= true;
2651 MockCTVerifier ct_verifier
;
2652 SetCTVerifier(&ct_verifier
);
2654 // Check that the SCT list is extracted as expected.
2655 EXPECT_CALL(ct_verifier
, Verify(_
, "", "test", _
, _
)).WillRepeatedly(
2656 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2658 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2659 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2660 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2663 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2668 bool IsValidOCSPResponse(const base::StringPiece
& input
) {
2669 base::StringPiece ocsp_response
= input
;
2670 base::StringPiece sequence
, response_status
, response_bytes
;
2671 return asn1::GetElement(&ocsp_response
, asn1::kSEQUENCE
, &sequence
) &&
2672 ocsp_response
.empty() &&
2673 asn1::GetElement(&sequence
, asn1::kENUMERATED
, &response_status
) &&
2674 asn1::GetElement(&sequence
,
2675 asn1::kContextSpecific
| asn1::kConstructed
| 0,
2676 &response_status
) &&
2682 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2683 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2684 SpawnedTestServer::SSLOptions ssl_options
;
2685 ssl_options
.staple_ocsp_response
= true;
2686 // The test server currently only knows how to generate OCSP responses
2687 // for a freshly minted certificate.
2688 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2690 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2693 ASSERT_TRUE(test_server
.Start());
2696 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2698 TestCompletionCallback callback
;
2699 scoped_ptr
<StreamSocket
> transport(
2700 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2701 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2704 SSLConfig ssl_config
;
2705 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2706 // Certificate Transparency verification regardless of whether the platform
2707 // is able to process the OCSP status itself.
2708 ssl_config
.signed_cert_timestamps_enabled
= true;
2710 MockCTVerifier ct_verifier
;
2711 SetCTVerifier(&ct_verifier
);
2713 // Check that the OCSP response is extracted and well-formed. It should be the
2714 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2715 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2716 // particular, it should not include the overall two-byte length prefix from
2718 EXPECT_CALL(ct_verifier
,
2719 Verify(_
, Truly(IsValidOCSPResponse
), "", _
, _
)).WillRepeatedly(
2720 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2722 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2723 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2724 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2727 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2730 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2731 SpawnedTestServer::SSLOptions ssl_options
;
2732 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2734 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2737 ASSERT_TRUE(test_server
.Start());
2740 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2742 TestCompletionCallback callback
;
2743 scoped_ptr
<StreamSocket
> transport(
2744 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2745 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2748 SSLConfig ssl_config
;
2749 ssl_config
.signed_cert_timestamps_enabled
= false;
2751 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2752 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2753 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2756 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2759 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2760 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2761 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2762 SpawnedTestServer::kLocalhost
,
2764 ASSERT_TRUE(test_server
.Start());
2767 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2769 TestCompletionCallback callback
;
2770 scoped_ptr
<StreamSocket
> transport(
2771 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2772 int rv
= transport
->Connect(callback
.callback());
2773 if (rv
== ERR_IO_PENDING
)
2774 rv
= callback
.WaitForResult();
2777 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2778 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2780 rv
= sock
->Connect(callback
.callback());
2781 if (rv
== ERR_IO_PENDING
)
2782 rv
= callback
.WaitForResult();
2785 // The socket was just connected. It should be idle because it is speaking
2786 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2788 EXPECT_TRUE(sock
->IsConnected());
2789 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2790 EXPECT_FALSE(sock
->WasEverUsed());
2792 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2793 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2794 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2795 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2797 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2798 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2800 if (rv
== ERR_IO_PENDING
)
2801 rv
= callback
.WaitForResult();
2802 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2804 // The socket has now been used.
2805 EXPECT_TRUE(sock
->WasEverUsed());
2807 // TODO(davidben): Read one byte to ensure the test server has responded and
2808 // then assert IsConnectedAndIdle is false. This currently doesn't work
2809 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2810 // SSL implementation's internal buffers. Either call PR_Available and
2811 // SSL_pending, although the former isn't actually implemented or perhaps
2812 // attempt to read one byte extra.
2815 // Tests that session caches are sharded by max_version.
2816 TEST_F(SSLClientSocketTest
, FallbackShardSessionCache
) {
2817 SpawnedTestServer::SSLOptions ssl_options
;
2818 ASSERT_TRUE(StartTestServer(ssl_options
));
2820 // Prepare a normal and fallback SSL config.
2821 SSLConfig ssl_config
;
2822 SSLConfig fallback_ssl_config
;
2823 fallback_ssl_config
.version_max
= SSL_PROTOCOL_VERSION_TLS1
;
2824 fallback_ssl_config
.version_fallback
= true;
2826 // Connect with a fallback config from the test server to add an entry to the
2828 TestCompletionCallback callback
;
2829 scoped_ptr
<StreamSocket
> transport(
2830 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2831 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2832 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2833 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
));
2834 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2836 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2837 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2838 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2839 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2841 // A non-fallback connection needs a full handshake.
2842 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2843 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2844 sock
= CreateSSLClientSocket(transport
.Pass(),
2845 test_server()->host_port_pair(), ssl_config
);
2846 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2847 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2848 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2849 // This does not check for equality because TLS 1.2 support is conditional on
2850 // system NSS features.
2851 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2852 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2854 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2855 // 1.2, the above test would not be sufficient to prove the session caches are
2856 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2857 // attempt to resume with two more connections.
2859 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2860 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2861 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2862 sock
= CreateSSLClientSocket(transport
.Pass(),
2863 test_server()->host_port_pair(), ssl_config
);
2864 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2865 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2866 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2867 // This does not check for equality because TLS 1.2 support is conditional on
2868 // system NSS features.
2869 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2870 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2872 // The fallback connection still resumes from its session cache. It cannot
2873 // offer the > TLS 1.0 session, so this must have been the session from the
2874 // first fallback connection.
2875 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2876 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2877 sock
= CreateSSLClientSocket(
2878 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
);
2879 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2880 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2881 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2882 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2883 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2886 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
2887 TEST_F(SSLClientSocketTest
, DeprecatedRC4
) {
2888 SpawnedTestServer::SSLOptions ssl_options
;
2889 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
2890 ASSERT_TRUE(StartTestServer(ssl_options
));
2892 // Normal handshakes with RC4 do not work.
2893 SSLConfig ssl_config
;
2894 TestCompletionCallback callback
;
2895 scoped_ptr
<StreamSocket
> transport(
2896 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2897 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2898 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2899 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
2900 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
,
2901 callback
.GetResult(sock
->Connect(callback
.callback())));
2903 // Enabling deprecated ciphers works fine.
2904 ssl_config
.enable_deprecated_cipher_suites
= true;
2905 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2906 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2907 sock
= CreateSSLClientSocket(transport
.Pass(),
2908 test_server()->host_port_pair(), ssl_config
);
2909 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2912 // Tests that enabling deprecated ciphers shards the session cache.
2913 TEST_F(SSLClientSocketTest
, DeprecatedShardSessionCache
) {
2914 SpawnedTestServer::SSLOptions ssl_options
;
2915 ASSERT_TRUE(StartTestServer(ssl_options
));
2917 // Prepare a normal and deprecated SSL config.
2918 SSLConfig ssl_config
;
2919 SSLConfig deprecated_ssl_config
;
2920 deprecated_ssl_config
.enable_deprecated_cipher_suites
= true;
2922 // Connect with deprecated ciphers enabled to warm the session cache cache.
2923 TestCompletionCallback callback
;
2924 scoped_ptr
<StreamSocket
> transport(
2925 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2926 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2927 scoped_ptr
<SSLClientSocket
> sock(
2928 CreateSSLClientSocket(transport
.Pass(), test_server()->host_port_pair(),
2929 deprecated_ssl_config
));
2930 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2932 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2933 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2935 // Test that re-connecting with deprecated ciphers enabled still resumes.
2936 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2937 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2938 sock
= CreateSSLClientSocket(
2939 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
2940 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2941 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2942 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2944 // However, a normal connection needs a full handshake.
2945 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2946 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2947 sock
= CreateSSLClientSocket(transport
.Pass(),
2948 test_server()->host_port_pair(), ssl_config
);
2949 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2950 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2951 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2953 // Clear the session cache for the inverse test.
2954 SSLClientSocket::ClearSessionCache();
2956 // Now make a normal connection to prime the session cache.
2957 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2958 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2959 sock
= CreateSSLClientSocket(transport
.Pass(),
2960 test_server()->host_port_pair(), ssl_config
);
2961 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2962 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2963 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2965 // A normal connection should be able to resume.
2966 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2967 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2968 sock
= CreateSSLClientSocket(transport
.Pass(),
2969 test_server()->host_port_pair(), ssl_config
);
2970 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2971 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2972 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2974 // However, enabling deprecated ciphers connects fresh.
2975 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2976 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2977 sock
= CreateSSLClientSocket(
2978 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
2979 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2980 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2981 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2984 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
2985 if (!SupportsAESGCM()) {
2986 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
2990 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
2991 SpawnedTestServer::SSLOptions server_options
;
2992 server_options
.key_exchanges
=
2993 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
2994 server_options
.bulk_ciphers
=
2995 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
2996 server_options
.enable_npn
= true;
2997 SSLConfig client_config
;
2998 client_config
.next_protos
.push_back(kProtoHTTP11
);
2999 ASSERT_NO_FATAL_FAILURE(
3000 TestFalseStart(server_options
, client_config
, true));
3003 // Test that False Start is disabled without NPN.
3004 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
3005 if (!SupportsAESGCM()) {
3006 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3010 SpawnedTestServer::SSLOptions server_options
;
3011 server_options
.key_exchanges
=
3012 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3013 server_options
.bulk_ciphers
=
3014 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3015 SSLConfig client_config
;
3016 client_config
.next_protos
.clear();
3017 ASSERT_NO_FATAL_FAILURE(
3018 TestFalseStart(server_options
, client_config
, false));
3021 // Test that False Start is disabled with plain RSA ciphers.
3022 TEST_F(SSLClientSocketFalseStartTest
, RSA
) {
3023 if (!SupportsAESGCM()) {
3024 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3028 SpawnedTestServer::SSLOptions server_options
;
3029 server_options
.key_exchanges
=
3030 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
3031 server_options
.bulk_ciphers
=
3032 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3033 server_options
.enable_npn
= true;
3034 SSLConfig client_config
;
3035 client_config
.next_protos
.push_back(kProtoHTTP11
);
3036 ASSERT_NO_FATAL_FAILURE(
3037 TestFalseStart(server_options
, client_config
, false));
3040 // Test that False Start is disabled with DHE_RSA ciphers.
3041 TEST_F(SSLClientSocketFalseStartTest
, DHE_RSA
) {
3042 if (!SupportsAESGCM()) {
3043 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3047 SpawnedTestServer::SSLOptions server_options
;
3048 server_options
.key_exchanges
=
3049 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
3050 server_options
.bulk_ciphers
=
3051 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3052 server_options
.enable_npn
= true;
3053 SSLConfig client_config
;
3054 client_config
.next_protos
.push_back(kProtoHTTP11
);
3055 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3058 // Test that False Start is disabled without an AEAD.
3059 TEST_F(SSLClientSocketFalseStartTest
, NoAEAD
) {
3060 SpawnedTestServer::SSLOptions server_options
;
3061 server_options
.key_exchanges
=
3062 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3063 server_options
.bulk_ciphers
=
3064 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
3065 server_options
.enable_npn
= true;
3066 SSLConfig client_config
;
3067 client_config
.next_protos
.push_back(kProtoHTTP11
);
3068 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3071 // Test that sessions are resumable after receiving the server Finished message.
3072 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
3073 if (!SupportsAESGCM()) {
3074 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3079 SpawnedTestServer::SSLOptions server_options
;
3080 server_options
.key_exchanges
=
3081 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3082 server_options
.bulk_ciphers
=
3083 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3084 server_options
.enable_npn
= true;
3085 SSLConfig client_config
;
3086 client_config
.next_protos
.push_back(kProtoHTTP11
);
3088 // Let a full handshake complete with False Start.
3089 ASSERT_NO_FATAL_FAILURE(
3090 TestFalseStart(server_options
, client_config
, true));
3092 // Make a second connection.
3093 TestCompletionCallback callback
;
3094 scoped_ptr
<StreamSocket
> transport2(
3095 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3096 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3097 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3098 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3099 ASSERT_TRUE(sock2
.get());
3100 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3102 // It should resume the session.
3104 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3105 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3108 // Test that sessions are not resumable before receiving the server Finished
3110 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinish
) {
3111 if (!SupportsAESGCM()) {
3112 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3117 SpawnedTestServer::SSLOptions server_options
;
3118 server_options
.key_exchanges
=
3119 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3120 server_options
.bulk_ciphers
=
3121 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3122 server_options
.enable_npn
= true;
3123 ASSERT_TRUE(StartTestServer(server_options
));
3125 SSLConfig client_config
;
3126 client_config
.next_protos
.push_back(kProtoHTTP11
);
3128 // Start a handshake up to the server Finished message.
3129 TestCompletionCallback callback
;
3130 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3131 scoped_ptr
<SSLClientSocket
> sock1
;
3132 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3133 client_config
, &callback
, &raw_transport1
, &sock1
));
3134 // Although raw_transport1 has the server Finished blocked, the handshake
3136 EXPECT_EQ(OK
, callback
.WaitForResult());
3138 // Continue to block the client (|sock1|) from processing the Finished
3139 // message, but allow it to arrive on the socket. This ensures that, from the
3140 // server's point of view, it has completed the handshake and added the
3141 // session to its session cache.
3143 // The actual read on |sock1| will not complete until the Finished message is
3144 // processed; however, pump the underlying transport so that it is read from
3145 // the socket. This still has the potential to race, but is generally unlikely
3146 // due to socket buffer sizes.
3147 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3148 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3149 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3150 raw_transport1
->WaitForReadResult();
3152 // Drop the old socket. This is needed because the Python test server can't
3153 // service two sockets in parallel.
3156 // Start a second connection.
3157 scoped_ptr
<StreamSocket
> transport2(
3158 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3159 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3160 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3161 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3162 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3164 // No session resumption because the first connection never received a server
3165 // Finished message.
3167 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3168 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3171 // Connect to a server using channel id. It should allow the connection.
3172 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
3173 SpawnedTestServer::SSLOptions ssl_options
;
3175 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3178 SSLConfig ssl_config
;
3179 ssl_config
.channel_id_enabled
= true;
3182 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3185 EXPECT_TRUE(sock_
->IsConnected());
3186 EXPECT_TRUE(sock_
->WasChannelIDSent());
3188 sock_
->Disconnect();
3189 EXPECT_FALSE(sock_
->IsConnected());
3192 // Connect to a server using Channel ID but failing to look up the Channel
3193 // ID. It should fail.
3194 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
3195 SpawnedTestServer::SSLOptions ssl_options
;
3197 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3199 EnableFailingChannelID();
3200 SSLConfig ssl_config
;
3201 ssl_config
.channel_id_enabled
= true;
3204 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3206 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3207 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3208 // error codes for now.
3209 // http://crbug.com/373670
3211 EXPECT_FALSE(sock_
->IsConnected());
3214 // Connect to a server using Channel ID but asynchronously failing to look up
3215 // the Channel ID. It should fail.
3216 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
3217 SpawnedTestServer::SSLOptions ssl_options
;
3219 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3221 EnableAsyncFailingChannelID();
3222 SSLConfig ssl_config
;
3223 ssl_config
.channel_id_enabled
= true;
3226 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3228 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
3229 EXPECT_FALSE(sock_
->IsConnected());