Removed 'anonymous' from namespace, added whitespace in thread_restrictions.cc
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blob77a0aab72aeb2fc5cb65696e72fbd5d7e3127e47
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)
46 #include <pk11pub.h>
47 #include "crypto/nss_util.h"
49 #if !defined(CKM_AES_GCM)
50 #define CKM_AES_GCM 0x00001087
51 #endif
53 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
54 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
55 #endif
56 #endif
58 //-----------------------------------------------------------------------------
60 using testing::_;
61 using testing::Return;
62 using testing::Truly;
64 namespace net {
66 namespace {
68 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
69 // forwarding the Socket and StreamSocket interfaces to the underlying
70 // transport.
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'
73 // StreamSocket.
74 class WrappedStreamSocket : public StreamSocket {
75 public:
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,
125 int buf_len,
126 const CompletionCallback& callback) override {
127 return transport_->Read(buf, buf_len, callback);
129 int Write(IOBuffer* buf,
130 int buf_len,
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);
141 protected:
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 {
152 public:
153 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
154 ~ReadBufferingStreamSocket() override {}
156 // Socket implementation:
157 int Read(IOBuffer* buf,
158 int buf_len,
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);
170 private:
171 enum State {
172 STATE_NONE,
173 STATE_READ,
174 STATE_READ_COMPLETE,
177 int DoLoop(int result);
178 int DoRead();
179 int DoReadComplete(int result);
180 void OnReadCompleted(int result);
182 State state_;
183 scoped_refptr<GrowableIOBuffer> read_buffer_;
184 int buffer_size_;
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()),
194 buffer_size_(0) {}
196 void ReadBufferingStreamSocket::SetBufferSize(int size) {
197 DCHECK(!user_read_buf_.get());
198 buffer_size_ = size;
199 read_buffer_->SetCapacity(size);
202 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
203 int buf_len,
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;
211 state_ = STATE_READ;
212 user_read_buf_ = buf;
213 int result = DoLoop(OK);
214 if (result == ERR_IO_PENDING)
215 user_read_callback_ = callback;
216 else
217 user_read_buf_ = NULL;
218 return result;
221 int ReadBufferingStreamSocket::DoLoop(int result) {
222 int rv = result;
223 do {
224 State current_state = state_;
225 state_ = STATE_NONE;
226 switch (current_state) {
227 case STATE_READ:
228 rv = DoRead();
229 break;
230 case STATE_READ_COMPLETE:
231 rv = DoReadComplete(rv);
232 break;
233 case STATE_NONE:
234 default:
235 NOTREACHED() << "Unexpected state: " << current_state;
236 rv = ERR_UNEXPECTED;
237 break;
239 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
240 return rv;
243 int ReadBufferingStreamSocket::DoRead() {
244 state_ = STATE_READ_COMPLETE;
245 int rv =
246 transport_->Read(read_buffer_.get(),
247 read_buffer_->RemainingCapacity(),
248 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
249 base::Unretained(this)));
250 return rv;
253 int ReadBufferingStreamSocket::DoReadComplete(int result) {
254 state_ = STATE_NONE;
255 if (result <= 0)
256 return result;
258 read_buffer_->set_offset(read_buffer_->offset() + result);
259 if (read_buffer_->RemainingCapacity() > 0) {
260 state_ = STATE_READ;
261 return OK;
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)
274 return;
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 {
282 public:
283 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
284 ~SynchronousErrorStreamSocket() override {}
286 // Socket implementation:
287 int Read(IOBuffer* buf,
288 int buf_len,
289 const CompletionCallback& callback) override;
290 int Write(IOBuffer* buf,
291 int buf_len,
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()
297 // is called again.
298 void SetNextReadError(int error) {
299 DCHECK_GE(0, 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) {
309 DCHECK_GE(0, error);
310 have_write_error_ = true;
311 pending_write_error_ = error;
314 private:
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,
333 int buf_len,
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,
341 int buf_len,
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
351 // semantics).
352 class FakeBlockingStreamSocket : public WrappedStreamSocket {
353 public:
354 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
355 ~FakeBlockingStreamSocket() override {}
357 // Socket implementation:
358 int Read(IOBuffer* buf,
359 int buf_len,
360 const CompletionCallback& callback) override;
361 int Write(IOBuffer* buf,
362 int buf_len,
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
376 // transport.
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.
384 void BlockWrite();
385 void UnblockWrite();
387 // Waits for the blocked Write() call to be scheduled.
388 void WaitForWrite();
390 private:
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
404 // completed.
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,
435 int len,
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;
452 OnReadCompleted(rv);
453 rv = ERR_IO_PENDING;
455 return rv;
458 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
459 int len,
460 const CompletionCallback& callback) {
461 DCHECK(buf);
462 DCHECK_LE(0, len);
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.
477 if (write_loop_)
478 write_loop_->Quit();
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)
495 return;
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_);
504 DCHECK(!read_loop_);
506 if (pending_read_result_ != ERR_IO_PENDING)
507 return;
508 read_loop_.reset(new base::RunLoop);
509 read_loop_->Run();
510 read_loop_.reset();
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())
526 return;
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();
534 } else {
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())
544 return;
545 write_loop_.reset(new base::RunLoop);
546 write_loop_->Run();
547 write_loop_.reset();
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
557 // called.
558 pending_read_result_ = result;
560 // Stop the WaitForReadResult() call if any.
561 if (read_loop_)
562 read_loop_->Quit();
563 } else {
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 {
574 public:
575 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
576 : WrappedStreamSocket(transport.Pass()),
577 read_count_(0),
578 write_count_(0) {}
579 ~CountingStreamSocket() override {}
581 // Socket implementation:
582 int Read(IOBuffer* buf,
583 int buf_len,
584 const CompletionCallback& callback) override {
585 read_count_++;
586 return transport_->Read(buf, buf_len, callback);
588 int Write(IOBuffer* buf,
589 int buf_len,
590 const CompletionCallback& callback) override {
591 write_count_++;
592 return transport_->Write(buf, buf_len, callback);
595 int read_count() const { return read_count_; }
596 int write_count() const { return write_count_; }
598 private:
599 int read_count_;
600 int write_count_;
603 // CompletionCallback that will delete the associated StreamSocket when
604 // the callback is invoked.
605 class DeleteSocketCallback : public TestCompletionCallbackBase {
606 public:
607 explicit DeleteSocketCallback(StreamSocket* socket)
608 : socket_(socket),
609 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
610 base::Unretained(this))) {}
611 ~DeleteSocketCallback() override {}
613 const CompletionCallback& callback() const { return callback_; }
615 private:
616 void OnComplete(int result) {
617 if (socket_) {
618 delete socket_;
619 socket_ = NULL;
620 } else {
621 ADD_FAILURE() << "Deleting socket twice";
623 SetResult(result);
626 StreamSocket* socket_;
627 CompletionCallback callback_;
629 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
632 // A ChannelIDStore that always returns an error when asked for a
633 // channel id.
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
654 // channel id.
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(
660 FROM_HERE,
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
678 // anything.
679 class MockCTVerifier : public CTVerifier {
680 public:
681 MOCK_METHOD5(Verify, int(X509Certificate*,
682 const std::string&,
683 const std::string&,
684 ct::CTVerifyResult*,
685 const BoundNetLog&));
686 MOCK_METHOD1(SetObserver, void(CTVerifier::Observer*));
689 class SSLClientSocketTest : public PlatformTest {
690 public:
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();
700 protected:
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
712 // on success.
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";
718 return false;
721 if (!test_server_->GetAddressList(&addr_)) {
722 LOG(ERROR) << "Could not get SpawnedTestServer address list";
723 return false;
725 return true;
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))
732 return false;
734 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
735 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
736 if (rv != OK) {
737 LOG(ERROR) << "Could not connect to SpawnedTestServer";
738 return false;
740 return true;
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";
767 return false;
770 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
771 return true;
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_;
779 TestNetLog log_;
781 private:
782 scoped_ptr<StreamSocket> transport_;
783 scoped_ptr<SpawnedTestServer> test_server_;
784 TestCompletionCallback callback_;
785 AddressList addr_;
788 // Verifies the correctness of GetSSLCertRequestInfo.
789 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
790 protected:
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())
798 return NULL;
800 AddressList addr;
801 if (!test_server.GetAddressList(&addr))
802 return NULL;
804 TestCompletionCallback callback;
805 TestNetLog log;
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();
811 EXPECT_EQ(OK, rv);
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());
822 sock->Disconnect();
823 EXPECT_FALSE(sock->IsConnected());
824 EXPECT_TRUE(
825 test_server.host_port_pair().Equals(request_info->host_and_port));
827 return request_info;
831 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
832 protected:
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()));
858 EXPECT_EQ(OK, rv);
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();
907 EXPECT_EQ(OK, rv);
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(),
918 kRequestTextSize,
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);
930 EXPECT_LT(0, rv);
931 } else {
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 {
941 protected:
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();
960 private:
961 scoped_ptr<ChannelIDService> channel_id_service_;
964 //-----------------------------------------------------------------------------
966 bool SupportsAESGCM() {
967 #if defined(USE_OPENSSL)
968 return true;
969 #else
970 crypto::EnsureNSSInit();
971 return PK11_TokenExists(CKM_AES_GCM) &&
972 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
973 #endif
976 } // namespace
978 TEST_F(SSLClientSocketTest, Connect) {
979 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
980 SpawnedTestServer::kLocalhost,
981 base::FilePath());
982 ASSERT_TRUE(test_server.Start());
984 AddressList addr;
985 ASSERT_TRUE(test_server.GetAddressList(&addr));
987 TestCompletionCallback callback;
988 TestNetLog log;
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();
994 EXPECT_EQ(OK, rv);
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();
1008 EXPECT_EQ(OK, rv);
1009 EXPECT_TRUE(sock->IsConnected());
1010 log.GetEntries(&entries);
1011 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1013 sock->Disconnect();
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);
1026 AddressList addr;
1027 ASSERT_TRUE(test_server.GetAddressList(&addr));
1029 TestCompletionCallback callback;
1030 TestNetLog log;
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();
1036 EXPECT_EQ(OK, rv);
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);
1070 AddressList addr;
1071 ASSERT_TRUE(test_server.GetAddressList(&addr));
1073 TestCompletionCallback callback;
1074 TestNetLog log;
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();
1080 EXPECT_EQ(OK, rv);
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 #if defined(OS_WIN)
1106 // Tests that certificates parsable by SSLClientSocket's internal SSL
1107 // implementation, but not X509Certificate are treated as fatal non-certificate
1108 // errors. This is regression test for https://crbug.com/91341.
1109 TEST_F(SSLClientSocketTest, ConnectBadValidity) {
1110 SpawnedTestServer::SSLOptions ssl_options(
1111 SpawnedTestServer::SSLOptions::CERT_BAD_VALIDITY);
1112 ASSERT_TRUE(ConnectToTestServer(ssl_options));
1113 SSLConfig ssl_config;
1114 int rv;
1115 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
1117 EXPECT_EQ(ERR_SSL_SERVER_CERT_BAD_FORMAT, rv);
1118 EXPECT_FALSE(IsCertificateError(rv));
1120 SSLInfo ssl_info;
1121 ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
1122 EXPECT_FALSE(ssl_info.cert);
1124 #endif // defined(OS_WIN)
1126 // Attempt to connect to a page which requests a client certificate. It should
1127 // return an error code on connect.
1128 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1129 SpawnedTestServer::SSLOptions ssl_options;
1130 ssl_options.request_client_certificate = true;
1131 SpawnedTestServer test_server(
1132 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1133 ASSERT_TRUE(test_server.Start());
1135 AddressList addr;
1136 ASSERT_TRUE(test_server.GetAddressList(&addr));
1138 TestCompletionCallback callback;
1139 TestNetLog log;
1140 scoped_ptr<StreamSocket> transport(
1141 new TCPClientSocket(addr, &log, NetLog::Source()));
1142 int rv = transport->Connect(callback.callback());
1143 if (rv == ERR_IO_PENDING)
1144 rv = callback.WaitForResult();
1145 EXPECT_EQ(OK, rv);
1147 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1148 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1150 EXPECT_FALSE(sock->IsConnected());
1152 rv = sock->Connect(callback.callback());
1154 TestNetLogEntry::List entries;
1155 log.GetEntries(&entries);
1156 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1157 if (rv == ERR_IO_PENDING)
1158 rv = callback.WaitForResult();
1160 log.GetEntries(&entries);
1161 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1162 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1163 EXPECT_FALSE(sock->IsConnected());
1166 // Connect to a server requesting optional client authentication. Send it a
1167 // null certificate. It should allow the connection.
1169 // TODO(davidben): Also test providing an actual certificate.
1170 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1171 SpawnedTestServer::SSLOptions ssl_options;
1172 ssl_options.request_client_certificate = true;
1173 SpawnedTestServer test_server(
1174 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1175 ASSERT_TRUE(test_server.Start());
1177 AddressList addr;
1178 ASSERT_TRUE(test_server.GetAddressList(&addr));
1180 TestCompletionCallback callback;
1181 TestNetLog log;
1182 scoped_ptr<StreamSocket> transport(
1183 new TCPClientSocket(addr, &log, NetLog::Source()));
1184 int rv = transport->Connect(callback.callback());
1185 if (rv == ERR_IO_PENDING)
1186 rv = callback.WaitForResult();
1187 EXPECT_EQ(OK, rv);
1189 SSLConfig ssl_config;
1190 ssl_config.send_client_cert = true;
1191 ssl_config.client_cert = NULL;
1193 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1194 transport.Pass(), test_server.host_port_pair(), ssl_config));
1196 EXPECT_FALSE(sock->IsConnected());
1198 // Our test server accepts certificate-less connections.
1199 // TODO(davidben): Add a test which requires them and verify the error.
1200 rv = sock->Connect(callback.callback());
1202 TestNetLogEntry::List entries;
1203 log.GetEntries(&entries);
1204 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1205 if (rv == ERR_IO_PENDING)
1206 rv = callback.WaitForResult();
1208 EXPECT_EQ(OK, rv);
1209 EXPECT_TRUE(sock->IsConnected());
1210 log.GetEntries(&entries);
1211 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1213 // We responded to the server's certificate request with a Certificate
1214 // message with no client certificate in it. ssl_info.client_cert_sent
1215 // should be false in this case.
1216 SSLInfo ssl_info;
1217 sock->GetSSLInfo(&ssl_info);
1218 EXPECT_FALSE(ssl_info.client_cert_sent);
1220 sock->Disconnect();
1221 EXPECT_FALSE(sock->IsConnected());
1224 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1225 // - Server closes an SSL connection (with a close_notify alert message).
1226 // - Server closes the underlying TCP connection directly.
1227 // - Server sends data unexpectedly.
1229 // Tests that the socket can be read from successfully. Also test that a peer's
1230 // close_notify alert is successfully processed without error.
1231 TEST_F(SSLClientSocketTest, Read) {
1232 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1233 SpawnedTestServer::kLocalhost,
1234 base::FilePath());
1235 ASSERT_TRUE(test_server.Start());
1237 AddressList addr;
1238 ASSERT_TRUE(test_server.GetAddressList(&addr));
1240 TestCompletionCallback callback;
1241 scoped_ptr<StreamSocket> transport(
1242 new TCPClientSocket(addr, NULL, NetLog::Source()));
1243 int rv = transport->Connect(callback.callback());
1244 if (rv == ERR_IO_PENDING)
1245 rv = callback.WaitForResult();
1246 EXPECT_EQ(OK, rv);
1248 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1249 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1251 rv = sock->Connect(callback.callback());
1252 if (rv == ERR_IO_PENDING)
1253 rv = callback.WaitForResult();
1254 EXPECT_EQ(OK, rv);
1255 EXPECT_TRUE(sock->IsConnected());
1257 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1258 scoped_refptr<IOBuffer> request_buffer(
1259 new IOBuffer(arraysize(request_text) - 1));
1260 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1262 rv = sock->Write(
1263 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1264 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1266 if (rv == ERR_IO_PENDING)
1267 rv = callback.WaitForResult();
1268 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1270 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1271 for (;;) {
1272 rv = sock->Read(buf.get(), 4096, callback.callback());
1273 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1275 if (rv == ERR_IO_PENDING)
1276 rv = callback.WaitForResult();
1278 EXPECT_GE(rv, 0);
1279 if (rv <= 0)
1280 break;
1283 // The peer should have cleanly closed the connection with a close_notify.
1284 EXPECT_EQ(0, rv);
1287 // Tests that SSLClientSocket properly handles when the underlying transport
1288 // synchronously fails a transport read in during the handshake. The error code
1289 // should be preserved so SSLv3 fallback logic can condition on it.
1290 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1291 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1292 SpawnedTestServer::kLocalhost,
1293 base::FilePath());
1294 ASSERT_TRUE(test_server.Start());
1296 AddressList addr;
1297 ASSERT_TRUE(test_server.GetAddressList(&addr));
1299 TestCompletionCallback callback;
1300 scoped_ptr<StreamSocket> real_transport(
1301 new TCPClientSocket(addr, NULL, NetLog::Source()));
1302 scoped_ptr<SynchronousErrorStreamSocket> transport(
1303 new SynchronousErrorStreamSocket(real_transport.Pass()));
1304 int rv = callback.GetResult(transport->Connect(callback.callback()));
1305 EXPECT_EQ(OK, rv);
1307 // Disable TLS False Start to avoid handshake non-determinism.
1308 SSLConfig ssl_config;
1309 ssl_config.false_start_enabled = false;
1311 SynchronousErrorStreamSocket* raw_transport = transport.get();
1312 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1313 transport.Pass(), test_server.host_port_pair(), ssl_config));
1315 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1317 rv = callback.GetResult(sock->Connect(callback.callback()));
1318 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1319 EXPECT_FALSE(sock->IsConnected());
1322 // Tests that the SSLClientSocket properly handles when the underlying transport
1323 // synchronously returns an error code - such as if an intermediary terminates
1324 // the socket connection uncleanly.
1325 // This is a regression test for http://crbug.com/238536
1326 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1327 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1328 SpawnedTestServer::kLocalhost,
1329 base::FilePath());
1330 ASSERT_TRUE(test_server.Start());
1332 AddressList addr;
1333 ASSERT_TRUE(test_server.GetAddressList(&addr));
1335 TestCompletionCallback callback;
1336 scoped_ptr<StreamSocket> real_transport(
1337 new TCPClientSocket(addr, NULL, NetLog::Source()));
1338 scoped_ptr<SynchronousErrorStreamSocket> transport(
1339 new SynchronousErrorStreamSocket(real_transport.Pass()));
1340 int rv = callback.GetResult(transport->Connect(callback.callback()));
1341 EXPECT_EQ(OK, rv);
1343 // Disable TLS False Start to avoid handshake non-determinism.
1344 SSLConfig ssl_config;
1345 ssl_config.false_start_enabled = false;
1347 SynchronousErrorStreamSocket* raw_transport = transport.get();
1348 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1349 transport.Pass(), test_server.host_port_pair(), ssl_config));
1351 rv = callback.GetResult(sock->Connect(callback.callback()));
1352 EXPECT_EQ(OK, rv);
1353 EXPECT_TRUE(sock->IsConnected());
1355 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1356 static const int kRequestTextSize =
1357 static_cast<int>(arraysize(request_text) - 1);
1358 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1359 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1361 rv = callback.GetResult(
1362 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1363 EXPECT_EQ(kRequestTextSize, rv);
1365 // Simulate an unclean/forcible shutdown.
1366 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1368 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1370 // Note: This test will hang if this bug has regressed. Simply checking that
1371 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1372 // result when using a dedicated task runner for NSS.
1373 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1374 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1377 // Tests that the SSLClientSocket properly handles when the underlying transport
1378 // asynchronously returns an error code while writing data - such as if an
1379 // intermediary terminates the socket connection uncleanly.
1380 // This is a regression test for http://crbug.com/249848
1381 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1382 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1383 SpawnedTestServer::kLocalhost,
1384 base::FilePath());
1385 ASSERT_TRUE(test_server.Start());
1387 AddressList addr;
1388 ASSERT_TRUE(test_server.GetAddressList(&addr));
1390 TestCompletionCallback callback;
1391 scoped_ptr<StreamSocket> real_transport(
1392 new TCPClientSocket(addr, NULL, NetLog::Source()));
1393 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1394 // is retained in order to configure additional errors.
1395 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1396 new SynchronousErrorStreamSocket(real_transport.Pass()));
1397 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1398 scoped_ptr<FakeBlockingStreamSocket> transport(
1399 new FakeBlockingStreamSocket(error_socket.Pass()));
1400 FakeBlockingStreamSocket* raw_transport = transport.get();
1401 int rv = callback.GetResult(transport->Connect(callback.callback()));
1402 EXPECT_EQ(OK, rv);
1404 // Disable TLS False Start to avoid handshake non-determinism.
1405 SSLConfig ssl_config;
1406 ssl_config.false_start_enabled = false;
1408 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1409 transport.Pass(), test_server.host_port_pair(), ssl_config));
1411 rv = callback.GetResult(sock->Connect(callback.callback()));
1412 EXPECT_EQ(OK, rv);
1413 EXPECT_TRUE(sock->IsConnected());
1415 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1416 static const int kRequestTextSize =
1417 static_cast<int>(arraysize(request_text) - 1);
1418 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1419 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1421 // Simulate an unclean/forcible shutdown on the underlying socket.
1422 // However, simulate this error asynchronously.
1423 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1424 raw_transport->BlockWrite();
1426 // This write should complete synchronously, because the TLS ciphertext
1427 // can be created and placed into the outgoing buffers independent of the
1428 // underlying transport.
1429 rv = callback.GetResult(
1430 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1431 EXPECT_EQ(kRequestTextSize, rv);
1433 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1435 rv = sock->Read(buf.get(), 4096, callback.callback());
1436 EXPECT_EQ(ERR_IO_PENDING, rv);
1438 // Now unblock the outgoing request, having it fail with the connection
1439 // being reset.
1440 raw_transport->UnblockWrite();
1442 // Note: This will cause an inifite loop if this bug has regressed. Simply
1443 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1444 // is a legitimate result when using a dedicated task runner for NSS.
1445 rv = callback.GetResult(rv);
1446 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1449 // If there is a Write failure at the transport with no follow-up Read, although
1450 // the write error will not be returned to the client until a future Read or
1451 // Write operation, SSLClientSocket should not spin attempting to re-write on
1452 // the socket. This is a regression test for part of https://crbug.com/381160.
1453 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1454 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1455 SpawnedTestServer::kLocalhost,
1456 base::FilePath());
1457 ASSERT_TRUE(test_server.Start());
1459 AddressList addr;
1460 ASSERT_TRUE(test_server.GetAddressList(&addr));
1462 TestCompletionCallback callback;
1463 scoped_ptr<StreamSocket> real_transport(
1464 new TCPClientSocket(addr, NULL, NetLog::Source()));
1465 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1466 // is retained in order to query them.
1467 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1468 new SynchronousErrorStreamSocket(real_transport.Pass()));
1469 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1470 scoped_ptr<CountingStreamSocket> counting_socket(
1471 new CountingStreamSocket(error_socket.Pass()));
1472 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1473 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1474 ASSERT_EQ(OK, rv);
1476 // Disable TLS False Start to avoid handshake non-determinism.
1477 SSLConfig ssl_config;
1478 ssl_config.false_start_enabled = false;
1480 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1481 counting_socket.Pass(), test_server.host_port_pair(), ssl_config));
1483 rv = callback.GetResult(sock->Connect(callback.callback()));
1484 ASSERT_EQ(OK, rv);
1485 ASSERT_TRUE(sock->IsConnected());
1487 // Simulate an unclean/forcible shutdown on the underlying socket.
1488 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1490 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1491 static const int kRequestTextSize =
1492 static_cast<int>(arraysize(request_text) - 1);
1493 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1494 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1496 // This write should complete synchronously, because the TLS ciphertext
1497 // can be created and placed into the outgoing buffers independent of the
1498 // underlying transport.
1499 rv = callback.GetResult(
1500 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1501 ASSERT_EQ(kRequestTextSize, rv);
1503 // Let the event loop spin for a little bit of time. Even on platforms where
1504 // pumping the state machine involve thread hops, there should be no further
1505 // writes on the transport socket.
1507 // TODO(davidben): Avoid the arbitrary timeout?
1508 int old_write_count = raw_counting_socket->write_count();
1509 base::RunLoop loop;
1510 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
1511 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1512 loop.Run();
1513 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1516 // Test the full duplex mode, with Read and Write pending at the same time.
1517 // This test also serves as a regression test for http://crbug.com/29815.
1518 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1519 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1520 SpawnedTestServer::kLocalhost,
1521 base::FilePath());
1522 ASSERT_TRUE(test_server.Start());
1524 AddressList addr;
1525 ASSERT_TRUE(test_server.GetAddressList(&addr));
1527 TestCompletionCallback callback; // Used for everything except Write.
1529 scoped_ptr<StreamSocket> transport(
1530 new TCPClientSocket(addr, NULL, NetLog::Source()));
1531 int rv = transport->Connect(callback.callback());
1532 if (rv == ERR_IO_PENDING)
1533 rv = callback.WaitForResult();
1534 EXPECT_EQ(OK, rv);
1536 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1537 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1539 rv = sock->Connect(callback.callback());
1540 if (rv == ERR_IO_PENDING)
1541 rv = callback.WaitForResult();
1542 EXPECT_EQ(OK, rv);
1543 EXPECT_TRUE(sock->IsConnected());
1545 // Issue a "hanging" Read first.
1546 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1547 rv = sock->Read(buf.get(), 4096, callback.callback());
1548 // We haven't written the request, so there should be no response yet.
1549 ASSERT_EQ(ERR_IO_PENDING, rv);
1551 // Write the request.
1552 // The request is padded with a User-Agent header to a size that causes the
1553 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1554 // This tests the fix for http://crbug.com/29815.
1555 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1556 for (int i = 0; i < 3770; ++i)
1557 request_text.push_back('*');
1558 request_text.append("\r\n\r\n");
1559 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1561 TestCompletionCallback callback2; // Used for Write only.
1562 rv = sock->Write(
1563 request_buffer.get(), request_text.size(), callback2.callback());
1564 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1566 if (rv == ERR_IO_PENDING)
1567 rv = callback2.WaitForResult();
1568 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1570 // Now get the Read result.
1571 rv = callback.WaitForResult();
1572 EXPECT_GT(rv, 0);
1575 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1576 // mode when the underlying transport is blocked on sending data. When the
1577 // underlying transport completes due to an error, it should invoke both the
1578 // Read() and Write() callbacks. If the socket is deleted by the Read()
1579 // callback, the Write() callback should not be invoked.
1580 // Regression test for http://crbug.com/232633
1581 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1582 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1583 SpawnedTestServer::kLocalhost,
1584 base::FilePath());
1585 ASSERT_TRUE(test_server.Start());
1587 AddressList addr;
1588 ASSERT_TRUE(test_server.GetAddressList(&addr));
1590 TestCompletionCallback callback;
1591 scoped_ptr<StreamSocket> real_transport(
1592 new TCPClientSocket(addr, NULL, NetLog::Source()));
1593 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1594 // is retained in order to configure additional errors.
1595 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1596 new SynchronousErrorStreamSocket(real_transport.Pass()));
1597 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1598 scoped_ptr<FakeBlockingStreamSocket> transport(
1599 new FakeBlockingStreamSocket(error_socket.Pass()));
1600 FakeBlockingStreamSocket* raw_transport = transport.get();
1602 int rv = callback.GetResult(transport->Connect(callback.callback()));
1603 EXPECT_EQ(OK, rv);
1605 // Disable TLS False Start to avoid handshake non-determinism.
1606 SSLConfig ssl_config;
1607 ssl_config.false_start_enabled = false;
1609 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
1610 transport.Pass(), test_server.host_port_pair(), ssl_config);
1612 rv = callback.GetResult(sock->Connect(callback.callback()));
1613 EXPECT_EQ(OK, rv);
1614 EXPECT_TRUE(sock->IsConnected());
1616 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1617 request_text.append(20 * 1024, '*');
1618 request_text.append("\r\n\r\n");
1619 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1620 new StringIOBuffer(request_text), request_text.size()));
1622 // Simulate errors being returned from the underlying Read() and Write() ...
1623 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1624 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1625 // ... but have those errors returned asynchronously. Because the Write() will
1626 // return first, this will trigger the error.
1627 raw_transport->BlockReadResult();
1628 raw_transport->BlockWrite();
1630 // Enqueue a Read() before calling Write(), which should "hang" due to
1631 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1632 SSLClientSocket* raw_sock = sock.get();
1633 DeleteSocketCallback read_callback(sock.release());
1634 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1635 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1637 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1638 ASSERT_EQ(ERR_IO_PENDING, rv);
1639 ASSERT_FALSE(read_callback.have_result());
1641 #if !defined(USE_OPENSSL)
1642 // NSS follows a pattern where a call to PR_Write will only consume as
1643 // much data as it can encode into application data records before the
1644 // internal memio buffer is full, which should only fill if writing a large
1645 // amount of data and the underlying transport is blocked. Once this happens,
1646 // NSS will return (total size of all application data records it wrote) - 1,
1647 // with the caller expected to resume with the remaining unsent data.
1649 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1650 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1651 // get the socket in the state needed for the test below.
1653 // This is not needed for OpenSSL, because for OpenSSL,
1654 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1655 // SSLClientSocketOpenSSL::Write() will not return until all of
1656 // |request_buffer| has been written to the underlying BIO (although not
1657 // necessarily the underlying transport).
1658 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1659 request_buffer->BytesRemaining(),
1660 callback.callback()));
1661 ASSERT_LT(0, rv);
1662 request_buffer->DidConsume(rv);
1664 // Guard to ensure that |request_buffer| was larger than all of the internal
1665 // buffers (transport, memio, NSS) along the way - otherwise the next call
1666 // to Write() will crash with an invalid buffer.
1667 ASSERT_LT(0, request_buffer->BytesRemaining());
1668 #endif
1670 // Attempt to write the remaining data. NSS will not be able to consume the
1671 // application data because the internal buffers are full, while OpenSSL will
1672 // return that its blocked because the underlying transport is blocked.
1673 rv = raw_sock->Write(request_buffer.get(),
1674 request_buffer->BytesRemaining(),
1675 callback.callback());
1676 ASSERT_EQ(ERR_IO_PENDING, rv);
1677 ASSERT_FALSE(callback.have_result());
1679 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1680 // call the Read() callback, deleting the socket and thus aborting calling
1681 // the Write() callback.
1682 raw_transport->UnblockWrite();
1684 rv = read_callback.WaitForResult();
1685 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1687 // The Write callback should not have been called.
1688 EXPECT_FALSE(callback.have_result());
1691 // Tests that the SSLClientSocket does not crash if data is received on the
1692 // transport socket after a failing write. This can occur if we have a Write
1693 // error in a SPDY socket.
1694 // Regression test for http://crbug.com/335557
1695 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1696 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1697 SpawnedTestServer::kLocalhost,
1698 base::FilePath());
1699 ASSERT_TRUE(test_server.Start());
1701 AddressList addr;
1702 ASSERT_TRUE(test_server.GetAddressList(&addr));
1704 TestCompletionCallback callback;
1705 scoped_ptr<StreamSocket> real_transport(
1706 new TCPClientSocket(addr, NULL, NetLog::Source()));
1707 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1708 // is retained in order to configure additional errors.
1709 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1710 new SynchronousErrorStreamSocket(real_transport.Pass()));
1711 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1712 scoped_ptr<FakeBlockingStreamSocket> transport(
1713 new FakeBlockingStreamSocket(error_socket.Pass()));
1714 FakeBlockingStreamSocket* raw_transport = transport.get();
1716 int rv = callback.GetResult(transport->Connect(callback.callback()));
1717 EXPECT_EQ(OK, rv);
1719 // Disable TLS False Start to avoid handshake non-determinism.
1720 SSLConfig ssl_config;
1721 ssl_config.false_start_enabled = false;
1723 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1724 transport.Pass(), test_server.host_port_pair(), ssl_config));
1726 rv = callback.GetResult(sock->Connect(callback.callback()));
1727 EXPECT_EQ(OK, rv);
1728 EXPECT_TRUE(sock->IsConnected());
1730 // Send a request so there is something to read from the socket.
1731 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1732 static const int kRequestTextSize =
1733 static_cast<int>(arraysize(request_text) - 1);
1734 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1735 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1737 rv = callback.GetResult(
1738 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1739 EXPECT_EQ(kRequestTextSize, rv);
1741 // Start a hanging read.
1742 TestCompletionCallback read_callback;
1743 raw_transport->BlockReadResult();
1744 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1745 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1746 EXPECT_EQ(ERR_IO_PENDING, rv);
1748 // Perform another write, but have it fail. Write a request larger than the
1749 // internal socket buffers so that the request hits the underlying transport
1750 // socket and detects the error.
1751 std::string long_request_text =
1752 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1753 long_request_text.append(20 * 1024, '*');
1754 long_request_text.append("\r\n\r\n");
1755 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1756 new StringIOBuffer(long_request_text), long_request_text.size()));
1758 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1760 // Write as much data as possible until hitting an error. This is necessary
1761 // for NSS. PR_Write will only consume as much data as it can encode into
1762 // application data records before the internal memio buffer is full, which
1763 // should only fill if writing a large amount of data and the underlying
1764 // transport is blocked. Once this happens, NSS will return (total size of all
1765 // application data records it wrote) - 1, with the caller expected to resume
1766 // with the remaining unsent data.
1767 do {
1768 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1769 long_request_buffer->BytesRemaining(),
1770 callback.callback()));
1771 if (rv > 0) {
1772 long_request_buffer->DidConsume(rv);
1773 // Abort if the entire buffer is ever consumed.
1774 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1776 } while (rv > 0);
1778 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1780 // Release the read.
1781 raw_transport->UnblockReadResult();
1782 rv = read_callback.WaitForResult();
1784 #if defined(USE_OPENSSL)
1785 // Should still read bytes despite the write error.
1786 EXPECT_LT(0, rv);
1787 #else
1788 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1789 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1790 // the write error stops future reads.
1791 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1792 #endif
1795 // Tests that SSLClientSocket fails the handshake if the underlying
1796 // transport is cleanly closed.
1797 TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
1798 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1799 SpawnedTestServer::kLocalhost,
1800 base::FilePath());
1801 ASSERT_TRUE(test_server.Start());
1803 AddressList addr;
1804 ASSERT_TRUE(test_server.GetAddressList(&addr));
1806 TestCompletionCallback callback;
1807 scoped_ptr<StreamSocket> real_transport(
1808 new TCPClientSocket(addr, NULL, NetLog::Source()));
1809 scoped_ptr<SynchronousErrorStreamSocket> transport(
1810 new SynchronousErrorStreamSocket(real_transport.Pass()));
1811 int rv = callback.GetResult(transport->Connect(callback.callback()));
1812 EXPECT_EQ(OK, rv);
1814 SynchronousErrorStreamSocket* raw_transport = transport.get();
1815 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1816 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1818 raw_transport->SetNextReadError(0);
1820 rv = callback.GetResult(sock->Connect(callback.callback()));
1821 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
1822 EXPECT_FALSE(sock->IsConnected());
1825 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1826 // is cleanly closed, but the peer does not send close_notify.
1827 // This is a regression test for https://crbug.com/422246
1828 TEST_F(SSLClientSocketTest, Read_WithZeroReturn) {
1829 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1830 SpawnedTestServer::kLocalhost,
1831 base::FilePath());
1832 ASSERT_TRUE(test_server.Start());
1834 AddressList addr;
1835 ASSERT_TRUE(test_server.GetAddressList(&addr));
1837 TestCompletionCallback callback;
1838 scoped_ptr<StreamSocket> real_transport(
1839 new TCPClientSocket(addr, NULL, NetLog::Source()));
1840 scoped_ptr<SynchronousErrorStreamSocket> transport(
1841 new SynchronousErrorStreamSocket(real_transport.Pass()));
1842 int rv = callback.GetResult(transport->Connect(callback.callback()));
1843 EXPECT_EQ(OK, rv);
1845 // Disable TLS False Start to ensure the handshake has completed.
1846 SSLConfig ssl_config;
1847 ssl_config.false_start_enabled = false;
1849 SynchronousErrorStreamSocket* raw_transport = transport.get();
1850 scoped_ptr<SSLClientSocket> sock(
1851 CreateSSLClientSocket(transport.Pass(),
1852 test_server.host_port_pair(),
1853 ssl_config));
1855 rv = callback.GetResult(sock->Connect(callback.callback()));
1856 EXPECT_EQ(OK, rv);
1857 EXPECT_TRUE(sock->IsConnected());
1859 raw_transport->SetNextReadError(0);
1860 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1861 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1862 EXPECT_EQ(0, rv);
1865 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1866 // underlying socket is cleanly closed asynchronously.
1867 // This is a regression test for https://crbug.com/422246
1868 TEST_F(SSLClientSocketTest, Read_WithAsyncZeroReturn) {
1869 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1870 SpawnedTestServer::kLocalhost,
1871 base::FilePath());
1872 ASSERT_TRUE(test_server.Start());
1874 AddressList addr;
1875 ASSERT_TRUE(test_server.GetAddressList(&addr));
1877 TestCompletionCallback callback;
1878 scoped_ptr<StreamSocket> real_transport(
1879 new TCPClientSocket(addr, NULL, NetLog::Source()));
1880 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1881 new SynchronousErrorStreamSocket(real_transport.Pass()));
1882 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1883 scoped_ptr<FakeBlockingStreamSocket> transport(
1884 new FakeBlockingStreamSocket(error_socket.Pass()));
1885 FakeBlockingStreamSocket* raw_transport = transport.get();
1886 int rv = callback.GetResult(transport->Connect(callback.callback()));
1887 EXPECT_EQ(OK, rv);
1889 // Disable TLS False Start to ensure the handshake has completed.
1890 SSLConfig ssl_config;
1891 ssl_config.false_start_enabled = false;
1893 scoped_ptr<SSLClientSocket> sock(
1894 CreateSSLClientSocket(transport.Pass(),
1895 test_server.host_port_pair(),
1896 ssl_config));
1898 rv = callback.GetResult(sock->Connect(callback.callback()));
1899 EXPECT_EQ(OK, rv);
1900 EXPECT_TRUE(sock->IsConnected());
1902 raw_error_socket->SetNextReadError(0);
1903 raw_transport->BlockReadResult();
1904 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1905 rv = sock->Read(buf.get(), 4096, callback.callback());
1906 EXPECT_EQ(ERR_IO_PENDING, rv);
1908 raw_transport->UnblockReadResult();
1909 rv = callback.GetResult(rv);
1910 EXPECT_EQ(0, rv);
1913 // Tests that fatal alerts from the peer are processed. This is a regression
1914 // test for https://crbug.com/466303.
1915 TEST_F(SSLClientSocketTest, Read_WithFatalAlert) {
1916 SpawnedTestServer::SSLOptions ssl_options;
1917 ssl_options.alert_after_handshake = true;
1918 ASSERT_TRUE(StartTestServer(ssl_options));
1920 SSLConfig ssl_config;
1921 TestCompletionCallback callback;
1922 scoped_ptr<StreamSocket> transport(
1923 new TCPClientSocket(addr(), &log_, NetLog::Source()));
1924 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
1925 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1926 transport.Pass(), test_server()->host_port_pair(), ssl_config));
1927 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
1929 // Receive the fatal alert.
1930 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1931 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(sock->Read(
1932 buf.get(), 4096, callback.callback())));
1935 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1936 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1937 SpawnedTestServer::kLocalhost,
1938 base::FilePath());
1939 ASSERT_TRUE(test_server.Start());
1941 AddressList addr;
1942 ASSERT_TRUE(test_server.GetAddressList(&addr));
1944 TestCompletionCallback callback;
1945 scoped_ptr<StreamSocket> transport(
1946 new TCPClientSocket(addr, NULL, NetLog::Source()));
1947 int rv = transport->Connect(callback.callback());
1948 if (rv == ERR_IO_PENDING)
1949 rv = callback.WaitForResult();
1950 EXPECT_EQ(OK, rv);
1952 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1953 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1955 rv = sock->Connect(callback.callback());
1956 if (rv == ERR_IO_PENDING)
1957 rv = callback.WaitForResult();
1958 EXPECT_EQ(OK, rv);
1960 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1961 scoped_refptr<IOBuffer> request_buffer(
1962 new IOBuffer(arraysize(request_text) - 1));
1963 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1965 rv = sock->Write(
1966 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1967 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1969 if (rv == ERR_IO_PENDING)
1970 rv = callback.WaitForResult();
1971 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1973 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1974 for (;;) {
1975 rv = sock->Read(buf.get(), 1, callback.callback());
1976 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1978 if (rv == ERR_IO_PENDING)
1979 rv = callback.WaitForResult();
1981 EXPECT_GE(rv, 0);
1982 if (rv <= 0)
1983 break;
1987 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1988 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1989 SpawnedTestServer::kLocalhost,
1990 base::FilePath());
1991 ASSERT_TRUE(test_server.Start());
1993 AddressList addr;
1994 ASSERT_TRUE(test_server.GetAddressList(&addr));
1996 TestCompletionCallback callback;
1998 scoped_ptr<StreamSocket> real_transport(
1999 new TCPClientSocket(addr, NULL, NetLog::Source()));
2000 scoped_ptr<ReadBufferingStreamSocket> transport(
2001 new ReadBufferingStreamSocket(real_transport.Pass()));
2002 ReadBufferingStreamSocket* raw_transport = transport.get();
2003 int rv = callback.GetResult(transport->Connect(callback.callback()));
2004 ASSERT_EQ(OK, rv);
2006 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2007 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2009 rv = callback.GetResult(sock->Connect(callback.callback()));
2010 ASSERT_EQ(OK, rv);
2011 ASSERT_TRUE(sock->IsConnected());
2013 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
2014 scoped_refptr<IOBuffer> request_buffer(
2015 new IOBuffer(arraysize(request_text) - 1));
2016 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2018 rv = callback.GetResult(sock->Write(
2019 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
2020 ASSERT_GT(rv, 0);
2021 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2023 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2024 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2025 // of SSL data is buffered first. The 15K of buffered data is made up of
2026 // many smaller SSL records (the TestServer writes along 1350 byte
2027 // plaintext boundaries), although there may also be a few records that are
2028 // smaller or larger, due to timing and SSL False Start.
2029 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2030 // the SSLClientSocket implementation, and larger than the minimum amount
2031 // of ciphertext necessary to contain the 8K of plaintext requested below.
2032 raw_transport->SetBufferSize(15000);
2034 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
2035 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
2036 ASSERT_EQ(rv, 8192);
2039 TEST_F(SSLClientSocketTest, Read_Interrupted) {
2040 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2041 SpawnedTestServer::kLocalhost,
2042 base::FilePath());
2043 ASSERT_TRUE(test_server.Start());
2045 AddressList addr;
2046 ASSERT_TRUE(test_server.GetAddressList(&addr));
2048 TestCompletionCallback callback;
2049 scoped_ptr<StreamSocket> transport(
2050 new TCPClientSocket(addr, NULL, NetLog::Source()));
2051 int rv = transport->Connect(callback.callback());
2052 if (rv == ERR_IO_PENDING)
2053 rv = callback.WaitForResult();
2054 EXPECT_EQ(OK, rv);
2056 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2057 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2059 rv = sock->Connect(callback.callback());
2060 if (rv == ERR_IO_PENDING)
2061 rv = callback.WaitForResult();
2062 EXPECT_EQ(OK, rv);
2064 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2065 scoped_refptr<IOBuffer> request_buffer(
2066 new IOBuffer(arraysize(request_text) - 1));
2067 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2069 rv = sock->Write(
2070 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2071 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2073 if (rv == ERR_IO_PENDING)
2074 rv = callback.WaitForResult();
2075 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2077 // Do a partial read and then exit. This test should not crash!
2078 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
2079 rv = sock->Read(buf.get(), 512, callback.callback());
2080 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
2082 if (rv == ERR_IO_PENDING)
2083 rv = callback.WaitForResult();
2085 EXPECT_GT(rv, 0);
2088 TEST_F(SSLClientSocketTest, Read_FullLogging) {
2089 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2090 SpawnedTestServer::kLocalhost,
2091 base::FilePath());
2092 ASSERT_TRUE(test_server.Start());
2094 AddressList addr;
2095 ASSERT_TRUE(test_server.GetAddressList(&addr));
2097 TestCompletionCallback callback;
2098 TestNetLog log;
2099 log.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes());
2100 scoped_ptr<StreamSocket> transport(
2101 new TCPClientSocket(addr, &log, NetLog::Source()));
2102 int rv = transport->Connect(callback.callback());
2103 if (rv == ERR_IO_PENDING)
2104 rv = callback.WaitForResult();
2105 EXPECT_EQ(OK, rv);
2107 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2108 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2110 rv = sock->Connect(callback.callback());
2111 if (rv == ERR_IO_PENDING)
2112 rv = callback.WaitForResult();
2113 EXPECT_EQ(OK, rv);
2114 EXPECT_TRUE(sock->IsConnected());
2116 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2117 scoped_refptr<IOBuffer> request_buffer(
2118 new IOBuffer(arraysize(request_text) - 1));
2119 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2121 rv = sock->Write(
2122 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2123 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2125 if (rv == ERR_IO_PENDING)
2126 rv = callback.WaitForResult();
2127 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2129 TestNetLogEntry::List entries;
2130 log.GetEntries(&entries);
2131 size_t last_index = ExpectLogContainsSomewhereAfter(
2132 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2134 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2135 for (;;) {
2136 rv = sock->Read(buf.get(), 4096, callback.callback());
2137 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2139 if (rv == ERR_IO_PENDING)
2140 rv = callback.WaitForResult();
2142 EXPECT_GE(rv, 0);
2143 if (rv <= 0)
2144 break;
2146 log.GetEntries(&entries);
2147 last_index =
2148 ExpectLogContainsSomewhereAfter(entries,
2149 last_index + 1,
2150 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2151 NetLog::PHASE_NONE);
2155 // Regression test for http://crbug.com/42538
2156 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2157 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2158 SpawnedTestServer::kLocalhost,
2159 base::FilePath());
2160 ASSERT_TRUE(test_server.Start());
2162 AddressList addr;
2163 TestCompletionCallback callback;
2165 static const unsigned char application_data[] = {
2166 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2167 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2168 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2169 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2170 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2171 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2172 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2173 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2174 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2175 0x0a};
2177 // All reads and writes complete synchronously (async=false).
2178 MockRead data_reads[] = {
2179 MockRead(SYNCHRONOUS,
2180 reinterpret_cast<const char*>(application_data),
2181 arraysize(application_data)),
2182 MockRead(SYNCHRONOUS, OK), };
2184 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2186 scoped_ptr<StreamSocket> transport(
2187 new MockTCPClientSocket(addr, NULL, &data));
2188 int rv = transport->Connect(callback.callback());
2189 if (rv == ERR_IO_PENDING)
2190 rv = callback.WaitForResult();
2191 EXPECT_EQ(OK, rv);
2193 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2194 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2196 rv = sock->Connect(callback.callback());
2197 if (rv == ERR_IO_PENDING)
2198 rv = callback.WaitForResult();
2199 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2202 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2203 // Rather than exhaustively disabling every AES_128_CBC ciphersuite defined at
2204 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2205 // disabling those cipher suites that the test server actually implements.
2206 const uint16 kCiphersToDisable[] = {
2207 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2208 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2209 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2212 SpawnedTestServer::SSLOptions ssl_options;
2213 // Enable only AES_128_CBC on the test server.
2214 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
2215 SpawnedTestServer test_server(
2216 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2217 ASSERT_TRUE(test_server.Start());
2219 AddressList addr;
2220 ASSERT_TRUE(test_server.GetAddressList(&addr));
2222 TestCompletionCallback callback;
2223 TestNetLog log;
2224 scoped_ptr<StreamSocket> transport(
2225 new TCPClientSocket(addr, &log, NetLog::Source()));
2226 int rv = transport->Connect(callback.callback());
2227 if (rv == ERR_IO_PENDING)
2228 rv = callback.WaitForResult();
2229 EXPECT_EQ(OK, rv);
2231 SSLConfig ssl_config;
2232 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2233 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2235 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2236 transport.Pass(), test_server.host_port_pair(), ssl_config));
2238 EXPECT_FALSE(sock->IsConnected());
2240 rv = sock->Connect(callback.callback());
2241 TestNetLogEntry::List entries;
2242 log.GetEntries(&entries);
2243 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2245 if (rv == ERR_IO_PENDING)
2246 rv = callback.WaitForResult();
2247 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, rv);
2248 // The exact ordering depends no whether an extra read is issued. Just check
2249 // the error is somewhere in the log.
2250 log.GetEntries(&entries);
2251 ExpectLogContainsSomewhere(
2252 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2254 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2255 // the socket when it encounters an error, whereas other implementations
2256 // leave it connected.
2257 // Because this an error that the test server is mutually aware of, as opposed
2258 // to being an error such as a certificate name mismatch, which is
2259 // client-only, the exact index of the SSL connect end depends on how
2260 // quickly the test server closes the underlying socket. If the test server
2261 // closes before the IO message loop pumps messages, there may be a 0-byte
2262 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2263 // result, the SSL connect end event will be the second-to-last entry,
2264 // rather than the last entry.
2265 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT) ||
2266 LogContainsEndEvent(entries, -2, NetLog::TYPE_SSL_CONNECT));
2269 // When creating an SSLClientSocket, it is allowed to pass in a
2270 // ClientSocketHandle that is not obtained from a client socket pool.
2271 // Here we verify that such a simple ClientSocketHandle, not associated with any
2272 // client socket pool, can be destroyed safely.
2273 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2274 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2275 SpawnedTestServer::kLocalhost,
2276 base::FilePath());
2277 ASSERT_TRUE(test_server.Start());
2279 AddressList addr;
2280 ASSERT_TRUE(test_server.GetAddressList(&addr));
2282 TestCompletionCallback callback;
2283 scoped_ptr<StreamSocket> transport(
2284 new TCPClientSocket(addr, NULL, NetLog::Source()));
2285 int rv = transport->Connect(callback.callback());
2286 if (rv == ERR_IO_PENDING)
2287 rv = callback.WaitForResult();
2288 EXPECT_EQ(OK, rv);
2290 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2291 socket_handle->SetSocket(transport.Pass());
2293 scoped_ptr<SSLClientSocket> sock(socket_factory_->CreateSSLClientSocket(
2294 socket_handle.Pass(), test_server.host_port_pair(), SSLConfig(),
2295 context_));
2297 EXPECT_FALSE(sock->IsConnected());
2298 rv = sock->Connect(callback.callback());
2299 if (rv == ERR_IO_PENDING)
2300 rv = callback.WaitForResult();
2301 EXPECT_EQ(OK, rv);
2304 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2305 // code and different keying label results in different keying material.
2306 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2307 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2308 SpawnedTestServer::kLocalhost,
2309 base::FilePath());
2310 ASSERT_TRUE(test_server.Start());
2312 AddressList addr;
2313 ASSERT_TRUE(test_server.GetAddressList(&addr));
2315 TestCompletionCallback callback;
2317 scoped_ptr<StreamSocket> transport(
2318 new TCPClientSocket(addr, NULL, NetLog::Source()));
2319 int rv = transport->Connect(callback.callback());
2320 if (rv == ERR_IO_PENDING)
2321 rv = callback.WaitForResult();
2322 EXPECT_EQ(OK, rv);
2324 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2325 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2327 rv = sock->Connect(callback.callback());
2328 if (rv == ERR_IO_PENDING)
2329 rv = callback.WaitForResult();
2330 EXPECT_EQ(OK, rv);
2331 EXPECT_TRUE(sock->IsConnected());
2333 const int kKeyingMaterialSize = 32;
2334 const char kKeyingLabel1[] = "client-socket-test-1";
2335 const char kKeyingContext1[] = "";
2336 unsigned char client_out1[kKeyingMaterialSize];
2337 memset(client_out1, 0, sizeof(client_out1));
2338 rv = sock->ExportKeyingMaterial(kKeyingLabel1, false, kKeyingContext1,
2339 client_out1, sizeof(client_out1));
2340 EXPECT_EQ(rv, OK);
2342 const char kKeyingLabel2[] = "client-socket-test-2";
2343 unsigned char client_out2[kKeyingMaterialSize];
2344 memset(client_out2, 0, sizeof(client_out2));
2345 rv = sock->ExportKeyingMaterial(kKeyingLabel2, false, kKeyingContext1,
2346 client_out2, sizeof(client_out2));
2347 EXPECT_EQ(rv, OK);
2348 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2350 const char kKeyingContext2[] = "context";
2351 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext2,
2352 client_out2, sizeof(client_out2));
2353 EXPECT_EQ(rv, OK);
2354 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2356 // Using an empty context should give different key material from not using a
2357 // context at all.
2358 memset(client_out2, 0, sizeof(client_out2));
2359 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext1,
2360 client_out2, sizeof(client_out2));
2361 EXPECT_EQ(rv, OK);
2362 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2365 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2366 // explicit NSS initialization.
2367 TEST(SSLClientSocket, ClearSessionCache) {
2368 SSLClientSocket::ClearSessionCache();
2371 TEST(SSLClientSocket, SerializeNextProtos) {
2372 NextProtoVector next_protos;
2373 next_protos.push_back(kProtoHTTP11);
2374 next_protos.push_back(kProtoSPDY31);
2375 static std::vector<uint8_t> serialized =
2376 SSLClientSocket::SerializeNextProtos(next_protos, true);
2377 ASSERT_EQ(18u, serialized.size());
2378 EXPECT_EQ(8, serialized[0]); // length("http/1.1")
2379 EXPECT_EQ('h', serialized[1]);
2380 EXPECT_EQ('t', serialized[2]);
2381 EXPECT_EQ('t', serialized[3]);
2382 EXPECT_EQ('p', serialized[4]);
2383 EXPECT_EQ('/', serialized[5]);
2384 EXPECT_EQ('1', serialized[6]);
2385 EXPECT_EQ('.', serialized[7]);
2386 EXPECT_EQ('1', serialized[8]);
2387 EXPECT_EQ(8, serialized[9]); // length("spdy/3.1")
2388 EXPECT_EQ('s', serialized[10]);
2389 EXPECT_EQ('p', serialized[11]);
2390 EXPECT_EQ('d', serialized[12]);
2391 EXPECT_EQ('y', serialized[13]);
2392 EXPECT_EQ('/', serialized[14]);
2393 EXPECT_EQ('3', serialized[15]);
2394 EXPECT_EQ('.', serialized[16]);
2395 EXPECT_EQ('1', serialized[17]);
2398 // Test that the server certificates are properly retrieved from the underlying
2399 // SSL stack.
2400 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2401 // The connection does not have to be successful.
2402 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2404 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2405 // This makes the server present redundant-server-chain.pem, which contains
2406 // intermediate certificates.
2407 SpawnedTestServer::SSLOptions ssl_options(
2408 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2409 SpawnedTestServer test_server(
2410 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2411 ASSERT_TRUE(test_server.Start());
2413 AddressList addr;
2414 ASSERT_TRUE(test_server.GetAddressList(&addr));
2416 TestCompletionCallback callback;
2417 scoped_ptr<StreamSocket> transport(
2418 new TCPClientSocket(addr, NULL, NetLog::Source()));
2419 int rv = transport->Connect(callback.callback());
2420 rv = callback.GetResult(rv);
2421 EXPECT_EQ(OK, rv);
2423 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2424 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2425 EXPECT_FALSE(sock->IsConnected());
2426 rv = sock->Connect(callback.callback());
2427 rv = callback.GetResult(rv);
2429 EXPECT_EQ(ERR_CERT_INVALID, rv);
2430 EXPECT_TRUE(sock->IsConnected());
2432 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2433 // certs from redundant-server-chain.pem.
2434 CertificateList server_certs =
2435 CreateCertificateListFromFile(GetTestCertsDirectory(),
2436 "redundant-server-chain.pem",
2437 X509Certificate::FORMAT_AUTO);
2439 // Get the server certificate as received client side.
2440 SSLInfo ssl_info;
2441 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2442 scoped_refptr<X509Certificate> server_certificate = ssl_info.unverified_cert;
2444 // Get the intermediates as received client side.
2445 const X509Certificate::OSCertHandles& server_intermediates =
2446 server_certificate->GetIntermediateCertificates();
2448 // Check that the unverified server certificate chain is properly retrieved
2449 // from the underlying ssl stack.
2450 ASSERT_EQ(4U, server_certs.size());
2452 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2453 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2455 ASSERT_EQ(3U, server_intermediates.size());
2457 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2458 server_certs[1]->os_cert_handle()));
2459 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2460 server_certs[2]->os_cert_handle()));
2461 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2462 server_certs[3]->os_cert_handle()));
2464 sock->Disconnect();
2465 EXPECT_FALSE(sock->IsConnected());
2468 // This tests that SSLInfo contains a properly re-constructed certificate
2469 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2470 // verified, not the chain as served by the server. (They may be different.)
2472 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2473 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2474 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2475 // a self-signed root. Such a situation can occur when a new root (C2) is
2476 // cross-certified by an old root (D) and has two different versions of its
2477 // floating around. Servers may supply C2 as an intermediate, but the
2478 // SSLClientSocket should return the chain that was verified, from
2479 // verify_result, instead.
2480 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2481 // By default, cause the CertVerifier to treat all certificates as
2482 // expired.
2483 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2485 CertificateList unverified_certs = CreateCertificateListFromFile(
2486 GetTestCertsDirectory(), "redundant-server-chain.pem",
2487 X509Certificate::FORMAT_AUTO);
2488 ASSERT_EQ(4u, unverified_certs.size());
2490 // We will expect SSLInfo to ultimately contain this chain.
2491 CertificateList certs =
2492 CreateCertificateListFromFile(GetTestCertsDirectory(),
2493 "redundant-validated-chain.pem",
2494 X509Certificate::FORMAT_AUTO);
2495 ASSERT_EQ(3U, certs.size());
2497 X509Certificate::OSCertHandles temp_intermediates;
2498 temp_intermediates.push_back(certs[1]->os_cert_handle());
2499 temp_intermediates.push_back(certs[2]->os_cert_handle());
2501 CertVerifyResult verify_result;
2502 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2503 certs[0]->os_cert_handle(), temp_intermediates);
2505 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2506 // rather than A->B->C.
2507 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2509 // Load and install the root for the validated chain.
2510 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2511 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2512 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2513 ScopedTestRoot scoped_root(root_cert.get());
2515 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2516 SpawnedTestServer::SSLOptions ssl_options(
2517 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2518 SpawnedTestServer test_server(
2519 SpawnedTestServer::TYPE_HTTPS,
2520 ssl_options,
2521 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2522 ASSERT_TRUE(test_server.Start());
2524 AddressList addr;
2525 ASSERT_TRUE(test_server.GetAddressList(&addr));
2527 TestCompletionCallback callback;
2528 TestNetLog log;
2529 scoped_ptr<StreamSocket> transport(
2530 new TCPClientSocket(addr, &log, NetLog::Source()));
2531 int rv = transport->Connect(callback.callback());
2532 if (rv == ERR_IO_PENDING)
2533 rv = callback.WaitForResult();
2534 EXPECT_EQ(OK, rv);
2536 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2537 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2538 EXPECT_FALSE(sock->IsConnected());
2539 rv = sock->Connect(callback.callback());
2541 TestNetLogEntry::List entries;
2542 log.GetEntries(&entries);
2543 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2544 if (rv == ERR_IO_PENDING)
2545 rv = callback.WaitForResult();
2547 EXPECT_EQ(OK, rv);
2548 EXPECT_TRUE(sock->IsConnected());
2549 log.GetEntries(&entries);
2550 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
2552 SSLInfo ssl_info;
2553 sock->GetSSLInfo(&ssl_info);
2555 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2556 // -> C2.
2557 const X509Certificate::OSCertHandles& intermediates =
2558 ssl_info.cert->GetIntermediateCertificates();
2559 ASSERT_EQ(2U, intermediates.size());
2560 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2561 certs[0]->os_cert_handle()));
2562 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2563 certs[1]->os_cert_handle()));
2564 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2565 certs[2]->os_cert_handle()));
2567 // Verify that SSLInfo also contains the chain as received from the server.
2568 const X509Certificate::OSCertHandles& served_intermediates =
2569 ssl_info.unverified_cert->GetIntermediateCertificates();
2570 ASSERT_EQ(3U, served_intermediates.size());
2571 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2572 ssl_info.cert->os_cert_handle(), unverified_certs[0]->os_cert_handle()));
2573 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2574 served_intermediates[0], unverified_certs[1]->os_cert_handle()));
2575 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2576 served_intermediates[1], unverified_certs[2]->os_cert_handle()));
2577 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2578 served_intermediates[2], unverified_certs[3]->os_cert_handle()));
2580 sock->Disconnect();
2581 EXPECT_FALSE(sock->IsConnected());
2584 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2585 SpawnedTestServer::SSLOptions ssl_options;
2586 ssl_options.request_client_certificate = true;
2587 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2588 ASSERT_TRUE(request_info.get());
2589 EXPECT_EQ(0u, request_info->cert_authorities.size());
2592 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2593 const base::FilePath::CharType kThawteFile[] =
2594 FILE_PATH_LITERAL("thawte.single.pem");
2595 const unsigned char kThawteDN[] = {
2596 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2597 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2598 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2599 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2600 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2601 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2602 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2603 const size_t kThawteLen = sizeof(kThawteDN);
2605 const base::FilePath::CharType kDiginotarFile[] =
2606 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2607 const unsigned char kDiginotarDN[] = {
2608 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2609 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2610 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2611 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2612 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2613 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2614 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2615 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2616 0x6c};
2617 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2619 SpawnedTestServer::SSLOptions ssl_options;
2620 ssl_options.request_client_certificate = true;
2621 ssl_options.client_authorities.push_back(
2622 GetTestClientCertsDirectory().Append(kThawteFile));
2623 ssl_options.client_authorities.push_back(
2624 GetTestClientCertsDirectory().Append(kDiginotarFile));
2625 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2626 ASSERT_TRUE(request_info.get());
2627 ASSERT_EQ(2u, request_info->cert_authorities.size());
2628 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2629 request_info->cert_authorities[0]);
2630 EXPECT_EQ(
2631 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2632 request_info->cert_authorities[1]);
2635 // cert_key_types is currently only populated on OpenSSL.
2636 #if defined(USE_OPENSSL)
2637 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2638 SpawnedTestServer::SSLOptions ssl_options;
2639 ssl_options.request_client_certificate = true;
2640 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2641 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2642 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2643 ASSERT_TRUE(request_info.get());
2644 ASSERT_EQ(2u, request_info->cert_key_types.size());
2645 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2646 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2648 #endif // defined(USE_OPENSSL)
2650 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2651 SpawnedTestServer::SSLOptions ssl_options;
2652 ssl_options.signed_cert_timestamps_tls_ext = "test";
2654 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2655 ssl_options,
2656 base::FilePath());
2657 ASSERT_TRUE(test_server.Start());
2659 AddressList addr;
2660 ASSERT_TRUE(test_server.GetAddressList(&addr));
2662 TestCompletionCallback callback;
2663 scoped_ptr<StreamSocket> transport(
2664 new TCPClientSocket(addr, &log_, NetLog::Source()));
2665 int rv = callback.GetResult(transport->Connect(callback.callback()));
2666 EXPECT_EQ(OK, rv);
2668 SSLConfig ssl_config;
2669 ssl_config.signed_cert_timestamps_enabled = true;
2671 MockCTVerifier ct_verifier;
2672 SetCTVerifier(&ct_verifier);
2674 // Check that the SCT list is extracted as expected.
2675 EXPECT_CALL(ct_verifier, Verify(_, "", "test", _, _)).WillRepeatedly(
2676 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2678 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2679 transport.Pass(), test_server.host_port_pair(), ssl_config));
2680 rv = callback.GetResult(sock->Connect(callback.callback()));
2681 EXPECT_EQ(OK, rv);
2683 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2686 namespace {
2688 bool IsValidOCSPResponse(const base::StringPiece& input) {
2689 base::StringPiece ocsp_response = input;
2690 base::StringPiece sequence, response_status, response_bytes;
2691 return asn1::GetElement(&ocsp_response, asn1::kSEQUENCE, &sequence) &&
2692 ocsp_response.empty() &&
2693 asn1::GetElement(&sequence, asn1::kENUMERATED, &response_status) &&
2694 asn1::GetElement(&sequence,
2695 asn1::kContextSpecific | asn1::kConstructed | 0,
2696 &response_status) &&
2697 sequence.empty();
2700 } // namespace
2702 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2703 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2704 SpawnedTestServer::SSLOptions ssl_options;
2705 ssl_options.staple_ocsp_response = true;
2706 // The test server currently only knows how to generate OCSP responses
2707 // for a freshly minted certificate.
2708 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2710 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2711 ssl_options,
2712 base::FilePath());
2713 ASSERT_TRUE(test_server.Start());
2715 AddressList addr;
2716 ASSERT_TRUE(test_server.GetAddressList(&addr));
2718 TestCompletionCallback callback;
2719 scoped_ptr<StreamSocket> transport(
2720 new TCPClientSocket(addr, &log_, NetLog::Source()));
2721 int rv = callback.GetResult(transport->Connect(callback.callback()));
2722 EXPECT_EQ(OK, rv);
2724 SSLConfig ssl_config;
2725 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2726 // Certificate Transparency verification regardless of whether the platform
2727 // is able to process the OCSP status itself.
2728 ssl_config.signed_cert_timestamps_enabled = true;
2730 MockCTVerifier ct_verifier;
2731 SetCTVerifier(&ct_verifier);
2733 // Check that the OCSP response is extracted and well-formed. It should be the
2734 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2735 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2736 // particular, it should not include the overall two-byte length prefix from
2737 // TLS.
2738 EXPECT_CALL(ct_verifier,
2739 Verify(_, Truly(IsValidOCSPResponse), "", _, _)).WillRepeatedly(
2740 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2742 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2743 transport.Pass(), test_server.host_port_pair(), ssl_config));
2744 rv = callback.GetResult(sock->Connect(callback.callback()));
2745 EXPECT_EQ(OK, rv);
2747 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2750 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2751 SpawnedTestServer::SSLOptions ssl_options;
2752 ssl_options.signed_cert_timestamps_tls_ext = "test";
2754 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2755 ssl_options,
2756 base::FilePath());
2757 ASSERT_TRUE(test_server.Start());
2759 AddressList addr;
2760 ASSERT_TRUE(test_server.GetAddressList(&addr));
2762 TestCompletionCallback callback;
2763 scoped_ptr<StreamSocket> transport(
2764 new TCPClientSocket(addr, &log_, NetLog::Source()));
2765 int rv = callback.GetResult(transport->Connect(callback.callback()));
2766 EXPECT_EQ(OK, rv);
2768 SSLConfig ssl_config;
2769 ssl_config.signed_cert_timestamps_enabled = false;
2771 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2772 transport.Pass(), test_server.host_port_pair(), ssl_config));
2773 rv = callback.GetResult(sock->Connect(callback.callback()));
2774 EXPECT_EQ(OK, rv);
2776 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2779 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2780 TEST_F(SSLClientSocketTest, ReuseStates) {
2781 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2782 SpawnedTestServer::kLocalhost,
2783 base::FilePath());
2784 ASSERT_TRUE(test_server.Start());
2786 AddressList addr;
2787 ASSERT_TRUE(test_server.GetAddressList(&addr));
2789 TestCompletionCallback callback;
2790 scoped_ptr<StreamSocket> transport(
2791 new TCPClientSocket(addr, NULL, NetLog::Source()));
2792 int rv = transport->Connect(callback.callback());
2793 if (rv == ERR_IO_PENDING)
2794 rv = callback.WaitForResult();
2795 EXPECT_EQ(OK, rv);
2797 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2798 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2800 rv = sock->Connect(callback.callback());
2801 if (rv == ERR_IO_PENDING)
2802 rv = callback.WaitForResult();
2803 EXPECT_EQ(OK, rv);
2805 // The socket was just connected. It should be idle because it is speaking
2806 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2807 // returns false.
2808 EXPECT_TRUE(sock->IsConnected());
2809 EXPECT_TRUE(sock->IsConnectedAndIdle());
2810 EXPECT_FALSE(sock->WasEverUsed());
2812 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2813 const size_t kRequestLen = arraysize(kRequestText) - 1;
2814 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2815 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2817 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2818 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2820 if (rv == ERR_IO_PENDING)
2821 rv = callback.WaitForResult();
2822 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2824 // The socket has now been used.
2825 EXPECT_TRUE(sock->WasEverUsed());
2827 // TODO(davidben): Read one byte to ensure the test server has responded and
2828 // then assert IsConnectedAndIdle is false. This currently doesn't work
2829 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2830 // SSL implementation's internal buffers. Either call PR_Available and
2831 // SSL_pending, although the former isn't actually implemented or perhaps
2832 // attempt to read one byte extra.
2835 // Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
2836 // been flushed completely out of SSLClientSocket's internal buffers. This is a
2837 // regression test for https://crbug.com/466147.
2838 TEST_F(SSLClientSocketTest, ReusableAfterWrite) {
2839 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2840 SpawnedTestServer::kLocalhost,
2841 base::FilePath());
2842 ASSERT_TRUE(test_server.Start());
2844 AddressList addr;
2845 ASSERT_TRUE(test_server.GetAddressList(&addr));
2847 TestCompletionCallback callback;
2848 scoped_ptr<StreamSocket> real_transport(
2849 new TCPClientSocket(addr, NULL, NetLog::Source()));
2850 scoped_ptr<FakeBlockingStreamSocket> transport(
2851 new FakeBlockingStreamSocket(real_transport.Pass()));
2852 FakeBlockingStreamSocket* raw_transport = transport.get();
2853 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2855 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2856 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2857 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2859 // Block any application data from reaching the network.
2860 raw_transport->BlockWrite();
2862 // Write a partial HTTP request.
2863 const char kRequestText[] = "GET / HTTP/1.0";
2864 const size_t kRequestLen = arraysize(kRequestText) - 1;
2865 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2866 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2868 // Although transport writes are blocked, both SSLClientSocketOpenSSL and
2869 // SSLClientSocketNSS complete the outer Write operation.
2870 EXPECT_EQ(static_cast<int>(kRequestLen),
2871 callback.GetResult(sock->Write(request_buffer.get(), kRequestLen,
2872 callback.callback())));
2874 // The Write operation is complete, so the socket should be treated as
2875 // reusable, in case the server returns an HTTP response before completely
2876 // consuming the request body. In this case, we assume the server will
2877 // properly drain the request body before trying to read the next request.
2878 EXPECT_TRUE(sock->IsConnectedAndIdle());
2881 // Tests that basic session resumption works.
2882 TEST_F(SSLClientSocketTest, SessionResumption) {
2883 SpawnedTestServer::SSLOptions ssl_options;
2884 ASSERT_TRUE(StartTestServer(ssl_options));
2886 // First, perform a full handshake.
2887 SSLConfig ssl_config;
2888 TestCompletionCallback callback;
2889 scoped_ptr<StreamSocket> transport(
2890 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2891 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2892 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2893 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2894 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2895 SSLInfo ssl_info;
2896 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2897 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2899 // The next connection should resume.
2900 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2901 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2902 sock = CreateSSLClientSocket(transport.Pass(),
2903 test_server()->host_port_pair(), ssl_config);
2904 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2905 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2906 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2908 // Using a different HostPortPair uses a different session cache key.
2909 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2910 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2911 sock = CreateSSLClientSocket(transport.Pass(),
2912 HostPortPair("example.com", 443), ssl_config);
2913 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2914 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2915 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2917 SSLClientSocket::ClearSessionCache();
2919 // After clearing the session cache, the next handshake doesn't resume.
2920 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2921 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2922 sock = CreateSSLClientSocket(transport.Pass(),
2923 test_server()->host_port_pair(), ssl_config);
2924 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2925 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2926 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2929 // Tests that connections with certificate errors do not add entries to the
2930 // session cache.
2931 TEST_F(SSLClientSocketTest, CertificateErrorNoResume) {
2932 SpawnedTestServer::SSLOptions ssl_options;
2933 ASSERT_TRUE(StartTestServer(ssl_options));
2935 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
2937 SSLConfig ssl_config;
2938 TestCompletionCallback callback;
2939 scoped_ptr<StreamSocket> transport(
2940 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2941 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2942 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2943 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2944 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID,
2945 callback.GetResult(sock->Connect(callback.callback())));
2947 cert_verifier_->set_default_result(OK);
2949 // The next connection should perform a full handshake.
2950 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2951 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2952 sock = CreateSSLClientSocket(transport.Pass(),
2953 test_server()->host_port_pair(), ssl_config);
2954 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2955 SSLInfo ssl_info;
2956 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2957 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2960 // Tests that session caches are sharded by max_version.
2961 TEST_F(SSLClientSocketTest, FallbackShardSessionCache) {
2962 SpawnedTestServer::SSLOptions ssl_options;
2963 ASSERT_TRUE(StartTestServer(ssl_options));
2965 // Prepare a normal and fallback SSL config.
2966 SSLConfig ssl_config;
2967 SSLConfig fallback_ssl_config;
2968 fallback_ssl_config.version_max = SSL_PROTOCOL_VERSION_TLS1;
2969 fallback_ssl_config.version_fallback_min = SSL_PROTOCOL_VERSION_TLS1;
2970 fallback_ssl_config.version_fallback = true;
2972 // Connect with a fallback config from the test server to add an entry to the
2973 // session cache.
2974 TestCompletionCallback callback;
2975 scoped_ptr<StreamSocket> transport(
2976 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2977 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2978 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2979 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config));
2980 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2981 SSLInfo ssl_info;
2982 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2983 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2984 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
2985 SSLConnectionStatusToVersion(ssl_info.connection_status));
2987 // A non-fallback connection needs a full handshake.
2988 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2989 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2990 sock = CreateSSLClientSocket(transport.Pass(),
2991 test_server()->host_port_pair(), ssl_config);
2992 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2993 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2994 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2995 // This does not check for equality because TLS 1.2 support is conditional on
2996 // system NSS features.
2997 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
2998 SSLConnectionStatusToVersion(ssl_info.connection_status));
3000 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
3001 // 1.2, the above test would not be sufficient to prove the session caches are
3002 // sharded. Implementations vary here, so, to avoid being sensitive to this,
3003 // attempt to resume with two more connections.
3005 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
3006 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3007 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3008 sock = CreateSSLClientSocket(transport.Pass(),
3009 test_server()->host_port_pair(), ssl_config);
3010 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3011 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3012 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3013 // This does not check for equality because TLS 1.2 support is conditional on
3014 // system NSS features.
3015 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
3016 SSLConnectionStatusToVersion(ssl_info.connection_status));
3018 // The fallback connection still resumes from its session cache. It cannot
3019 // offer the > TLS 1.0 session, so this must have been the session from the
3020 // first fallback connection.
3021 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3022 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3023 sock = CreateSSLClientSocket(
3024 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config);
3025 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3026 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3027 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3028 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
3029 SSLConnectionStatusToVersion(ssl_info.connection_status));
3032 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
3033 TEST_F(SSLClientSocketTest, DeprecatedRC4) {
3034 SpawnedTestServer::SSLOptions ssl_options;
3035 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
3036 ASSERT_TRUE(StartTestServer(ssl_options));
3038 // Normal handshakes with RC4 do not work.
3039 SSLConfig ssl_config;
3040 TestCompletionCallback callback;
3041 scoped_ptr<StreamSocket> transport(
3042 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3043 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3044 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
3045 transport.Pass(), test_server()->host_port_pair(), ssl_config));
3046 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH,
3047 callback.GetResult(sock->Connect(callback.callback())));
3049 // Enabling deprecated ciphers works fine.
3050 ssl_config.enable_deprecated_cipher_suites = true;
3051 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3052 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3053 sock = CreateSSLClientSocket(transport.Pass(),
3054 test_server()->host_port_pair(), ssl_config);
3055 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3058 // Tests that enabling deprecated ciphers shards the session cache.
3059 TEST_F(SSLClientSocketTest, DeprecatedShardSessionCache) {
3060 SpawnedTestServer::SSLOptions ssl_options;
3061 ASSERT_TRUE(StartTestServer(ssl_options));
3063 // Prepare a normal and deprecated SSL config.
3064 SSLConfig ssl_config;
3065 SSLConfig deprecated_ssl_config;
3066 deprecated_ssl_config.enable_deprecated_cipher_suites = true;
3068 // Connect with deprecated ciphers enabled to warm the session cache cache.
3069 TestCompletionCallback callback;
3070 scoped_ptr<StreamSocket> transport(
3071 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3072 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3073 scoped_ptr<SSLClientSocket> sock(
3074 CreateSSLClientSocket(transport.Pass(), test_server()->host_port_pair(),
3075 deprecated_ssl_config));
3076 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3077 SSLInfo ssl_info;
3078 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3079 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3081 // Test that re-connecting with deprecated ciphers enabled still resumes.
3082 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3083 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3084 sock = CreateSSLClientSocket(
3085 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3086 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3087 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3088 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3090 // However, a normal connection needs a full handshake.
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_FULL, ssl_info.handshake_type);
3099 // Clear the session cache for the inverse test.
3100 SSLClientSocket::ClearSessionCache();
3102 // Now make a normal connection to prime the session cache.
3103 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3104 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3105 sock = CreateSSLClientSocket(transport.Pass(),
3106 test_server()->host_port_pair(), ssl_config);
3107 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3108 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3109 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3111 // A normal connection should be able to resume.
3112 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3113 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3114 sock = CreateSSLClientSocket(transport.Pass(),
3115 test_server()->host_port_pair(), ssl_config);
3116 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3117 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3118 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3120 // However, enabling deprecated ciphers connects fresh.
3121 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3122 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3123 sock = CreateSSLClientSocket(
3124 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3125 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3126 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3127 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3130 TEST_F(SSLClientSocketTest, RequireECDHE) {
3131 // Run test server without ECDHE.
3132 SpawnedTestServer::SSLOptions ssl_options;
3133 ssl_options.key_exchanges = SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
3134 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, ssl_options,
3135 base::FilePath());
3136 ASSERT_TRUE(test_server.Start());
3138 AddressList addr;
3139 ASSERT_TRUE(test_server.GetAddressList(&addr));
3141 TestCompletionCallback callback;
3142 TestNetLog log;
3143 scoped_ptr<StreamSocket> transport(
3144 new TCPClientSocket(addr, &log, NetLog::Source()));
3145 int rv = transport->Connect(callback.callback());
3146 rv = callback.GetResult(rv);
3147 EXPECT_EQ(OK, rv);
3149 SSLConfig config;
3150 config.require_ecdhe = true;
3152 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
3153 transport.Pass(), test_server.host_port_pair(), config));
3155 rv = sock->Connect(callback.callback());
3156 rv = callback.GetResult(rv);
3158 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, rv);
3161 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
3162 if (!SupportsAESGCM()) {
3163 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3164 return;
3167 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
3168 SpawnedTestServer::SSLOptions server_options;
3169 server_options.key_exchanges =
3170 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3171 server_options.bulk_ciphers =
3172 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3173 server_options.enable_npn = true;
3174 SSLConfig client_config;
3175 client_config.next_protos.push_back(kProtoHTTP11);
3176 ASSERT_NO_FATAL_FAILURE(
3177 TestFalseStart(server_options, client_config, true));
3180 // Test that False Start is disabled without NPN.
3181 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
3182 if (!SupportsAESGCM()) {
3183 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3184 return;
3187 SpawnedTestServer::SSLOptions server_options;
3188 server_options.key_exchanges =
3189 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3190 server_options.bulk_ciphers =
3191 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3192 SSLConfig client_config;
3193 client_config.next_protos.clear();
3194 ASSERT_NO_FATAL_FAILURE(
3195 TestFalseStart(server_options, client_config, false));
3198 // Test that False Start is disabled with plain RSA ciphers.
3199 TEST_F(SSLClientSocketFalseStartTest, RSA) {
3200 if (!SupportsAESGCM()) {
3201 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3202 return;
3205 SpawnedTestServer::SSLOptions server_options;
3206 server_options.key_exchanges =
3207 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
3208 server_options.bulk_ciphers =
3209 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3210 server_options.enable_npn = true;
3211 SSLConfig client_config;
3212 client_config.next_protos.push_back(kProtoHTTP11);
3213 ASSERT_NO_FATAL_FAILURE(
3214 TestFalseStart(server_options, client_config, false));
3217 // Test that False Start is disabled with DHE_RSA ciphers.
3218 TEST_F(SSLClientSocketFalseStartTest, DHE_RSA) {
3219 if (!SupportsAESGCM()) {
3220 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3221 return;
3224 SpawnedTestServer::SSLOptions server_options;
3225 server_options.key_exchanges =
3226 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
3227 server_options.bulk_ciphers =
3228 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3229 server_options.enable_npn = true;
3230 SSLConfig client_config;
3231 client_config.next_protos.push_back(kProtoHTTP11);
3232 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3235 // Test that False Start is disabled without an AEAD.
3236 TEST_F(SSLClientSocketFalseStartTest, NoAEAD) {
3237 SpawnedTestServer::SSLOptions server_options;
3238 server_options.key_exchanges =
3239 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3240 server_options.bulk_ciphers =
3241 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
3242 server_options.enable_npn = true;
3243 SSLConfig client_config;
3244 client_config.next_protos.push_back(kProtoHTTP11);
3245 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3248 // Test that sessions are resumable after receiving the server Finished message.
3249 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
3250 if (!SupportsAESGCM()) {
3251 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3252 return;
3255 // Start a server.
3256 SpawnedTestServer::SSLOptions server_options;
3257 server_options.key_exchanges =
3258 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3259 server_options.bulk_ciphers =
3260 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3261 server_options.enable_npn = true;
3262 SSLConfig client_config;
3263 client_config.next_protos.push_back(kProtoHTTP11);
3265 // Let a full handshake complete with False Start.
3266 ASSERT_NO_FATAL_FAILURE(
3267 TestFalseStart(server_options, client_config, true));
3269 // Make a second connection.
3270 TestCompletionCallback callback;
3271 scoped_ptr<StreamSocket> transport2(
3272 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3273 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3274 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3275 transport2.Pass(), test_server()->host_port_pair(), client_config);
3276 ASSERT_TRUE(sock2.get());
3277 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3279 // It should resume the session.
3280 SSLInfo ssl_info;
3281 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3282 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3285 // Test that False Started sessions are not resumable before receiving the
3286 // server Finished message.
3287 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinished) {
3288 if (!SupportsAESGCM()) {
3289 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3290 return;
3293 // Start a server.
3294 SpawnedTestServer::SSLOptions server_options;
3295 server_options.key_exchanges =
3296 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3297 server_options.bulk_ciphers =
3298 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3299 server_options.enable_npn = true;
3300 ASSERT_TRUE(StartTestServer(server_options));
3302 SSLConfig client_config;
3303 client_config.next_protos.push_back(kProtoHTTP11);
3305 // Start a handshake up to the server Finished message.
3306 TestCompletionCallback callback;
3307 FakeBlockingStreamSocket* raw_transport1 = NULL;
3308 scoped_ptr<SSLClientSocket> sock1;
3309 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3310 client_config, &callback, &raw_transport1, &sock1));
3311 // Although raw_transport1 has the server Finished blocked, the handshake
3312 // still completes.
3313 EXPECT_EQ(OK, callback.WaitForResult());
3315 // Continue to block the client (|sock1|) from processing the Finished
3316 // message, but allow it to arrive on the socket. This ensures that, from the
3317 // server's point of view, it has completed the handshake and added the
3318 // session to its session cache.
3320 // The actual read on |sock1| will not complete until the Finished message is
3321 // processed; however, pump the underlying transport so that it is read from
3322 // the socket. NOTE: This may flakily pass if the server's final flight
3323 // doesn't come in one Read.
3324 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3325 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3326 EXPECT_EQ(ERR_IO_PENDING, rv);
3327 raw_transport1->WaitForReadResult();
3329 // Drop the old socket. This is needed because the Python test server can't
3330 // service two sockets in parallel.
3331 sock1.reset();
3333 // Start a second connection.
3334 scoped_ptr<StreamSocket> transport2(
3335 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3336 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3337 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3338 transport2.Pass(), test_server()->host_port_pair(), client_config);
3339 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3341 // No session resumption because the first connection never received a server
3342 // Finished message.
3343 SSLInfo ssl_info;
3344 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3345 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3348 // Test that False Started sessions are not resumable if the server Finished
3349 // message was bad.
3350 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBadFinished) {
3351 if (!SupportsAESGCM()) {
3352 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3353 return;
3356 // Start a server.
3357 SpawnedTestServer::SSLOptions server_options;
3358 server_options.key_exchanges =
3359 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3360 server_options.bulk_ciphers =
3361 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3362 server_options.enable_npn = true;
3363 ASSERT_TRUE(StartTestServer(server_options));
3365 SSLConfig client_config;
3366 client_config.next_protos.push_back(kProtoHTTP11);
3368 // Start a handshake up to the server Finished message.
3369 TestCompletionCallback callback;
3370 FakeBlockingStreamSocket* raw_transport1 = NULL;
3371 scoped_ptr<SSLClientSocket> sock1;
3372 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3373 client_config, &callback, &raw_transport1, &sock1));
3374 // Although raw_transport1 has the server Finished blocked, the handshake
3375 // still completes.
3376 EXPECT_EQ(OK, callback.WaitForResult());
3378 // Continue to block the client (|sock1|) from processing the Finished
3379 // message, but allow it to arrive on the socket. This ensures that, from the
3380 // server's point of view, it has completed the handshake and added the
3381 // session to its session cache.
3383 // The actual read on |sock1| will not complete until the Finished message is
3384 // processed; however, pump the underlying transport so that it is read from
3385 // the socket.
3386 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3387 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3388 EXPECT_EQ(ERR_IO_PENDING, rv);
3389 raw_transport1->WaitForReadResult();
3391 // The server's second leg, or part of it, is now received but not yet sent to
3392 // |sock1|. Before doing so, break the server's second leg.
3393 int bytes_read = raw_transport1->pending_read_result();
3394 ASSERT_LT(0, bytes_read);
3395 raw_transport1->pending_read_buf()->data()[bytes_read - 1]++;
3397 // Unblock the Finished message. |sock1->Read| should now fail.
3398 raw_transport1->UnblockReadResult();
3399 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(rv));
3401 // Drop the old socket. This is needed because the Python test server can't
3402 // service two sockets in parallel.
3403 sock1.reset();
3405 // Start a second connection.
3406 scoped_ptr<StreamSocket> transport2(
3407 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3408 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3409 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3410 transport2.Pass(), test_server()->host_port_pair(), client_config);
3411 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3413 // No session resumption because the first connection never received a server
3414 // Finished message.
3415 SSLInfo ssl_info;
3416 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3417 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3420 // Connect to a server using channel id. It should allow the connection.
3421 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
3422 SpawnedTestServer::SSLOptions ssl_options;
3424 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3426 EnableChannelID();
3427 SSLConfig ssl_config;
3428 ssl_config.channel_id_enabled = true;
3430 int rv;
3431 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3433 EXPECT_EQ(OK, rv);
3434 EXPECT_TRUE(sock_->IsConnected());
3435 SSLInfo ssl_info;
3436 ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
3437 EXPECT_TRUE(ssl_info.channel_id_sent);
3439 sock_->Disconnect();
3440 EXPECT_FALSE(sock_->IsConnected());
3443 // Connect to a server using Channel ID but failing to look up the Channel
3444 // ID. It should fail.
3445 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
3446 SpawnedTestServer::SSLOptions ssl_options;
3448 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3450 EnableFailingChannelID();
3451 SSLConfig ssl_config;
3452 ssl_config.channel_id_enabled = true;
3454 int rv;
3455 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3457 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3458 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3459 // error codes for now.
3460 // http://crbug.com/373670
3461 EXPECT_NE(OK, rv);
3462 EXPECT_FALSE(sock_->IsConnected());
3465 // Connect to a server using Channel ID but asynchronously failing to look up
3466 // the Channel ID. It should fail.
3467 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
3468 SpawnedTestServer::SSLOptions ssl_options;
3470 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3472 EnableAsyncFailingChannelID();
3473 SSLConfig ssl_config;
3474 ssl_config.channel_id_enabled = true;
3476 int rv;
3477 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3479 EXPECT_EQ(ERR_UNEXPECTED, rv);
3480 EXPECT_FALSE(sock_->IsConnected());
3483 } // namespace net