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/location.h"
9 #include "base/memory/ref_counted.h"
10 #include "base/run_loop.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "base/time/time.h"
14 #include "net/base/address_list.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/test_completion_callback.h"
18 #include "net/base/test_data_directory.h"
19 #include "net/cert/asn1_util.h"
20 #include "net/cert/ct_verifier.h"
21 #include "net/cert/mock_cert_verifier.h"
22 #include "net/cert/test_root_certs.h"
23 #include "net/dns/host_resolver.h"
24 #include "net/http/transport_security_state.h"
25 #include "net/log/net_log.h"
26 #include "net/log/test_net_log.h"
27 #include "net/log/test_net_log_entry.h"
28 #include "net/log/test_net_log_util.h"
29 #include "net/socket/client_socket_factory.h"
30 #include "net/socket/client_socket_handle.h"
31 #include "net/socket/socket_test_util.h"
32 #include "net/socket/tcp_client_socket.h"
33 #include "net/ssl/channel_id_service.h"
34 #include "net/ssl/default_channel_id_store.h"
35 #include "net/ssl/ssl_cert_request_info.h"
36 #include "net/ssl/ssl_config_service.h"
37 #include "net/ssl/ssl_connection_status_flags.h"
38 #include "net/ssl/ssl_info.h"
39 #include "net/test/cert_test_util.h"
40 #include "net/test/spawned_test_server/spawned_test_server.h"
41 #include "testing/gmock/include/gmock/gmock.h"
42 #include "testing/gtest/include/gtest/gtest.h"
43 #include "testing/platform_test.h"
45 #if !defined(USE_OPENSSL)
47 #include "crypto/nss_util.h"
49 #if !defined(CKM_AES_GCM)
50 #define CKM_AES_GCM 0x00001087
53 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
54 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
58 //-----------------------------------------------------------------------------
61 using testing::Return
;
68 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
69 // forwarding the Socket and StreamSocket interfaces to the underlying
71 // This is to provide a common base class for subclasses to override specific
72 // StreamSocket methods for testing, while still communicating with a 'real'
74 class WrappedStreamSocket
: public StreamSocket
{
76 explicit WrappedStreamSocket(scoped_ptr
<StreamSocket
> transport
)
77 : transport_(transport
.Pass()) {}
78 ~WrappedStreamSocket() override
{}
80 // StreamSocket implementation:
81 int Connect(const CompletionCallback
& callback
) override
{
82 return transport_
->Connect(callback
);
84 void Disconnect() override
{ transport_
->Disconnect(); }
85 bool IsConnected() const override
{ return transport_
->IsConnected(); }
86 bool IsConnectedAndIdle() const override
{
87 return transport_
->IsConnectedAndIdle();
89 int GetPeerAddress(IPEndPoint
* address
) const override
{
90 return transport_
->GetPeerAddress(address
);
92 int GetLocalAddress(IPEndPoint
* address
) const override
{
93 return transport_
->GetLocalAddress(address
);
95 const BoundNetLog
& NetLog() const override
{ return transport_
->NetLog(); }
96 void SetSubresourceSpeculation() override
{
97 transport_
->SetSubresourceSpeculation();
99 void SetOmniboxSpeculation() override
{ transport_
->SetOmniboxSpeculation(); }
100 bool WasEverUsed() const override
{ return transport_
->WasEverUsed(); }
101 bool UsingTCPFastOpen() const override
{
102 return transport_
->UsingTCPFastOpen();
104 bool WasNpnNegotiated() const override
{
105 return transport_
->WasNpnNegotiated();
107 NextProto
GetNegotiatedProtocol() const override
{
108 return transport_
->GetNegotiatedProtocol();
110 bool GetSSLInfo(SSLInfo
* ssl_info
) override
{
111 return transport_
->GetSSLInfo(ssl_info
);
113 void GetConnectionAttempts(ConnectionAttempts
* out
) const override
{
114 transport_
->GetConnectionAttempts(out
);
116 void ClearConnectionAttempts() override
{
117 transport_
->ClearConnectionAttempts();
119 void AddConnectionAttempts(const ConnectionAttempts
& attempts
) override
{
120 transport_
->AddConnectionAttempts(attempts
);
123 // Socket implementation:
124 int Read(IOBuffer
* buf
,
126 const CompletionCallback
& callback
) override
{
127 return transport_
->Read(buf
, buf_len
, callback
);
129 int Write(IOBuffer
* buf
,
131 const CompletionCallback
& callback
) override
{
132 return transport_
->Write(buf
, buf_len
, callback
);
134 int SetReceiveBufferSize(int32 size
) override
{
135 return transport_
->SetReceiveBufferSize(size
);
137 int SetSendBufferSize(int32 size
) override
{
138 return transport_
->SetSendBufferSize(size
);
142 scoped_ptr
<StreamSocket
> transport_
;
145 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
146 // will ensure a certain amount of data is internally buffered before
147 // satisfying a Read() request. It exists to mimic OS-level internal
148 // buffering, but in a way to guarantee that X number of bytes will be
149 // returned to callers of Read(), regardless of how quickly the OS receives
150 // them from the TestServer.
151 class ReadBufferingStreamSocket
: public WrappedStreamSocket
{
153 explicit ReadBufferingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
154 ~ReadBufferingStreamSocket() override
{}
156 // Socket implementation:
157 int Read(IOBuffer
* buf
,
159 const CompletionCallback
& callback
) override
;
161 // Sets the internal buffer to |size|. This must not be greater than
162 // the largest value supplied to Read() - that is, it does not handle
163 // having "leftovers" at the end of Read().
164 // Each call to Read() will be prevented from completion until at least
165 // |size| data has been read.
166 // Set to 0 to turn off buffering, causing Read() to transparently
167 // read via the underlying transport.
168 void SetBufferSize(int size
);
177 int DoLoop(int result
);
179 int DoReadComplete(int result
);
180 void OnReadCompleted(int result
);
183 scoped_refptr
<GrowableIOBuffer
> read_buffer_
;
186 scoped_refptr
<IOBuffer
> user_read_buf_
;
187 CompletionCallback user_read_callback_
;
190 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
191 scoped_ptr
<StreamSocket
> transport
)
192 : WrappedStreamSocket(transport
.Pass()),
193 read_buffer_(new GrowableIOBuffer()),
196 void ReadBufferingStreamSocket::SetBufferSize(int size
) {
197 DCHECK(!user_read_buf_
.get());
199 read_buffer_
->SetCapacity(size
);
202 int ReadBufferingStreamSocket::Read(IOBuffer
* buf
,
204 const CompletionCallback
& callback
) {
205 if (buffer_size_
== 0)
206 return transport_
->Read(buf
, buf_len
, callback
);
208 if (buf_len
< buffer_size_
)
209 return ERR_UNEXPECTED
;
212 user_read_buf_
= buf
;
213 int result
= DoLoop(OK
);
214 if (result
== ERR_IO_PENDING
)
215 user_read_callback_
= callback
;
217 user_read_buf_
= NULL
;
221 int ReadBufferingStreamSocket::DoLoop(int result
) {
224 State current_state
= state_
;
226 switch (current_state
) {
230 case STATE_READ_COMPLETE
:
231 rv
= DoReadComplete(rv
);
235 NOTREACHED() << "Unexpected state: " << current_state
;
239 } while (rv
!= ERR_IO_PENDING
&& state_
!= STATE_NONE
);
243 int ReadBufferingStreamSocket::DoRead() {
244 state_
= STATE_READ_COMPLETE
;
246 transport_
->Read(read_buffer_
.get(),
247 read_buffer_
->RemainingCapacity(),
248 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted
,
249 base::Unretained(this)));
253 int ReadBufferingStreamSocket::DoReadComplete(int result
) {
258 read_buffer_
->set_offset(read_buffer_
->offset() + result
);
259 if (read_buffer_
->RemainingCapacity() > 0) {
264 memcpy(user_read_buf_
->data(),
265 read_buffer_
->StartOfBuffer(),
266 read_buffer_
->capacity());
267 read_buffer_
->set_offset(0);
268 return read_buffer_
->capacity();
271 void ReadBufferingStreamSocket::OnReadCompleted(int result
) {
272 result
= DoLoop(result
);
273 if (result
== ERR_IO_PENDING
)
276 user_read_buf_
= NULL
;
277 base::ResetAndReturn(&user_read_callback_
).Run(result
);
280 // Simulates synchronously receiving an error during Read() or Write()
281 class SynchronousErrorStreamSocket
: public WrappedStreamSocket
{
283 explicit SynchronousErrorStreamSocket(scoped_ptr
<StreamSocket
> transport
);
284 ~SynchronousErrorStreamSocket() override
{}
286 // Socket implementation:
287 int Read(IOBuffer
* buf
,
289 const CompletionCallback
& callback
) override
;
290 int Write(IOBuffer
* buf
,
292 const CompletionCallback
& callback
) override
;
294 // Sets the next Read() call and all future calls to return |error|.
295 // If there is already a pending asynchronous read, the configured error
296 // will not be returned until that asynchronous read has completed and Read()
298 void SetNextReadError(int error
) {
300 have_read_error_
= true;
301 pending_read_error_
= error
;
304 // Sets the next Write() call and all future calls to return |error|.
305 // If there is already a pending asynchronous write, the configured error
306 // will not be returned until that asynchronous write has completed and
307 // Write() is called again.
308 void SetNextWriteError(int error
) {
310 have_write_error_
= true;
311 pending_write_error_
= error
;
315 bool have_read_error_
;
316 int pending_read_error_
;
318 bool have_write_error_
;
319 int pending_write_error_
;
321 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket
);
324 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
325 scoped_ptr
<StreamSocket
> transport
)
326 : WrappedStreamSocket(transport
.Pass()),
327 have_read_error_(false),
328 pending_read_error_(OK
),
329 have_write_error_(false),
330 pending_write_error_(OK
) {}
332 int SynchronousErrorStreamSocket::Read(IOBuffer
* buf
,
334 const CompletionCallback
& callback
) {
335 if (have_read_error_
)
336 return pending_read_error_
;
337 return transport_
->Read(buf
, buf_len
, callback
);
340 int SynchronousErrorStreamSocket::Write(IOBuffer
* buf
,
342 const CompletionCallback
& callback
) {
343 if (have_write_error_
)
344 return pending_write_error_
;
345 return transport_
->Write(buf
, buf_len
, callback
);
348 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
349 // underlying transport needing to complete things asynchronously in a
350 // deterministic manner (e.g.: independent of the TestServer and the OS's
352 class FakeBlockingStreamSocket
: public WrappedStreamSocket
{
354 explicit FakeBlockingStreamSocket(scoped_ptr
<StreamSocket
> transport
);
355 ~FakeBlockingStreamSocket() override
{}
357 // Socket implementation:
358 int Read(IOBuffer
* buf
,
360 const CompletionCallback
& callback
) override
;
361 int Write(IOBuffer
* buf
,
363 const CompletionCallback
& callback
) override
;
365 int pending_read_result() const { return pending_read_result_
; }
366 IOBuffer
* pending_read_buf() const { return pending_read_buf_
.get(); }
368 // Blocks read results on the socket. Reads will not complete until
369 // UnblockReadResult() has been called and a result is ready from the
370 // underlying transport. Note: if BlockReadResult() is called while there is a
371 // hanging asynchronous Read(), that Read is blocked.
372 void BlockReadResult();
373 void UnblockReadResult();
375 // Waits for the blocked Read() call to be complete at the underlying
377 void WaitForReadResult();
379 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
380 // underlying transport until UnblockWrite() has been called. Note: if there
381 // is a pending asynchronous write, it is NOT blocked. For purposes of
382 // blocking writes, data is considered to have reached the underlying
383 // transport as soon as Write() is called.
387 // Waits for the blocked Write() call to be scheduled.
391 // Handles completion from the underlying transport read.
392 void OnReadCompleted(int result
);
394 // True if read callbacks are blocked.
395 bool should_block_read_
;
397 // The buffer for the pending read, or NULL if not consumed.
398 scoped_refptr
<IOBuffer
> pending_read_buf_
;
400 // The user callback for the pending read call.
401 CompletionCallback pending_read_callback_
;
403 // The result for the blocked read callback, or ERR_IO_PENDING if not
405 int pending_read_result_
;
407 // WaitForReadResult() wait loop.
408 scoped_ptr
<base::RunLoop
> read_loop_
;
410 // True if write calls are blocked.
411 bool should_block_write_
;
413 // The buffer for the pending write, or NULL if not scheduled.
414 scoped_refptr
<IOBuffer
> pending_write_buf_
;
416 // The callback for the pending write call.
417 CompletionCallback pending_write_callback_
;
419 // The length for the pending write, or -1 if not scheduled.
420 int pending_write_len_
;
422 // WaitForWrite() wait loop.
423 scoped_ptr
<base::RunLoop
> write_loop_
;
426 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
427 scoped_ptr
<StreamSocket
> transport
)
428 : WrappedStreamSocket(transport
.Pass()),
429 should_block_read_(false),
430 pending_read_result_(ERR_IO_PENDING
),
431 should_block_write_(false),
432 pending_write_len_(-1) {}
434 int FakeBlockingStreamSocket::Read(IOBuffer
* buf
,
436 const CompletionCallback
& callback
) {
437 DCHECK(!pending_read_buf_
);
438 DCHECK(pending_read_callback_
.is_null());
439 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
440 DCHECK(!callback
.is_null());
442 int rv
= transport_
->Read(buf
, len
, base::Bind(
443 &FakeBlockingStreamSocket::OnReadCompleted
, base::Unretained(this)));
444 if (rv
== ERR_IO_PENDING
) {
445 // Save the callback to be called later.
446 pending_read_buf_
= buf
;
447 pending_read_callback_
= callback
;
448 } else if (should_block_read_
) {
449 // Save the callback and read result to be called later.
450 pending_read_buf_
= buf
;
451 pending_read_callback_
= callback
;
458 int FakeBlockingStreamSocket::Write(IOBuffer
* buf
,
460 const CompletionCallback
& callback
) {
464 if (!should_block_write_
)
465 return transport_
->Write(buf
, len
, callback
);
467 // Schedule the write, but do nothing.
468 DCHECK(!pending_write_buf_
.get());
469 DCHECK_EQ(-1, pending_write_len_
);
470 DCHECK(pending_write_callback_
.is_null());
471 DCHECK(!callback
.is_null());
472 pending_write_buf_
= buf
;
473 pending_write_len_
= len
;
474 pending_write_callback_
= callback
;
476 // Stop the write loop, if any.
479 return ERR_IO_PENDING
;
482 void FakeBlockingStreamSocket::BlockReadResult() {
483 DCHECK(!should_block_read_
);
484 should_block_read_
= true;
487 void FakeBlockingStreamSocket::UnblockReadResult() {
488 DCHECK(should_block_read_
);
489 should_block_read_
= false;
491 // If the operation is still pending in the underlying transport, immediately
492 // return - OnReadCompleted() will handle invoking the callback once the
493 // transport has completed.
494 if (pending_read_result_
== ERR_IO_PENDING
)
496 int result
= pending_read_result_
;
497 pending_read_buf_
= nullptr;
498 pending_read_result_
= ERR_IO_PENDING
;
499 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
502 void FakeBlockingStreamSocket::WaitForReadResult() {
503 DCHECK(should_block_read_
);
506 if (pending_read_result_
!= ERR_IO_PENDING
)
508 read_loop_
.reset(new base::RunLoop
);
511 DCHECK_NE(ERR_IO_PENDING
, pending_read_result_
);
514 void FakeBlockingStreamSocket::BlockWrite() {
515 DCHECK(!should_block_write_
);
516 should_block_write_
= true;
519 void FakeBlockingStreamSocket::UnblockWrite() {
520 DCHECK(should_block_write_
);
521 should_block_write_
= false;
523 // Do nothing if UnblockWrite() was called after BlockWrite(),
524 // without a Write() in between.
525 if (!pending_write_buf_
.get())
528 int rv
= transport_
->Write(
529 pending_write_buf_
.get(), pending_write_len_
, pending_write_callback_
);
530 pending_write_buf_
= NULL
;
531 pending_write_len_
= -1;
532 if (rv
== ERR_IO_PENDING
) {
533 pending_write_callback_
.Reset();
535 base::ResetAndReturn(&pending_write_callback_
).Run(rv
);
539 void FakeBlockingStreamSocket::WaitForWrite() {
540 DCHECK(should_block_write_
);
541 DCHECK(!write_loop_
);
543 if (pending_write_buf_
.get())
545 write_loop_
.reset(new base::RunLoop
);
548 DCHECK(pending_write_buf_
.get());
551 void FakeBlockingStreamSocket::OnReadCompleted(int result
) {
552 DCHECK_EQ(ERR_IO_PENDING
, pending_read_result_
);
553 DCHECK(!pending_read_callback_
.is_null());
555 if (should_block_read_
) {
556 // Store the result so that the callback can be invoked once Unblock() is
558 pending_read_result_
= result
;
560 // Stop the WaitForReadResult() call if any.
564 // Either the Read() was never blocked or UnblockReadResult() was called
565 // before the Read() completed. Either way, return the result to the caller.
566 pending_read_buf_
= nullptr;
567 base::ResetAndReturn(&pending_read_callback_
).Run(result
);
571 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
572 // reads and writes on the socket.
573 class CountingStreamSocket
: public WrappedStreamSocket
{
575 explicit CountingStreamSocket(scoped_ptr
<StreamSocket
> transport
)
576 : WrappedStreamSocket(transport
.Pass()),
579 ~CountingStreamSocket() override
{}
581 // Socket implementation:
582 int Read(IOBuffer
* buf
,
584 const CompletionCallback
& callback
) override
{
586 return transport_
->Read(buf
, buf_len
, callback
);
588 int Write(IOBuffer
* buf
,
590 const CompletionCallback
& callback
) override
{
592 return transport_
->Write(buf
, buf_len
, callback
);
595 int read_count() const { return read_count_
; }
596 int write_count() const { return write_count_
; }
603 // CompletionCallback that will delete the associated StreamSocket when
604 // the callback is invoked.
605 class DeleteSocketCallback
: public TestCompletionCallbackBase
{
607 explicit DeleteSocketCallback(StreamSocket
* socket
)
609 callback_(base::Bind(&DeleteSocketCallback::OnComplete
,
610 base::Unretained(this))) {}
611 ~DeleteSocketCallback() override
{}
613 const CompletionCallback
& callback() const { return callback_
; }
616 void OnComplete(int result
) {
621 ADD_FAILURE() << "Deleting socket twice";
626 StreamSocket
* socket_
;
627 CompletionCallback callback_
;
629 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback
);
632 // A ChannelIDStore that always returns an error when asked for a
634 class FailingChannelIDStore
: public ChannelIDStore
{
635 int GetChannelID(const std::string
& server_identifier
,
636 scoped_ptr
<crypto::ECPrivateKey
>* key_result
,
637 const GetChannelIDCallback
& callback
) override
{
638 return ERR_UNEXPECTED
;
640 void SetChannelID(scoped_ptr
<ChannelID
> channel_id
) override
{}
641 void DeleteChannelID(const std::string
& server_identifier
,
642 const base::Closure
& completion_callback
) override
{}
643 void DeleteAllCreatedBetween(
644 base::Time delete_begin
,
645 base::Time delete_end
,
646 const base::Closure
& completion_callback
) override
{}
647 void DeleteAll(const base::Closure
& completion_callback
) override
{}
648 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
649 int GetChannelIDCount() override
{ return 0; }
650 void SetForceKeepSessionState() override
{}
653 // A ChannelIDStore that asynchronously returns an error when asked for a
655 class AsyncFailingChannelIDStore
: public ChannelIDStore
{
656 int GetChannelID(const std::string
& server_identifier
,
657 scoped_ptr
<crypto::ECPrivateKey
>* key_result
,
658 const GetChannelIDCallback
& callback
) override
{
659 base::ThreadTaskRunnerHandle::Get()->PostTask(
661 base::Bind(callback
, ERR_UNEXPECTED
, server_identifier
, nullptr));
662 return ERR_IO_PENDING
;
664 void SetChannelID(scoped_ptr
<ChannelID
> channel_id
) override
{}
665 void DeleteChannelID(const std::string
& server_identifier
,
666 const base::Closure
& completion_callback
) override
{}
667 void DeleteAllCreatedBetween(
668 base::Time delete_begin
,
669 base::Time delete_end
,
670 const base::Closure
& completion_callback
) override
{}
671 void DeleteAll(const base::Closure
& completion_callback
) override
{}
672 void GetAllChannelIDs(const GetChannelIDListCallback
& callback
) override
{}
673 int GetChannelIDCount() override
{ return 0; }
674 void SetForceKeepSessionState() override
{}
677 // A mock CTVerifier that records every call to Verify but doesn't verify
679 class MockCTVerifier
: public CTVerifier
{
681 MOCK_METHOD5(Verify
, int(X509Certificate
*,
685 const BoundNetLog
&));
686 MOCK_METHOD1(SetObserver
, void(CTVerifier::Observer
*));
689 class SSLClientSocketTest
: public PlatformTest
{
691 SSLClientSocketTest()
692 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
693 cert_verifier_(new MockCertVerifier
),
694 transport_security_state_(new TransportSecurityState
) {
695 cert_verifier_
->set_default_result(OK
);
696 context_
.cert_verifier
= cert_verifier_
.get();
697 context_
.transport_security_state
= transport_security_state_
.get();
701 // The address of the spawned test server, after calling StartTestServer().
702 const AddressList
& addr() const { return addr_
; }
704 // The SpawnedTestServer object, after calling StartTestServer().
705 const SpawnedTestServer
* test_server() const { return test_server_
.get(); }
707 void SetCTVerifier(CTVerifier
* ct_verifier
) {
708 context_
.cert_transparency_verifier
= ct_verifier
;
711 // Starts the test server with SSL configuration |ssl_options|. Returns true
713 bool StartTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
714 test_server_
.reset(new SpawnedTestServer(
715 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath()));
716 if (!test_server_
->Start()) {
717 LOG(ERROR
) << "Could not start SpawnedTestServer";
721 if (!test_server_
->GetAddressList(&addr_
)) {
722 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
728 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
729 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
730 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions
& ssl_options
) {
731 if (!StartTestServer(ssl_options
))
734 transport_
.reset(new TCPClientSocket(addr_
, &log_
, NetLog::Source()));
735 int rv
= callback_
.GetResult(transport_
->Connect(callback_
.callback()));
737 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
743 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
744 scoped_ptr
<StreamSocket
> transport_socket
,
745 const HostPortPair
& host_and_port
,
746 const SSLConfig
& ssl_config
) {
747 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
748 connection
->SetSocket(transport_socket
.Pass());
749 return socket_factory_
->CreateSSLClientSocket(
750 connection
.Pass(), host_and_port
, ssl_config
, context_
);
753 // Create an SSLClientSocket object and use it to connect to a test
754 // server, then wait for connection results. This must be called after
755 // a successful ConnectToTestServer() call.
756 // |ssl_config| the SSL configuration to use.
757 // |result| will retrieve the ::Connect() result value.
758 // Returns true on success, false otherwise. Success means that the socket
759 // could be created and its Connect() was called, not that the connection
760 // itself was a success.
761 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
, int* result
) {
762 sock_
= CreateSSLClientSocket(
763 transport_
.Pass(), test_server_
->host_port_pair(), ssl_config
);
765 if (sock_
->IsConnected()) {
766 LOG(ERROR
) << "SSL Socket prematurely connected";
770 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
774 ClientSocketFactory
* socket_factory_
;
775 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
776 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
777 SSLClientSocketContext context_
;
778 scoped_ptr
<SSLClientSocket
> sock_
;
782 scoped_ptr
<StreamSocket
> transport_
;
783 scoped_ptr
<SpawnedTestServer
> test_server_
;
784 TestCompletionCallback callback_
;
788 // Verifies the correctness of GetSSLCertRequestInfo.
789 class SSLClientSocketCertRequestInfoTest
: public SSLClientSocketTest
{
791 // Creates a test server with the given SSLOptions, connects to it and returns
792 // the SSLCertRequestInfo reported by the socket.
793 scoped_refptr
<SSLCertRequestInfo
> GetCertRequest(
794 SpawnedTestServer::SSLOptions ssl_options
) {
795 SpawnedTestServer
test_server(
796 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
797 if (!test_server
.Start())
801 if (!test_server
.GetAddressList(&addr
))
804 TestCompletionCallback callback
;
806 scoped_ptr
<StreamSocket
> transport(
807 new TCPClientSocket(addr
, &log
, NetLog::Source()));
808 int rv
= transport
->Connect(callback
.callback());
809 if (rv
== ERR_IO_PENDING
)
810 rv
= callback
.WaitForResult();
813 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
814 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
815 EXPECT_FALSE(sock
->IsConnected());
817 rv
= sock
->Connect(callback
.callback());
818 if (rv
== ERR_IO_PENDING
)
819 rv
= callback
.WaitForResult();
820 scoped_refptr
<SSLCertRequestInfo
> request_info
= new SSLCertRequestInfo();
821 sock
->GetSSLCertRequestInfo(request_info
.get());
823 EXPECT_FALSE(sock
->IsConnected());
825 test_server
.host_port_pair().Equals(request_info
->host_and_port
));
831 class SSLClientSocketFalseStartTest
: public SSLClientSocketTest
{
833 // Creates an SSLClientSocket with |client_config| attached to a
834 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
835 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
836 // so |*out_raw_transport| is a raw pointer.
838 // The client socket will begin a connect using |callback| but stop before the
839 // server's finished message is received. The finished message will be blocked
840 // in |*out_raw_transport|. To complete the handshake and successfully read
841 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
842 // the client successfully false started, |callback.WaitForResult()| will
843 // return OK without unblocking transport reads. But Read() will still block.)
845 // Must be called after StartTestServer is called.
846 void CreateAndConnectUntilServerFinishedReceived(
847 const SSLConfig
& client_config
,
848 TestCompletionCallback
* callback
,
849 FakeBlockingStreamSocket
** out_raw_transport
,
850 scoped_ptr
<SSLClientSocket
>* out_sock
) {
851 CHECK(test_server());
853 scoped_ptr
<StreamSocket
> real_transport(
854 new TCPClientSocket(addr(), NULL
, NetLog::Source()));
855 scoped_ptr
<FakeBlockingStreamSocket
> transport(
856 new FakeBlockingStreamSocket(real_transport
.Pass()));
857 int rv
= callback
->GetResult(transport
->Connect(callback
->callback()));
860 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
861 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
862 transport
.Pass(), test_server()->host_port_pair(), client_config
);
864 // Connect. Stop before the client processes the first server leg
865 // (ServerHello, etc.)
866 raw_transport
->BlockReadResult();
867 rv
= sock
->Connect(callback
->callback());
868 EXPECT_EQ(ERR_IO_PENDING
, rv
);
869 raw_transport
->WaitForReadResult();
871 // Release the ServerHello and wait for the client to write
872 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
873 // server's leg to complete, since it may span multiple reads.)
874 EXPECT_FALSE(callback
->have_result());
875 raw_transport
->BlockWrite();
876 raw_transport
->UnblockReadResult();
877 raw_transport
->WaitForWrite();
879 // And, finally, release that and block the next server leg
880 // (ChangeCipherSpec, Finished).
881 raw_transport
->BlockReadResult();
882 raw_transport
->UnblockWrite();
884 *out_raw_transport
= raw_transport
;
885 *out_sock
= sock
.Pass();
888 void TestFalseStart(const SpawnedTestServer::SSLOptions
& server_options
,
889 const SSLConfig
& client_config
,
890 bool expect_false_start
) {
891 ASSERT_TRUE(StartTestServer(server_options
));
893 TestCompletionCallback callback
;
894 FakeBlockingStreamSocket
* raw_transport
= NULL
;
895 scoped_ptr
<SSLClientSocket
> sock
;
896 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
897 client_config
, &callback
, &raw_transport
, &sock
));
899 if (expect_false_start
) {
900 // When False Starting, the handshake should complete before receiving the
901 // Change Cipher Spec and Finished messages.
903 // Note: callback.have_result() may not be true without waiting. The NSS
904 // state machine sometimes lives on a separate thread, so this thread may
905 // not yet have processed the signal that the handshake has completed.
906 int rv
= callback
.WaitForResult();
908 EXPECT_TRUE(sock
->IsConnected());
910 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
911 static const int kRequestTextSize
=
912 static_cast<int>(arraysize(request_text
) - 1);
913 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
914 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
916 // Write the request.
917 rv
= callback
.GetResult(sock
->Write(request_buffer
.get(),
919 callback
.callback()));
920 EXPECT_EQ(kRequestTextSize
, rv
);
922 // The read will hang; it's waiting for the peer to complete the
923 // handshake, and the handshake is still blocked.
924 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
925 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
927 // After releasing reads, the connection proceeds.
928 raw_transport
->UnblockReadResult();
929 rv
= callback
.GetResult(rv
);
932 // False Start is not enabled, so the handshake will not complete because
933 // the server second leg is blocked.
934 base::RunLoop().RunUntilIdle();
935 EXPECT_FALSE(callback
.have_result());
940 class SSLClientSocketChannelIDTest
: public SSLClientSocketTest
{
942 void EnableChannelID() {
943 channel_id_service_
.reset(new ChannelIDService(
944 new DefaultChannelIDStore(NULL
), base::ThreadTaskRunnerHandle::Get()));
945 context_
.channel_id_service
= channel_id_service_
.get();
948 void EnableFailingChannelID() {
949 channel_id_service_
.reset(new ChannelIDService(
950 new FailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
951 context_
.channel_id_service
= channel_id_service_
.get();
954 void EnableAsyncFailingChannelID() {
955 channel_id_service_
.reset(new ChannelIDService(
956 new AsyncFailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
957 context_
.channel_id_service
= channel_id_service_
.get();
961 scoped_ptr
<ChannelIDService
> channel_id_service_
;
964 //-----------------------------------------------------------------------------
966 bool SupportsAESGCM() {
967 #if defined(USE_OPENSSL)
970 crypto::EnsureNSSInit();
971 return PK11_TokenExists(CKM_AES_GCM
) &&
972 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256
);
978 TEST_F(SSLClientSocketTest
, Connect
) {
979 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
980 SpawnedTestServer::kLocalhost
,
982 ASSERT_TRUE(test_server
.Start());
985 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
987 TestCompletionCallback callback
;
989 scoped_ptr
<StreamSocket
> transport(
990 new TCPClientSocket(addr
, &log
, NetLog::Source()));
991 int rv
= transport
->Connect(callback
.callback());
992 if (rv
== ERR_IO_PENDING
)
993 rv
= callback
.WaitForResult();
996 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
997 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
999 EXPECT_FALSE(sock
->IsConnected());
1001 rv
= sock
->Connect(callback
.callback());
1003 TestNetLogEntry::List entries
;
1004 log
.GetEntries(&entries
);
1005 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1006 if (rv
== ERR_IO_PENDING
)
1007 rv
= callback
.WaitForResult();
1009 EXPECT_TRUE(sock
->IsConnected());
1010 log
.GetEntries(&entries
);
1011 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
1014 EXPECT_FALSE(sock
->IsConnected());
1017 TEST_F(SSLClientSocketTest
, ConnectExpired
) {
1018 SpawnedTestServer::SSLOptions
ssl_options(
1019 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
1020 SpawnedTestServer
test_server(
1021 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1022 ASSERT_TRUE(test_server
.Start());
1024 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
1027 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1029 TestCompletionCallback callback
;
1031 scoped_ptr
<StreamSocket
> transport(
1032 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1033 int rv
= transport
->Connect(callback
.callback());
1034 if (rv
== ERR_IO_PENDING
)
1035 rv
= callback
.WaitForResult();
1038 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1039 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1041 EXPECT_FALSE(sock
->IsConnected());
1043 rv
= sock
->Connect(callback
.callback());
1045 TestNetLogEntry::List entries
;
1046 log
.GetEntries(&entries
);
1047 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1048 if (rv
== ERR_IO_PENDING
)
1049 rv
= callback
.WaitForResult();
1051 EXPECT_EQ(ERR_CERT_DATE_INVALID
, rv
);
1053 // Rather than testing whether or not the underlying socket is connected,
1054 // test that the handshake has finished. This is because it may be
1055 // desirable to disconnect the socket before showing a user prompt, since
1056 // the user may take indefinitely long to respond.
1057 log
.GetEntries(&entries
);
1058 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
1061 TEST_F(SSLClientSocketTest
, ConnectMismatched
) {
1062 SpawnedTestServer::SSLOptions
ssl_options(
1063 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
1064 SpawnedTestServer
test_server(
1065 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1066 ASSERT_TRUE(test_server
.Start());
1068 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
1071 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1073 TestCompletionCallback callback
;
1075 scoped_ptr
<StreamSocket
> transport(
1076 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1077 int rv
= transport
->Connect(callback
.callback());
1078 if (rv
== ERR_IO_PENDING
)
1079 rv
= callback
.WaitForResult();
1082 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1083 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1085 EXPECT_FALSE(sock
->IsConnected());
1087 rv
= sock
->Connect(callback
.callback());
1089 TestNetLogEntry::List entries
;
1090 log
.GetEntries(&entries
);
1091 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1092 if (rv
== ERR_IO_PENDING
)
1093 rv
= callback
.WaitForResult();
1095 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
, rv
);
1097 // Rather than testing whether or not the underlying socket is connected,
1098 // test that the handshake has finished. This is because it may be
1099 // desirable to disconnect the socket before showing a user prompt, since
1100 // the user may take indefinitely long to respond.
1101 log
.GetEntries(&entries
);
1102 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
1105 // Attempt to connect to a page which requests a client certificate. It should
1106 // return an error code on connect.
1107 TEST_F(SSLClientSocketTest
, ConnectClientAuthCertRequested
) {
1108 SpawnedTestServer::SSLOptions ssl_options
;
1109 ssl_options
.request_client_certificate
= true;
1110 SpawnedTestServer
test_server(
1111 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1112 ASSERT_TRUE(test_server
.Start());
1115 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1117 TestCompletionCallback callback
;
1119 scoped_ptr
<StreamSocket
> transport(
1120 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1121 int rv
= transport
->Connect(callback
.callback());
1122 if (rv
== ERR_IO_PENDING
)
1123 rv
= callback
.WaitForResult();
1126 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1127 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1129 EXPECT_FALSE(sock
->IsConnected());
1131 rv
= sock
->Connect(callback
.callback());
1133 TestNetLogEntry::List entries
;
1134 log
.GetEntries(&entries
);
1135 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1136 if (rv
== ERR_IO_PENDING
)
1137 rv
= callback
.WaitForResult();
1139 log
.GetEntries(&entries
);
1140 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
1141 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
1142 EXPECT_FALSE(sock
->IsConnected());
1145 // Connect to a server requesting optional client authentication. Send it a
1146 // null certificate. It should allow the connection.
1148 // TODO(davidben): Also test providing an actual certificate.
1149 TEST_F(SSLClientSocketTest
, ConnectClientAuthSendNullCert
) {
1150 SpawnedTestServer::SSLOptions ssl_options
;
1151 ssl_options
.request_client_certificate
= true;
1152 SpawnedTestServer
test_server(
1153 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
1154 ASSERT_TRUE(test_server
.Start());
1157 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1159 TestCompletionCallback callback
;
1161 scoped_ptr
<StreamSocket
> transport(
1162 new TCPClientSocket(addr
, &log
, NetLog::Source()));
1163 int rv
= transport
->Connect(callback
.callback());
1164 if (rv
== ERR_IO_PENDING
)
1165 rv
= callback
.WaitForResult();
1168 SSLConfig ssl_config
;
1169 ssl_config
.send_client_cert
= true;
1170 ssl_config
.client_cert
= NULL
;
1172 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1173 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1175 EXPECT_FALSE(sock
->IsConnected());
1177 // Our test server accepts certificate-less connections.
1178 // TODO(davidben): Add a test which requires them and verify the error.
1179 rv
= sock
->Connect(callback
.callback());
1181 TestNetLogEntry::List entries
;
1182 log
.GetEntries(&entries
);
1183 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
1184 if (rv
== ERR_IO_PENDING
)
1185 rv
= callback
.WaitForResult();
1188 EXPECT_TRUE(sock
->IsConnected());
1189 log
.GetEntries(&entries
);
1190 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
1192 // We responded to the server's certificate request with a Certificate
1193 // message with no client certificate in it. ssl_info.client_cert_sent
1194 // should be false in this case.
1196 sock
->GetSSLInfo(&ssl_info
);
1197 EXPECT_FALSE(ssl_info
.client_cert_sent
);
1200 EXPECT_FALSE(sock
->IsConnected());
1203 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1204 // - Server closes an SSL connection (with a close_notify alert message).
1205 // - Server closes the underlying TCP connection directly.
1206 // - Server sends data unexpectedly.
1208 // Tests that the socket can be read from successfully. Also test that a peer's
1209 // close_notify alert is successfully processed without error.
1210 TEST_F(SSLClientSocketTest
, Read
) {
1211 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1212 SpawnedTestServer::kLocalhost
,
1214 ASSERT_TRUE(test_server
.Start());
1217 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1219 TestCompletionCallback callback
;
1220 scoped_ptr
<StreamSocket
> transport(
1221 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1222 int rv
= transport
->Connect(callback
.callback());
1223 if (rv
== ERR_IO_PENDING
)
1224 rv
= callback
.WaitForResult();
1227 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1228 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1230 rv
= sock
->Connect(callback
.callback());
1231 if (rv
== ERR_IO_PENDING
)
1232 rv
= callback
.WaitForResult();
1234 EXPECT_TRUE(sock
->IsConnected());
1236 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1237 scoped_refptr
<IOBuffer
> request_buffer(
1238 new IOBuffer(arraysize(request_text
) - 1));
1239 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1242 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1243 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1245 if (rv
== ERR_IO_PENDING
)
1246 rv
= callback
.WaitForResult();
1247 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1249 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1251 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1252 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1254 if (rv
== ERR_IO_PENDING
)
1255 rv
= callback
.WaitForResult();
1262 // The peer should have cleanly closed the connection with a close_notify.
1266 // Tests that SSLClientSocket properly handles when the underlying transport
1267 // synchronously fails a transport read in during the handshake. The error code
1268 // should be preserved so SSLv3 fallback logic can condition on it.
1269 TEST_F(SSLClientSocketTest
, Connect_WithSynchronousError
) {
1270 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1271 SpawnedTestServer::kLocalhost
,
1273 ASSERT_TRUE(test_server
.Start());
1276 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1278 TestCompletionCallback callback
;
1279 scoped_ptr
<StreamSocket
> real_transport(
1280 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1281 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1282 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1283 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1286 // Disable TLS False Start to avoid handshake non-determinism.
1287 SSLConfig ssl_config
;
1288 ssl_config
.false_start_enabled
= false;
1290 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1291 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1292 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1294 raw_transport
->SetNextWriteError(ERR_CONNECTION_RESET
);
1296 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1297 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1298 EXPECT_FALSE(sock
->IsConnected());
1301 // Tests that the SSLClientSocket properly handles when the underlying transport
1302 // synchronously returns an error code - such as if an intermediary terminates
1303 // the socket connection uncleanly.
1304 // This is a regression test for http://crbug.com/238536
1305 TEST_F(SSLClientSocketTest
, Read_WithSynchronousError
) {
1306 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1307 SpawnedTestServer::kLocalhost
,
1309 ASSERT_TRUE(test_server
.Start());
1312 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1314 TestCompletionCallback callback
;
1315 scoped_ptr
<StreamSocket
> real_transport(
1316 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1317 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1318 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1319 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1322 // Disable TLS False Start to avoid handshake non-determinism.
1323 SSLConfig ssl_config
;
1324 ssl_config
.false_start_enabled
= false;
1326 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1327 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1328 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1330 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1332 EXPECT_TRUE(sock
->IsConnected());
1334 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1335 static const int kRequestTextSize
=
1336 static_cast<int>(arraysize(request_text
) - 1);
1337 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1338 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1340 rv
= callback
.GetResult(
1341 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1342 EXPECT_EQ(kRequestTextSize
, rv
);
1344 // Simulate an unclean/forcible shutdown.
1345 raw_transport
->SetNextReadError(ERR_CONNECTION_RESET
);
1347 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1349 // Note: This test will hang if this bug has regressed. Simply checking that
1350 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1351 // result when using a dedicated task runner for NSS.
1352 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1353 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1356 // Tests that the SSLClientSocket properly handles when the underlying transport
1357 // asynchronously returns an error code while writing data - such as if an
1358 // intermediary terminates the socket connection uncleanly.
1359 // This is a regression test for http://crbug.com/249848
1360 TEST_F(SSLClientSocketTest
, Write_WithSynchronousError
) {
1361 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1362 SpawnedTestServer::kLocalhost
,
1364 ASSERT_TRUE(test_server
.Start());
1367 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1369 TestCompletionCallback callback
;
1370 scoped_ptr
<StreamSocket
> real_transport(
1371 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1372 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1373 // is retained in order to configure additional errors.
1374 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1375 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1376 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1377 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1378 new FakeBlockingStreamSocket(error_socket
.Pass()));
1379 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1380 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1383 // Disable TLS False Start to avoid handshake non-determinism.
1384 SSLConfig ssl_config
;
1385 ssl_config
.false_start_enabled
= false;
1387 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1388 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1390 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1392 EXPECT_TRUE(sock
->IsConnected());
1394 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1395 static const int kRequestTextSize
=
1396 static_cast<int>(arraysize(request_text
) - 1);
1397 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1398 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1400 // Simulate an unclean/forcible shutdown on the underlying socket.
1401 // However, simulate this error asynchronously.
1402 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1403 raw_transport
->BlockWrite();
1405 // This write should complete synchronously, because the TLS ciphertext
1406 // can be created and placed into the outgoing buffers independent of the
1407 // underlying transport.
1408 rv
= callback
.GetResult(
1409 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1410 EXPECT_EQ(kRequestTextSize
, rv
);
1412 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1414 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1415 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1417 // Now unblock the outgoing request, having it fail with the connection
1419 raw_transport
->UnblockWrite();
1421 // Note: This will cause an inifite loop if this bug has regressed. Simply
1422 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1423 // is a legitimate result when using a dedicated task runner for NSS.
1424 rv
= callback
.GetResult(rv
);
1425 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1428 // If there is a Write failure at the transport with no follow-up Read, although
1429 // the write error will not be returned to the client until a future Read or
1430 // Write operation, SSLClientSocket should not spin attempting to re-write on
1431 // the socket. This is a regression test for part of https://crbug.com/381160.
1432 TEST_F(SSLClientSocketTest
, Write_WithSynchronousErrorNoRead
) {
1433 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1434 SpawnedTestServer::kLocalhost
,
1436 ASSERT_TRUE(test_server
.Start());
1439 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1441 TestCompletionCallback callback
;
1442 scoped_ptr
<StreamSocket
> real_transport(
1443 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1444 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1445 // is retained in order to query them.
1446 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1447 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1448 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1449 scoped_ptr
<CountingStreamSocket
> counting_socket(
1450 new CountingStreamSocket(error_socket
.Pass()));
1451 CountingStreamSocket
* raw_counting_socket
= counting_socket
.get();
1452 int rv
= callback
.GetResult(counting_socket
->Connect(callback
.callback()));
1455 // Disable TLS False Start to avoid handshake non-determinism.
1456 SSLConfig ssl_config
;
1457 ssl_config
.false_start_enabled
= false;
1459 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1460 counting_socket
.Pass(), test_server
.host_port_pair(), ssl_config
));
1462 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1464 ASSERT_TRUE(sock
->IsConnected());
1466 // Simulate an unclean/forcible shutdown on the underlying socket.
1467 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1469 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1470 static const int kRequestTextSize
=
1471 static_cast<int>(arraysize(request_text
) - 1);
1472 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1473 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1475 // This write should complete synchronously, because the TLS ciphertext
1476 // can be created and placed into the outgoing buffers independent of the
1477 // underlying transport.
1478 rv
= callback
.GetResult(
1479 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1480 ASSERT_EQ(kRequestTextSize
, rv
);
1482 // Let the event loop spin for a little bit of time. Even on platforms where
1483 // pumping the state machine involve thread hops, there should be no further
1484 // writes on the transport socket.
1486 // TODO(davidben): Avoid the arbitrary timeout?
1487 int old_write_count
= raw_counting_socket
->write_count();
1489 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
1490 FROM_HERE
, loop
.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1492 EXPECT_EQ(old_write_count
, raw_counting_socket
->write_count());
1495 // Test the full duplex mode, with Read and Write pending at the same time.
1496 // This test also serves as a regression test for http://crbug.com/29815.
1497 TEST_F(SSLClientSocketTest
, Read_FullDuplex
) {
1498 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1499 SpawnedTestServer::kLocalhost
,
1501 ASSERT_TRUE(test_server
.Start());
1504 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1506 TestCompletionCallback callback
; // Used for everything except Write.
1508 scoped_ptr
<StreamSocket
> transport(
1509 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1510 int rv
= transport
->Connect(callback
.callback());
1511 if (rv
== ERR_IO_PENDING
)
1512 rv
= callback
.WaitForResult();
1515 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1516 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1518 rv
= sock
->Connect(callback
.callback());
1519 if (rv
== ERR_IO_PENDING
)
1520 rv
= callback
.WaitForResult();
1522 EXPECT_TRUE(sock
->IsConnected());
1524 // Issue a "hanging" Read first.
1525 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1526 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1527 // We haven't written the request, so there should be no response yet.
1528 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1530 // Write the request.
1531 // The request is padded with a User-Agent header to a size that causes the
1532 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1533 // This tests the fix for http://crbug.com/29815.
1534 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1535 for (int i
= 0; i
< 3770; ++i
)
1536 request_text
.push_back('*');
1537 request_text
.append("\r\n\r\n");
1538 scoped_refptr
<IOBuffer
> request_buffer(new StringIOBuffer(request_text
));
1540 TestCompletionCallback callback2
; // Used for Write only.
1542 request_buffer
.get(), request_text
.size(), callback2
.callback());
1543 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1545 if (rv
== ERR_IO_PENDING
)
1546 rv
= callback2
.WaitForResult();
1547 EXPECT_EQ(static_cast<int>(request_text
.size()), rv
);
1549 // Now get the Read result.
1550 rv
= callback
.WaitForResult();
1554 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1555 // mode when the underlying transport is blocked on sending data. When the
1556 // underlying transport completes due to an error, it should invoke both the
1557 // Read() and Write() callbacks. If the socket is deleted by the Read()
1558 // callback, the Write() callback should not be invoked.
1559 // Regression test for http://crbug.com/232633
1560 TEST_F(SSLClientSocketTest
, Read_DeleteWhilePendingFullDuplex
) {
1561 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1562 SpawnedTestServer::kLocalhost
,
1564 ASSERT_TRUE(test_server
.Start());
1567 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1569 TestCompletionCallback callback
;
1570 scoped_ptr
<StreamSocket
> real_transport(
1571 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1572 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1573 // is retained in order to configure additional errors.
1574 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1575 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1576 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1577 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1578 new FakeBlockingStreamSocket(error_socket
.Pass()));
1579 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1581 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1584 // Disable TLS False Start to avoid handshake non-determinism.
1585 SSLConfig ssl_config
;
1586 ssl_config
.false_start_enabled
= false;
1588 scoped_ptr
<SSLClientSocket
> sock
= CreateSSLClientSocket(
1589 transport
.Pass(), test_server
.host_port_pair(), ssl_config
);
1591 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1593 EXPECT_TRUE(sock
->IsConnected());
1595 std::string request_text
= "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1596 request_text
.append(20 * 1024, '*');
1597 request_text
.append("\r\n\r\n");
1598 scoped_refptr
<DrainableIOBuffer
> request_buffer(new DrainableIOBuffer(
1599 new StringIOBuffer(request_text
), request_text
.size()));
1601 // Simulate errors being returned from the underlying Read() and Write() ...
1602 raw_error_socket
->SetNextReadError(ERR_CONNECTION_RESET
);
1603 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1604 // ... but have those errors returned asynchronously. Because the Write() will
1605 // return first, this will trigger the error.
1606 raw_transport
->BlockReadResult();
1607 raw_transport
->BlockWrite();
1609 // Enqueue a Read() before calling Write(), which should "hang" due to
1610 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1611 SSLClientSocket
* raw_sock
= sock
.get();
1612 DeleteSocketCallback
read_callback(sock
.release());
1613 scoped_refptr
<IOBuffer
> read_buf(new IOBuffer(4096));
1614 rv
= raw_sock
->Read(read_buf
.get(), 4096, read_callback
.callback());
1616 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1617 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1618 ASSERT_FALSE(read_callback
.have_result());
1620 #if !defined(USE_OPENSSL)
1621 // NSS follows a pattern where a call to PR_Write will only consume as
1622 // much data as it can encode into application data records before the
1623 // internal memio buffer is full, which should only fill if writing a large
1624 // amount of data and the underlying transport is blocked. Once this happens,
1625 // NSS will return (total size of all application data records it wrote) - 1,
1626 // with the caller expected to resume with the remaining unsent data.
1628 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1629 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1630 // get the socket in the state needed for the test below.
1632 // This is not needed for OpenSSL, because for OpenSSL,
1633 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1634 // SSLClientSocketOpenSSL::Write() will not return until all of
1635 // |request_buffer| has been written to the underlying BIO (although not
1636 // necessarily the underlying transport).
1637 rv
= callback
.GetResult(raw_sock
->Write(request_buffer
.get(),
1638 request_buffer
->BytesRemaining(),
1639 callback
.callback()));
1641 request_buffer
->DidConsume(rv
);
1643 // Guard to ensure that |request_buffer| was larger than all of the internal
1644 // buffers (transport, memio, NSS) along the way - otherwise the next call
1645 // to Write() will crash with an invalid buffer.
1646 ASSERT_LT(0, request_buffer
->BytesRemaining());
1649 // Attempt to write the remaining data. NSS will not be able to consume the
1650 // application data because the internal buffers are full, while OpenSSL will
1651 // return that its blocked because the underlying transport is blocked.
1652 rv
= raw_sock
->Write(request_buffer
.get(),
1653 request_buffer
->BytesRemaining(),
1654 callback
.callback());
1655 ASSERT_EQ(ERR_IO_PENDING
, rv
);
1656 ASSERT_FALSE(callback
.have_result());
1658 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1659 // call the Read() callback, deleting the socket and thus aborting calling
1660 // the Write() callback.
1661 raw_transport
->UnblockWrite();
1663 rv
= read_callback
.WaitForResult();
1664 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1666 // The Write callback should not have been called.
1667 EXPECT_FALSE(callback
.have_result());
1670 // Tests that the SSLClientSocket does not crash if data is received on the
1671 // transport socket after a failing write. This can occur if we have a Write
1672 // error in a SPDY socket.
1673 // Regression test for http://crbug.com/335557
1674 TEST_F(SSLClientSocketTest
, Read_WithWriteError
) {
1675 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1676 SpawnedTestServer::kLocalhost
,
1678 ASSERT_TRUE(test_server
.Start());
1681 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1683 TestCompletionCallback callback
;
1684 scoped_ptr
<StreamSocket
> real_transport(
1685 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1686 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1687 // is retained in order to configure additional errors.
1688 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1689 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1690 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1691 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1692 new FakeBlockingStreamSocket(error_socket
.Pass()));
1693 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1695 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1698 // Disable TLS False Start to avoid handshake non-determinism.
1699 SSLConfig ssl_config
;
1700 ssl_config
.false_start_enabled
= false;
1702 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1703 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
1705 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1707 EXPECT_TRUE(sock
->IsConnected());
1709 // Send a request so there is something to read from the socket.
1710 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1711 static const int kRequestTextSize
=
1712 static_cast<int>(arraysize(request_text
) - 1);
1713 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestTextSize
));
1714 memcpy(request_buffer
->data(), request_text
, kRequestTextSize
);
1716 rv
= callback
.GetResult(
1717 sock
->Write(request_buffer
.get(), kRequestTextSize
, callback
.callback()));
1718 EXPECT_EQ(kRequestTextSize
, rv
);
1720 // Start a hanging read.
1721 TestCompletionCallback read_callback
;
1722 raw_transport
->BlockReadResult();
1723 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1724 rv
= sock
->Read(buf
.get(), 4096, read_callback
.callback());
1725 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1727 // Perform another write, but have it fail. Write a request larger than the
1728 // internal socket buffers so that the request hits the underlying transport
1729 // socket and detects the error.
1730 std::string long_request_text
=
1731 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1732 long_request_text
.append(20 * 1024, '*');
1733 long_request_text
.append("\r\n\r\n");
1734 scoped_refptr
<DrainableIOBuffer
> long_request_buffer(new DrainableIOBuffer(
1735 new StringIOBuffer(long_request_text
), long_request_text
.size()));
1737 raw_error_socket
->SetNextWriteError(ERR_CONNECTION_RESET
);
1739 // Write as much data as possible until hitting an error. This is necessary
1740 // for NSS. PR_Write will only consume as much data as it can encode into
1741 // application data records before the internal memio buffer is full, which
1742 // should only fill if writing a large amount of data and the underlying
1743 // transport is blocked. Once this happens, NSS will return (total size of all
1744 // application data records it wrote) - 1, with the caller expected to resume
1745 // with the remaining unsent data.
1747 rv
= callback
.GetResult(sock
->Write(long_request_buffer
.get(),
1748 long_request_buffer
->BytesRemaining(),
1749 callback
.callback()));
1751 long_request_buffer
->DidConsume(rv
);
1752 // Abort if the entire buffer is ever consumed.
1753 ASSERT_LT(0, long_request_buffer
->BytesRemaining());
1757 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1759 // Release the read.
1760 raw_transport
->UnblockReadResult();
1761 rv
= read_callback
.WaitForResult();
1763 #if defined(USE_OPENSSL)
1764 // Should still read bytes despite the write error.
1767 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1768 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1769 // the write error stops future reads.
1770 EXPECT_EQ(ERR_CONNECTION_RESET
, rv
);
1774 // Tests that SSLClientSocket fails the handshake if the underlying
1775 // transport is cleanly closed.
1776 TEST_F(SSLClientSocketTest
, Connect_WithZeroReturn
) {
1777 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1778 SpawnedTestServer::kLocalhost
,
1780 ASSERT_TRUE(test_server
.Start());
1783 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1785 TestCompletionCallback callback
;
1786 scoped_ptr
<StreamSocket
> real_transport(
1787 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1788 scoped_ptr
<SynchronousErrorStreamSocket
> transport(
1789 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1790 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1793 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1794 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1795 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1797 raw_transport
->SetNextReadError(0);
1799 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1800 EXPECT_EQ(ERR_CONNECTION_CLOSED
, rv
);
1801 EXPECT_FALSE(sock
->IsConnected());
1804 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1805 // is cleanly closed, but the peer does not send close_notify.
1806 // This is a regression test for https://crbug.com/422246
1807 TEST_F(SSLClientSocketTest
, Read_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 // Disable TLS False Start to ensure the handshake has completed.
1825 SSLConfig ssl_config
;
1826 ssl_config
.false_start_enabled
= false;
1828 SynchronousErrorStreamSocket
* raw_transport
= transport
.get();
1829 scoped_ptr
<SSLClientSocket
> sock(
1830 CreateSSLClientSocket(transport
.Pass(),
1831 test_server
.host_port_pair(),
1834 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1836 EXPECT_TRUE(sock
->IsConnected());
1838 raw_transport
->SetNextReadError(0);
1839 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1840 rv
= callback
.GetResult(sock
->Read(buf
.get(), 4096, callback
.callback()));
1844 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1845 // underlying socket is cleanly closed asynchronously.
1846 // This is a regression test for https://crbug.com/422246
1847 TEST_F(SSLClientSocketTest
, Read_WithAsyncZeroReturn
) {
1848 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1849 SpawnedTestServer::kLocalhost
,
1851 ASSERT_TRUE(test_server
.Start());
1854 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1856 TestCompletionCallback callback
;
1857 scoped_ptr
<StreamSocket
> real_transport(
1858 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1859 scoped_ptr
<SynchronousErrorStreamSocket
> error_socket(
1860 new SynchronousErrorStreamSocket(real_transport
.Pass()));
1861 SynchronousErrorStreamSocket
* raw_error_socket
= error_socket
.get();
1862 scoped_ptr
<FakeBlockingStreamSocket
> transport(
1863 new FakeBlockingStreamSocket(error_socket
.Pass()));
1864 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
1865 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1868 // Disable TLS False Start to ensure the handshake has completed.
1869 SSLConfig ssl_config
;
1870 ssl_config
.false_start_enabled
= false;
1872 scoped_ptr
<SSLClientSocket
> sock(
1873 CreateSSLClientSocket(transport
.Pass(),
1874 test_server
.host_port_pair(),
1877 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1879 EXPECT_TRUE(sock
->IsConnected());
1881 raw_error_socket
->SetNextReadError(0);
1882 raw_transport
->BlockReadResult();
1883 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1884 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
1885 EXPECT_EQ(ERR_IO_PENDING
, rv
);
1887 raw_transport
->UnblockReadResult();
1888 rv
= callback
.GetResult(rv
);
1892 // Tests that fatal alerts from the peer are processed. This is a regression
1893 // test for https://crbug.com/466303.
1894 TEST_F(SSLClientSocketTest
, Read_WithFatalAlert
) {
1895 SpawnedTestServer::SSLOptions ssl_options
;
1896 ssl_options
.alert_after_handshake
= true;
1897 ASSERT_TRUE(StartTestServer(ssl_options
));
1899 SSLConfig ssl_config
;
1900 TestCompletionCallback callback
;
1901 scoped_ptr
<StreamSocket
> transport(
1902 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
1903 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
1904 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1905 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
1906 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
1908 // Receive the fatal alert.
1909 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
1910 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, callback
.GetResult(sock
->Read(
1911 buf
.get(), 4096, callback
.callback())));
1914 TEST_F(SSLClientSocketTest
, Read_SmallChunks
) {
1915 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1916 SpawnedTestServer::kLocalhost
,
1918 ASSERT_TRUE(test_server
.Start());
1921 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1923 TestCompletionCallback callback
;
1924 scoped_ptr
<StreamSocket
> transport(
1925 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1926 int rv
= transport
->Connect(callback
.callback());
1927 if (rv
== ERR_IO_PENDING
)
1928 rv
= callback
.WaitForResult();
1931 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1932 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1934 rv
= sock
->Connect(callback
.callback());
1935 if (rv
== ERR_IO_PENDING
)
1936 rv
= callback
.WaitForResult();
1939 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
1940 scoped_refptr
<IOBuffer
> request_buffer(
1941 new IOBuffer(arraysize(request_text
) - 1));
1942 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1945 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
1946 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1948 if (rv
== ERR_IO_PENDING
)
1949 rv
= callback
.WaitForResult();
1950 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
1952 scoped_refptr
<IOBuffer
> buf(new IOBuffer(1));
1954 rv
= sock
->Read(buf
.get(), 1, callback
.callback());
1955 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
1957 if (rv
== ERR_IO_PENDING
)
1958 rv
= callback
.WaitForResult();
1966 TEST_F(SSLClientSocketTest
, Read_ManySmallRecords
) {
1967 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
1968 SpawnedTestServer::kLocalhost
,
1970 ASSERT_TRUE(test_server
.Start());
1973 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
1975 TestCompletionCallback callback
;
1977 scoped_ptr
<StreamSocket
> real_transport(
1978 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
1979 scoped_ptr
<ReadBufferingStreamSocket
> transport(
1980 new ReadBufferingStreamSocket(real_transport
.Pass()));
1981 ReadBufferingStreamSocket
* raw_transport
= transport
.get();
1982 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
1985 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
1986 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
1988 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
1990 ASSERT_TRUE(sock
->IsConnected());
1992 const char request_text
[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1993 scoped_refptr
<IOBuffer
> request_buffer(
1994 new IOBuffer(arraysize(request_text
) - 1));
1995 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
1997 rv
= callback
.GetResult(sock
->Write(
1998 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback()));
2000 ASSERT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2002 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2003 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2004 // of SSL data is buffered first. The 15K of buffered data is made up of
2005 // many smaller SSL records (the TestServer writes along 1350 byte
2006 // plaintext boundaries), although there may also be a few records that are
2007 // smaller or larger, due to timing and SSL False Start.
2008 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2009 // the SSLClientSocket implementation, and larger than the minimum amount
2010 // of ciphertext necessary to contain the 8K of plaintext requested below.
2011 raw_transport
->SetBufferSize(15000);
2013 scoped_refptr
<IOBuffer
> buffer(new IOBuffer(8192));
2014 rv
= callback
.GetResult(sock
->Read(buffer
.get(), 8192, callback
.callback()));
2015 ASSERT_EQ(rv
, 8192);
2018 TEST_F(SSLClientSocketTest
, Read_Interrupted
) {
2019 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2020 SpawnedTestServer::kLocalhost
,
2022 ASSERT_TRUE(test_server
.Start());
2025 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2027 TestCompletionCallback callback
;
2028 scoped_ptr
<StreamSocket
> transport(
2029 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2030 int rv
= transport
->Connect(callback
.callback());
2031 if (rv
== ERR_IO_PENDING
)
2032 rv
= callback
.WaitForResult();
2035 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2036 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2038 rv
= sock
->Connect(callback
.callback());
2039 if (rv
== ERR_IO_PENDING
)
2040 rv
= callback
.WaitForResult();
2043 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2044 scoped_refptr
<IOBuffer
> request_buffer(
2045 new IOBuffer(arraysize(request_text
) - 1));
2046 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2049 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2050 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2052 if (rv
== ERR_IO_PENDING
)
2053 rv
= callback
.WaitForResult();
2054 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2056 // Do a partial read and then exit. This test should not crash!
2057 scoped_refptr
<IOBuffer
> buf(new IOBuffer(512));
2058 rv
= sock
->Read(buf
.get(), 512, callback
.callback());
2059 EXPECT_TRUE(rv
> 0 || rv
== ERR_IO_PENDING
);
2061 if (rv
== ERR_IO_PENDING
)
2062 rv
= callback
.WaitForResult();
2067 TEST_F(SSLClientSocketTest
, Read_FullLogging
) {
2068 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2069 SpawnedTestServer::kLocalhost
,
2071 ASSERT_TRUE(test_server
.Start());
2074 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2076 TestCompletionCallback callback
;
2078 log
.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes());
2079 scoped_ptr
<StreamSocket
> transport(
2080 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2081 int rv
= transport
->Connect(callback
.callback());
2082 if (rv
== ERR_IO_PENDING
)
2083 rv
= callback
.WaitForResult();
2086 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2087 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2089 rv
= sock
->Connect(callback
.callback());
2090 if (rv
== ERR_IO_PENDING
)
2091 rv
= callback
.WaitForResult();
2093 EXPECT_TRUE(sock
->IsConnected());
2095 const char request_text
[] = "GET / HTTP/1.0\r\n\r\n";
2096 scoped_refptr
<IOBuffer
> request_buffer(
2097 new IOBuffer(arraysize(request_text
) - 1));
2098 memcpy(request_buffer
->data(), request_text
, arraysize(request_text
) - 1);
2101 request_buffer
.get(), arraysize(request_text
) - 1, callback
.callback());
2102 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2104 if (rv
== ERR_IO_PENDING
)
2105 rv
= callback
.WaitForResult();
2106 EXPECT_EQ(static_cast<int>(arraysize(request_text
) - 1), rv
);
2108 TestNetLogEntry::List entries
;
2109 log
.GetEntries(&entries
);
2110 size_t last_index
= ExpectLogContainsSomewhereAfter(
2111 entries
, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT
, NetLog::PHASE_NONE
);
2113 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
2115 rv
= sock
->Read(buf
.get(), 4096, callback
.callback());
2116 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2118 if (rv
== ERR_IO_PENDING
)
2119 rv
= callback
.WaitForResult();
2125 log
.GetEntries(&entries
);
2127 ExpectLogContainsSomewhereAfter(entries
,
2129 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED
,
2130 NetLog::PHASE_NONE
);
2134 // Regression test for http://crbug.com/42538
2135 TEST_F(SSLClientSocketTest
, PrematureApplicationData
) {
2136 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2137 SpawnedTestServer::kLocalhost
,
2139 ASSERT_TRUE(test_server
.Start());
2142 TestCompletionCallback callback
;
2144 static const unsigned char application_data
[] = {
2145 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2146 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2147 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2148 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2149 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2150 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2151 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2152 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2153 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2156 // All reads and writes complete synchronously (async=false).
2157 MockRead data_reads
[] = {
2158 MockRead(SYNCHRONOUS
,
2159 reinterpret_cast<const char*>(application_data
),
2160 arraysize(application_data
)),
2161 MockRead(SYNCHRONOUS
, OK
), };
2163 StaticSocketDataProvider
data(data_reads
, arraysize(data_reads
), NULL
, 0);
2165 scoped_ptr
<StreamSocket
> transport(
2166 new MockTCPClientSocket(addr
, NULL
, &data
));
2167 int rv
= transport
->Connect(callback
.callback());
2168 if (rv
== ERR_IO_PENDING
)
2169 rv
= callback
.WaitForResult();
2172 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2173 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2175 rv
= sock
->Connect(callback
.callback());
2176 if (rv
== ERR_IO_PENDING
)
2177 rv
= callback
.WaitForResult();
2178 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, rv
);
2181 TEST_F(SSLClientSocketTest
, CipherSuiteDisables
) {
2182 // Rather than exhaustively disabling every AES_128_CBC ciphersuite defined at
2183 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2184 // disabling those cipher suites that the test server actually implements.
2185 const uint16 kCiphersToDisable
[] = {
2186 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2187 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2188 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2191 SpawnedTestServer::SSLOptions ssl_options
;
2192 // Enable only AES_128_CBC on the test server.
2193 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
2194 SpawnedTestServer
test_server(
2195 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2196 ASSERT_TRUE(test_server
.Start());
2199 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2201 TestCompletionCallback callback
;
2203 scoped_ptr
<StreamSocket
> transport(
2204 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2205 int rv
= transport
->Connect(callback
.callback());
2206 if (rv
== ERR_IO_PENDING
)
2207 rv
= callback
.WaitForResult();
2210 SSLConfig ssl_config
;
2211 for (size_t i
= 0; i
< arraysize(kCiphersToDisable
); ++i
)
2212 ssl_config
.disabled_cipher_suites
.push_back(kCiphersToDisable
[i
]);
2214 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2215 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2217 EXPECT_FALSE(sock
->IsConnected());
2219 rv
= sock
->Connect(callback
.callback());
2220 TestNetLogEntry::List entries
;
2221 log
.GetEntries(&entries
);
2222 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2224 if (rv
== ERR_IO_PENDING
)
2225 rv
= callback
.WaitForResult();
2226 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
, rv
);
2227 // The exact ordering depends no whether an extra read is issued. Just check
2228 // the error is somewhere in the log.
2229 log
.GetEntries(&entries
);
2230 ExpectLogContainsSomewhere(
2231 entries
, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR
, NetLog::PHASE_NONE
);
2233 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2234 // the socket when it encounters an error, whereas other implementations
2235 // leave it connected.
2236 // Because this an error that the test server is mutually aware of, as opposed
2237 // to being an error such as a certificate name mismatch, which is
2238 // client-only, the exact index of the SSL connect end depends on how
2239 // quickly the test server closes the underlying socket. If the test server
2240 // closes before the IO message loop pumps messages, there may be a 0-byte
2241 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2242 // result, the SSL connect end event will be the second-to-last entry,
2243 // rather than the last entry.
2244 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
) ||
2245 LogContainsEndEvent(entries
, -2, NetLog::TYPE_SSL_CONNECT
));
2248 // When creating an SSLClientSocket, it is allowed to pass in a
2249 // ClientSocketHandle that is not obtained from a client socket pool.
2250 // Here we verify that such a simple ClientSocketHandle, not associated with any
2251 // client socket pool, can be destroyed safely.
2252 TEST_F(SSLClientSocketTest
, ClientSocketHandleNotFromPool
) {
2253 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2254 SpawnedTestServer::kLocalhost
,
2256 ASSERT_TRUE(test_server
.Start());
2259 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2261 TestCompletionCallback callback
;
2262 scoped_ptr
<StreamSocket
> transport(
2263 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2264 int rv
= transport
->Connect(callback
.callback());
2265 if (rv
== ERR_IO_PENDING
)
2266 rv
= callback
.WaitForResult();
2269 scoped_ptr
<ClientSocketHandle
> socket_handle(new ClientSocketHandle());
2270 socket_handle
->SetSocket(transport
.Pass());
2272 scoped_ptr
<SSLClientSocket
> sock(socket_factory_
->CreateSSLClientSocket(
2273 socket_handle
.Pass(), test_server
.host_port_pair(), SSLConfig(),
2276 EXPECT_FALSE(sock
->IsConnected());
2277 rv
= sock
->Connect(callback
.callback());
2278 if (rv
== ERR_IO_PENDING
)
2279 rv
= callback
.WaitForResult();
2283 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2284 // code and different keying label results in different keying material.
2285 TEST_F(SSLClientSocketTest
, ExportKeyingMaterial
) {
2286 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2287 SpawnedTestServer::kLocalhost
,
2289 ASSERT_TRUE(test_server
.Start());
2292 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2294 TestCompletionCallback callback
;
2296 scoped_ptr
<StreamSocket
> transport(
2297 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2298 int rv
= transport
->Connect(callback
.callback());
2299 if (rv
== ERR_IO_PENDING
)
2300 rv
= callback
.WaitForResult();
2303 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2304 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2306 rv
= sock
->Connect(callback
.callback());
2307 if (rv
== ERR_IO_PENDING
)
2308 rv
= callback
.WaitForResult();
2310 EXPECT_TRUE(sock
->IsConnected());
2312 const int kKeyingMaterialSize
= 32;
2313 const char kKeyingLabel1
[] = "client-socket-test-1";
2314 const char kKeyingContext1
[] = "";
2315 unsigned char client_out1
[kKeyingMaterialSize
];
2316 memset(client_out1
, 0, sizeof(client_out1
));
2317 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, false, kKeyingContext1
,
2318 client_out1
, sizeof(client_out1
));
2321 const char kKeyingLabel2
[] = "client-socket-test-2";
2322 unsigned char client_out2
[kKeyingMaterialSize
];
2323 memset(client_out2
, 0, sizeof(client_out2
));
2324 rv
= sock
->ExportKeyingMaterial(kKeyingLabel2
, false, kKeyingContext1
,
2325 client_out2
, sizeof(client_out2
));
2327 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2329 const char kKeyingContext2
[] = "context";
2330 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext2
,
2331 client_out2
, sizeof(client_out2
));
2333 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2335 // Using an empty context should give different key material from not using a
2337 memset(client_out2
, 0, sizeof(client_out2
));
2338 rv
= sock
->ExportKeyingMaterial(kKeyingLabel1
, true, kKeyingContext1
,
2339 client_out2
, sizeof(client_out2
));
2341 EXPECT_NE(memcmp(client_out1
, client_out2
, kKeyingMaterialSize
), 0);
2344 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2345 // explicit NSS initialization.
2346 TEST(SSLClientSocket
, ClearSessionCache
) {
2347 SSLClientSocket::ClearSessionCache();
2350 TEST(SSLClientSocket
, SerializeNextProtos
) {
2351 NextProtoVector next_protos
;
2352 next_protos
.push_back(kProtoHTTP11
);
2353 next_protos
.push_back(kProtoSPDY31
);
2354 static std::vector
<uint8_t> serialized
=
2355 SSLClientSocket::SerializeNextProtos(next_protos
, true);
2356 ASSERT_EQ(18u, serialized
.size());
2357 EXPECT_EQ(8, serialized
[0]); // length("http/1.1")
2358 EXPECT_EQ('h', serialized
[1]);
2359 EXPECT_EQ('t', serialized
[2]);
2360 EXPECT_EQ('t', serialized
[3]);
2361 EXPECT_EQ('p', serialized
[4]);
2362 EXPECT_EQ('/', serialized
[5]);
2363 EXPECT_EQ('1', serialized
[6]);
2364 EXPECT_EQ('.', serialized
[7]);
2365 EXPECT_EQ('1', serialized
[8]);
2366 EXPECT_EQ(8, serialized
[9]); // length("spdy/3.1")
2367 EXPECT_EQ('s', serialized
[10]);
2368 EXPECT_EQ('p', serialized
[11]);
2369 EXPECT_EQ('d', serialized
[12]);
2370 EXPECT_EQ('y', serialized
[13]);
2371 EXPECT_EQ('/', serialized
[14]);
2372 EXPECT_EQ('3', serialized
[15]);
2373 EXPECT_EQ('.', serialized
[16]);
2374 EXPECT_EQ('1', serialized
[17]);
2377 // Test that the server certificates are properly retrieved from the underlying
2379 TEST_F(SSLClientSocketTest
, VerifyServerChainProperlyOrdered
) {
2380 // The connection does not have to be successful.
2381 cert_verifier_
->set_default_result(ERR_CERT_INVALID
);
2383 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2384 // This makes the server present redundant-server-chain.pem, which contains
2385 // intermediate certificates.
2386 SpawnedTestServer::SSLOptions
ssl_options(
2387 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2388 SpawnedTestServer
test_server(
2389 SpawnedTestServer::TYPE_HTTPS
, ssl_options
, base::FilePath());
2390 ASSERT_TRUE(test_server
.Start());
2393 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2395 TestCompletionCallback callback
;
2396 scoped_ptr
<StreamSocket
> transport(
2397 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2398 int rv
= transport
->Connect(callback
.callback());
2399 rv
= callback
.GetResult(rv
);
2402 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2403 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2404 EXPECT_FALSE(sock
->IsConnected());
2405 rv
= sock
->Connect(callback
.callback());
2406 rv
= callback
.GetResult(rv
);
2408 EXPECT_EQ(ERR_CERT_INVALID
, rv
);
2409 EXPECT_TRUE(sock
->IsConnected());
2411 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2412 // certs from redundant-server-chain.pem.
2413 CertificateList server_certs
=
2414 CreateCertificateListFromFile(GetTestCertsDirectory(),
2415 "redundant-server-chain.pem",
2416 X509Certificate::FORMAT_AUTO
);
2418 // Get the server certificate as received client side.
2420 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2421 scoped_refptr
<X509Certificate
> server_certificate
= ssl_info
.unverified_cert
;
2423 // Get the intermediates as received client side.
2424 const X509Certificate::OSCertHandles
& server_intermediates
=
2425 server_certificate
->GetIntermediateCertificates();
2427 // Check that the unverified server certificate chain is properly retrieved
2428 // from the underlying ssl stack.
2429 ASSERT_EQ(4U, server_certs
.size());
2431 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2432 server_certificate
->os_cert_handle(), server_certs
[0]->os_cert_handle()));
2434 ASSERT_EQ(3U, server_intermediates
.size());
2436 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[0],
2437 server_certs
[1]->os_cert_handle()));
2438 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[1],
2439 server_certs
[2]->os_cert_handle()));
2440 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates
[2],
2441 server_certs
[3]->os_cert_handle()));
2444 EXPECT_FALSE(sock
->IsConnected());
2447 // This tests that SSLInfo contains a properly re-constructed certificate
2448 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2449 // verified, not the chain as served by the server. (They may be different.)
2451 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2452 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2453 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2454 // a self-signed root. Such a situation can occur when a new root (C2) is
2455 // cross-certified by an old root (D) and has two different versions of its
2456 // floating around. Servers may supply C2 as an intermediate, but the
2457 // SSLClientSocket should return the chain that was verified, from
2458 // verify_result, instead.
2459 TEST_F(SSLClientSocketTest
, VerifyReturnChainProperlyOrdered
) {
2460 // By default, cause the CertVerifier to treat all certificates as
2462 cert_verifier_
->set_default_result(ERR_CERT_DATE_INVALID
);
2464 CertificateList unverified_certs
= CreateCertificateListFromFile(
2465 GetTestCertsDirectory(), "redundant-server-chain.pem",
2466 X509Certificate::FORMAT_AUTO
);
2467 ASSERT_EQ(4u, unverified_certs
.size());
2469 // We will expect SSLInfo to ultimately contain this chain.
2470 CertificateList certs
=
2471 CreateCertificateListFromFile(GetTestCertsDirectory(),
2472 "redundant-validated-chain.pem",
2473 X509Certificate::FORMAT_AUTO
);
2474 ASSERT_EQ(3U, certs
.size());
2476 X509Certificate::OSCertHandles temp_intermediates
;
2477 temp_intermediates
.push_back(certs
[1]->os_cert_handle());
2478 temp_intermediates
.push_back(certs
[2]->os_cert_handle());
2480 CertVerifyResult verify_result
;
2481 verify_result
.verified_cert
= X509Certificate::CreateFromHandle(
2482 certs
[0]->os_cert_handle(), temp_intermediates
);
2484 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2485 // rather than A->B->C.
2486 cert_verifier_
->AddResultForCert(certs
[0].get(), verify_result
, OK
);
2488 // Load and install the root for the validated chain.
2489 scoped_refptr
<X509Certificate
> root_cert
= ImportCertFromFile(
2490 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2491 ASSERT_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
2492 ScopedTestRoot
scoped_root(root_cert
.get());
2494 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2495 SpawnedTestServer::SSLOptions
ssl_options(
2496 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT
);
2497 SpawnedTestServer
test_server(
2498 SpawnedTestServer::TYPE_HTTPS
,
2500 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2501 ASSERT_TRUE(test_server
.Start());
2504 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2506 TestCompletionCallback callback
;
2508 scoped_ptr
<StreamSocket
> transport(
2509 new TCPClientSocket(addr
, &log
, NetLog::Source()));
2510 int rv
= transport
->Connect(callback
.callback());
2511 if (rv
== ERR_IO_PENDING
)
2512 rv
= callback
.WaitForResult();
2515 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2516 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2517 EXPECT_FALSE(sock
->IsConnected());
2518 rv
= sock
->Connect(callback
.callback());
2520 TestNetLogEntry::List entries
;
2521 log
.GetEntries(&entries
);
2522 EXPECT_TRUE(LogContainsBeginEvent(entries
, 5, NetLog::TYPE_SSL_CONNECT
));
2523 if (rv
== ERR_IO_PENDING
)
2524 rv
= callback
.WaitForResult();
2527 EXPECT_TRUE(sock
->IsConnected());
2528 log
.GetEntries(&entries
);
2529 EXPECT_TRUE(LogContainsEndEvent(entries
, -1, NetLog::TYPE_SSL_CONNECT
));
2532 sock
->GetSSLInfo(&ssl_info
);
2534 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2536 const X509Certificate::OSCertHandles
& intermediates
=
2537 ssl_info
.cert
->GetIntermediateCertificates();
2538 ASSERT_EQ(2U, intermediates
.size());
2539 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info
.cert
->os_cert_handle(),
2540 certs
[0]->os_cert_handle()));
2541 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[0],
2542 certs
[1]->os_cert_handle()));
2543 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates
[1],
2544 certs
[2]->os_cert_handle()));
2546 // Verify that SSLInfo also contains the chain as received from the server.
2547 const X509Certificate::OSCertHandles
& served_intermediates
=
2548 ssl_info
.unverified_cert
->GetIntermediateCertificates();
2549 ASSERT_EQ(3U, served_intermediates
.size());
2550 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2551 ssl_info
.cert
->os_cert_handle(), unverified_certs
[0]->os_cert_handle()));
2552 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2553 served_intermediates
[0], unverified_certs
[1]->os_cert_handle()));
2554 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2555 served_intermediates
[1], unverified_certs
[2]->os_cert_handle()));
2556 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2557 served_intermediates
[2], unverified_certs
[3]->os_cert_handle()));
2560 EXPECT_FALSE(sock
->IsConnected());
2563 TEST_F(SSLClientSocketCertRequestInfoTest
, NoAuthorities
) {
2564 SpawnedTestServer::SSLOptions ssl_options
;
2565 ssl_options
.request_client_certificate
= true;
2566 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2567 ASSERT_TRUE(request_info
.get());
2568 EXPECT_EQ(0u, request_info
->cert_authorities
.size());
2571 TEST_F(SSLClientSocketCertRequestInfoTest
, TwoAuthorities
) {
2572 const base::FilePath::CharType kThawteFile
[] =
2573 FILE_PATH_LITERAL("thawte.single.pem");
2574 const unsigned char kThawteDN
[] = {
2575 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2576 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2577 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2578 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2579 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2580 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2581 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2582 const size_t kThawteLen
= sizeof(kThawteDN
);
2584 const base::FilePath::CharType kDiginotarFile
[] =
2585 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2586 const unsigned char kDiginotarDN
[] = {
2587 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2588 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2589 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2590 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2591 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2592 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2593 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2594 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2596 const size_t kDiginotarLen
= sizeof(kDiginotarDN
);
2598 SpawnedTestServer::SSLOptions ssl_options
;
2599 ssl_options
.request_client_certificate
= true;
2600 ssl_options
.client_authorities
.push_back(
2601 GetTestClientCertsDirectory().Append(kThawteFile
));
2602 ssl_options
.client_authorities
.push_back(
2603 GetTestClientCertsDirectory().Append(kDiginotarFile
));
2604 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2605 ASSERT_TRUE(request_info
.get());
2606 ASSERT_EQ(2u, request_info
->cert_authorities
.size());
2607 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN
), kThawteLen
),
2608 request_info
->cert_authorities
[0]);
2610 std::string(reinterpret_cast<const char*>(kDiginotarDN
), kDiginotarLen
),
2611 request_info
->cert_authorities
[1]);
2614 // cert_key_types is currently only populated on OpenSSL.
2615 #if defined(USE_OPENSSL)
2616 TEST_F(SSLClientSocketCertRequestInfoTest
, CertKeyTypes
) {
2617 SpawnedTestServer::SSLOptions ssl_options
;
2618 ssl_options
.request_client_certificate
= true;
2619 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_RSA_SIGN
);
2620 ssl_options
.client_cert_types
.push_back(CLIENT_CERT_ECDSA_SIGN
);
2621 scoped_refptr
<SSLCertRequestInfo
> request_info
= GetCertRequest(ssl_options
);
2622 ASSERT_TRUE(request_info
.get());
2623 ASSERT_EQ(2u, request_info
->cert_key_types
.size());
2624 EXPECT_EQ(CLIENT_CERT_RSA_SIGN
, request_info
->cert_key_types
[0]);
2625 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN
, request_info
->cert_key_types
[1]);
2627 #endif // defined(USE_OPENSSL)
2629 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledTLSExtension
) {
2630 SpawnedTestServer::SSLOptions ssl_options
;
2631 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2633 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2636 ASSERT_TRUE(test_server
.Start());
2639 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2641 TestCompletionCallback callback
;
2642 scoped_ptr
<StreamSocket
> transport(
2643 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2644 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2647 SSLConfig ssl_config
;
2648 ssl_config
.signed_cert_timestamps_enabled
= true;
2650 MockCTVerifier ct_verifier
;
2651 SetCTVerifier(&ct_verifier
);
2653 // Check that the SCT list is extracted as expected.
2654 EXPECT_CALL(ct_verifier
, Verify(_
, "", "test", _
, _
)).WillRepeatedly(
2655 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2657 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2658 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2659 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2662 EXPECT_TRUE(sock
->signed_cert_timestamps_received_
);
2667 bool IsValidOCSPResponse(const base::StringPiece
& input
) {
2668 base::StringPiece ocsp_response
= input
;
2669 base::StringPiece sequence
, response_status
, response_bytes
;
2670 return asn1::GetElement(&ocsp_response
, asn1::kSEQUENCE
, &sequence
) &&
2671 ocsp_response
.empty() &&
2672 asn1::GetElement(&sequence
, asn1::kENUMERATED
, &response_status
) &&
2673 asn1::GetElement(&sequence
,
2674 asn1::kContextSpecific
| asn1::kConstructed
| 0,
2675 &response_status
) &&
2681 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2682 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsEnabledOCSP
) {
2683 SpawnedTestServer::SSLOptions ssl_options
;
2684 ssl_options
.staple_ocsp_response
= true;
2685 // The test server currently only knows how to generate OCSP responses
2686 // for a freshly minted certificate.
2687 ssl_options
.server_certificate
= SpawnedTestServer::SSLOptions::CERT_AUTO
;
2689 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2692 ASSERT_TRUE(test_server
.Start());
2695 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2697 TestCompletionCallback callback
;
2698 scoped_ptr
<StreamSocket
> transport(
2699 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2700 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2703 SSLConfig ssl_config
;
2704 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2705 // Certificate Transparency verification regardless of whether the platform
2706 // is able to process the OCSP status itself.
2707 ssl_config
.signed_cert_timestamps_enabled
= true;
2709 MockCTVerifier ct_verifier
;
2710 SetCTVerifier(&ct_verifier
);
2712 // Check that the OCSP response is extracted and well-formed. It should be the
2713 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2714 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2715 // particular, it should not include the overall two-byte length prefix from
2717 EXPECT_CALL(ct_verifier
,
2718 Verify(_
, Truly(IsValidOCSPResponse
), "", _
, _
)).WillRepeatedly(
2719 Return(ERR_CT_NO_SCTS_VERIFIED_OK
));
2721 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2722 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2723 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2726 EXPECT_TRUE(sock
->stapled_ocsp_response_received_
);
2729 TEST_F(SSLClientSocketTest
, ConnectSignedCertTimestampsDisabled
) {
2730 SpawnedTestServer::SSLOptions ssl_options
;
2731 ssl_options
.signed_cert_timestamps_tls_ext
= "test";
2733 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2736 ASSERT_TRUE(test_server
.Start());
2739 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2741 TestCompletionCallback callback
;
2742 scoped_ptr
<StreamSocket
> transport(
2743 new TCPClientSocket(addr
, &log_
, NetLog::Source()));
2744 int rv
= callback
.GetResult(transport
->Connect(callback
.callback()));
2747 SSLConfig ssl_config
;
2748 ssl_config
.signed_cert_timestamps_enabled
= false;
2750 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2751 transport
.Pass(), test_server
.host_port_pair(), ssl_config
));
2752 rv
= callback
.GetResult(sock
->Connect(callback
.callback()));
2755 EXPECT_FALSE(sock
->signed_cert_timestamps_received_
);
2758 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2759 TEST_F(SSLClientSocketTest
, ReuseStates
) {
2760 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2761 SpawnedTestServer::kLocalhost
,
2763 ASSERT_TRUE(test_server
.Start());
2766 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2768 TestCompletionCallback callback
;
2769 scoped_ptr
<StreamSocket
> transport(
2770 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2771 int rv
= transport
->Connect(callback
.callback());
2772 if (rv
== ERR_IO_PENDING
)
2773 rv
= callback
.WaitForResult();
2776 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2777 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2779 rv
= sock
->Connect(callback
.callback());
2780 if (rv
== ERR_IO_PENDING
)
2781 rv
= callback
.WaitForResult();
2784 // The socket was just connected. It should be idle because it is speaking
2785 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2787 EXPECT_TRUE(sock
->IsConnected());
2788 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2789 EXPECT_FALSE(sock
->WasEverUsed());
2791 const char kRequestText
[] = "GET / HTTP/1.0\r\n\r\n";
2792 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2793 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2794 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2796 rv
= sock
->Write(request_buffer
.get(), kRequestLen
, callback
.callback());
2797 EXPECT_TRUE(rv
>= 0 || rv
== ERR_IO_PENDING
);
2799 if (rv
== ERR_IO_PENDING
)
2800 rv
= callback
.WaitForResult();
2801 EXPECT_EQ(static_cast<int>(kRequestLen
), rv
);
2803 // The socket has now been used.
2804 EXPECT_TRUE(sock
->WasEverUsed());
2806 // TODO(davidben): Read one byte to ensure the test server has responded and
2807 // then assert IsConnectedAndIdle is false. This currently doesn't work
2808 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2809 // SSL implementation's internal buffers. Either call PR_Available and
2810 // SSL_pending, although the former isn't actually implemented or perhaps
2811 // attempt to read one byte extra.
2814 // Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
2815 // been flushed completely out of SSLClientSocket's internal buffers. This is a
2816 // regression test for https://crbug.com/466147.
2817 TEST_F(SSLClientSocketTest
, ReusableAfterWrite
) {
2818 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
,
2819 SpawnedTestServer::kLocalhost
,
2821 ASSERT_TRUE(test_server
.Start());
2824 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
2826 TestCompletionCallback callback
;
2827 scoped_ptr
<StreamSocket
> real_transport(
2828 new TCPClientSocket(addr
, NULL
, NetLog::Source()));
2829 scoped_ptr
<FakeBlockingStreamSocket
> transport(
2830 new FakeBlockingStreamSocket(real_transport
.Pass()));
2831 FakeBlockingStreamSocket
* raw_transport
= transport
.get();
2832 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2834 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2835 transport
.Pass(), test_server
.host_port_pair(), SSLConfig()));
2836 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2838 // Block any application data from reaching the network.
2839 raw_transport
->BlockWrite();
2841 // Write a partial HTTP request.
2842 const char kRequestText
[] = "GET / HTTP/1.0";
2843 const size_t kRequestLen
= arraysize(kRequestText
) - 1;
2844 scoped_refptr
<IOBuffer
> request_buffer(new IOBuffer(kRequestLen
));
2845 memcpy(request_buffer
->data(), kRequestText
, kRequestLen
);
2847 // Although transport writes are blocked, both SSLClientSocketOpenSSL and
2848 // SSLClientSocketNSS complete the outer Write operation.
2849 EXPECT_EQ(static_cast<int>(kRequestLen
),
2850 callback
.GetResult(sock
->Write(request_buffer
.get(), kRequestLen
,
2851 callback
.callback())));
2853 // The Write operation is complete, so the socket should be treated as
2854 // reusable, in case the server returns an HTTP response before completely
2855 // consuming the request body. In this case, we assume the server will
2856 // properly drain the request body before trying to read the next request.
2857 EXPECT_TRUE(sock
->IsConnectedAndIdle());
2860 // Tests that basic session resumption works.
2861 TEST_F(SSLClientSocketTest
, SessionResumption
) {
2862 SpawnedTestServer::SSLOptions ssl_options
;
2863 ASSERT_TRUE(StartTestServer(ssl_options
));
2865 // First, perform a full handshake.
2866 SSLConfig ssl_config
;
2867 TestCompletionCallback callback
;
2868 scoped_ptr
<StreamSocket
> transport(
2869 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2870 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2871 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2872 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
2873 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2875 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2876 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2878 // The next connection should resume.
2879 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2880 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2881 sock
= CreateSSLClientSocket(transport
.Pass(),
2882 test_server()->host_port_pair(), ssl_config
);
2883 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2884 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2885 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2887 // Using a different HostPortPair uses a different session cache key.
2888 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2889 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2890 sock
= CreateSSLClientSocket(transport
.Pass(),
2891 HostPortPair("example.com", 443), ssl_config
);
2892 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2893 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2894 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2896 SSLClientSocket::ClearSessionCache();
2898 // After clearing the session cache, the next handshake doesn't resume.
2899 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2900 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2901 sock
= CreateSSLClientSocket(transport
.Pass(),
2902 test_server()->host_port_pair(), ssl_config
);
2903 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2904 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2905 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2908 // Tests that connections with certificate errors do not add entries to the
2910 TEST_F(SSLClientSocketTest
, CertificateErrorNoResume
) {
2911 SpawnedTestServer::SSLOptions ssl_options
;
2912 ASSERT_TRUE(StartTestServer(ssl_options
));
2914 cert_verifier_
->set_default_result(ERR_CERT_COMMON_NAME_INVALID
);
2916 SSLConfig ssl_config
;
2917 TestCompletionCallback callback
;
2918 scoped_ptr
<StreamSocket
> transport(
2919 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2920 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2921 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2922 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
2923 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID
,
2924 callback
.GetResult(sock
->Connect(callback
.callback())));
2926 cert_verifier_
->set_default_result(OK
);
2928 // The next connection should perform a full handshake.
2929 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2930 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2931 sock
= CreateSSLClientSocket(transport
.Pass(),
2932 test_server()->host_port_pair(), ssl_config
);
2933 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2935 ASSERT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2936 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2939 // Tests that session caches are sharded by max_version.
2940 TEST_F(SSLClientSocketTest
, FallbackShardSessionCache
) {
2941 SpawnedTestServer::SSLOptions ssl_options
;
2942 ASSERT_TRUE(StartTestServer(ssl_options
));
2944 // Prepare a normal and fallback SSL config.
2945 SSLConfig ssl_config
;
2946 SSLConfig fallback_ssl_config
;
2947 fallback_ssl_config
.version_max
= SSL_PROTOCOL_VERSION_TLS1
;
2948 fallback_ssl_config
.version_fallback_min
= SSL_PROTOCOL_VERSION_TLS1
;
2949 fallback_ssl_config
.version_fallback
= true;
2951 // Connect with a fallback config from the test server to add an entry to the
2953 TestCompletionCallback callback
;
2954 scoped_ptr
<StreamSocket
> transport(
2955 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2956 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2957 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
2958 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
));
2959 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2961 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2962 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
2963 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
2964 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2966 // A non-fallback connection needs a full handshake.
2967 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2968 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2969 sock
= CreateSSLClientSocket(transport
.Pass(),
2970 test_server()->host_port_pair(), ssl_config
);
2971 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 // This does not check for equality because TLS 1.2 support is conditional on
2975 // system NSS features.
2976 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2977 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2979 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2980 // 1.2, the above test would not be sufficient to prove the session caches are
2981 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2982 // attempt to resume with two more connections.
2984 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2985 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
2986 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
2987 sock
= CreateSSLClientSocket(transport
.Pass(),
2988 test_server()->host_port_pair(), ssl_config
);
2989 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
2990 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
2991 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
2992 // This does not check for equality because TLS 1.2 support is conditional on
2993 // system NSS features.
2994 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1
,
2995 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
2997 // The fallback connection still resumes from its session cache. It cannot
2998 // offer the > TLS 1.0 session, so this must have been the session from the
2999 // first fallback connection.
3000 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3001 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3002 sock
= CreateSSLClientSocket(
3003 transport
.Pass(), test_server()->host_port_pair(), fallback_ssl_config
);
3004 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3005 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3006 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3007 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1
,
3008 SSLConnectionStatusToVersion(ssl_info
.connection_status
));
3011 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
3012 TEST_F(SSLClientSocketTest
, DeprecatedRC4
) {
3013 SpawnedTestServer::SSLOptions ssl_options
;
3014 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
3015 ASSERT_TRUE(StartTestServer(ssl_options
));
3017 // Normal handshakes with RC4 do not work.
3018 SSLConfig ssl_config
;
3019 TestCompletionCallback callback
;
3020 scoped_ptr
<StreamSocket
> transport(
3021 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3022 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3023 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
3024 transport
.Pass(), test_server()->host_port_pair(), ssl_config
));
3025 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
,
3026 callback
.GetResult(sock
->Connect(callback
.callback())));
3028 // Enabling deprecated ciphers works fine.
3029 ssl_config
.enable_deprecated_cipher_suites
= true;
3030 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3031 ASSERT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3032 sock
= CreateSSLClientSocket(transport
.Pass(),
3033 test_server()->host_port_pair(), ssl_config
);
3034 ASSERT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3037 // Tests that enabling deprecated ciphers shards the session cache.
3038 TEST_F(SSLClientSocketTest
, DeprecatedShardSessionCache
) {
3039 SpawnedTestServer::SSLOptions ssl_options
;
3040 ASSERT_TRUE(StartTestServer(ssl_options
));
3042 // Prepare a normal and deprecated SSL config.
3043 SSLConfig ssl_config
;
3044 SSLConfig deprecated_ssl_config
;
3045 deprecated_ssl_config
.enable_deprecated_cipher_suites
= true;
3047 // Connect with deprecated ciphers enabled to warm the session cache cache.
3048 TestCompletionCallback callback
;
3049 scoped_ptr
<StreamSocket
> transport(
3050 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3051 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3052 scoped_ptr
<SSLClientSocket
> sock(
3053 CreateSSLClientSocket(transport
.Pass(), test_server()->host_port_pair(),
3054 deprecated_ssl_config
));
3055 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3057 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3058 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3060 // Test that re-connecting with deprecated ciphers enabled still resumes.
3061 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3062 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3063 sock
= CreateSSLClientSocket(
3064 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
3065 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3066 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3067 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3069 // However, a normal connection needs a full handshake.
3070 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3071 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3072 sock
= CreateSSLClientSocket(transport
.Pass(),
3073 test_server()->host_port_pair(), ssl_config
);
3074 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3075 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3076 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3078 // Clear the session cache for the inverse test.
3079 SSLClientSocket::ClearSessionCache();
3081 // Now make a normal connection to prime the session cache.
3082 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3083 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3084 sock
= CreateSSLClientSocket(transport
.Pass(),
3085 test_server()->host_port_pair(), ssl_config
);
3086 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3087 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3088 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3090 // A normal connection should be able to resume.
3091 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3092 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3093 sock
= CreateSSLClientSocket(transport
.Pass(),
3094 test_server()->host_port_pair(), ssl_config
);
3095 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3096 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3097 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3099 // However, enabling deprecated ciphers connects fresh.
3100 transport
.reset(new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3101 EXPECT_EQ(OK
, callback
.GetResult(transport
->Connect(callback
.callback())));
3102 sock
= CreateSSLClientSocket(
3103 transport
.Pass(), test_server()->host_port_pair(), deprecated_ssl_config
);
3104 EXPECT_EQ(OK
, callback
.GetResult(sock
->Connect(callback
.callback())));
3105 EXPECT_TRUE(sock
->GetSSLInfo(&ssl_info
));
3106 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3109 TEST_F(SSLClientSocketTest
, RequireECDHE
) {
3110 // Run test server without ECDHE.
3111 SpawnedTestServer::SSLOptions ssl_options
;
3112 ssl_options
.key_exchanges
= SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
3113 SpawnedTestServer
test_server(SpawnedTestServer::TYPE_HTTPS
, ssl_options
,
3115 ASSERT_TRUE(test_server
.Start());
3118 ASSERT_TRUE(test_server
.GetAddressList(&addr
));
3120 TestCompletionCallback callback
;
3122 scoped_ptr
<StreamSocket
> transport(
3123 new TCPClientSocket(addr
, &log
, NetLog::Source()));
3124 int rv
= transport
->Connect(callback
.callback());
3125 rv
= callback
.GetResult(rv
);
3129 config
.require_ecdhe
= true;
3131 scoped_ptr
<SSLClientSocket
> sock(CreateSSLClientSocket(
3132 transport
.Pass(), test_server
.host_port_pair(), config
));
3134 rv
= sock
->Connect(callback
.callback());
3135 rv
= callback
.GetResult(rv
);
3137 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
, rv
);
3140 TEST_F(SSLClientSocketFalseStartTest
, FalseStartEnabled
) {
3141 if (!SupportsAESGCM()) {
3142 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3146 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
3147 SpawnedTestServer::SSLOptions server_options
;
3148 server_options
.key_exchanges
=
3149 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3150 server_options
.bulk_ciphers
=
3151 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3152 server_options
.enable_npn
= true;
3153 SSLConfig client_config
;
3154 client_config
.next_protos
.push_back(kProtoHTTP11
);
3155 ASSERT_NO_FATAL_FAILURE(
3156 TestFalseStart(server_options
, client_config
, true));
3159 // Test that False Start is disabled without NPN.
3160 TEST_F(SSLClientSocketFalseStartTest
, NoNPN
) {
3161 if (!SupportsAESGCM()) {
3162 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3166 SpawnedTestServer::SSLOptions server_options
;
3167 server_options
.key_exchanges
=
3168 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3169 server_options
.bulk_ciphers
=
3170 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3171 SSLConfig client_config
;
3172 client_config
.next_protos
.clear();
3173 ASSERT_NO_FATAL_FAILURE(
3174 TestFalseStart(server_options
, client_config
, false));
3177 // Test that False Start is disabled with plain RSA ciphers.
3178 TEST_F(SSLClientSocketFalseStartTest
, RSA
) {
3179 if (!SupportsAESGCM()) {
3180 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3184 SpawnedTestServer::SSLOptions server_options
;
3185 server_options
.key_exchanges
=
3186 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA
;
3187 server_options
.bulk_ciphers
=
3188 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3189 server_options
.enable_npn
= true;
3190 SSLConfig client_config
;
3191 client_config
.next_protos
.push_back(kProtoHTTP11
);
3192 ASSERT_NO_FATAL_FAILURE(
3193 TestFalseStart(server_options
, client_config
, false));
3196 // Test that False Start is disabled with DHE_RSA ciphers.
3197 TEST_F(SSLClientSocketFalseStartTest
, DHE_RSA
) {
3198 if (!SupportsAESGCM()) {
3199 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3203 SpawnedTestServer::SSLOptions server_options
;
3204 server_options
.key_exchanges
=
3205 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA
;
3206 server_options
.bulk_ciphers
=
3207 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3208 server_options
.enable_npn
= true;
3209 SSLConfig client_config
;
3210 client_config
.next_protos
.push_back(kProtoHTTP11
);
3211 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3214 // Test that False Start is disabled without an AEAD.
3215 TEST_F(SSLClientSocketFalseStartTest
, NoAEAD
) {
3216 SpawnedTestServer::SSLOptions server_options
;
3217 server_options
.key_exchanges
=
3218 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3219 server_options
.bulk_ciphers
=
3220 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128
;
3221 server_options
.enable_npn
= true;
3222 SSLConfig client_config
;
3223 client_config
.next_protos
.push_back(kProtoHTTP11
);
3224 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options
, client_config
, false));
3227 // Test that sessions are resumable after receiving the server Finished message.
3228 TEST_F(SSLClientSocketFalseStartTest
, SessionResumption
) {
3229 if (!SupportsAESGCM()) {
3230 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3235 SpawnedTestServer::SSLOptions server_options
;
3236 server_options
.key_exchanges
=
3237 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3238 server_options
.bulk_ciphers
=
3239 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3240 server_options
.enable_npn
= true;
3241 SSLConfig client_config
;
3242 client_config
.next_protos
.push_back(kProtoHTTP11
);
3244 // Let a full handshake complete with False Start.
3245 ASSERT_NO_FATAL_FAILURE(
3246 TestFalseStart(server_options
, client_config
, true));
3248 // Make a second connection.
3249 TestCompletionCallback callback
;
3250 scoped_ptr
<StreamSocket
> transport2(
3251 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3252 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3253 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3254 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3255 ASSERT_TRUE(sock2
.get());
3256 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3258 // It should resume the session.
3260 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3261 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME
, ssl_info
.handshake_type
);
3264 // Test that False Started sessions are not resumable before receiving the
3265 // server Finished message.
3266 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBeforeFinished
) {
3267 if (!SupportsAESGCM()) {
3268 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3273 SpawnedTestServer::SSLOptions server_options
;
3274 server_options
.key_exchanges
=
3275 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3276 server_options
.bulk_ciphers
=
3277 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3278 server_options
.enable_npn
= true;
3279 ASSERT_TRUE(StartTestServer(server_options
));
3281 SSLConfig client_config
;
3282 client_config
.next_protos
.push_back(kProtoHTTP11
);
3284 // Start a handshake up to the server Finished message.
3285 TestCompletionCallback callback
;
3286 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3287 scoped_ptr
<SSLClientSocket
> sock1
;
3288 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3289 client_config
, &callback
, &raw_transport1
, &sock1
));
3290 // Although raw_transport1 has the server Finished blocked, the handshake
3292 EXPECT_EQ(OK
, callback
.WaitForResult());
3294 // Continue to block the client (|sock1|) from processing the Finished
3295 // message, but allow it to arrive on the socket. This ensures that, from the
3296 // server's point of view, it has completed the handshake and added the
3297 // session to its session cache.
3299 // The actual read on |sock1| will not complete until the Finished message is
3300 // processed; however, pump the underlying transport so that it is read from
3301 // the socket. NOTE: This may flakily pass if the server's final flight
3302 // doesn't come in one Read.
3303 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3304 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3305 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3306 raw_transport1
->WaitForReadResult();
3308 // Drop the old socket. This is needed because the Python test server can't
3309 // service two sockets in parallel.
3312 // Start a second connection.
3313 scoped_ptr
<StreamSocket
> transport2(
3314 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3315 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3316 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3317 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3318 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3320 // No session resumption because the first connection never received a server
3321 // Finished message.
3323 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3324 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3327 // Test that False Started sessions are not resumable if the server Finished
3329 TEST_F(SSLClientSocketFalseStartTest
, NoSessionResumptionBadFinished
) {
3330 if (!SupportsAESGCM()) {
3331 LOG(WARNING
) << "Skipping test because AES-GCM is not supported.";
3336 SpawnedTestServer::SSLOptions server_options
;
3337 server_options
.key_exchanges
=
3338 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA
;
3339 server_options
.bulk_ciphers
=
3340 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM
;
3341 server_options
.enable_npn
= true;
3342 ASSERT_TRUE(StartTestServer(server_options
));
3344 SSLConfig client_config
;
3345 client_config
.next_protos
.push_back(kProtoHTTP11
);
3347 // Start a handshake up to the server Finished message.
3348 TestCompletionCallback callback
;
3349 FakeBlockingStreamSocket
* raw_transport1
= NULL
;
3350 scoped_ptr
<SSLClientSocket
> sock1
;
3351 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3352 client_config
, &callback
, &raw_transport1
, &sock1
));
3353 // Although raw_transport1 has the server Finished blocked, the handshake
3355 EXPECT_EQ(OK
, callback
.WaitForResult());
3357 // Continue to block the client (|sock1|) from processing the Finished
3358 // message, but allow it to arrive on the socket. This ensures that, from the
3359 // server's point of view, it has completed the handshake and added the
3360 // session to its session cache.
3362 // The actual read on |sock1| will not complete until the Finished message is
3363 // processed; however, pump the underlying transport so that it is read from
3365 scoped_refptr
<IOBuffer
> buf(new IOBuffer(4096));
3366 int rv
= sock1
->Read(buf
.get(), 4096, callback
.callback());
3367 EXPECT_EQ(ERR_IO_PENDING
, rv
);
3368 raw_transport1
->WaitForReadResult();
3370 // The server's second leg, or part of it, is now received but not yet sent to
3371 // |sock1|. Before doing so, break the server's second leg.
3372 int bytes_read
= raw_transport1
->pending_read_result();
3373 ASSERT_LT(0, bytes_read
);
3374 raw_transport1
->pending_read_buf()->data()[bytes_read
- 1]++;
3376 // Unblock the Finished message. |sock1->Read| should now fail.
3377 raw_transport1
->UnblockReadResult();
3378 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR
, callback
.GetResult(rv
));
3380 // Drop the old socket. This is needed because the Python test server can't
3381 // service two sockets in parallel.
3384 // Start a second connection.
3385 scoped_ptr
<StreamSocket
> transport2(
3386 new TCPClientSocket(addr(), &log_
, NetLog::Source()));
3387 EXPECT_EQ(OK
, callback
.GetResult(transport2
->Connect(callback
.callback())));
3388 scoped_ptr
<SSLClientSocket
> sock2
= CreateSSLClientSocket(
3389 transport2
.Pass(), test_server()->host_port_pair(), client_config
);
3390 EXPECT_EQ(OK
, callback
.GetResult(sock2
->Connect(callback
.callback())));
3392 // No session resumption because the first connection never received a server
3393 // Finished message.
3395 EXPECT_TRUE(sock2
->GetSSLInfo(&ssl_info
));
3396 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL
, ssl_info
.handshake_type
);
3399 // Connect to a server using channel id. It should allow the connection.
3400 TEST_F(SSLClientSocketChannelIDTest
, SendChannelID
) {
3401 SpawnedTestServer::SSLOptions ssl_options
;
3403 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3406 SSLConfig ssl_config
;
3407 ssl_config
.channel_id_enabled
= true;
3410 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3413 EXPECT_TRUE(sock_
->IsConnected());
3415 ASSERT_TRUE(sock_
->GetSSLInfo(&ssl_info
));
3416 EXPECT_TRUE(ssl_info
.channel_id_sent
);
3418 sock_
->Disconnect();
3419 EXPECT_FALSE(sock_
->IsConnected());
3422 // Connect to a server using Channel ID but failing to look up the Channel
3423 // ID. It should fail.
3424 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelID
) {
3425 SpawnedTestServer::SSLOptions ssl_options
;
3427 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3429 EnableFailingChannelID();
3430 SSLConfig ssl_config
;
3431 ssl_config
.channel_id_enabled
= true;
3434 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3436 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3437 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3438 // error codes for now.
3439 // http://crbug.com/373670
3441 EXPECT_FALSE(sock_
->IsConnected());
3444 // Connect to a server using Channel ID but asynchronously failing to look up
3445 // the Channel ID. It should fail.
3446 TEST_F(SSLClientSocketChannelIDTest
, FailingChannelIDAsync
) {
3447 SpawnedTestServer::SSLOptions ssl_options
;
3449 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
3451 EnableAsyncFailingChannelID();
3452 SSLConfig ssl_config
;
3453 ssl_config
.channel_id_enabled
= true;
3456 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
3458 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
3459 EXPECT_FALSE(sock_
->IsConnected());