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 int pending_read_result() const { return pending_read_result_
; }
352 IOBuffer
* pending_read_buf() const { return pending_read_buf_
.get(); }
354 // Blocks read results on the socket. Reads will not complete until
355 // UnblockReadResult() has been called and a result is ready from the
356 // underlying transport. Note: if BlockReadResult() is called while there is a
357 // hanging asynchronous Read(), that Read is blocked.
358 void BlockReadResult();
359 void UnblockReadResult();
361 // Waits for the blocked Read() call to be complete at the underlying
363 void WaitForReadResult();
365 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
366 // underlying transport until UnblockWrite() has been called. Note: if there
367 // is a pending asynchronous write, it is NOT blocked. For purposes of
368 // blocking writes, data is considered to have reached the underlying
369 // transport as soon as Write() is called.
373 // Waits for the blocked Write() call to be scheduled.
377 // Handles completion from the underlying transport read.
378 void OnReadCompleted(int result
);
380 // True if read callbacks are blocked.
381 bool should_block_read_
;
383 // The buffer for the pending read, or NULL if not consumed.
384 scoped_refptr
<IOBuffer
> pending_read_buf_
;
386 // The user callback for the pending read call.
387 CompletionCallback pending_read_callback_
;
389 // The result for the blocked read callback, or ERR_IO_PENDING if not
391 int pending_read_result_
;
393 // WaitForReadResult() wait loop.
394 scoped_ptr
<base::RunLoop
> read_loop_
;
396 // True if write calls are blocked.
397 bool should_block_write_
;
399 // The buffer for the pending write, or NULL if not scheduled.
400 scoped_refptr
<IOBuffer
> pending_write_buf_
;
402 // The callback for the pending write call.
403 CompletionCallback pending_write_callback_
;
405 // The length for the pending write, or -1 if not scheduled.
406 int pending_write_len_
;
408 // WaitForWrite() wait loop.
409 scoped_ptr
<base::RunLoop
> write_loop_
;
412 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
413 scoped_ptr
<StreamSocket
> transport
)
414 : WrappedStreamSocket(transport
.Pass()),
415 should_block_read_(false),
416 pending_read_result_(ERR_IO_PENDING
),
417 should_block_write_(false),
418 pending_write_len_(-1) {}
420 int FakeBlockingStreamSocket::Read(IOBuffer
* buf
,
422 const CompletionCallback
& callback
) {
423 DCHECK(!pending_read_buf_
);
424 DCHECK(pending_read_callback_
.is_null());
425 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
426 DCHECK(!callback
.is_null());
428 int rv
= transport_
->Read(buf
, len
, base::Bind(
429 &FakeBlockingStreamSocket::OnReadCompleted
, base::Unretained(this)));
430 if (rv
== ERR_IO_PENDING
) {
431 // Save the callback to be called later.
432 pending_read_buf_
= buf
;
433 pending_read_callback_
= callback
;
434 } else if (should_block_read_
) {
435 // Save the callback and read result to be called later.
436 pending_read_buf_
= buf
;
437 pending_read_callback_
= callback
;
444 int FakeBlockingStreamSocket::Write(IOBuffer
* buf
,
446 const CompletionCallback
& callback
) {
450 if (!should_block_write_
)
451 return transport_
->Write(buf
, len
, callback
);
453 // Schedule the write, but do nothing.
454 DCHECK(!pending_write_buf_
.get());
455 DCHECK_EQ(-1, pending_write_len_
);
456 DCHECK(pending_write_callback_
.is_null());
457 DCHECK(!callback
.is_null());
458 pending_write_buf_
= buf
;
459 pending_write_len_
= len
;
460 pending_write_callback_
= callback
;
462 // Stop the write loop, if any.
465 return ERR_IO_PENDING
;
468 void FakeBlockingStreamSocket::BlockReadResult() {
469 DCHECK(!should_block_read_
);
470 should_block_read_
= true;
473 void FakeBlockingStreamSocket::UnblockReadResult() {
474 DCHECK(should_block_read_
);
475 should_block_read_
= false;
477 // If the operation is still pending in the underlying transport, immediately
478 // return - OnReadCompleted() will handle invoking the callback once the
479 // transport has completed.
480 if (pending_read_result_
== ERR_IO_PENDING
)
482 int result
= pending_read_result_
;
483 pending_read_buf_
= nullptr;
484 pending_read_result_
= ERR_IO_PENDING
;
485 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
488 void FakeBlockingStreamSocket::WaitForReadResult() {
489 DCHECK(should_block_read_
);
492 if (pending_read_result_
!= ERR_IO_PENDING
)
494 read_loop_
.reset(new base::RunLoop
);
497 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
500 void FakeBlockingStreamSocket::BlockWrite() {
501 DCHECK(!should_block_write_
);
502 should_block_write_
= true;
505 void FakeBlockingStreamSocket::UnblockWrite() {
506 DCHECK(should_block_write_
);
507 should_block_write_
= false;
509 // Do nothing if UnblockWrite() was called after BlockWrite(),
510 // without a Write() in between.
511 if (!pending_write_buf_
.get())
514 int rv
= transport_
->Write(
515 pending_write_buf_
.get(), pending_write_len_
, pending_write_callback_
);
516 pending_write_buf_
= NULL
;
517 pending_write_len_
= -1;
518 if (rv
== ERR_IO_PENDING
) {
519 pending_write_callback_
.Reset();
521 base::ResetAndReturn(&pending_write_callback_
).Run(rv
);
525 void FakeBlockingStreamSocket::WaitForWrite() {
526 DCHECK(should_block_write_
);
527 DCHECK(!write_loop_
);
529 if (pending_write_buf_
.get())
531 write_loop_
.reset(new base::RunLoop
);
534 DCHECK(pending_write_buf_
.get());
537 void FakeBlockingStreamSocket::OnReadCompleted(int result
) {
538 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
539 DCHECK(!pending_read_callback_
.is_null());
541 if (should_block_read_
) {
542 // Store the result so that the callback can be invoked once Unblock() is
544 pending_read_result_
= result
;
546 // Stop the WaitForReadResult() call if any.
550 // Either the Read() was never blocked or UnblockReadResult() was called
551 // before the Read() completed. Either way, return the result to the caller.
552 pending_read_buf_
= nullptr;
553 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
557 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
558 // reads and writes on the socket.
559 class CountingStreamSocket
: public WrappedStreamSocket
{
561 explicit CountingStreamSocket(scoped_ptr
<StreamSocket
> transport
)
562 : WrappedStreamSocket(transport
.Pass()),
565 ~CountingStreamSocket() override
{}
567 // Socket implementation:
568 int Read(IOBuffer
* buf
,
570 const CompletionCallback
& callback
) override
{
572 return transport_
->Read(buf
, buf_len
, callback
);
574 int Write(IOBuffer
* buf
,
576 const CompletionCallback
& callback
) override
{
578 return transport_
->Write(buf
, buf_len
, callback
);
581 int read_count() const { return read_count_
; }
582 int write_count() const { return write_count_
; }
589 // CompletionCallback that will delete the associated StreamSocket when
590 // the callback is invoked.
591 class DeleteSocketCallback
: public TestCompletionCallbackBase
{
593 explicit DeleteSocketCallback(StreamSocket
* socket
)
595 callback_(base::Bind(&DeleteSocketCallback::OnComplete
,
596 base::Unretained(this))) {}
597 ~DeleteSocketCallback() override
{}
599 const CompletionCallback
& callback() const { return callback_
; }
602 void OnComplete(int result
) {
607 ADD_FAILURE() << "Deleting socket twice";
612 StreamSocket
* socket_
;
613 CompletionCallback callback_
;
615 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback
);
618 // A ChannelIDStore that always returns an error when asked for a
620 class FailingChannelIDStore
: public ChannelIDStore
{
621 int GetChannelID(const std::string
& server_identifier
,
622 base::Time
* expiration_time
,
623 std::string
* private_key_result
,
624 std::string
* cert_result
,
625 const GetChannelIDCallback
& callback
) override
{
626 return ERR_UNEXPECTED
;
628 void SetChannelID(const std::string
& server_identifier
,
629 base::Time creation_time
,
630 base::Time expiration_time
,
631 const std::string
& private_key
,
632 const std::string
& cert
) override
{}
633 void DeleteChannelID(const std::string
& server_identifier
,
634 const base::Closure
& completion_callback
) override
{}
635 void DeleteAllCreatedBetween(
636 base::Time delete_begin
,
637 base::Time delete_end
,
638 const base::Closure
& completion_callback
) override
{}
639 void DeleteAll(const base::Closure
& completion_callback
) override
{}
640 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
641 int GetChannelIDCount() override
{ return 0; }
642 void SetForceKeepSessionState() override
{}
645 // A ChannelIDStore that asynchronously returns an error when asked for a
647 class AsyncFailingChannelIDStore
: public ChannelIDStore
{
648 int GetChannelID(const std::string
& server_identifier
,
649 base::Time
* expiration_time
,
650 std::string
* private_key_result
,
651 std::string
* cert_result
,
652 const GetChannelIDCallback
& callback
) override
{
653 base::MessageLoop::current()->PostTask(
654 FROM_HERE
, base::Bind(callback
, ERR_UNEXPECTED
,
655 server_identifier
, base::Time(), "", ""));
656 return ERR_IO_PENDING
;
658 void SetChannelID(const std::string
& server_identifier
,
659 base::Time creation_time
,
660 base::Time expiration_time
,
661 const std::string
& private_key
,
662 const std::string
& cert
) override
{}
663 void DeleteChannelID(const std::string
& server_identifier
,
664 const base::Closure
& completion_callback
) override
{}
665 void DeleteAllCreatedBetween(
666 base::Time delete_begin
,
667 base::Time delete_end
,
668 const base::Closure
& completion_callback
) override
{}
669 void DeleteAll(const base::Closure
& completion_callback
) override
{}
670 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
671 int GetChannelIDCount() override
{ return 0; }
672 void SetForceKeepSessionState() override
{}
675 // A mock CTVerifier that records every call to Verify but doesn't verify
677 class MockCTVerifier
: public CTVerifier
{
679 MOCK_METHOD5(Verify
, int(X509Certificate
*,
683 const BoundNetLog
&));
686 class SSLClientSocketTest
: public PlatformTest
{
688 SSLClientSocketTest()
689 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
690 cert_verifier_(new MockCertVerifier
),
691 transport_security_state_(new TransportSecurityState
) {
692 cert_verifier_
->set_default_result(OK
);
693 context_
.cert_verifier
= cert_verifier_
.get();
694 context_
.transport_security_state
= transport_security_state_
.get();
698 // The address of the spawned test server, after calling StartTestServer().
699 const AddressList
& addr() const { return addr_
; }
701 // The SpawnedTestServer object, after calling StartTestServer().
702 const SpawnedTestServer
* test_server() const { return test_server_
.get(); }
704 void SetCTVerifier(CTVerifier
* ct_verifier
) {
705 context_
.cert_transparency_verifier
= ct_verifier
;
708 // Starts the test server with SSL configuration |ssl_options|. Returns true
710 bool StartTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
711 test_server_
.reset(new SpawnedTestServer(
712 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath()));
713 if (!test_server_
->Start()) {
714 LOG(ERROR
) << "Could not start SpawnedTestServer";
718 if (!test_server_
->GetAddressList(&addr_
)) {
719 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
725 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
726 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
727 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
728 if (!StartTestServer(ssl_options
))
731 transport_
.reset(new TCPClientSocket(addr_
, &log_
, NetLog::Source()));
732 int rv
= callback_
.GetResult(transport_
->Connect(callback_
.callback()));
734 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
740 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
741 scoped_ptr
<StreamSocket
> transport_socket
,
742 const HostPortPair
& host_and_port
,
743 const SSLConfig
& ssl_config
) {
744 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
745 connection
->SetSocket(transport_socket
.Pass());
746 return socket_factory_
->CreateSSLClientSocket(
747 connection
.Pass(), host_and_port
, ssl_config
, context_
);
750 // Create an SSLClientSocket object and use it to connect to a test
751 // server, then wait for connection results. This must be called after
752 // a successful ConnectToTestServer() call.
753 // |ssl_config| the SSL configuration to use.
754 // |result| will retrieve the ::Connect() result value.
755 // Returns true on success, false otherwise. Success means that the socket
756 // could be created and its Connect() was called, not that the connection
757 // itself was a success.
758 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
, int* result
) {
759 sock_
= CreateSSLClientSocket(
760 transport_
.Pass(), test_server_
->host_port_pair(), ssl_config
);
762 if (sock_
->IsConnected()) {
763 LOG(ERROR
) << "SSL Socket prematurely connected";
767 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
771 ClientSocketFactory
* socket_factory_
;
772 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
773 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
774 SSLClientSocketContext context_
;
775 scoped_ptr
<SSLClientSocket
> sock_
;
779 scoped_ptr
<StreamSocket
> transport_
;
780 scoped_ptr
<SpawnedTestServer
> test_server_
;
781 TestCompletionCallback callback_
;
785 // Verifies the correctness of GetSSLCertRequestInfo.
786 class SSLClientSocketCertRequestInfoTest
: public SSLClientSocketTest
{
788 // Creates a test server with the given SSLOptions, connects to it and returns
789 // the SSLCertRequestInfo reported by the socket.
790 scoped_refptr
<SSLCertRequestInfo
> GetCertRequest(
791 SpawnedTestServer::SSLOptions ssl_options
) {
792 SpawnedTestServer
test_server(
793 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
794 if (!test_server
.Start())
798 if (!test_server
.GetAddressList(&addr
))
801 TestCompletionCallback callback
;
803 scoped_ptr
<StreamSocket
> transport(
804 new TCPClientSocket(addr
, &log
, NetLog::Source()));
805 int rv
= transport
->Connect(callback
.callback());
806 if (rv
== ERR_IO_PENDING
)
807 rv
= callback
.WaitForResult();
810 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
811 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
812 EXPECT_FALSE(sock
->IsConnected());
814 rv
= sock
->Connect(callback
.callback());
815 if (rv
== ERR_IO_PENDING
)
816 rv
= callback
.WaitForResult();
817 scoped_refptr
<SSLCertRequestInfo
> request_info
= new SSLCertRequestInfo();
818 sock
->GetSSLCertRequestInfo(request_info
.get());
820 EXPECT_FALSE(sock
->IsConnected());
822 test_server
.host_port_pair().Equals(request_info
->host_and_port
));
828 class SSLClientSocketFalseStartTest
: public SSLClientSocketTest
{
830 // Creates an SSLClientSocket with |client_config| attached to a
831 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
832 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
833 // so |*out_raw_transport| is a raw pointer.
835 // The client socket will begin a connect using |callback| but stop before the
836 // server's finished message is received. The finished message will be blocked
837 // in |*out_raw_transport|. To complete the handshake and successfully read
838 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
839 // the client successfully false started, |callback.WaitForResult()| will
840 // return OK without unblocking transport reads. But Read() will still block.)
842 // Must be called after StartTestServer is called.
843 void CreateAndConnectUntilServerFinishedReceived(
844 const SSLConfig
& client_config
,
845 TestCompletionCallback
* callback
,
846 FakeBlockingStreamSocket
** out_raw_transport
,
847 scoped_ptr
<SSLClientSocket
>* out_sock
) {
848 CHECK(test_server());
850 scoped_ptr
<StreamSocket
> real_transport(
851 new TCPClientSocket(addr(), NULL
, NetLog::Source()));
852 scoped_ptr
<FakeBlockingStreamSocket
> transport(
853 new FakeBlockingStreamSocket(real_transport
.Pass()));
854 int rv
= callback
->GetResult(transport
->Connect(callback
->callback()));
857 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
858 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
859 transport
.Pass(), test_server()->host_port_pair(), client_config
);
861 // Connect. Stop before the client processes the first server leg
862 // (ServerHello, etc.)
863 raw_transport
->BlockReadResult();
864 rv
= sock
->Connect(callback
->callback());
865 EXPECT_EQ(ERR_IO_PENDING
, rv
);
866 raw_transport
->WaitForReadResult();
868 // Release the ServerHello and wait for the client to write
869 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
870 // server's leg to complete, since it may span multiple reads.)
871 EXPECT_FALSE(callback
->have_result());
872 raw_transport
->BlockWrite();
873 raw_transport
->UnblockReadResult();
874 raw_transport
->WaitForWrite();
876 // And, finally, release that and block the next server leg
877 // (ChangeCipherSpec, Finished).
878 raw_transport
->BlockReadResult();
879 raw_transport
->UnblockWrite();
881 *out_raw_transport
= raw_transport
;
882 *out_sock
= sock
.Pass();
885 void TestFalseStart(const SpawnedTestServer::SSLOptions
& server_options
,
886 const SSLConfig
& client_config
,
887 bool expect_false_start
) {
888 ASSERT_TRUE(StartTestServer(server_options
));
890 TestCompletionCallback callback
;
891 FakeBlockingStreamSocket
* raw_transport
= NULL
;
892 scoped_ptr
<SSLClientSocket
> sock
;
893 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
894 client_config
, &callback
, &raw_transport
, &sock
));
896 if (expect_false_start
) {
897 // When False Starting, the handshake should complete before receiving the
898 // Change Cipher Spec and Finished messages.
900 // Note: callback.have_result() may not be true without waiting. The NSS
901 // state machine sometimes lives on a separate thread, so this thread may
902 // not yet have processed the signal that the handshake has completed.
903 int rv
= callback
.WaitForResult();
905 EXPECT_TRUE(sock
->IsConnected());
907 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
908 static const int kRequestTextSize
=
909 static_cast<int>(arraysize(request_text
) - 1);
910 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
911 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
913 // Write the request.
914 rv
= callback
.GetResult(sock
->Write(request_buffer
.get(),
916 callback
.callback()));
917 EXPECT_EQ(kRequestTextSize
, rv
);
919 // The read will hang; it's waiting for the peer to complete the
920 // handshake, and the handshake is still blocked.
921 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
922 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
924 // After releasing reads, the connection proceeds.
925 raw_transport
->UnblockReadResult();
926 rv
= callback
.GetResult(rv
);
929 // False Start is not enabled, so the handshake will not complete because
930 // the server second leg is blocked.
931 base::RunLoop().RunUntilIdle();
932 EXPECT_FALSE(callback
.have_result());
937 class SSLClientSocketChannelIDTest
: public SSLClientSocketTest
{
939 void EnableChannelID() {
940 channel_id_service_
.reset(
941 new ChannelIDService(new DefaultChannelIDStore(NULL
),
942 base::MessageLoopProxy::current()));
943 context_
.channel_id_service
= channel_id_service_
.get();
946 void EnableFailingChannelID() {
947 channel_id_service_
.reset(new ChannelIDService(
948 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
949 context_
.channel_id_service
= channel_id_service_
.get();
952 void EnableAsyncFailingChannelID() {
953 channel_id_service_
.reset(new ChannelIDService(
954 new AsyncFailingChannelIDStore(),
955 base::MessageLoopProxy::current()));
956 context_
.channel_id_service
= channel_id_service_
.get();
960 scoped_ptr
<ChannelIDService
> channel_id_service_
;
963 //-----------------------------------------------------------------------------
965 // LogContainsSSLConnectEndEvent returns true if the given index in the given
966 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
967 // merge the first application data record with the Finished message when false
968 // starting. However, in order to avoid the server timing out the handshake,
969 // they'll give up waiting for application data and send the Finished after a
970 // timeout. This means that an SSL connect end event may appear as a socket
972 static bool LogContainsSSLConnectEndEvent(
973 const TestNetLog::CapturedEntryList
& log
,
975 return LogContainsEndEvent(log
, i
, NetLog::TYPE_SSL_CONNECT
) ||
977 log
, i
, NetLog::TYPE_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
980 bool SupportsAESGCM() {
981 #if defined(USE_OPENSSL)
984 crypto::EnsureNSSInit();
985 return PK11_TokenExists(CKM_AES_GCM
) &&
986 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
);
992 TEST_F(SSLClientSocketTest
, Connect
) {
993 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
994 SpawnedTestServer::kLocalhost
,
996 ASSERT_TRUE(test_server
.Start());
999 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1001 TestCompletionCallback callback
;
1003 scoped_ptr
<StreamSocket
> transport(
1004 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1005 int rv
= transport
->Connect(callback
.callback());
1006 if (rv
== ERR_IO_PENDING
)
1007 rv
= callback
.WaitForResult();
1010 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1011 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1013 EXPECT_FALSE(sock
->IsConnected());
1015 rv
= sock
->Connect(callback
.callback());
1017 TestNetLog::CapturedEntryList entries
;
1018 log
.GetEntries(&entries
);
1019 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1020 if (rv
== ERR_IO_PENDING
)
1021 rv
= callback
.WaitForResult();
1023 EXPECT_TRUE(sock
->IsConnected());
1024 log
.GetEntries(&entries
);
1025 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1028 EXPECT_FALSE(sock
->IsConnected());
1031 TEST_F(SSLClientSocketTest
, ConnectExpired
) {
1032 SpawnedTestServer::SSLOptions
ssl_options(
1033 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
1034 SpawnedTestServer
test_server(
1035 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1036 ASSERT_TRUE(test_server
.Start());
1038 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
1041 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1043 TestCompletionCallback callback
;
1045 scoped_ptr
<StreamSocket
> transport(
1046 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1047 int rv
= transport
->Connect(callback
.callback());
1048 if (rv
== ERR_IO_PENDING
)
1049 rv
= callback
.WaitForResult();
1052 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1053 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1055 EXPECT_FALSE(sock
->IsConnected());
1057 rv
= sock
->Connect(callback
.callback());
1059 TestNetLog::CapturedEntryList entries
;
1060 log
.GetEntries(&entries
);
1061 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1062 if (rv
== ERR_IO_PENDING
)
1063 rv
= callback
.WaitForResult();
1065 EXPECT_EQ(ERR_CERT_DATE_INVALID
, rv
);
1067 // Rather than testing whether or not the underlying socket is connected,
1068 // test that the handshake has finished. This is because it may be
1069 // desirable to disconnect the socket before showing a user prompt, since
1070 // the user may take indefinitely long to respond.
1071 log
.GetEntries(&entries
);
1072 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1075 TEST_F(SSLClientSocketTest
, ConnectMismatched
) {
1076 SpawnedTestServer::SSLOptions
ssl_options(
1077 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
1078 SpawnedTestServer
test_server(
1079 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1080 ASSERT_TRUE(test_server
.Start());
1082 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
1085 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1087 TestCompletionCallback callback
;
1089 scoped_ptr
<StreamSocket
> transport(
1090 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1091 int rv
= transport
->Connect(callback
.callback());
1092 if (rv
== ERR_IO_PENDING
)
1093 rv
= callback
.WaitForResult();
1096 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1097 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1099 EXPECT_FALSE(sock
->IsConnected());
1101 rv
= sock
->Connect(callback
.callback());
1103 TestNetLog::CapturedEntryList entries
;
1104 log
.GetEntries(&entries
);
1105 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1106 if (rv
== ERR_IO_PENDING
)
1107 rv
= callback
.WaitForResult();
1109 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
, rv
);
1111 // Rather than testing whether or not the underlying socket is connected,
1112 // test that the handshake has finished. This is because it may be
1113 // desirable to disconnect the socket before showing a user prompt, since
1114 // the user may take indefinitely long to respond.
1115 log
.GetEntries(&entries
);
1116 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1119 // Attempt to connect to a page which requests a client certificate. It should
1120 // return an error code on connect.
1121 TEST_F(SSLClientSocketTest
, ConnectClientAuthCertRequested
) {
1122 SpawnedTestServer::SSLOptions ssl_options
;
1123 ssl_options
.request_client_certificate
= true;
1124 SpawnedTestServer
test_server(
1125 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1126 ASSERT_TRUE(test_server
.Start());
1129 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1131 TestCompletionCallback callback
;
1133 scoped_ptr
<StreamSocket
> transport(
1134 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1135 int rv
= transport
->Connect(callback
.callback());
1136 if (rv
== ERR_IO_PENDING
)
1137 rv
= callback
.WaitForResult();
1140 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1141 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1143 EXPECT_FALSE(sock
->IsConnected());
1145 rv
= sock
->Connect(callback
.callback());
1147 TestNetLog::CapturedEntryList entries
;
1148 log
.GetEntries(&entries
);
1149 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1150 if (rv
== ERR_IO_PENDING
)
1151 rv
= callback
.WaitForResult();
1153 log
.GetEntries(&entries
);
1154 // Because we prematurely kill the handshake at CertificateRequest,
1155 // the server may still send data (notably the ServerHelloDone)
1156 // after the error is returned. As a result, the SSL_CONNECT may not
1157 // be the last entry. See http://crbug.com/54445. We use
1158 // ExpectLogContainsSomewhere instead of
1159 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1160 // extra read instead of two. This occurs before the handshake ends,
1161 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1164 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1165 // fixed and we can respond to the first CertificateRequest
1166 // without closing the socket, add a unit test for sending the
1167 // certificate. This test may still be useful as we'll want to close
1168 // the socket on a timeout if the user takes a long time to pick a
1169 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1170 ExpectLogContainsSomewhere(
1171 entries
, 0, NetLog::TYPE_SSL_CONNECT
, NetLog::PHASE_END
);
1172 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
1173 EXPECT_FALSE(sock
->IsConnected());
1176 // Connect to a server requesting optional client authentication. Send it a
1177 // null certificate. It should allow the connection.
1179 // TODO(davidben): Also test providing an actual certificate.
1180 TEST_F(SSLClientSocketTest
, ConnectClientAuthSendNullCert
) {
1181 SpawnedTestServer::SSLOptions ssl_options
;
1182 ssl_options
.request_client_certificate
= true;
1183 SpawnedTestServer
test_server(
1184 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1185 ASSERT_TRUE(test_server
.Start());
1188 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1190 TestCompletionCallback callback
;
1192 scoped_ptr
<StreamSocket
> transport(
1193 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1194 int rv
= transport
->Connect(callback
.callback());
1195 if (rv
== ERR_IO_PENDING
)
1196 rv
= callback
.WaitForResult();
1199 SSLConfig ssl_config
;
1200 ssl_config
.send_client_cert
= true;
1201 ssl_config
.client_cert
= NULL
;
1203 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1204 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1206 EXPECT_FALSE(sock
->IsConnected());
1208 // Our test server accepts certificate-less connections.
1209 // TODO(davidben): Add a test which requires them and verify the error.
1210 rv
= sock
->Connect(callback
.callback());
1212 TestNetLog::CapturedEntryList entries
;
1213 log
.GetEntries(&entries
);
1214 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1215 if (rv
== ERR_IO_PENDING
)
1216 rv
= callback
.WaitForResult();
1219 EXPECT_TRUE(sock
->IsConnected());
1220 log
.GetEntries(&entries
);
1221 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
1223 // We responded to the server's certificate request with a Certificate
1224 // message with no client certificate in it. ssl_info.client_cert_sent
1225 // should be false in this case.
1227 sock
->GetSSLInfo(&ssl_info
);
1228 EXPECT_FALSE(ssl_info
.client_cert_sent
);
1231 EXPECT_FALSE(sock
->IsConnected());
1234 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1235 // - Server closes an SSL connection (with a close_notify alert message).
1236 // - Server closes the underlying TCP connection directly.
1237 // - Server sends data unexpectedly.
1239 // Tests that the socket can be read from successfully. Also test that a peer's
1240 // close_notify alert is successfully processed without error.
1241 TEST_F(SSLClientSocketTest
, Read
) {
1242 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1243 SpawnedTestServer::kLocalhost
,
1245 ASSERT_TRUE(test_server
.Start());
1248 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1250 TestCompletionCallback callback
;
1251 scoped_ptr
<StreamSocket
> transport(
1252 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1253 int rv
= transport
->Connect(callback
.callback());
1254 if (rv
== ERR_IO_PENDING
)
1255 rv
= callback
.WaitForResult();
1258 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1259 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1261 rv
= sock
->Connect(callback
.callback());
1262 if (rv
== ERR_IO_PENDING
)
1263 rv
= callback
.WaitForResult();
1265 EXPECT_TRUE(sock
->IsConnected());
1267 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1268 scoped_refptr
<IOBuffer
> request_buffer(
1269 new IOBuffer(arraysize(request_text
) - 1));
1270 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1273 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1274 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1276 if (rv
== ERR_IO_PENDING
)
1277 rv
= callback
.WaitForResult();
1278 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1280 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1282 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1283 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1285 if (rv
== ERR_IO_PENDING
)
1286 rv
= callback
.WaitForResult();
1293 // The peer should have cleanly closed the connection with a close_notify.
1297 // Tests that SSLClientSocket properly handles when the underlying transport
1298 // synchronously fails a transport read in during the handshake. The error code
1299 // should be preserved so SSLv3 fallback logic can condition on it.
1300 TEST_F(SSLClientSocketTest
, Connect_WithSynchronousError
) {
1301 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1302 SpawnedTestServer::kLocalhost
,
1304 ASSERT_TRUE(test_server
.Start());
1307 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1309 TestCompletionCallback callback
;
1310 scoped_ptr
<StreamSocket
> real_transport(
1311 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1312 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1313 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1314 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1317 // Disable TLS False Start to avoid handshake non-determinism.
1318 SSLConfig ssl_config
;
1319 ssl_config
.false_start_enabled
= false;
1321 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1322 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1323 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1325 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
1327 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1328 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1329 EXPECT_FALSE(sock
->IsConnected());
1332 // Tests that the SSLClientSocket properly handles when the underlying transport
1333 // synchronously returns an error code - such as if an intermediary terminates
1334 // the socket connection uncleanly.
1335 // This is a regression test for http://crbug.com/238536
1336 TEST_F(SSLClientSocketTest
, Read_WithSynchronousError
) {
1337 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1338 SpawnedTestServer::kLocalhost
,
1340 ASSERT_TRUE(test_server
.Start());
1343 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1345 TestCompletionCallback callback
;
1346 scoped_ptr
<StreamSocket
> real_transport(
1347 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1348 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1349 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1350 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1353 // Disable TLS False Start to avoid handshake non-determinism.
1354 SSLConfig ssl_config
;
1355 ssl_config
.false_start_enabled
= false;
1357 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1358 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1359 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1361 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1363 EXPECT_TRUE(sock
->IsConnected());
1365 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1366 static const int kRequestTextSize
=
1367 static_cast<int>(arraysize(request_text
) - 1);
1368 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1369 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1371 rv
= callback
.GetResult(
1372 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1373 EXPECT_EQ(kRequestTextSize
, rv
);
1375 // Simulate an unclean/forcible shutdown.
1376 raw_transport
->SetNextReadError(ERR_CONNECTION_RESET
);
1378 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1380 // Note: This test will hang if this bug has regressed. Simply checking that
1381 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1382 // result when using a dedicated task runner for NSS.
1383 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1384 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1387 // Tests that the SSLClientSocket properly handles when the underlying transport
1388 // asynchronously returns an error code while writing data - such as if an
1389 // intermediary terminates the socket connection uncleanly.
1390 // This is a regression test for http://crbug.com/249848
1391 TEST_F(SSLClientSocketTest
, Write_WithSynchronousError
) {
1392 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1393 SpawnedTestServer::kLocalhost
,
1395 ASSERT_TRUE(test_server
.Start());
1398 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1400 TestCompletionCallback callback
;
1401 scoped_ptr
<StreamSocket
> real_transport(
1402 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1403 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1404 // is retained in order to configure additional errors.
1405 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1406 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1407 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1408 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1409 new FakeBlockingStreamSocket(error_socket
.Pass()));
1410 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1411 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1414 // Disable TLS False Start to avoid handshake non-determinism.
1415 SSLConfig ssl_config
;
1416 ssl_config
.false_start_enabled
= false;
1418 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1419 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1421 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1423 EXPECT_TRUE(sock
->IsConnected());
1425 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1426 static const int kRequestTextSize
=
1427 static_cast<int>(arraysize(request_text
) - 1);
1428 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1429 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1431 // Simulate an unclean/forcible shutdown on the underlying socket.
1432 // However, simulate this error asynchronously.
1433 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1434 raw_transport
->BlockWrite();
1436 // This write should complete synchronously, because the TLS ciphertext
1437 // can be created and placed into the outgoing buffers independent of the
1438 // underlying transport.
1439 rv
= callback
.GetResult(
1440 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1441 EXPECT_EQ(kRequestTextSize
, rv
);
1443 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1445 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1446 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1448 // Now unblock the outgoing request, having it fail with the connection
1450 raw_transport
->UnblockWrite();
1452 // Note: This will cause an inifite loop if this bug has regressed. Simply
1453 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1454 // is a legitimate result when using a dedicated task runner for NSS.
1455 rv
= callback
.GetResult(rv
);
1456 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1459 // If there is a Write failure at the transport with no follow-up Read, although
1460 // the write error will not be returned to the client until a future Read or
1461 // Write operation, SSLClientSocket should not spin attempting to re-write on
1462 // the socket. This is a regression test for part of https://crbug.com/381160.
1463 TEST_F(SSLClientSocketTest
, Write_WithSynchronousErrorNoRead
) {
1464 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1465 SpawnedTestServer::kLocalhost
,
1467 ASSERT_TRUE(test_server
.Start());
1470 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1472 TestCompletionCallback callback
;
1473 scoped_ptr
<StreamSocket
> real_transport(
1474 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1475 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1476 // is retained in order to query them.
1477 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1478 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1479 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1480 scoped_ptr
<CountingStreamSocket
> counting_socket(
1481 new CountingStreamSocket(error_socket
.Pass()));
1482 CountingStreamSocket
* raw_counting_socket
= counting_socket
.get();
1483 int rv
= callback
.GetResult(counting_socket
->Connect(callback
.callback()));
1486 // Disable TLS False Start to avoid handshake non-determinism.
1487 SSLConfig ssl_config
;
1488 ssl_config
.false_start_enabled
= false;
1490 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1491 counting_socket
.Pass(), test_server
.host_port_pair(), ssl_config
));
1493 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1495 ASSERT_TRUE(sock
->IsConnected());
1497 // Simulate an unclean/forcible shutdown on the underlying socket.
1498 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1500 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1501 static const int kRequestTextSize
=
1502 static_cast<int>(arraysize(request_text
) - 1);
1503 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1504 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1506 // This write should complete synchronously, because the TLS ciphertext
1507 // can be created and placed into the outgoing buffers independent of the
1508 // underlying transport.
1509 rv
= callback
.GetResult(
1510 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1511 ASSERT_EQ(kRequestTextSize
, rv
);
1513 // Let the event loop spin for a little bit of time. Even on platforms where
1514 // pumping the state machine involve thread hops, there should be no further
1515 // writes on the transport socket.
1517 // TODO(davidben): Avoid the arbitrary timeout?
1518 int old_write_count
= raw_counting_socket
->write_count();
1520 base::MessageLoop::current()->PostDelayedTask(
1521 FROM_HERE
, loop
.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1523 EXPECT_EQ(old_write_count
, raw_counting_socket
->write_count());
1526 // Test the full duplex mode, with Read and Write pending at the same time.
1527 // This test also serves as a regression test for http://crbug.com/29815.
1528 TEST_F(SSLClientSocketTest
, Read_FullDuplex
) {
1529 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1530 SpawnedTestServer::kLocalhost
,
1532 ASSERT_TRUE(test_server
.Start());
1535 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1537 TestCompletionCallback callback
; // Used for everything except Write.
1539 scoped_ptr
<StreamSocket
> transport(
1540 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1541 int rv
= transport
->Connect(callback
.callback());
1542 if (rv
== ERR_IO_PENDING
)
1543 rv
= callback
.WaitForResult();
1546 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1547 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1549 rv
= sock
->Connect(callback
.callback());
1550 if (rv
== ERR_IO_PENDING
)
1551 rv
= callback
.WaitForResult();
1553 EXPECT_TRUE(sock
->IsConnected());
1555 // Issue a "hanging" Read first.
1556 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1557 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1558 // We haven't written the request, so there should be no response yet.
1559 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1561 // Write the request.
1562 // The request is padded with a User-Agent header to a size that causes the
1563 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1564 // This tests the fix for http://crbug.com/29815.
1565 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1566 for (int i
= 0; i
< 3770; ++i
)
1567 request_text
.push_back('*');
1568 request_text
.append("\r\n\r\n");
1569 scoped_refptr
<IOBuffer
> request_buffer(new StringIOBuffer(request_text
));
1571 TestCompletionCallback callback2
; // Used for Write only.
1573 request_buffer
.get(), request_text
.size(), callback2
.callback());
1574 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1576 if (rv
== ERR_IO_PENDING
)
1577 rv
= callback2
.WaitForResult();
1578 EXPECT_EQ(static_cast<int>(request_text
.size()), rv
);
1580 // Now get the Read result.
1581 rv
= callback
.WaitForResult();
1585 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1586 // mode when the underlying transport is blocked on sending data. When the
1587 // underlying transport completes due to an error, it should invoke both the
1588 // Read() and Write() callbacks. If the socket is deleted by the Read()
1589 // callback, the Write() callback should not be invoked.
1590 // Regression test for http://crbug.com/232633
1591 TEST_F(SSLClientSocketTest
, Read_DeleteWhilePendingFullDuplex
) {
1592 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1593 SpawnedTestServer::kLocalhost
,
1595 ASSERT_TRUE(test_server
.Start());
1598 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1600 TestCompletionCallback callback
;
1601 scoped_ptr
<StreamSocket
> real_transport(
1602 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1603 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1604 // is retained in order to configure additional errors.
1605 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1606 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1607 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1608 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1609 new FakeBlockingStreamSocket(error_socket
.Pass()));
1610 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1612 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1615 // Disable TLS False Start to avoid handshake non-determinism.
1616 SSLConfig ssl_config
;
1617 ssl_config
.false_start_enabled
= false;
1619 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
1620 transport
.Pass(), test_server
.host_port_pair(), ssl_config
);
1622 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1624 EXPECT_TRUE(sock
->IsConnected());
1626 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1627 request_text
.append(20 * 1024, '*');
1628 request_text
.append("\r\n\r\n");
1629 scoped_refptr
<DrainableIOBuffer
> request_buffer(new DrainableIOBuffer(
1630 new StringIOBuffer(request_text
), request_text
.size()));
1632 // Simulate errors being returned from the underlying Read() and Write() ...
1633 raw_error_socket
->SetNextReadError(ERR_CONNECTION_RESET
);
1634 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1635 // ... but have those errors returned asynchronously. Because the Write() will
1636 // return first, this will trigger the error.
1637 raw_transport
->BlockReadResult();
1638 raw_transport
->BlockWrite();
1640 // Enqueue a Read() before calling Write(), which should "hang" due to
1641 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1642 SSLClientSocket
* raw_sock
= sock
.get();
1643 DeleteSocketCallback
read_callback(sock
.release());
1644 scoped_refptr
<IOBuffer
> read_buf(new IOBuffer(4096));
1645 rv
= raw_sock
->Read(read_buf
.get(), 4096, read_callback
.callback());
1647 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1648 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1649 ASSERT_FALSE(read_callback
.have_result());
1651 #if !defined(USE_OPENSSL)
1652 // NSS follows a pattern where a call to PR_Write will only consume as
1653 // much data as it can encode into application data records before the
1654 // internal memio buffer is full, which should only fill if writing a large
1655 // amount of data and the underlying transport is blocked. Once this happens,
1656 // NSS will return (total size of all application data records it wrote) - 1,
1657 // with the caller expected to resume with the remaining unsent data.
1659 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1660 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1661 // get the socket in the state needed for the test below.
1663 // This is not needed for OpenSSL, because for OpenSSL,
1664 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1665 // SSLClientSocketOpenSSL::Write() will not return until all of
1666 // |request_buffer| has been written to the underlying BIO (although not
1667 // necessarily the underlying transport).
1668 rv
= callback
.GetResult(raw_sock
->Write(request_buffer
.get(),
1669 request_buffer
->BytesRemaining(),
1670 callback
.callback()));
1672 request_buffer
->DidConsume(rv
);
1674 // Guard to ensure that |request_buffer| was larger than all of the internal
1675 // buffers (transport, memio, NSS) along the way - otherwise the next call
1676 // to Write() will crash with an invalid buffer.
1677 ASSERT_LT(0, request_buffer
->BytesRemaining());
1680 // Attempt to write the remaining data. NSS will not be able to consume the
1681 // application data because the internal buffers are full, while OpenSSL will
1682 // return that its blocked because the underlying transport is blocked.
1683 rv
= raw_sock
->Write(request_buffer
.get(),
1684 request_buffer
->BytesRemaining(),
1685 callback
.callback());
1686 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1687 ASSERT_FALSE(callback
.have_result());
1689 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1690 // call the Read() callback, deleting the socket and thus aborting calling
1691 // the Write() callback.
1692 raw_transport
->UnblockWrite();
1694 rv
= read_callback
.WaitForResult();
1695 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1697 // The Write callback should not have been called.
1698 EXPECT_FALSE(callback
.have_result());
1701 // Tests that the SSLClientSocket does not crash if data is received on the
1702 // transport socket after a failing write. This can occur if we have a Write
1703 // error in a SPDY socket.
1704 // Regression test for http://crbug.com/335557
1705 TEST_F(SSLClientSocketTest
, Read_WithWriteError
) {
1706 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1707 SpawnedTestServer::kLocalhost
,
1709 ASSERT_TRUE(test_server
.Start());
1712 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1714 TestCompletionCallback callback
;
1715 scoped_ptr
<StreamSocket
> real_transport(
1716 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1717 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1718 // is retained in order to configure additional errors.
1719 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1720 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1721 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1722 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1723 new FakeBlockingStreamSocket(error_socket
.Pass()));
1724 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1726 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1729 // Disable TLS False Start to avoid handshake non-determinism.
1730 SSLConfig ssl_config
;
1731 ssl_config
.false_start_enabled
= false;
1733 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1734 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1736 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1738 EXPECT_TRUE(sock
->IsConnected());
1740 // Send a request so there is something to read from the socket.
1741 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1742 static const int kRequestTextSize
=
1743 static_cast<int>(arraysize(request_text
) - 1);
1744 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1745 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1747 rv
= callback
.GetResult(
1748 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1749 EXPECT_EQ(kRequestTextSize
, rv
);
1751 // Start a hanging read.
1752 TestCompletionCallback read_callback
;
1753 raw_transport
->BlockReadResult();
1754 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1755 rv
= sock
->Read(buf
.get(), 4096, read_callback
.callback());
1756 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1758 // Perform another write, but have it fail. Write a request larger than the
1759 // internal socket buffers so that the request hits the underlying transport
1760 // socket and detects the error.
1761 std::string long_request_text
=
1762 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1763 long_request_text
.append(20 * 1024, '*');
1764 long_request_text
.append("\r\n\r\n");
1765 scoped_refptr
<DrainableIOBuffer
> long_request_buffer(new DrainableIOBuffer(
1766 new StringIOBuffer(long_request_text
), long_request_text
.size()));
1768 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1770 // Write as much data as possible until hitting an error. This is necessary
1771 // for NSS. PR_Write will only consume as much data as it can encode into
1772 // application data records before the internal memio buffer is full, which
1773 // should only fill if writing a large amount of data and the underlying
1774 // transport is blocked. Once this happens, NSS will return (total size of all
1775 // application data records it wrote) - 1, with the caller expected to resume
1776 // with the remaining unsent data.
1778 rv
= callback
.GetResult(sock
->Write(long_request_buffer
.get(),
1779 long_request_buffer
->BytesRemaining(),
1780 callback
.callback()));
1782 long_request_buffer
->DidConsume(rv
);
1783 // Abort if the entire buffer is ever consumed.
1784 ASSERT_LT(0, long_request_buffer
->BytesRemaining());
1788 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1790 // Release the read.
1791 raw_transport
->UnblockReadResult();
1792 rv
= read_callback
.WaitForResult();
1794 #if defined(USE_OPENSSL)
1795 // Should still read bytes despite the write error.
1798 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1799 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1800 // the write error stops future reads.
1801 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1805 // Tests that SSLClientSocket fails the handshake if the underlying
1806 // transport is cleanly closed.
1807 TEST_F(SSLClientSocketTest
, Connect_WithZeroReturn
) {
1808 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1809 SpawnedTestServer::kLocalhost
,
1811 ASSERT_TRUE(test_server
.Start());
1814 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1816 TestCompletionCallback callback
;
1817 scoped_ptr
<StreamSocket
> real_transport(
1818 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1819 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1820 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1821 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1824 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1825 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1826 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1828 raw_transport
->SetNextReadError(0);
1830 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1831 EXPECT_EQ(ERR_CONNECTION_CLOSED
, rv
);
1832 EXPECT_FALSE(sock
->IsConnected());
1835 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1836 // is cleanly closed, but the peer does not send close_notify.
1837 // This is a regression test for https://crbug.com/422246
1838 TEST_F(SSLClientSocketTest
, Read_WithZeroReturn
) {
1839 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1840 SpawnedTestServer::kLocalhost
,
1842 ASSERT_TRUE(test_server
.Start());
1845 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1847 TestCompletionCallback callback
;
1848 scoped_ptr
<StreamSocket
> real_transport(
1849 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1850 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1851 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1852 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1855 // Disable TLS False Start to ensure the handshake has completed.
1856 SSLConfig ssl_config
;
1857 ssl_config
.false_start_enabled
= false;
1859 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1860 scoped_ptr
<SSLClientSocket
> sock(
1861 CreateSSLClientSocket(transport
.Pass(),
1862 test_server
.host_port_pair(),
1865 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1867 EXPECT_TRUE(sock
->IsConnected());
1869 raw_transport
->SetNextReadError(0);
1870 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1871 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1875 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1876 // underlying socket is cleanly closed asynchronously.
1877 // This is a regression test for https://crbug.com/422246
1878 TEST_F(SSLClientSocketTest
, Read_WithAsyncZeroReturn
) {
1879 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1880 SpawnedTestServer::kLocalhost
,
1882 ASSERT_TRUE(test_server
.Start());
1885 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1887 TestCompletionCallback callback
;
1888 scoped_ptr
<StreamSocket
> real_transport(
1889 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1890 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1891 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1892 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1893 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1894 new FakeBlockingStreamSocket(error_socket
.Pass()));
1895 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1896 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1899 // Disable TLS False Start to ensure the handshake has completed.
1900 SSLConfig ssl_config
;
1901 ssl_config
.false_start_enabled
= false;
1903 scoped_ptr
<SSLClientSocket
> sock(
1904 CreateSSLClientSocket(transport
.Pass(),
1905 test_server
.host_port_pair(),
1908 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1910 EXPECT_TRUE(sock
->IsConnected());
1912 raw_error_socket
->SetNextReadError(0);
1913 raw_transport
->BlockReadResult();
1914 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1915 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1916 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1918 raw_transport
->UnblockReadResult();
1919 rv
= callback
.GetResult(rv
);
1923 // Tests that fatal alerts from the peer are processed. This is a regression
1924 // test for https://crbug.com/466303.
1925 TEST_F(SSLClientSocketTest
, Read_WithFatalAlert
) {
1926 SpawnedTestServer::SSLOptions ssl_options
;
1927 ssl_options
.alert_after_handshake
= true;
1928 ASSERT_TRUE(StartTestServer(ssl_options
));
1930 SSLConfig ssl_config
;
1931 TestCompletionCallback callback
;
1932 scoped_ptr
<StreamSocket
> transport(
1933 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
1934 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
1935 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1936 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
1937 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
1939 // Receive the fatal alert.
1940 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1941 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, callback
.GetResult(sock
->Read(
1942 buf
.get(), 4096, callback
.callback())));
1945 TEST_F(SSLClientSocketTest
, Read_SmallChunks
) {
1946 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1947 SpawnedTestServer::kLocalhost
,
1949 ASSERT_TRUE(test_server
.Start());
1952 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1954 TestCompletionCallback callback
;
1955 scoped_ptr
<StreamSocket
> transport(
1956 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1957 int rv
= transport
->Connect(callback
.callback());
1958 if (rv
== ERR_IO_PENDING
)
1959 rv
= callback
.WaitForResult();
1962 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1963 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1965 rv
= sock
->Connect(callback
.callback());
1966 if (rv
== ERR_IO_PENDING
)
1967 rv
= callback
.WaitForResult();
1970 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1971 scoped_refptr
<IOBuffer
> request_buffer(
1972 new IOBuffer(arraysize(request_text
) - 1));
1973 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1976 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1977 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1979 if (rv
== ERR_IO_PENDING
)
1980 rv
= callback
.WaitForResult();
1981 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1983 scoped_refptr
<IOBuffer
> buf(new IOBuffer(1));
1985 rv
= sock
->Read(buf
.get(), 1, callback
.callback());
1986 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1988 if (rv
== ERR_IO_PENDING
)
1989 rv
= callback
.WaitForResult();
1997 TEST_F(SSLClientSocketTest
, Read_ManySmallRecords
) {
1998 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1999 SpawnedTestServer::kLocalhost
,
2001 ASSERT_TRUE(test_server
.Start());
2004 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2006 TestCompletionCallback callback
;
2008 scoped_ptr
<StreamSocket
> real_transport(
2009 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2010 scoped_ptr
<ReadBufferingStreamSocket
> transport(
2011 new ReadBufferingStreamSocket(real_transport
.Pass()));
2012 ReadBufferingStreamSocket
* raw_transport
= transport
.get();
2013 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2016 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2017 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2019 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2021 ASSERT_TRUE(sock
->IsConnected());
2023 const char request_text
[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
2024 scoped_refptr
<IOBuffer
> request_buffer(
2025 new IOBuffer(arraysize(request_text
) - 1));
2026 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2028 rv
= callback
.GetResult(sock
->Write(
2029 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback()));
2031 ASSERT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2033 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2034 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2035 // of SSL data is buffered first. The 15K of buffered data is made up of
2036 // many smaller SSL records (the TestServer writes along 1350 byte
2037 // plaintext boundaries), although there may also be a few records that are
2038 // smaller or larger, due to timing and SSL False Start.
2039 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2040 // the SSLClientSocket implementation, and larger than the minimum amount
2041 // of ciphertext necessary to contain the 8K of plaintext requested below.
2042 raw_transport
->SetBufferSize(15000);
2044 scoped_refptr
<IOBuffer
> buffer(new IOBuffer(8192));
2045 rv
= callback
.GetResult(sock
->Read(buffer
.get(), 8192, callback
.callback()));
2046 ASSERT_EQ(rv
, 8192);
2049 TEST_F(SSLClientSocketTest
, Read_Interrupted
) {
2050 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2051 SpawnedTestServer::kLocalhost
,
2053 ASSERT_TRUE(test_server
.Start());
2056 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2058 TestCompletionCallback callback
;
2059 scoped_ptr
<StreamSocket
> transport(
2060 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2061 int rv
= transport
->Connect(callback
.callback());
2062 if (rv
== ERR_IO_PENDING
)
2063 rv
= callback
.WaitForResult();
2066 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2067 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2069 rv
= sock
->Connect(callback
.callback());
2070 if (rv
== ERR_IO_PENDING
)
2071 rv
= callback
.WaitForResult();
2074 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2075 scoped_refptr
<IOBuffer
> request_buffer(
2076 new IOBuffer(arraysize(request_text
) - 1));
2077 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2080 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2081 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2083 if (rv
== ERR_IO_PENDING
)
2084 rv
= callback
.WaitForResult();
2085 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2087 // Do a partial read and then exit. This test should not crash!
2088 scoped_refptr
<IOBuffer
> buf(new IOBuffer(512));
2089 rv
= sock
->Read(buf
.get(), 512, callback
.callback());
2090 EXPECT_TRUE(rv
> 0 || rv
== ERR_IO_PENDING
);
2092 if (rv
== ERR_IO_PENDING
)
2093 rv
= callback
.WaitForResult();
2098 TEST_F(SSLClientSocketTest
, Read_FullLogging
) {
2099 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2100 SpawnedTestServer::kLocalhost
,
2102 ASSERT_TRUE(test_server
.Start());
2105 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2107 TestCompletionCallback callback
;
2109 log
.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes());
2110 scoped_ptr
<StreamSocket
> transport(
2111 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2112 int rv
= transport
->Connect(callback
.callback());
2113 if (rv
== ERR_IO_PENDING
)
2114 rv
= callback
.WaitForResult();
2117 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2118 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2120 rv
= sock
->Connect(callback
.callback());
2121 if (rv
== ERR_IO_PENDING
)
2122 rv
= callback
.WaitForResult();
2124 EXPECT_TRUE(sock
->IsConnected());
2126 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2127 scoped_refptr
<IOBuffer
> request_buffer(
2128 new IOBuffer(arraysize(request_text
) - 1));
2129 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2132 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2133 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2135 if (rv
== ERR_IO_PENDING
)
2136 rv
= callback
.WaitForResult();
2137 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2139 TestNetLog::CapturedEntryList entries
;
2140 log
.GetEntries(&entries
);
2141 size_t last_index
= ExpectLogContainsSomewhereAfter(
2142 entries
, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
2144 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
2146 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
2147 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2149 if (rv
== ERR_IO_PENDING
)
2150 rv
= callback
.WaitForResult();
2156 log
.GetEntries(&entries
);
2158 ExpectLogContainsSomewhereAfter(entries
,
2160 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
2161 NetLog::PHASE_NONE
);
2165 // Regression test for http://crbug.com/42538
2166 TEST_F(SSLClientSocketTest
, PrematureApplicationData
) {
2167 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2168 SpawnedTestServer::kLocalhost
,
2170 ASSERT_TRUE(test_server
.Start());
2173 TestCompletionCallback callback
;
2175 static const unsigned char application_data
[] = {
2176 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2177 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2178 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2179 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2180 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2181 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2182 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2183 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2184 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2187 // All reads and writes complete synchronously (async=false).
2188 MockRead data_reads
[] = {
2189 MockRead(SYNCHRONOUS
,
2190 reinterpret_cast<const char*>(application_data
),
2191 arraysize(application_data
)),
2192 MockRead(SYNCHRONOUS
, OK
), };
2194 StaticSocketDataProvider
data(data_reads
, arraysize(data_reads
), NULL
, 0);
2196 scoped_ptr
<StreamSocket
> transport(
2197 new MockTCPClientSocket(addr
, NULL
, &data
));
2198 int rv
= transport
->Connect(callback
.callback());
2199 if (rv
== ERR_IO_PENDING
)
2200 rv
= callback
.WaitForResult();
2203 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2204 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2206 rv
= sock
->Connect(callback
.callback());
2207 if (rv
== ERR_IO_PENDING
)
2208 rv
= callback
.WaitForResult();
2209 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, rv
);
2212 TEST_F(SSLClientSocketTest
, CipherSuiteDisables
) {
2213 // Rather than exhaustively disabling every AES_128_CBC ciphersuite defined at
2214 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2215 // disabling those cipher suites that the test server actually implements.
2216 const uint16 kCiphersToDisable
[] = {
2217 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2218 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2219 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2222 SpawnedTestServer::SSLOptions ssl_options
;
2223 // Enable only AES_128_CBC on the test server.
2224 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
2225 SpawnedTestServer
test_server(
2226 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2227 ASSERT_TRUE(test_server
.Start());
2230 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2232 TestCompletionCallback callback
;
2234 scoped_ptr
<StreamSocket
> transport(
2235 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2236 int rv
= transport
->Connect(callback
.callback());
2237 if (rv
== ERR_IO_PENDING
)
2238 rv
= callback
.WaitForResult();
2241 SSLConfig ssl_config
;
2242 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2243 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2245 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2246 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2248 EXPECT_FALSE(sock
->IsConnected());
2250 rv
= sock
->Connect(callback
.callback());
2251 TestNetLog::CapturedEntryList entries
;
2252 log
.GetEntries(&entries
);
2253 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2255 if (rv
== ERR_IO_PENDING
)
2256 rv
= callback
.WaitForResult();
2257 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
, rv
);
2258 // The exact ordering depends no whether an extra read is issued. Just check
2259 // the error is somewhere in the log.
2260 log
.GetEntries(&entries
);
2261 ExpectLogContainsSomewhere(
2262 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2264 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2265 // the socket when it encounters an error, whereas other implementations
2266 // leave it connected.
2267 // Because this an error that the test server is mutually aware of, as opposed
2268 // to being an error such as a certificate name mismatch, which is
2269 // client-only, the exact index of the SSL connect end depends on how
2270 // quickly the test server closes the underlying socket. If the test server
2271 // closes before the IO message loop pumps messages, there may be a 0-byte
2272 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2273 // result, the SSL connect end event will be the second-to-last entry,
2274 // rather than the last entry.
2275 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1) ||
2276 LogContainsSSLConnectEndEvent(entries
, -2));
2279 // When creating an SSLClientSocket, it is allowed to pass in a
2280 // ClientSocketHandle that is not obtained from a client socket pool.
2281 // Here we verify that such a simple ClientSocketHandle, not associated with any
2282 // client socket pool, can be destroyed safely.
2283 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2284 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2285 SpawnedTestServer::kLocalhost
,
2287 ASSERT_TRUE(test_server
.Start());
2290 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2292 TestCompletionCallback callback
;
2293 scoped_ptr
<StreamSocket
> transport(
2294 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2295 int rv
= transport
->Connect(callback
.callback());
2296 if (rv
== ERR_IO_PENDING
)
2297 rv
= callback
.WaitForResult();
2300 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2301 socket_handle
->SetSocket(transport
.Pass());
2303 scoped_ptr
<SSLClientSocket
> sock(socket_factory_
->CreateSSLClientSocket(
2304 socket_handle
.Pass(), test_server
.host_port_pair(), SSLConfig(),
2307 EXPECT_FALSE(sock
->IsConnected());
2308 rv
= sock
->Connect(callback
.callback());
2309 if (rv
== ERR_IO_PENDING
)
2310 rv
= callback
.WaitForResult();
2314 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2315 // code and different keying label results in different keying material.
2316 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2317 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2318 SpawnedTestServer::kLocalhost
,
2320 ASSERT_TRUE(test_server
.Start());
2323 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2325 TestCompletionCallback callback
;
2327 scoped_ptr
<StreamSocket
> transport(
2328 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2329 int rv
= transport
->Connect(callback
.callback());
2330 if (rv
== ERR_IO_PENDING
)
2331 rv
= callback
.WaitForResult();
2334 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2335 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2337 rv
= sock
->Connect(callback
.callback());
2338 if (rv
== ERR_IO_PENDING
)
2339 rv
= callback
.WaitForResult();
2341 EXPECT_TRUE(sock
->IsConnected());
2343 const int kKeyingMaterialSize
= 32;
2344 const char kKeyingLabel1
[] = "client-socket-test-1";
2345 const char kKeyingContext1
[] = "";
2346 unsigned char client_out1
[kKeyingMaterialSize
];
2347 memset(client_out1
, 0, sizeof(client_out1
));
2348 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, false, kKeyingContext1
,
2349 client_out1
, sizeof(client_out1
));
2352 const char kKeyingLabel2
[] = "client-socket-test-2";
2353 unsigned char client_out2
[kKeyingMaterialSize
];
2354 memset(client_out2
, 0, sizeof(client_out2
));
2355 rv
= sock
->ExportKeyingMaterial(kKeyingLabel2
, false, kKeyingContext1
,
2356 client_out2
, sizeof(client_out2
));
2358 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2360 const char kKeyingContext2
[] = "context";
2361 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext2
,
2362 client_out2
, sizeof(client_out2
));
2364 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2366 // Using an empty context should give different key material from not using a
2368 memset(client_out2
, 0, sizeof(client_out2
));
2369 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext1
,
2370 client_out2
, sizeof(client_out2
));
2372 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2375 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2376 // explicit NSS initialization.
2377 TEST(SSLClientSocket
, ClearSessionCache
) {
2378 SSLClientSocket::ClearSessionCache();
2381 TEST(SSLClientSocket
, SerializeNextProtos
) {
2382 NextProtoVector next_protos
;
2383 next_protos
.push_back(kProtoHTTP11
);
2384 next_protos
.push_back(kProtoSPDY31
);
2385 static std::vector
<uint8_t> serialized
=
2386 SSLClientSocket::SerializeNextProtos(next_protos
, true);
2387 ASSERT_EQ(18u, serialized
.size());
2388 EXPECT_EQ(8, serialized
[0]); // length("http/1.1")
2389 EXPECT_EQ('h', serialized
[1]);
2390 EXPECT_EQ('t', serialized
[2]);
2391 EXPECT_EQ('t', serialized
[3]);
2392 EXPECT_EQ('p', serialized
[4]);
2393 EXPECT_EQ('/', serialized
[5]);
2394 EXPECT_EQ('1', serialized
[6]);
2395 EXPECT_EQ('.', serialized
[7]);
2396 EXPECT_EQ('1', serialized
[8]);
2397 EXPECT_EQ(8, serialized
[9]); // length("spdy/3.1")
2398 EXPECT_EQ('s', serialized
[10]);
2399 EXPECT_EQ('p', serialized
[11]);
2400 EXPECT_EQ('d', serialized
[12]);
2401 EXPECT_EQ('y', serialized
[13]);
2402 EXPECT_EQ('/', serialized
[14]);
2403 EXPECT_EQ('3', serialized
[15]);
2404 EXPECT_EQ('.', serialized
[16]);
2405 EXPECT_EQ('1', serialized
[17]);
2408 // Test that the server certificates are properly retrieved from the underlying
2410 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2411 // The connection does not have to be successful.
2412 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2414 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2415 // This makes the server present redundant-server-chain.pem, which contains
2416 // intermediate certificates.
2417 SpawnedTestServer::SSLOptions
ssl_options(
2418 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2419 SpawnedTestServer
test_server(
2420 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2421 ASSERT_TRUE(test_server
.Start());
2424 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2426 TestCompletionCallback callback
;
2427 scoped_ptr
<StreamSocket
> transport(
2428 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2429 int rv
= transport
->Connect(callback
.callback());
2430 rv
= callback
.GetResult(rv
);
2433 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2434 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2435 EXPECT_FALSE(sock
->IsConnected());
2436 rv
= sock
->Connect(callback
.callback());
2437 rv
= callback
.GetResult(rv
);
2439 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2440 EXPECT_TRUE(sock
->IsConnected());
2442 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2443 // certs from redundant-server-chain.pem.
2444 CertificateList server_certs
=
2445 CreateCertificateListFromFile(GetTestCertsDirectory(),
2446 "redundant-server-chain.pem",
2447 X509Certificate::FORMAT_AUTO
);
2449 // Get the server certificate as received client side.
2450 scoped_refptr
<X509Certificate
> server_certificate
=
2451 sock
->GetUnverifiedServerCertificateChain();
2453 // Get the intermediates as received client side.
2454 const X509Certificate::OSCertHandles
& server_intermediates
=
2455 server_certificate
->GetIntermediateCertificates();
2457 // Check that the unverified server certificate chain is properly retrieved
2458 // from the underlying ssl stack.
2459 ASSERT_EQ(4U, server_certs
.size());
2461 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2462 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2464 ASSERT_EQ(3U, server_intermediates
.size());
2466 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2467 server_certs
[1]->os_cert_handle()));
2468 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2469 server_certs
[2]->os_cert_handle()));
2470 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2471 server_certs
[3]->os_cert_handle()));
2474 EXPECT_FALSE(sock
->IsConnected());
2477 // This tests that SSLInfo contains a properly re-constructed certificate
2478 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2479 // verified, not the chain as served by the server. (They may be different.)
2481 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2482 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2483 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2484 // a self-signed root. Such a situation can occur when a new root (C2) is
2485 // cross-certified by an old root (D) and has two different versions of its
2486 // floating around. Servers may supply C2 as an intermediate, but the
2487 // SSLClientSocket should return the chain that was verified, from
2488 // verify_result, instead.
2489 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2490 // By default, cause the CertVerifier to treat all certificates as
2492 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2494 // We will expect SSLInfo to ultimately contain this chain.
2495 CertificateList certs
=
2496 CreateCertificateListFromFile(GetTestCertsDirectory(),
2497 "redundant-validated-chain.pem",
2498 X509Certificate::FORMAT_AUTO
);
2499 ASSERT_EQ(3U, certs
.size());
2501 X509Certificate::OSCertHandles temp_intermediates
;
2502 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2503 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2505 CertVerifyResult verify_result
;
2506 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2507 certs
[0]->os_cert_handle(), temp_intermediates
);
2509 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2510 // rather than A->B->C.
2511 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2513 // Load and install the root for the validated chain.
2514 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2515 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2516 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
2517 ScopedTestRoot
scoped_root(root_cert
.get());
2519 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2520 SpawnedTestServer::SSLOptions
ssl_options(
2521 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2522 SpawnedTestServer
test_server(
2523 SpawnedTestServer::TYPE_HTTPS
,
2525 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2526 ASSERT_TRUE(test_server
.Start());
2529 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2531 TestCompletionCallback callback
;
2533 scoped_ptr
<StreamSocket
> transport(
2534 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2535 int rv
= transport
->Connect(callback
.callback());
2536 if (rv
== ERR_IO_PENDING
)
2537 rv
= callback
.WaitForResult();
2540 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2541 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2542 EXPECT_FALSE(sock
->IsConnected());
2543 rv
= sock
->Connect(callback
.callback());
2545 TestNetLog::CapturedEntryList entries
;
2546 log
.GetEntries(&entries
);
2547 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2548 if (rv
== ERR_IO_PENDING
)
2549 rv
= callback
.WaitForResult();
2552 EXPECT_TRUE(sock
->IsConnected());
2553 log
.GetEntries(&entries
);
2554 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries
, -1));
2557 sock
->GetSSLInfo(&ssl_info
);
2559 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2561 const X509Certificate::OSCertHandles
& intermediates
=
2562 ssl_info
.cert
->GetIntermediateCertificates();
2563 ASSERT_EQ(2U, intermediates
.size());
2564 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2565 certs
[0]->os_cert_handle()));
2566 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2567 certs
[1]->os_cert_handle()));
2568 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2569 certs
[2]->os_cert_handle()));
2572 EXPECT_FALSE(sock
->IsConnected());
2575 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2576 SpawnedTestServer::SSLOptions ssl_options
;
2577 ssl_options
.request_client_certificate
= true;
2578 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2579 ASSERT_TRUE(request_info
.get());
2580 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2583 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2584 const base::FilePath::CharType kThawteFile
[] =
2585 FILE_PATH_LITERAL("thawte.single.pem");
2586 const unsigned char kThawteDN
[] = {
2587 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2588 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2589 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2590 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2591 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2592 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2593 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2594 const size_t kThawteLen
= sizeof(kThawteDN
);
2596 const base::FilePath::CharType kDiginotarFile
[] =
2597 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2598 const unsigned char kDiginotarDN
[] = {
2599 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2600 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2601 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2602 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2603 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2604 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2605 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2606 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2608 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2610 SpawnedTestServer::SSLOptions ssl_options
;
2611 ssl_options
.request_client_certificate
= true;
2612 ssl_options
.client_authorities
.push_back(
2613 GetTestClientCertsDirectory().Append(kThawteFile
));
2614 ssl_options
.client_authorities
.push_back(
2615 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2616 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2617 ASSERT_TRUE(request_info
.get());
2618 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2619 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2620 request_info
->cert_authorities
[0]);
2622 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2623 request_info
->cert_authorities
[1]);
2626 // cert_key_types is currently only populated on OpenSSL.
2627 #if defined(USE_OPENSSL)
2628 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2629 SpawnedTestServer::SSLOptions ssl_options
;
2630 ssl_options
.request_client_certificate
= true;
2631 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2632 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2633 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2634 ASSERT_TRUE(request_info
.get());
2635 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2636 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2637 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2639 #endif // defined(USE_OPENSSL)
2641 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2642 SpawnedTestServer::SSLOptions ssl_options
;
2643 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2645 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2648 ASSERT_TRUE(test_server
.Start());
2651 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2653 TestCompletionCallback callback
;
2654 scoped_ptr
<StreamSocket
> transport(
2655 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2656 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2659 SSLConfig ssl_config
;
2660 ssl_config
.signed_cert_timestamps_enabled
= true;
2662 MockCTVerifier ct_verifier
;
2663 SetCTVerifier(&ct_verifier
);
2665 // Check that the SCT list is extracted as expected.
2666 EXPECT_CALL(ct_verifier
, Verify(_
, "", "test", _
, _
)).WillRepeatedly(
2667 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2669 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2670 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2671 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2674 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2679 bool IsValidOCSPResponse(const base::StringPiece
& input
) {
2680 base::StringPiece ocsp_response
= input
;
2681 base::StringPiece sequence
, response_status
, response_bytes
;
2682 return asn1::GetElement(&ocsp_response
, asn1::kSEQUENCE
, &sequence
) &&
2683 ocsp_response
.empty() &&
2684 asn1::GetElement(&sequence
, asn1::kENUMERATED
, &response_status
) &&
2685 asn1::GetElement(&sequence
,
2686 asn1::kContextSpecific
| asn1::kConstructed
| 0,
2687 &response_status
) &&
2693 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2694 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2695 SpawnedTestServer::SSLOptions ssl_options
;
2696 ssl_options
.staple_ocsp_response
= true;
2697 // The test server currently only knows how to generate OCSP responses
2698 // for a freshly minted certificate.
2699 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2701 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2704 ASSERT_TRUE(test_server
.Start());
2707 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2709 TestCompletionCallback callback
;
2710 scoped_ptr
<StreamSocket
> transport(
2711 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2712 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2715 SSLConfig ssl_config
;
2716 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2717 // Certificate Transparency verification regardless of whether the platform
2718 // is able to process the OCSP status itself.
2719 ssl_config
.signed_cert_timestamps_enabled
= true;
2721 MockCTVerifier ct_verifier
;
2722 SetCTVerifier(&ct_verifier
);
2724 // Check that the OCSP response is extracted and well-formed. It should be the
2725 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2726 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2727 // particular, it should not include the overall two-byte length prefix from
2729 EXPECT_CALL(ct_verifier
,
2730 Verify(_
, Truly(IsValidOCSPResponse
), "", _
, _
)).WillRepeatedly(
2731 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2733 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2734 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2735 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2738 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2741 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2742 SpawnedTestServer::SSLOptions ssl_options
;
2743 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2745 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2748 ASSERT_TRUE(test_server
.Start());
2751 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2753 TestCompletionCallback callback
;
2754 scoped_ptr
<StreamSocket
> transport(
2755 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2756 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2759 SSLConfig ssl_config
;
2760 ssl_config
.signed_cert_timestamps_enabled
= false;
2762 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2763 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2764 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2767 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2770 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2771 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2772 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2773 SpawnedTestServer::kLocalhost
,
2775 ASSERT_TRUE(test_server
.Start());
2778 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2780 TestCompletionCallback callback
;
2781 scoped_ptr
<StreamSocket
> transport(
2782 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2783 int rv
= transport
->Connect(callback
.callback());
2784 if (rv
== ERR_IO_PENDING
)
2785 rv
= callback
.WaitForResult();
2788 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2789 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2791 rv
= sock
->Connect(callback
.callback());
2792 if (rv
== ERR_IO_PENDING
)
2793 rv
= callback
.WaitForResult();
2796 // The socket was just connected. It should be idle because it is speaking
2797 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2799 EXPECT_TRUE(sock
->IsConnected());
2800 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2801 EXPECT_FALSE(sock
->WasEverUsed());
2803 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2804 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2805 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2806 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2808 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2809 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2811 if (rv
== ERR_IO_PENDING
)
2812 rv
= callback
.WaitForResult();
2813 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2815 // The socket has now been used.
2816 EXPECT_TRUE(sock
->WasEverUsed());
2818 // TODO(davidben): Read one byte to ensure the test server has responded and
2819 // then assert IsConnectedAndIdle is false. This currently doesn't work
2820 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2821 // SSL implementation's internal buffers. Either call PR_Available and
2822 // SSL_pending, although the former isn't actually implemented or perhaps
2823 // attempt to read one byte extra.
2826 // Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
2827 // been flushed completely out of SSLClientSocket's internal buffers. This is a
2828 // regression test for https://crbug.com/466147.
2829 TEST_F(SSLClientSocketTest
, ReusableAfterWrite
) {
2830 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2831 SpawnedTestServer::kLocalhost
,
2833 ASSERT_TRUE(test_server
.Start());
2836 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2838 TestCompletionCallback callback
;
2839 scoped_ptr
<StreamSocket
> real_transport(
2840 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2841 scoped_ptr
<FakeBlockingStreamSocket
> transport(
2842 new FakeBlockingStreamSocket(real_transport
.Pass()));
2843 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
2844 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2846 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2847 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2848 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2850 // Block any application data from reaching the network.
2851 raw_transport
->BlockWrite();
2853 // Write a partial HTTP request.
2854 const char kRequestText
[] = "GET / HTTP/1.0";
2855 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2856 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2857 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2859 // Although transport writes are blocked, both SSLClientSocketOpenSSL and
2860 // SSLClientSocketNSS complete the outer Write operation.
2861 EXPECT_EQ(static_cast<int>(kRequestLen
),
2862 callback
.GetResult(sock
->Write(request_buffer
.get(), kRequestLen
,
2863 callback
.callback())));
2865 // The Write operation is complete, so the socket should be treated as
2866 // reusable, in case the server returns an HTTP response before completely
2867 // consuming the request body. In this case, we assume the server will
2868 // properly drain the request body before trying to read the next request.
2869 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2872 // Tests that basic session resumption works.
2873 TEST_F(SSLClientSocketTest
, SessionResumption
) {
2874 SpawnedTestServer::SSLOptions ssl_options
;
2875 ASSERT_TRUE(StartTestServer(ssl_options
));
2877 // First, perform a full handshake.
2878 SSLConfig ssl_config
;
2879 TestCompletionCallback callback
;
2880 scoped_ptr
<StreamSocket
> transport(
2881 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2882 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2883 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2884 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
2885 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2887 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2888 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2890 // The next connection should resume.
2891 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2892 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2893 sock
= CreateSSLClientSocket(transport
.Pass(),
2894 test_server()->host_port_pair(), ssl_config
);
2895 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2896 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2897 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2899 // Using a different HostPortPair uses a different session cache key.
2900 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2901 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2902 sock
= CreateSSLClientSocket(transport
.Pass(),
2903 HostPortPair("example.com", 443), ssl_config
);
2904 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2905 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2906 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2908 SSLClientSocket::ClearSessionCache();
2910 // After clearing the session cache, the next handshake doesn't resume.
2911 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2912 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2913 sock
= CreateSSLClientSocket(transport
.Pass(),
2914 test_server()->host_port_pair(), ssl_config
);
2915 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2916 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2917 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2920 // Tests that connections with certificate errors do not add entries to the
2922 TEST_F(SSLClientSocketTest
, CertificateErrorNoResume
) {
2923 SpawnedTestServer::SSLOptions ssl_options
;
2924 ASSERT_TRUE(StartTestServer(ssl_options
));
2926 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
2928 SSLConfig ssl_config
;
2929 TestCompletionCallback callback
;
2930 scoped_ptr
<StreamSocket
> transport(
2931 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2932 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2933 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2934 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
2935 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
,
2936 callback
.GetResult(sock
->Connect(callback
.callback())));
2938 cert_verifier_
->set_default_result(OK
);
2940 // The next connection should perform a full handshake.
2941 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2942 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2943 sock
= CreateSSLClientSocket(transport
.Pass(),
2944 test_server()->host_port_pair(), ssl_config
);
2945 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2947 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2948 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2951 // Tests that session caches are sharded by max_version.
2952 TEST_F(SSLClientSocketTest
, FallbackShardSessionCache
) {
2953 SpawnedTestServer::SSLOptions ssl_options
;
2954 ASSERT_TRUE(StartTestServer(ssl_options
));
2956 // Prepare a normal and fallback SSL config.
2957 SSLConfig ssl_config
;
2958 SSLConfig fallback_ssl_config
;
2959 fallback_ssl_config
.version_max
= SSL_PROTOCOL_VERSION_TLS1
;
2960 fallback_ssl_config
.version_fallback
= true;
2962 // Connect with a fallback config from the test server to add an entry to the
2964 TestCompletionCallback callback
;
2965 scoped_ptr
<StreamSocket
> transport(
2966 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2967 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2968 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2969 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
));
2970 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2972 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2973 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2974 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2975 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2977 // A non-fallback connection needs a full handshake.
2978 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2979 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2980 sock
= CreateSSLClientSocket(transport
.Pass(),
2981 test_server()->host_port_pair(), ssl_config
);
2982 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2983 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2984 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2985 // This does not check for equality because TLS 1.2 support is conditional on
2986 // system NSS features.
2987 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2988 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2990 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2991 // 1.2, the above test would not be sufficient to prove the session caches are
2992 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2993 // attempt to resume with two more connections.
2995 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2996 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2997 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2998 sock
= CreateSSLClientSocket(transport
.Pass(),
2999 test_server()->host_port_pair(), ssl_config
);
3000 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3001 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3002 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3003 // This does not check for equality because TLS 1.2 support is conditional on
3004 // system NSS features.
3005 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
3006 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
3008 // The fallback connection still resumes from its session cache. It cannot
3009 // offer the > TLS 1.0 session, so this must have been the session from the
3010 // first fallback connection.
3011 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3012 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3013 sock
= CreateSSLClientSocket(
3014 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
);
3015 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3016 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3017 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3018 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
3019 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
3022 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
3023 TEST_F(SSLClientSocketTest
, DeprecatedRC4
) {
3024 SpawnedTestServer::SSLOptions ssl_options
;
3025 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
3026 ASSERT_TRUE(StartTestServer(ssl_options
));
3028 // Normal handshakes with RC4 do not work.
3029 SSLConfig ssl_config
;
3030 TestCompletionCallback callback
;
3031 scoped_ptr
<StreamSocket
> transport(
3032 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3033 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3034 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
3035 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
3036 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
,
3037 callback
.GetResult(sock
->Connect(callback
.callback())));
3039 // Enabling deprecated ciphers works fine.
3040 ssl_config
.enable_deprecated_cipher_suites
= true;
3041 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3042 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3043 sock
= CreateSSLClientSocket(transport
.Pass(),
3044 test_server()->host_port_pair(), ssl_config
);
3045 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3048 // Tests that enabling deprecated ciphers shards the session cache.
3049 TEST_F(SSLClientSocketTest
, DeprecatedShardSessionCache
) {
3050 SpawnedTestServer::SSLOptions ssl_options
;
3051 ASSERT_TRUE(StartTestServer(ssl_options
));
3053 // Prepare a normal and deprecated SSL config.
3054 SSLConfig ssl_config
;
3055 SSLConfig deprecated_ssl_config
;
3056 deprecated_ssl_config
.enable_deprecated_cipher_suites
= true;
3058 // Connect with deprecated ciphers enabled to warm the session cache cache.
3059 TestCompletionCallback callback
;
3060 scoped_ptr
<StreamSocket
> transport(
3061 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3062 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3063 scoped_ptr
<SSLClientSocket
> sock(
3064 CreateSSLClientSocket(transport
.Pass(), test_server()->host_port_pair(),
3065 deprecated_ssl_config
));
3066 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3068 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3069 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3071 // Test that re-connecting with deprecated ciphers enabled still resumes.
3072 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3073 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3074 sock
= CreateSSLClientSocket(
3075 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
3076 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3077 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3078 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3080 // However, a normal connection needs a full handshake.
3081 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3082 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3083 sock
= CreateSSLClientSocket(transport
.Pass(),
3084 test_server()->host_port_pair(), ssl_config
);
3085 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3086 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3087 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3089 // Clear the session cache for the inverse test.
3090 SSLClientSocket::ClearSessionCache();
3092 // Now make a normal connection to prime the session cache.
3093 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3094 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3095 sock
= CreateSSLClientSocket(transport
.Pass(),
3096 test_server()->host_port_pair(), ssl_config
);
3097 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3098 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3099 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3101 // A normal connection should be able to resume.
3102 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3103 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3104 sock
= CreateSSLClientSocket(transport
.Pass(),
3105 test_server()->host_port_pair(), ssl_config
);
3106 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3107 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3108 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3110 // However, enabling deprecated ciphers connects fresh.
3111 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3112 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3113 sock
= CreateSSLClientSocket(
3114 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
3115 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3116 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3117 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3120 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
3121 if (!SupportsAESGCM()) {
3122 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3126 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
3127 SpawnedTestServer::SSLOptions server_options
;
3128 server_options
.key_exchanges
=
3129 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3130 server_options
.bulk_ciphers
=
3131 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3132 server_options
.enable_npn
= true;
3133 SSLConfig client_config
;
3134 client_config
.next_protos
.push_back(kProtoHTTP11
);
3135 ASSERT_NO_FATAL_FAILURE(
3136 TestFalseStart(server_options
, client_config
, true));
3139 // Test that False Start is disabled without NPN.
3140 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
3141 if (!SupportsAESGCM()) {
3142 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3146 SpawnedTestServer::SSLOptions server_options
;
3147 server_options
.key_exchanges
=
3148 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3149 server_options
.bulk_ciphers
=
3150 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3151 SSLConfig client_config
;
3152 client_config
.next_protos
.clear();
3153 ASSERT_NO_FATAL_FAILURE(
3154 TestFalseStart(server_options
, client_config
, false));
3157 // Test that False Start is disabled with plain RSA ciphers.
3158 TEST_F(SSLClientSocketFalseStartTest
, RSA
) {
3159 if (!SupportsAESGCM()) {
3160 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3164 SpawnedTestServer::SSLOptions server_options
;
3165 server_options
.key_exchanges
=
3166 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
3167 server_options
.bulk_ciphers
=
3168 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3169 server_options
.enable_npn
= true;
3170 SSLConfig client_config
;
3171 client_config
.next_protos
.push_back(kProtoHTTP11
);
3172 ASSERT_NO_FATAL_FAILURE(
3173 TestFalseStart(server_options
, client_config
, false));
3176 // Test that False Start is disabled with DHE_RSA ciphers.
3177 TEST_F(SSLClientSocketFalseStartTest
, DHE_RSA
) {
3178 if (!SupportsAESGCM()) {
3179 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3183 SpawnedTestServer::SSLOptions server_options
;
3184 server_options
.key_exchanges
=
3185 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
3186 server_options
.bulk_ciphers
=
3187 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3188 server_options
.enable_npn
= true;
3189 SSLConfig client_config
;
3190 client_config
.next_protos
.push_back(kProtoHTTP11
);
3191 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3194 // Test that False Start is disabled without an AEAD.
3195 TEST_F(SSLClientSocketFalseStartTest
, NoAEAD
) {
3196 SpawnedTestServer::SSLOptions server_options
;
3197 server_options
.key_exchanges
=
3198 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3199 server_options
.bulk_ciphers
=
3200 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
3201 server_options
.enable_npn
= true;
3202 SSLConfig client_config
;
3203 client_config
.next_protos
.push_back(kProtoHTTP11
);
3204 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3207 // Test that sessions are resumable after receiving the server Finished message.
3208 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
3209 if (!SupportsAESGCM()) {
3210 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3215 SpawnedTestServer::SSLOptions server_options
;
3216 server_options
.key_exchanges
=
3217 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3218 server_options
.bulk_ciphers
=
3219 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3220 server_options
.enable_npn
= true;
3221 SSLConfig client_config
;
3222 client_config
.next_protos
.push_back(kProtoHTTP11
);
3224 // Let a full handshake complete with False Start.
3225 ASSERT_NO_FATAL_FAILURE(
3226 TestFalseStart(server_options
, client_config
, true));
3228 // Make a second connection.
3229 TestCompletionCallback callback
;
3230 scoped_ptr
<StreamSocket
> transport2(
3231 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3232 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3233 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3234 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3235 ASSERT_TRUE(sock2
.get());
3236 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3238 // It should resume the session.
3240 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3241 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3244 // Test that False Started sessions are not resumable before receiving the
3245 // server Finished message.
3246 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinished
) {
3247 if (!SupportsAESGCM()) {
3248 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3253 SpawnedTestServer::SSLOptions server_options
;
3254 server_options
.key_exchanges
=
3255 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3256 server_options
.bulk_ciphers
=
3257 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3258 server_options
.enable_npn
= true;
3259 ASSERT_TRUE(StartTestServer(server_options
));
3261 SSLConfig client_config
;
3262 client_config
.next_protos
.push_back(kProtoHTTP11
);
3264 // Start a handshake up to the server Finished message.
3265 TestCompletionCallback callback
;
3266 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3267 scoped_ptr
<SSLClientSocket
> sock1
;
3268 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3269 client_config
, &callback
, &raw_transport1
, &sock1
));
3270 // Although raw_transport1 has the server Finished blocked, the handshake
3272 EXPECT_EQ(OK
, callback
.WaitForResult());
3274 // Continue to block the client (|sock1|) from processing the Finished
3275 // message, but allow it to arrive on the socket. This ensures that, from the
3276 // server's point of view, it has completed the handshake and added the
3277 // session to its session cache.
3279 // The actual read on |sock1| will not complete until the Finished message is
3280 // processed; however, pump the underlying transport so that it is read from
3281 // the socket. NOTE: This may flakily pass if the server's final flight
3282 // doesn't come in one Read.
3283 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3284 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3285 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3286 raw_transport1
->WaitForReadResult();
3288 // Drop the old socket. This is needed because the Python test server can't
3289 // service two sockets in parallel.
3292 // Start a second connection.
3293 scoped_ptr
<StreamSocket
> transport2(
3294 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3295 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3296 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3297 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3298 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3300 // No session resumption because the first connection never received a server
3301 // Finished message.
3303 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3304 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3307 // Test that False Started sessions are not resumable if the server Finished
3309 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBadFinished
) {
3310 if (!SupportsAESGCM()) {
3311 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3316 SpawnedTestServer::SSLOptions server_options
;
3317 server_options
.key_exchanges
=
3318 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3319 server_options
.bulk_ciphers
=
3320 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3321 server_options
.enable_npn
= true;
3322 ASSERT_TRUE(StartTestServer(server_options
));
3324 SSLConfig client_config
;
3325 client_config
.next_protos
.push_back(kProtoHTTP11
);
3327 // Start a handshake up to the server Finished message.
3328 TestCompletionCallback callback
;
3329 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3330 scoped_ptr
<SSLClientSocket
> sock1
;
3331 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3332 client_config
, &callback
, &raw_transport1
, &sock1
));
3333 // Although raw_transport1 has the server Finished blocked, the handshake
3335 EXPECT_EQ(OK
, callback
.WaitForResult());
3337 // Continue to block the client (|sock1|) from processing the Finished
3338 // message, but allow it to arrive on the socket. This ensures that, from the
3339 // server's point of view, it has completed the handshake and added the
3340 // session to its session cache.
3342 // The actual read on |sock1| will not complete until the Finished message is
3343 // processed; however, pump the underlying transport so that it is read from
3345 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3346 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3347 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3348 raw_transport1
->WaitForReadResult();
3350 // The server's second leg, or part of it, is now received but not yet sent to
3351 // |sock1|. Before doing so, break the server's second leg.
3352 int bytes_read
= raw_transport1
->pending_read_result();
3353 ASSERT_LT(0, bytes_read
);
3354 raw_transport1
->pending_read_buf()->data()[bytes_read
- 1]++;
3356 // Unblock the Finished message. |sock1->Read| should now fail.
3357 raw_transport1
->UnblockReadResult();
3358 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, callback
.GetResult(rv
));
3360 // Drop the old socket. This is needed because the Python test server can't
3361 // service two sockets in parallel.
3364 // Start a second connection.
3365 scoped_ptr
<StreamSocket
> transport2(
3366 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3367 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3368 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3369 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3370 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3372 // No session resumption because the first connection never received a server
3373 // Finished message.
3375 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3376 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3379 // Connect to a server using channel id. It should allow the connection.
3380 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
3381 SpawnedTestServer::SSLOptions ssl_options
;
3383 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3386 SSLConfig ssl_config
;
3387 ssl_config
.channel_id_enabled
= true;
3390 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3393 EXPECT_TRUE(sock_
->IsConnected());
3394 EXPECT_TRUE(sock_
->WasChannelIDSent());
3396 sock_
->Disconnect();
3397 EXPECT_FALSE(sock_
->IsConnected());
3400 // Connect to a server using Channel ID but failing to look up the Channel
3401 // ID. It should fail.
3402 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
3403 SpawnedTestServer::SSLOptions ssl_options
;
3405 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3407 EnableFailingChannelID();
3408 SSLConfig ssl_config
;
3409 ssl_config
.channel_id_enabled
= true;
3412 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3414 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3415 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3416 // error codes for now.
3417 // http://crbug.com/373670
3419 EXPECT_FALSE(sock_
->IsConnected());
3422 // Connect to a server using Channel ID but asynchronously failing to look up
3423 // the Channel ID. It should fail.
3424 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
3425 SpawnedTestServer::SSLOptions ssl_options
;
3427 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3429 EnableAsyncFailingChannelID();
3430 SSLConfig ssl_config
;
3431 ssl_config
.channel_id_enabled
= true;
3434 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3436 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
3437 EXPECT_FALSE(sock_
->IsConnected());