Handle failed fetches/decodes from BitmapFetcher.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blobc93473ffe495ae67b020f29aac6a15e5d2102a6c
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&));
688 class SSLClientSocketTest : public PlatformTest {
689 public:
690 SSLClientSocketTest()
691 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
692 cert_verifier_(new MockCertVerifier),
693 transport_security_state_(new TransportSecurityState) {
694 cert_verifier_->set_default_result(OK);
695 context_.cert_verifier = cert_verifier_.get();
696 context_.transport_security_state = transport_security_state_.get();
699 protected:
700 // The address of the spawned test server, after calling StartTestServer().
701 const AddressList& addr() const { return addr_; }
703 // The SpawnedTestServer object, after calling StartTestServer().
704 const SpawnedTestServer* test_server() const { return test_server_.get(); }
706 void SetCTVerifier(CTVerifier* ct_verifier) {
707 context_.cert_transparency_verifier = ct_verifier;
710 // Starts the test server with SSL configuration |ssl_options|. Returns true
711 // on success.
712 bool StartTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
713 test_server_.reset(new SpawnedTestServer(
714 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath()));
715 if (!test_server_->Start()) {
716 LOG(ERROR) << "Could not start SpawnedTestServer";
717 return false;
720 if (!test_server_->GetAddressList(&addr_)) {
721 LOG(ERROR) << "Could not get SpawnedTestServer address list";
722 return false;
724 return true;
727 // Sets up a TCP connection to a HTTPS server. To actually do the SSL
728 // handshake, follow up with call to CreateAndConnectSSLClientSocket() below.
729 bool ConnectToTestServer(const SpawnedTestServer::SSLOptions& ssl_options) {
730 if (!StartTestServer(ssl_options))
731 return false;
733 transport_.reset(new TCPClientSocket(addr_, &log_, NetLog::Source()));
734 int rv = callback_.GetResult(transport_->Connect(callback_.callback()));
735 if (rv != OK) {
736 LOG(ERROR) << "Could not connect to SpawnedTestServer";
737 return false;
739 return true;
742 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
743 scoped_ptr<StreamSocket> transport_socket,
744 const HostPortPair& host_and_port,
745 const SSLConfig& ssl_config) {
746 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
747 connection->SetSocket(transport_socket.Pass());
748 return socket_factory_->CreateSSLClientSocket(
749 connection.Pass(), host_and_port, ssl_config, context_);
752 // Create an SSLClientSocket object and use it to connect to a test
753 // server, then wait for connection results. This must be called after
754 // a successful ConnectToTestServer() call.
755 // |ssl_config| the SSL configuration to use.
756 // |result| will retrieve the ::Connect() result value.
757 // Returns true on success, false otherwise. Success means that the socket
758 // could be created and its Connect() was called, not that the connection
759 // itself was a success.
760 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config, int* result) {
761 sock_ = CreateSSLClientSocket(
762 transport_.Pass(), test_server_->host_port_pair(), ssl_config);
764 if (sock_->IsConnected()) {
765 LOG(ERROR) << "SSL Socket prematurely connected";
766 return false;
769 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
770 return true;
773 ClientSocketFactory* socket_factory_;
774 scoped_ptr<MockCertVerifier> cert_verifier_;
775 scoped_ptr<TransportSecurityState> transport_security_state_;
776 SSLClientSocketContext context_;
777 scoped_ptr<SSLClientSocket> sock_;
778 TestNetLog log_;
780 private:
781 scoped_ptr<StreamSocket> transport_;
782 scoped_ptr<SpawnedTestServer> test_server_;
783 TestCompletionCallback callback_;
784 AddressList addr_;
787 // Verifies the correctness of GetSSLCertRequestInfo.
788 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
789 protected:
790 // Creates a test server with the given SSLOptions, connects to it and returns
791 // the SSLCertRequestInfo reported by the socket.
792 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
793 SpawnedTestServer::SSLOptions ssl_options) {
794 SpawnedTestServer test_server(
795 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
796 if (!test_server.Start())
797 return NULL;
799 AddressList addr;
800 if (!test_server.GetAddressList(&addr))
801 return NULL;
803 TestCompletionCallback callback;
804 TestNetLog log;
805 scoped_ptr<StreamSocket> transport(
806 new TCPClientSocket(addr, &log, NetLog::Source()));
807 int rv = transport->Connect(callback.callback());
808 if (rv == ERR_IO_PENDING)
809 rv = callback.WaitForResult();
810 EXPECT_EQ(OK, rv);
812 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
813 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
814 EXPECT_FALSE(sock->IsConnected());
816 rv = sock->Connect(callback.callback());
817 if (rv == ERR_IO_PENDING)
818 rv = callback.WaitForResult();
819 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
820 sock->GetSSLCertRequestInfo(request_info.get());
821 sock->Disconnect();
822 EXPECT_FALSE(sock->IsConnected());
823 EXPECT_TRUE(
824 test_server.host_port_pair().Equals(request_info->host_and_port));
826 return request_info;
830 class SSLClientSocketFalseStartTest : public SSLClientSocketTest {
831 protected:
832 // Creates an SSLClientSocket with |client_config| attached to a
833 // FakeBlockingStreamSocket, returning both in |*out_raw_transport| and
834 // |*out_sock|. The FakeBlockingStreamSocket is owned by the SSLClientSocket,
835 // so |*out_raw_transport| is a raw pointer.
837 // The client socket will begin a connect using |callback| but stop before the
838 // server's finished message is received. The finished message will be blocked
839 // in |*out_raw_transport|. To complete the handshake and successfully read
840 // data, the caller must unblock reads on |*out_raw_transport|. (Note that, if
841 // the client successfully false started, |callback.WaitForResult()| will
842 // return OK without unblocking transport reads. But Read() will still block.)
844 // Must be called after StartTestServer is called.
845 void CreateAndConnectUntilServerFinishedReceived(
846 const SSLConfig& client_config,
847 TestCompletionCallback* callback,
848 FakeBlockingStreamSocket** out_raw_transport,
849 scoped_ptr<SSLClientSocket>* out_sock) {
850 CHECK(test_server());
852 scoped_ptr<StreamSocket> real_transport(
853 new TCPClientSocket(addr(), NULL, NetLog::Source()));
854 scoped_ptr<FakeBlockingStreamSocket> transport(
855 new FakeBlockingStreamSocket(real_transport.Pass()));
856 int rv = callback->GetResult(transport->Connect(callback->callback()));
857 EXPECT_EQ(OK, rv);
859 FakeBlockingStreamSocket* raw_transport = transport.get();
860 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
861 transport.Pass(), test_server()->host_port_pair(), client_config);
863 // Connect. Stop before the client processes the first server leg
864 // (ServerHello, etc.)
865 raw_transport->BlockReadResult();
866 rv = sock->Connect(callback->callback());
867 EXPECT_EQ(ERR_IO_PENDING, rv);
868 raw_transport->WaitForReadResult();
870 // Release the ServerHello and wait for the client to write
871 // ClientKeyExchange, etc. (A proxy for waiting for the entirety of the
872 // server's leg to complete, since it may span multiple reads.)
873 EXPECT_FALSE(callback->have_result());
874 raw_transport->BlockWrite();
875 raw_transport->UnblockReadResult();
876 raw_transport->WaitForWrite();
878 // And, finally, release that and block the next server leg
879 // (ChangeCipherSpec, Finished).
880 raw_transport->BlockReadResult();
881 raw_transport->UnblockWrite();
883 *out_raw_transport = raw_transport;
884 *out_sock = sock.Pass();
887 void TestFalseStart(const SpawnedTestServer::SSLOptions& server_options,
888 const SSLConfig& client_config,
889 bool expect_false_start) {
890 ASSERT_TRUE(StartTestServer(server_options));
892 TestCompletionCallback callback;
893 FakeBlockingStreamSocket* raw_transport = NULL;
894 scoped_ptr<SSLClientSocket> sock;
895 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
896 client_config, &callback, &raw_transport, &sock));
898 if (expect_false_start) {
899 // When False Starting, the handshake should complete before receiving the
900 // Change Cipher Spec and Finished messages.
902 // Note: callback.have_result() may not be true without waiting. The NSS
903 // state machine sometimes lives on a separate thread, so this thread may
904 // not yet have processed the signal that the handshake has completed.
905 int rv = callback.WaitForResult();
906 EXPECT_EQ(OK, rv);
907 EXPECT_TRUE(sock->IsConnected());
909 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
910 static const int kRequestTextSize =
911 static_cast<int>(arraysize(request_text) - 1);
912 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
913 memcpy(request_buffer->data(), request_text, kRequestTextSize);
915 // Write the request.
916 rv = callback.GetResult(sock->Write(request_buffer.get(),
917 kRequestTextSize,
918 callback.callback()));
919 EXPECT_EQ(kRequestTextSize, rv);
921 // The read will hang; it's waiting for the peer to complete the
922 // handshake, and the handshake is still blocked.
923 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
924 rv = sock->Read(buf.get(), 4096, callback.callback());
926 // After releasing reads, the connection proceeds.
927 raw_transport->UnblockReadResult();
928 rv = callback.GetResult(rv);
929 EXPECT_LT(0, rv);
930 } else {
931 // False Start is not enabled, so the handshake will not complete because
932 // the server second leg is blocked.
933 base::RunLoop().RunUntilIdle();
934 EXPECT_FALSE(callback.have_result());
939 class SSLClientSocketChannelIDTest : public SSLClientSocketTest {
940 protected:
941 void EnableChannelID() {
942 channel_id_service_.reset(new ChannelIDService(
943 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
944 context_.channel_id_service = channel_id_service_.get();
947 void EnableFailingChannelID() {
948 channel_id_service_.reset(new ChannelIDService(
949 new FailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
950 context_.channel_id_service = channel_id_service_.get();
953 void EnableAsyncFailingChannelID() {
954 channel_id_service_.reset(new ChannelIDService(
955 new AsyncFailingChannelIDStore(), base::ThreadTaskRunnerHandle::Get()));
956 context_.channel_id_service = channel_id_service_.get();
959 private:
960 scoped_ptr<ChannelIDService> channel_id_service_;
963 //-----------------------------------------------------------------------------
965 bool SupportsAESGCM() {
966 #if defined(USE_OPENSSL)
967 return true;
968 #else
969 crypto::EnsureNSSInit();
970 return PK11_TokenExists(CKM_AES_GCM) &&
971 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
972 #endif
975 } // namespace
977 TEST_F(SSLClientSocketTest, Connect) {
978 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
979 SpawnedTestServer::kLocalhost,
980 base::FilePath());
981 ASSERT_TRUE(test_server.Start());
983 AddressList addr;
984 ASSERT_TRUE(test_server.GetAddressList(&addr));
986 TestCompletionCallback callback;
987 TestNetLog log;
988 scoped_ptr<StreamSocket> transport(
989 new TCPClientSocket(addr, &log, NetLog::Source()));
990 int rv = transport->Connect(callback.callback());
991 if (rv == ERR_IO_PENDING)
992 rv = callback.WaitForResult();
993 EXPECT_EQ(OK, rv);
995 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
996 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
998 EXPECT_FALSE(sock->IsConnected());
1000 rv = sock->Connect(callback.callback());
1002 TestNetLogEntry::List entries;
1003 log.GetEntries(&entries);
1004 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1005 if (rv == ERR_IO_PENDING)
1006 rv = callback.WaitForResult();
1007 EXPECT_EQ(OK, rv);
1008 EXPECT_TRUE(sock->IsConnected());
1009 log.GetEntries(&entries);
1010 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1012 sock->Disconnect();
1013 EXPECT_FALSE(sock->IsConnected());
1016 TEST_F(SSLClientSocketTest, ConnectExpired) {
1017 SpawnedTestServer::SSLOptions ssl_options(
1018 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
1019 SpawnedTestServer test_server(
1020 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1021 ASSERT_TRUE(test_server.Start());
1023 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1025 AddressList addr;
1026 ASSERT_TRUE(test_server.GetAddressList(&addr));
1028 TestCompletionCallback callback;
1029 TestNetLog log;
1030 scoped_ptr<StreamSocket> transport(
1031 new TCPClientSocket(addr, &log, NetLog::Source()));
1032 int rv = transport->Connect(callback.callback());
1033 if (rv == ERR_IO_PENDING)
1034 rv = callback.WaitForResult();
1035 EXPECT_EQ(OK, rv);
1037 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1038 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1040 EXPECT_FALSE(sock->IsConnected());
1042 rv = sock->Connect(callback.callback());
1044 TestNetLogEntry::List entries;
1045 log.GetEntries(&entries);
1046 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1047 if (rv == ERR_IO_PENDING)
1048 rv = callback.WaitForResult();
1050 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1052 // Rather than testing whether or not the underlying socket is connected,
1053 // test that the handshake has finished. This is because it may be
1054 // desirable to disconnect the socket before showing a user prompt, since
1055 // the user may take indefinitely long to respond.
1056 log.GetEntries(&entries);
1057 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1060 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1061 SpawnedTestServer::SSLOptions ssl_options(
1062 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1063 SpawnedTestServer test_server(
1064 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1065 ASSERT_TRUE(test_server.Start());
1067 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1069 AddressList addr;
1070 ASSERT_TRUE(test_server.GetAddressList(&addr));
1072 TestCompletionCallback callback;
1073 TestNetLog log;
1074 scoped_ptr<StreamSocket> transport(
1075 new TCPClientSocket(addr, &log, NetLog::Source()));
1076 int rv = transport->Connect(callback.callback());
1077 if (rv == ERR_IO_PENDING)
1078 rv = callback.WaitForResult();
1079 EXPECT_EQ(OK, rv);
1081 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1082 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1084 EXPECT_FALSE(sock->IsConnected());
1086 rv = sock->Connect(callback.callback());
1088 TestNetLogEntry::List entries;
1089 log.GetEntries(&entries);
1090 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1091 if (rv == ERR_IO_PENDING)
1092 rv = callback.WaitForResult();
1094 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1096 // Rather than testing whether or not the underlying socket is connected,
1097 // test that the handshake has finished. This is because it may be
1098 // desirable to disconnect the socket before showing a user prompt, since
1099 // the user may take indefinitely long to respond.
1100 log.GetEntries(&entries);
1101 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1104 // Attempt to connect to a page which requests a client certificate. It should
1105 // return an error code on connect.
1106 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1107 SpawnedTestServer::SSLOptions ssl_options;
1108 ssl_options.request_client_certificate = true;
1109 SpawnedTestServer test_server(
1110 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1111 ASSERT_TRUE(test_server.Start());
1113 AddressList addr;
1114 ASSERT_TRUE(test_server.GetAddressList(&addr));
1116 TestCompletionCallback callback;
1117 TestNetLog log;
1118 scoped_ptr<StreamSocket> transport(
1119 new TCPClientSocket(addr, &log, NetLog::Source()));
1120 int rv = transport->Connect(callback.callback());
1121 if (rv == ERR_IO_PENDING)
1122 rv = callback.WaitForResult();
1123 EXPECT_EQ(OK, rv);
1125 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1126 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1128 EXPECT_FALSE(sock->IsConnected());
1130 rv = sock->Connect(callback.callback());
1132 TestNetLogEntry::List entries;
1133 log.GetEntries(&entries);
1134 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1135 if (rv == ERR_IO_PENDING)
1136 rv = callback.WaitForResult();
1138 log.GetEntries(&entries);
1139 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1140 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1141 EXPECT_FALSE(sock->IsConnected());
1144 // Connect to a server requesting optional client authentication. Send it a
1145 // null certificate. It should allow the connection.
1147 // TODO(davidben): Also test providing an actual certificate.
1148 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1149 SpawnedTestServer::SSLOptions ssl_options;
1150 ssl_options.request_client_certificate = true;
1151 SpawnedTestServer test_server(
1152 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1153 ASSERT_TRUE(test_server.Start());
1155 AddressList addr;
1156 ASSERT_TRUE(test_server.GetAddressList(&addr));
1158 TestCompletionCallback callback;
1159 TestNetLog log;
1160 scoped_ptr<StreamSocket> transport(
1161 new TCPClientSocket(addr, &log, NetLog::Source()));
1162 int rv = transport->Connect(callback.callback());
1163 if (rv == ERR_IO_PENDING)
1164 rv = callback.WaitForResult();
1165 EXPECT_EQ(OK, rv);
1167 SSLConfig ssl_config;
1168 ssl_config.send_client_cert = true;
1169 ssl_config.client_cert = NULL;
1171 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1172 transport.Pass(), test_server.host_port_pair(), ssl_config));
1174 EXPECT_FALSE(sock->IsConnected());
1176 // Our test server accepts certificate-less connections.
1177 // TODO(davidben): Add a test which requires them and verify the error.
1178 rv = sock->Connect(callback.callback());
1180 TestNetLogEntry::List entries;
1181 log.GetEntries(&entries);
1182 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1183 if (rv == ERR_IO_PENDING)
1184 rv = callback.WaitForResult();
1186 EXPECT_EQ(OK, rv);
1187 EXPECT_TRUE(sock->IsConnected());
1188 log.GetEntries(&entries);
1189 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
1191 // We responded to the server's certificate request with a Certificate
1192 // message with no client certificate in it. ssl_info.client_cert_sent
1193 // should be false in this case.
1194 SSLInfo ssl_info;
1195 sock->GetSSLInfo(&ssl_info);
1196 EXPECT_FALSE(ssl_info.client_cert_sent);
1198 sock->Disconnect();
1199 EXPECT_FALSE(sock->IsConnected());
1202 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1203 // - Server closes an SSL connection (with a close_notify alert message).
1204 // - Server closes the underlying TCP connection directly.
1205 // - Server sends data unexpectedly.
1207 // Tests that the socket can be read from successfully. Also test that a peer's
1208 // close_notify alert is successfully processed without error.
1209 TEST_F(SSLClientSocketTest, Read) {
1210 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1211 SpawnedTestServer::kLocalhost,
1212 base::FilePath());
1213 ASSERT_TRUE(test_server.Start());
1215 AddressList addr;
1216 ASSERT_TRUE(test_server.GetAddressList(&addr));
1218 TestCompletionCallback callback;
1219 scoped_ptr<StreamSocket> transport(
1220 new TCPClientSocket(addr, NULL, NetLog::Source()));
1221 int rv = transport->Connect(callback.callback());
1222 if (rv == ERR_IO_PENDING)
1223 rv = callback.WaitForResult();
1224 EXPECT_EQ(OK, rv);
1226 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1227 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1229 rv = sock->Connect(callback.callback());
1230 if (rv == ERR_IO_PENDING)
1231 rv = callback.WaitForResult();
1232 EXPECT_EQ(OK, rv);
1233 EXPECT_TRUE(sock->IsConnected());
1235 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1236 scoped_refptr<IOBuffer> request_buffer(
1237 new IOBuffer(arraysize(request_text) - 1));
1238 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1240 rv = sock->Write(
1241 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1242 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1244 if (rv == ERR_IO_PENDING)
1245 rv = callback.WaitForResult();
1246 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1248 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1249 for (;;) {
1250 rv = sock->Read(buf.get(), 4096, callback.callback());
1251 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1253 if (rv == ERR_IO_PENDING)
1254 rv = callback.WaitForResult();
1256 EXPECT_GE(rv, 0);
1257 if (rv <= 0)
1258 break;
1261 // The peer should have cleanly closed the connection with a close_notify.
1262 EXPECT_EQ(0, rv);
1265 // Tests that SSLClientSocket properly handles when the underlying transport
1266 // synchronously fails a transport read in during the handshake. The error code
1267 // should be preserved so SSLv3 fallback logic can condition on it.
1268 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1269 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1270 SpawnedTestServer::kLocalhost,
1271 base::FilePath());
1272 ASSERT_TRUE(test_server.Start());
1274 AddressList addr;
1275 ASSERT_TRUE(test_server.GetAddressList(&addr));
1277 TestCompletionCallback callback;
1278 scoped_ptr<StreamSocket> real_transport(
1279 new TCPClientSocket(addr, NULL, NetLog::Source()));
1280 scoped_ptr<SynchronousErrorStreamSocket> transport(
1281 new SynchronousErrorStreamSocket(real_transport.Pass()));
1282 int rv = callback.GetResult(transport->Connect(callback.callback()));
1283 EXPECT_EQ(OK, rv);
1285 // Disable TLS False Start to avoid handshake non-determinism.
1286 SSLConfig ssl_config;
1287 ssl_config.false_start_enabled = false;
1289 SynchronousErrorStreamSocket* raw_transport = transport.get();
1290 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1291 transport.Pass(), test_server.host_port_pair(), ssl_config));
1293 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1295 rv = callback.GetResult(sock->Connect(callback.callback()));
1296 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1297 EXPECT_FALSE(sock->IsConnected());
1300 // Tests that the SSLClientSocket properly handles when the underlying transport
1301 // synchronously returns an error code - such as if an intermediary terminates
1302 // the socket connection uncleanly.
1303 // This is a regression test for http://crbug.com/238536
1304 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1305 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1306 SpawnedTestServer::kLocalhost,
1307 base::FilePath());
1308 ASSERT_TRUE(test_server.Start());
1310 AddressList addr;
1311 ASSERT_TRUE(test_server.GetAddressList(&addr));
1313 TestCompletionCallback callback;
1314 scoped_ptr<StreamSocket> real_transport(
1315 new TCPClientSocket(addr, NULL, NetLog::Source()));
1316 scoped_ptr<SynchronousErrorStreamSocket> transport(
1317 new SynchronousErrorStreamSocket(real_transport.Pass()));
1318 int rv = callback.GetResult(transport->Connect(callback.callback()));
1319 EXPECT_EQ(OK, rv);
1321 // Disable TLS False Start to avoid handshake non-determinism.
1322 SSLConfig ssl_config;
1323 ssl_config.false_start_enabled = false;
1325 SynchronousErrorStreamSocket* raw_transport = transport.get();
1326 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1327 transport.Pass(), test_server.host_port_pair(), ssl_config));
1329 rv = callback.GetResult(sock->Connect(callback.callback()));
1330 EXPECT_EQ(OK, rv);
1331 EXPECT_TRUE(sock->IsConnected());
1333 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1334 static const int kRequestTextSize =
1335 static_cast<int>(arraysize(request_text) - 1);
1336 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1337 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1339 rv = callback.GetResult(
1340 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1341 EXPECT_EQ(kRequestTextSize, rv);
1343 // Simulate an unclean/forcible shutdown.
1344 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1346 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1348 // Note: This test will hang if this bug has regressed. Simply checking that
1349 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1350 // result when using a dedicated task runner for NSS.
1351 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1352 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1355 // Tests that the SSLClientSocket properly handles when the underlying transport
1356 // asynchronously returns an error code while writing data - such as if an
1357 // intermediary terminates the socket connection uncleanly.
1358 // This is a regression test for http://crbug.com/249848
1359 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1360 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1361 SpawnedTestServer::kLocalhost,
1362 base::FilePath());
1363 ASSERT_TRUE(test_server.Start());
1365 AddressList addr;
1366 ASSERT_TRUE(test_server.GetAddressList(&addr));
1368 TestCompletionCallback callback;
1369 scoped_ptr<StreamSocket> real_transport(
1370 new TCPClientSocket(addr, NULL, NetLog::Source()));
1371 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1372 // is retained in order to configure additional errors.
1373 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1374 new SynchronousErrorStreamSocket(real_transport.Pass()));
1375 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1376 scoped_ptr<FakeBlockingStreamSocket> transport(
1377 new FakeBlockingStreamSocket(error_socket.Pass()));
1378 FakeBlockingStreamSocket* raw_transport = transport.get();
1379 int rv = callback.GetResult(transport->Connect(callback.callback()));
1380 EXPECT_EQ(OK, rv);
1382 // Disable TLS False Start to avoid handshake non-determinism.
1383 SSLConfig ssl_config;
1384 ssl_config.false_start_enabled = false;
1386 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1387 transport.Pass(), test_server.host_port_pair(), ssl_config));
1389 rv = callback.GetResult(sock->Connect(callback.callback()));
1390 EXPECT_EQ(OK, rv);
1391 EXPECT_TRUE(sock->IsConnected());
1393 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1394 static const int kRequestTextSize =
1395 static_cast<int>(arraysize(request_text) - 1);
1396 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1397 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1399 // Simulate an unclean/forcible shutdown on the underlying socket.
1400 // However, simulate this error asynchronously.
1401 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1402 raw_transport->BlockWrite();
1404 // This write should complete synchronously, because the TLS ciphertext
1405 // can be created and placed into the outgoing buffers independent of the
1406 // underlying transport.
1407 rv = callback.GetResult(
1408 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1409 EXPECT_EQ(kRequestTextSize, rv);
1411 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1413 rv = sock->Read(buf.get(), 4096, callback.callback());
1414 EXPECT_EQ(ERR_IO_PENDING, rv);
1416 // Now unblock the outgoing request, having it fail with the connection
1417 // being reset.
1418 raw_transport->UnblockWrite();
1420 // Note: This will cause an inifite loop if this bug has regressed. Simply
1421 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1422 // is a legitimate result when using a dedicated task runner for NSS.
1423 rv = callback.GetResult(rv);
1424 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1427 // If there is a Write failure at the transport with no follow-up Read, although
1428 // the write error will not be returned to the client until a future Read or
1429 // Write operation, SSLClientSocket should not spin attempting to re-write on
1430 // the socket. This is a regression test for part of https://crbug.com/381160.
1431 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1432 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1433 SpawnedTestServer::kLocalhost,
1434 base::FilePath());
1435 ASSERT_TRUE(test_server.Start());
1437 AddressList addr;
1438 ASSERT_TRUE(test_server.GetAddressList(&addr));
1440 TestCompletionCallback callback;
1441 scoped_ptr<StreamSocket> real_transport(
1442 new TCPClientSocket(addr, NULL, NetLog::Source()));
1443 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1444 // is retained in order to query them.
1445 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1446 new SynchronousErrorStreamSocket(real_transport.Pass()));
1447 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1448 scoped_ptr<CountingStreamSocket> counting_socket(
1449 new CountingStreamSocket(error_socket.Pass()));
1450 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1451 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1452 ASSERT_EQ(OK, rv);
1454 // Disable TLS False Start to avoid handshake non-determinism.
1455 SSLConfig ssl_config;
1456 ssl_config.false_start_enabled = false;
1458 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1459 counting_socket.Pass(), test_server.host_port_pair(), ssl_config));
1461 rv = callback.GetResult(sock->Connect(callback.callback()));
1462 ASSERT_EQ(OK, rv);
1463 ASSERT_TRUE(sock->IsConnected());
1465 // Simulate an unclean/forcible shutdown on the underlying socket.
1466 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1468 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1469 static const int kRequestTextSize =
1470 static_cast<int>(arraysize(request_text) - 1);
1471 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1472 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1474 // This write should complete synchronously, because the TLS ciphertext
1475 // can be created and placed into the outgoing buffers independent of the
1476 // underlying transport.
1477 rv = callback.GetResult(
1478 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1479 ASSERT_EQ(kRequestTextSize, rv);
1481 // Let the event loop spin for a little bit of time. Even on platforms where
1482 // pumping the state machine involve thread hops, there should be no further
1483 // writes on the transport socket.
1485 // TODO(davidben): Avoid the arbitrary timeout?
1486 int old_write_count = raw_counting_socket->write_count();
1487 base::RunLoop loop;
1488 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
1489 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1490 loop.Run();
1491 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1494 // Test the full duplex mode, with Read and Write pending at the same time.
1495 // This test also serves as a regression test for http://crbug.com/29815.
1496 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1497 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1498 SpawnedTestServer::kLocalhost,
1499 base::FilePath());
1500 ASSERT_TRUE(test_server.Start());
1502 AddressList addr;
1503 ASSERT_TRUE(test_server.GetAddressList(&addr));
1505 TestCompletionCallback callback; // Used for everything except Write.
1507 scoped_ptr<StreamSocket> transport(
1508 new TCPClientSocket(addr, NULL, NetLog::Source()));
1509 int rv = transport->Connect(callback.callback());
1510 if (rv == ERR_IO_PENDING)
1511 rv = callback.WaitForResult();
1512 EXPECT_EQ(OK, rv);
1514 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1515 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1517 rv = sock->Connect(callback.callback());
1518 if (rv == ERR_IO_PENDING)
1519 rv = callback.WaitForResult();
1520 EXPECT_EQ(OK, rv);
1521 EXPECT_TRUE(sock->IsConnected());
1523 // Issue a "hanging" Read first.
1524 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1525 rv = sock->Read(buf.get(), 4096, callback.callback());
1526 // We haven't written the request, so there should be no response yet.
1527 ASSERT_EQ(ERR_IO_PENDING, rv);
1529 // Write the request.
1530 // The request is padded with a User-Agent header to a size that causes the
1531 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1532 // This tests the fix for http://crbug.com/29815.
1533 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1534 for (int i = 0; i < 3770; ++i)
1535 request_text.push_back('*');
1536 request_text.append("\r\n\r\n");
1537 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1539 TestCompletionCallback callback2; // Used for Write only.
1540 rv = sock->Write(
1541 request_buffer.get(), request_text.size(), callback2.callback());
1542 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1544 if (rv == ERR_IO_PENDING)
1545 rv = callback2.WaitForResult();
1546 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1548 // Now get the Read result.
1549 rv = callback.WaitForResult();
1550 EXPECT_GT(rv, 0);
1553 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1554 // mode when the underlying transport is blocked on sending data. When the
1555 // underlying transport completes due to an error, it should invoke both the
1556 // Read() and Write() callbacks. If the socket is deleted by the Read()
1557 // callback, the Write() callback should not be invoked.
1558 // Regression test for http://crbug.com/232633
1559 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1560 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1561 SpawnedTestServer::kLocalhost,
1562 base::FilePath());
1563 ASSERT_TRUE(test_server.Start());
1565 AddressList addr;
1566 ASSERT_TRUE(test_server.GetAddressList(&addr));
1568 TestCompletionCallback callback;
1569 scoped_ptr<StreamSocket> real_transport(
1570 new TCPClientSocket(addr, NULL, NetLog::Source()));
1571 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1572 // is retained in order to configure additional errors.
1573 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1574 new SynchronousErrorStreamSocket(real_transport.Pass()));
1575 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1576 scoped_ptr<FakeBlockingStreamSocket> transport(
1577 new FakeBlockingStreamSocket(error_socket.Pass()));
1578 FakeBlockingStreamSocket* raw_transport = transport.get();
1580 int rv = callback.GetResult(transport->Connect(callback.callback()));
1581 EXPECT_EQ(OK, rv);
1583 // Disable TLS False Start to avoid handshake non-determinism.
1584 SSLConfig ssl_config;
1585 ssl_config.false_start_enabled = false;
1587 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
1588 transport.Pass(), test_server.host_port_pair(), ssl_config);
1590 rv = callback.GetResult(sock->Connect(callback.callback()));
1591 EXPECT_EQ(OK, rv);
1592 EXPECT_TRUE(sock->IsConnected());
1594 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1595 request_text.append(20 * 1024, '*');
1596 request_text.append("\r\n\r\n");
1597 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1598 new StringIOBuffer(request_text), request_text.size()));
1600 // Simulate errors being returned from the underlying Read() and Write() ...
1601 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1602 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1603 // ... but have those errors returned asynchronously. Because the Write() will
1604 // return first, this will trigger the error.
1605 raw_transport->BlockReadResult();
1606 raw_transport->BlockWrite();
1608 // Enqueue a Read() before calling Write(), which should "hang" due to
1609 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1610 SSLClientSocket* raw_sock = sock.get();
1611 DeleteSocketCallback read_callback(sock.release());
1612 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1613 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1615 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1616 ASSERT_EQ(ERR_IO_PENDING, rv);
1617 ASSERT_FALSE(read_callback.have_result());
1619 #if !defined(USE_OPENSSL)
1620 // NSS follows a pattern where a call to PR_Write will only consume as
1621 // much data as it can encode into application data records before the
1622 // internal memio buffer is full, which should only fill if writing a large
1623 // amount of data and the underlying transport is blocked. Once this happens,
1624 // NSS will return (total size of all application data records it wrote) - 1,
1625 // with the caller expected to resume with the remaining unsent data.
1627 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1628 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1629 // get the socket in the state needed for the test below.
1631 // This is not needed for OpenSSL, because for OpenSSL,
1632 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1633 // SSLClientSocketOpenSSL::Write() will not return until all of
1634 // |request_buffer| has been written to the underlying BIO (although not
1635 // necessarily the underlying transport).
1636 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1637 request_buffer->BytesRemaining(),
1638 callback.callback()));
1639 ASSERT_LT(0, rv);
1640 request_buffer->DidConsume(rv);
1642 // Guard to ensure that |request_buffer| was larger than all of the internal
1643 // buffers (transport, memio, NSS) along the way - otherwise the next call
1644 // to Write() will crash with an invalid buffer.
1645 ASSERT_LT(0, request_buffer->BytesRemaining());
1646 #endif
1648 // Attempt to write the remaining data. NSS will not be able to consume the
1649 // application data because the internal buffers are full, while OpenSSL will
1650 // return that its blocked because the underlying transport is blocked.
1651 rv = raw_sock->Write(request_buffer.get(),
1652 request_buffer->BytesRemaining(),
1653 callback.callback());
1654 ASSERT_EQ(ERR_IO_PENDING, rv);
1655 ASSERT_FALSE(callback.have_result());
1657 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1658 // call the Read() callback, deleting the socket and thus aborting calling
1659 // the Write() callback.
1660 raw_transport->UnblockWrite();
1662 rv = read_callback.WaitForResult();
1663 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1665 // The Write callback should not have been called.
1666 EXPECT_FALSE(callback.have_result());
1669 // Tests that the SSLClientSocket does not crash if data is received on the
1670 // transport socket after a failing write. This can occur if we have a Write
1671 // error in a SPDY socket.
1672 // Regression test for http://crbug.com/335557
1673 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1674 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1675 SpawnedTestServer::kLocalhost,
1676 base::FilePath());
1677 ASSERT_TRUE(test_server.Start());
1679 AddressList addr;
1680 ASSERT_TRUE(test_server.GetAddressList(&addr));
1682 TestCompletionCallback callback;
1683 scoped_ptr<StreamSocket> real_transport(
1684 new TCPClientSocket(addr, NULL, NetLog::Source()));
1685 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1686 // is retained in order to configure additional errors.
1687 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1688 new SynchronousErrorStreamSocket(real_transport.Pass()));
1689 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1690 scoped_ptr<FakeBlockingStreamSocket> transport(
1691 new FakeBlockingStreamSocket(error_socket.Pass()));
1692 FakeBlockingStreamSocket* raw_transport = transport.get();
1694 int rv = callback.GetResult(transport->Connect(callback.callback()));
1695 EXPECT_EQ(OK, rv);
1697 // Disable TLS False Start to avoid handshake non-determinism.
1698 SSLConfig ssl_config;
1699 ssl_config.false_start_enabled = false;
1701 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1702 transport.Pass(), test_server.host_port_pair(), ssl_config));
1704 rv = callback.GetResult(sock->Connect(callback.callback()));
1705 EXPECT_EQ(OK, rv);
1706 EXPECT_TRUE(sock->IsConnected());
1708 // Send a request so there is something to read from the socket.
1709 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1710 static const int kRequestTextSize =
1711 static_cast<int>(arraysize(request_text) - 1);
1712 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1713 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1715 rv = callback.GetResult(
1716 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1717 EXPECT_EQ(kRequestTextSize, rv);
1719 // Start a hanging read.
1720 TestCompletionCallback read_callback;
1721 raw_transport->BlockReadResult();
1722 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1723 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1724 EXPECT_EQ(ERR_IO_PENDING, rv);
1726 // Perform another write, but have it fail. Write a request larger than the
1727 // internal socket buffers so that the request hits the underlying transport
1728 // socket and detects the error.
1729 std::string long_request_text =
1730 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1731 long_request_text.append(20 * 1024, '*');
1732 long_request_text.append("\r\n\r\n");
1733 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1734 new StringIOBuffer(long_request_text), long_request_text.size()));
1736 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1738 // Write as much data as possible until hitting an error. This is necessary
1739 // for NSS. PR_Write will only consume as much data as it can encode into
1740 // application data records before the internal memio buffer is full, which
1741 // should only fill if writing a large amount of data and the underlying
1742 // transport is blocked. Once this happens, NSS will return (total size of all
1743 // application data records it wrote) - 1, with the caller expected to resume
1744 // with the remaining unsent data.
1745 do {
1746 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1747 long_request_buffer->BytesRemaining(),
1748 callback.callback()));
1749 if (rv > 0) {
1750 long_request_buffer->DidConsume(rv);
1751 // Abort if the entire buffer is ever consumed.
1752 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1754 } while (rv > 0);
1756 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1758 // Release the read.
1759 raw_transport->UnblockReadResult();
1760 rv = read_callback.WaitForResult();
1762 #if defined(USE_OPENSSL)
1763 // Should still read bytes despite the write error.
1764 EXPECT_LT(0, rv);
1765 #else
1766 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1767 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1768 // the write error stops future reads.
1769 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1770 #endif
1773 // Tests that SSLClientSocket fails the handshake if the underlying
1774 // transport is cleanly closed.
1775 TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
1776 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1777 SpawnedTestServer::kLocalhost,
1778 base::FilePath());
1779 ASSERT_TRUE(test_server.Start());
1781 AddressList addr;
1782 ASSERT_TRUE(test_server.GetAddressList(&addr));
1784 TestCompletionCallback callback;
1785 scoped_ptr<StreamSocket> real_transport(
1786 new TCPClientSocket(addr, NULL, NetLog::Source()));
1787 scoped_ptr<SynchronousErrorStreamSocket> transport(
1788 new SynchronousErrorStreamSocket(real_transport.Pass()));
1789 int rv = callback.GetResult(transport->Connect(callback.callback()));
1790 EXPECT_EQ(OK, rv);
1792 SynchronousErrorStreamSocket* raw_transport = transport.get();
1793 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1794 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1796 raw_transport->SetNextReadError(0);
1798 rv = callback.GetResult(sock->Connect(callback.callback()));
1799 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
1800 EXPECT_FALSE(sock->IsConnected());
1803 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1804 // is cleanly closed, but the peer does not send close_notify.
1805 // This is a regression test for https://crbug.com/422246
1806 TEST_F(SSLClientSocketTest, Read_WithZeroReturn) {
1807 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1808 SpawnedTestServer::kLocalhost,
1809 base::FilePath());
1810 ASSERT_TRUE(test_server.Start());
1812 AddressList addr;
1813 ASSERT_TRUE(test_server.GetAddressList(&addr));
1815 TestCompletionCallback callback;
1816 scoped_ptr<StreamSocket> real_transport(
1817 new TCPClientSocket(addr, NULL, NetLog::Source()));
1818 scoped_ptr<SynchronousErrorStreamSocket> transport(
1819 new SynchronousErrorStreamSocket(real_transport.Pass()));
1820 int rv = callback.GetResult(transport->Connect(callback.callback()));
1821 EXPECT_EQ(OK, rv);
1823 // Disable TLS False Start to ensure the handshake has completed.
1824 SSLConfig ssl_config;
1825 ssl_config.false_start_enabled = false;
1827 SynchronousErrorStreamSocket* raw_transport = transport.get();
1828 scoped_ptr<SSLClientSocket> sock(
1829 CreateSSLClientSocket(transport.Pass(),
1830 test_server.host_port_pair(),
1831 ssl_config));
1833 rv = callback.GetResult(sock->Connect(callback.callback()));
1834 EXPECT_EQ(OK, rv);
1835 EXPECT_TRUE(sock->IsConnected());
1837 raw_transport->SetNextReadError(0);
1838 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1839 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1840 EXPECT_EQ(0, rv);
1843 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1844 // underlying socket is cleanly closed asynchronously.
1845 // This is a regression test for https://crbug.com/422246
1846 TEST_F(SSLClientSocketTest, Read_WithAsyncZeroReturn) {
1847 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1848 SpawnedTestServer::kLocalhost,
1849 base::FilePath());
1850 ASSERT_TRUE(test_server.Start());
1852 AddressList addr;
1853 ASSERT_TRUE(test_server.GetAddressList(&addr));
1855 TestCompletionCallback callback;
1856 scoped_ptr<StreamSocket> real_transport(
1857 new TCPClientSocket(addr, NULL, NetLog::Source()));
1858 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1859 new SynchronousErrorStreamSocket(real_transport.Pass()));
1860 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1861 scoped_ptr<FakeBlockingStreamSocket> transport(
1862 new FakeBlockingStreamSocket(error_socket.Pass()));
1863 FakeBlockingStreamSocket* raw_transport = transport.get();
1864 int rv = callback.GetResult(transport->Connect(callback.callback()));
1865 EXPECT_EQ(OK, rv);
1867 // Disable TLS False Start to ensure the handshake has completed.
1868 SSLConfig ssl_config;
1869 ssl_config.false_start_enabled = false;
1871 scoped_ptr<SSLClientSocket> sock(
1872 CreateSSLClientSocket(transport.Pass(),
1873 test_server.host_port_pair(),
1874 ssl_config));
1876 rv = callback.GetResult(sock->Connect(callback.callback()));
1877 EXPECT_EQ(OK, rv);
1878 EXPECT_TRUE(sock->IsConnected());
1880 raw_error_socket->SetNextReadError(0);
1881 raw_transport->BlockReadResult();
1882 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1883 rv = sock->Read(buf.get(), 4096, callback.callback());
1884 EXPECT_EQ(ERR_IO_PENDING, rv);
1886 raw_transport->UnblockReadResult();
1887 rv = callback.GetResult(rv);
1888 EXPECT_EQ(0, rv);
1891 // Tests that fatal alerts from the peer are processed. This is a regression
1892 // test for https://crbug.com/466303.
1893 TEST_F(SSLClientSocketTest, Read_WithFatalAlert) {
1894 SpawnedTestServer::SSLOptions ssl_options;
1895 ssl_options.alert_after_handshake = true;
1896 ASSERT_TRUE(StartTestServer(ssl_options));
1898 SSLConfig ssl_config;
1899 TestCompletionCallback callback;
1900 scoped_ptr<StreamSocket> transport(
1901 new TCPClientSocket(addr(), &log_, NetLog::Source()));
1902 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
1903 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1904 transport.Pass(), test_server()->host_port_pair(), ssl_config));
1905 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
1907 // Receive the fatal alert.
1908 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1909 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(sock->Read(
1910 buf.get(), 4096, callback.callback())));
1913 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1914 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1915 SpawnedTestServer::kLocalhost,
1916 base::FilePath());
1917 ASSERT_TRUE(test_server.Start());
1919 AddressList addr;
1920 ASSERT_TRUE(test_server.GetAddressList(&addr));
1922 TestCompletionCallback callback;
1923 scoped_ptr<StreamSocket> transport(
1924 new TCPClientSocket(addr, NULL, NetLog::Source()));
1925 int rv = transport->Connect(callback.callback());
1926 if (rv == ERR_IO_PENDING)
1927 rv = callback.WaitForResult();
1928 EXPECT_EQ(OK, rv);
1930 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1931 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1933 rv = sock->Connect(callback.callback());
1934 if (rv == ERR_IO_PENDING)
1935 rv = callback.WaitForResult();
1936 EXPECT_EQ(OK, rv);
1938 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1939 scoped_refptr<IOBuffer> request_buffer(
1940 new IOBuffer(arraysize(request_text) - 1));
1941 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1943 rv = sock->Write(
1944 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1945 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1947 if (rv == ERR_IO_PENDING)
1948 rv = callback.WaitForResult();
1949 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1951 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1952 for (;;) {
1953 rv = sock->Read(buf.get(), 1, callback.callback());
1954 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1956 if (rv == ERR_IO_PENDING)
1957 rv = callback.WaitForResult();
1959 EXPECT_GE(rv, 0);
1960 if (rv <= 0)
1961 break;
1965 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1966 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1967 SpawnedTestServer::kLocalhost,
1968 base::FilePath());
1969 ASSERT_TRUE(test_server.Start());
1971 AddressList addr;
1972 ASSERT_TRUE(test_server.GetAddressList(&addr));
1974 TestCompletionCallback callback;
1976 scoped_ptr<StreamSocket> real_transport(
1977 new TCPClientSocket(addr, NULL, NetLog::Source()));
1978 scoped_ptr<ReadBufferingStreamSocket> transport(
1979 new ReadBufferingStreamSocket(real_transport.Pass()));
1980 ReadBufferingStreamSocket* raw_transport = transport.get();
1981 int rv = callback.GetResult(transport->Connect(callback.callback()));
1982 ASSERT_EQ(OK, rv);
1984 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1985 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1987 rv = callback.GetResult(sock->Connect(callback.callback()));
1988 ASSERT_EQ(OK, rv);
1989 ASSERT_TRUE(sock->IsConnected());
1991 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1992 scoped_refptr<IOBuffer> request_buffer(
1993 new IOBuffer(arraysize(request_text) - 1));
1994 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1996 rv = callback.GetResult(sock->Write(
1997 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1998 ASSERT_GT(rv, 0);
1999 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2001 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2002 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2003 // of SSL data is buffered first. The 15K of buffered data is made up of
2004 // many smaller SSL records (the TestServer writes along 1350 byte
2005 // plaintext boundaries), although there may also be a few records that are
2006 // smaller or larger, due to timing and SSL False Start.
2007 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2008 // the SSLClientSocket implementation, and larger than the minimum amount
2009 // of ciphertext necessary to contain the 8K of plaintext requested below.
2010 raw_transport->SetBufferSize(15000);
2012 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
2013 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
2014 ASSERT_EQ(rv, 8192);
2017 TEST_F(SSLClientSocketTest, Read_Interrupted) {
2018 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2019 SpawnedTestServer::kLocalhost,
2020 base::FilePath());
2021 ASSERT_TRUE(test_server.Start());
2023 AddressList addr;
2024 ASSERT_TRUE(test_server.GetAddressList(&addr));
2026 TestCompletionCallback callback;
2027 scoped_ptr<StreamSocket> transport(
2028 new TCPClientSocket(addr, NULL, NetLog::Source()));
2029 int rv = transport->Connect(callback.callback());
2030 if (rv == ERR_IO_PENDING)
2031 rv = callback.WaitForResult();
2032 EXPECT_EQ(OK, rv);
2034 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2035 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2037 rv = sock->Connect(callback.callback());
2038 if (rv == ERR_IO_PENDING)
2039 rv = callback.WaitForResult();
2040 EXPECT_EQ(OK, rv);
2042 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2043 scoped_refptr<IOBuffer> request_buffer(
2044 new IOBuffer(arraysize(request_text) - 1));
2045 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2047 rv = sock->Write(
2048 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2049 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2051 if (rv == ERR_IO_PENDING)
2052 rv = callback.WaitForResult();
2053 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2055 // Do a partial read and then exit. This test should not crash!
2056 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
2057 rv = sock->Read(buf.get(), 512, callback.callback());
2058 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
2060 if (rv == ERR_IO_PENDING)
2061 rv = callback.WaitForResult();
2063 EXPECT_GT(rv, 0);
2066 TEST_F(SSLClientSocketTest, Read_FullLogging) {
2067 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2068 SpawnedTestServer::kLocalhost,
2069 base::FilePath());
2070 ASSERT_TRUE(test_server.Start());
2072 AddressList addr;
2073 ASSERT_TRUE(test_server.GetAddressList(&addr));
2075 TestCompletionCallback callback;
2076 TestNetLog log;
2077 log.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes());
2078 scoped_ptr<StreamSocket> transport(
2079 new TCPClientSocket(addr, &log, NetLog::Source()));
2080 int rv = transport->Connect(callback.callback());
2081 if (rv == ERR_IO_PENDING)
2082 rv = callback.WaitForResult();
2083 EXPECT_EQ(OK, rv);
2085 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2086 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2088 rv = sock->Connect(callback.callback());
2089 if (rv == ERR_IO_PENDING)
2090 rv = callback.WaitForResult();
2091 EXPECT_EQ(OK, rv);
2092 EXPECT_TRUE(sock->IsConnected());
2094 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2095 scoped_refptr<IOBuffer> request_buffer(
2096 new IOBuffer(arraysize(request_text) - 1));
2097 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2099 rv = sock->Write(
2100 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2101 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2103 if (rv == ERR_IO_PENDING)
2104 rv = callback.WaitForResult();
2105 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2107 TestNetLogEntry::List entries;
2108 log.GetEntries(&entries);
2109 size_t last_index = ExpectLogContainsSomewhereAfter(
2110 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2112 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2113 for (;;) {
2114 rv = sock->Read(buf.get(), 4096, callback.callback());
2115 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2117 if (rv == ERR_IO_PENDING)
2118 rv = callback.WaitForResult();
2120 EXPECT_GE(rv, 0);
2121 if (rv <= 0)
2122 break;
2124 log.GetEntries(&entries);
2125 last_index =
2126 ExpectLogContainsSomewhereAfter(entries,
2127 last_index + 1,
2128 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2129 NetLog::PHASE_NONE);
2133 // Regression test for http://crbug.com/42538
2134 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2135 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2136 SpawnedTestServer::kLocalhost,
2137 base::FilePath());
2138 ASSERT_TRUE(test_server.Start());
2140 AddressList addr;
2141 TestCompletionCallback callback;
2143 static const unsigned char application_data[] = {
2144 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2145 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2146 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2147 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2148 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2149 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2150 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2151 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2152 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2153 0x0a};
2155 // All reads and writes complete synchronously (async=false).
2156 MockRead data_reads[] = {
2157 MockRead(SYNCHRONOUS,
2158 reinterpret_cast<const char*>(application_data),
2159 arraysize(application_data)),
2160 MockRead(SYNCHRONOUS, OK), };
2162 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2164 scoped_ptr<StreamSocket> transport(
2165 new MockTCPClientSocket(addr, NULL, &data));
2166 int rv = transport->Connect(callback.callback());
2167 if (rv == ERR_IO_PENDING)
2168 rv = callback.WaitForResult();
2169 EXPECT_EQ(OK, rv);
2171 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2172 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2174 rv = sock->Connect(callback.callback());
2175 if (rv == ERR_IO_PENDING)
2176 rv = callback.WaitForResult();
2177 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2180 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2181 // Rather than exhaustively disabling every AES_128_CBC ciphersuite defined at
2182 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2183 // disabling those cipher suites that the test server actually implements.
2184 const uint16 kCiphersToDisable[] = {
2185 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2186 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2187 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2190 SpawnedTestServer::SSLOptions ssl_options;
2191 // Enable only AES_128_CBC on the test server.
2192 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
2193 SpawnedTestServer test_server(
2194 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2195 ASSERT_TRUE(test_server.Start());
2197 AddressList addr;
2198 ASSERT_TRUE(test_server.GetAddressList(&addr));
2200 TestCompletionCallback callback;
2201 TestNetLog log;
2202 scoped_ptr<StreamSocket> transport(
2203 new TCPClientSocket(addr, &log, NetLog::Source()));
2204 int rv = transport->Connect(callback.callback());
2205 if (rv == ERR_IO_PENDING)
2206 rv = callback.WaitForResult();
2207 EXPECT_EQ(OK, rv);
2209 SSLConfig ssl_config;
2210 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2211 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2213 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2214 transport.Pass(), test_server.host_port_pair(), ssl_config));
2216 EXPECT_FALSE(sock->IsConnected());
2218 rv = sock->Connect(callback.callback());
2219 TestNetLogEntry::List entries;
2220 log.GetEntries(&entries);
2221 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2223 if (rv == ERR_IO_PENDING)
2224 rv = callback.WaitForResult();
2225 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, rv);
2226 // The exact ordering depends no whether an extra read is issued. Just check
2227 // the error is somewhere in the log.
2228 log.GetEntries(&entries);
2229 ExpectLogContainsSomewhere(
2230 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2232 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2233 // the socket when it encounters an error, whereas other implementations
2234 // leave it connected.
2235 // Because this an error that the test server is mutually aware of, as opposed
2236 // to being an error such as a certificate name mismatch, which is
2237 // client-only, the exact index of the SSL connect end depends on how
2238 // quickly the test server closes the underlying socket. If the test server
2239 // closes before the IO message loop pumps messages, there may be a 0-byte
2240 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2241 // result, the SSL connect end event will be the second-to-last entry,
2242 // rather than the last entry.
2243 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT) ||
2244 LogContainsEndEvent(entries, -2, NetLog::TYPE_SSL_CONNECT));
2247 // When creating an SSLClientSocket, it is allowed to pass in a
2248 // ClientSocketHandle that is not obtained from a client socket pool.
2249 // Here we verify that such a simple ClientSocketHandle, not associated with any
2250 // client socket pool, can be destroyed safely.
2251 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
2252 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2253 SpawnedTestServer::kLocalhost,
2254 base::FilePath());
2255 ASSERT_TRUE(test_server.Start());
2257 AddressList addr;
2258 ASSERT_TRUE(test_server.GetAddressList(&addr));
2260 TestCompletionCallback callback;
2261 scoped_ptr<StreamSocket> transport(
2262 new TCPClientSocket(addr, NULL, NetLog::Source()));
2263 int rv = transport->Connect(callback.callback());
2264 if (rv == ERR_IO_PENDING)
2265 rv = callback.WaitForResult();
2266 EXPECT_EQ(OK, rv);
2268 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2269 socket_handle->SetSocket(transport.Pass());
2271 scoped_ptr<SSLClientSocket> sock(socket_factory_->CreateSSLClientSocket(
2272 socket_handle.Pass(), test_server.host_port_pair(), SSLConfig(),
2273 context_));
2275 EXPECT_FALSE(sock->IsConnected());
2276 rv = sock->Connect(callback.callback());
2277 if (rv == ERR_IO_PENDING)
2278 rv = callback.WaitForResult();
2279 EXPECT_EQ(OK, rv);
2282 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2283 // code and different keying label results in different keying material.
2284 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2285 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2286 SpawnedTestServer::kLocalhost,
2287 base::FilePath());
2288 ASSERT_TRUE(test_server.Start());
2290 AddressList addr;
2291 ASSERT_TRUE(test_server.GetAddressList(&addr));
2293 TestCompletionCallback callback;
2295 scoped_ptr<StreamSocket> transport(
2296 new TCPClientSocket(addr, NULL, NetLog::Source()));
2297 int rv = transport->Connect(callback.callback());
2298 if (rv == ERR_IO_PENDING)
2299 rv = callback.WaitForResult();
2300 EXPECT_EQ(OK, rv);
2302 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2303 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2305 rv = sock->Connect(callback.callback());
2306 if (rv == ERR_IO_PENDING)
2307 rv = callback.WaitForResult();
2308 EXPECT_EQ(OK, rv);
2309 EXPECT_TRUE(sock->IsConnected());
2311 const int kKeyingMaterialSize = 32;
2312 const char kKeyingLabel1[] = "client-socket-test-1";
2313 const char kKeyingContext1[] = "";
2314 unsigned char client_out1[kKeyingMaterialSize];
2315 memset(client_out1, 0, sizeof(client_out1));
2316 rv = sock->ExportKeyingMaterial(kKeyingLabel1, false, kKeyingContext1,
2317 client_out1, sizeof(client_out1));
2318 EXPECT_EQ(rv, OK);
2320 const char kKeyingLabel2[] = "client-socket-test-2";
2321 unsigned char client_out2[kKeyingMaterialSize];
2322 memset(client_out2, 0, sizeof(client_out2));
2323 rv = sock->ExportKeyingMaterial(kKeyingLabel2, false, kKeyingContext1,
2324 client_out2, sizeof(client_out2));
2325 EXPECT_EQ(rv, OK);
2326 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2328 const char kKeyingContext2[] = "context";
2329 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext2,
2330 client_out2, sizeof(client_out2));
2331 EXPECT_EQ(rv, OK);
2332 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2334 // Using an empty context should give different key material from not using a
2335 // context at all.
2336 memset(client_out2, 0, sizeof(client_out2));
2337 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext1,
2338 client_out2, sizeof(client_out2));
2339 EXPECT_EQ(rv, OK);
2340 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2343 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2344 // explicit NSS initialization.
2345 TEST(SSLClientSocket, ClearSessionCache) {
2346 SSLClientSocket::ClearSessionCache();
2349 TEST(SSLClientSocket, SerializeNextProtos) {
2350 NextProtoVector next_protos;
2351 next_protos.push_back(kProtoHTTP11);
2352 next_protos.push_back(kProtoSPDY31);
2353 static std::vector<uint8_t> serialized =
2354 SSLClientSocket::SerializeNextProtos(next_protos, true);
2355 ASSERT_EQ(18u, serialized.size());
2356 EXPECT_EQ(8, serialized[0]); // length("http/1.1")
2357 EXPECT_EQ('h', serialized[1]);
2358 EXPECT_EQ('t', serialized[2]);
2359 EXPECT_EQ('t', serialized[3]);
2360 EXPECT_EQ('p', serialized[4]);
2361 EXPECT_EQ('/', serialized[5]);
2362 EXPECT_EQ('1', serialized[6]);
2363 EXPECT_EQ('.', serialized[7]);
2364 EXPECT_EQ('1', serialized[8]);
2365 EXPECT_EQ(8, serialized[9]); // length("spdy/3.1")
2366 EXPECT_EQ('s', serialized[10]);
2367 EXPECT_EQ('p', serialized[11]);
2368 EXPECT_EQ('d', serialized[12]);
2369 EXPECT_EQ('y', serialized[13]);
2370 EXPECT_EQ('/', serialized[14]);
2371 EXPECT_EQ('3', serialized[15]);
2372 EXPECT_EQ('.', serialized[16]);
2373 EXPECT_EQ('1', serialized[17]);
2376 // Test that the server certificates are properly retrieved from the underlying
2377 // SSL stack.
2378 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2379 // The connection does not have to be successful.
2380 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2382 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2383 // This makes the server present redundant-server-chain.pem, which contains
2384 // intermediate certificates.
2385 SpawnedTestServer::SSLOptions ssl_options(
2386 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2387 SpawnedTestServer test_server(
2388 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2389 ASSERT_TRUE(test_server.Start());
2391 AddressList addr;
2392 ASSERT_TRUE(test_server.GetAddressList(&addr));
2394 TestCompletionCallback callback;
2395 scoped_ptr<StreamSocket> transport(
2396 new TCPClientSocket(addr, NULL, NetLog::Source()));
2397 int rv = transport->Connect(callback.callback());
2398 rv = callback.GetResult(rv);
2399 EXPECT_EQ(OK, rv);
2401 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2402 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2403 EXPECT_FALSE(sock->IsConnected());
2404 rv = sock->Connect(callback.callback());
2405 rv = callback.GetResult(rv);
2407 EXPECT_EQ(ERR_CERT_INVALID, rv);
2408 EXPECT_TRUE(sock->IsConnected());
2410 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2411 // certs from redundant-server-chain.pem.
2412 CertificateList server_certs =
2413 CreateCertificateListFromFile(GetTestCertsDirectory(),
2414 "redundant-server-chain.pem",
2415 X509Certificate::FORMAT_AUTO);
2417 // Get the server certificate as received client side.
2418 SSLInfo ssl_info;
2419 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2420 scoped_refptr<X509Certificate> server_certificate = ssl_info.unverified_cert;
2422 // Get the intermediates as received client side.
2423 const X509Certificate::OSCertHandles& server_intermediates =
2424 server_certificate->GetIntermediateCertificates();
2426 // Check that the unverified server certificate chain is properly retrieved
2427 // from the underlying ssl stack.
2428 ASSERT_EQ(4U, server_certs.size());
2430 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2431 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2433 ASSERT_EQ(3U, server_intermediates.size());
2435 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2436 server_certs[1]->os_cert_handle()));
2437 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2438 server_certs[2]->os_cert_handle()));
2439 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2440 server_certs[3]->os_cert_handle()));
2442 sock->Disconnect();
2443 EXPECT_FALSE(sock->IsConnected());
2446 // This tests that SSLInfo contains a properly re-constructed certificate
2447 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2448 // verified, not the chain as served by the server. (They may be different.)
2450 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2451 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2452 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2453 // a self-signed root. Such a situation can occur when a new root (C2) is
2454 // cross-certified by an old root (D) and has two different versions of its
2455 // floating around. Servers may supply C2 as an intermediate, but the
2456 // SSLClientSocket should return the chain that was verified, from
2457 // verify_result, instead.
2458 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2459 // By default, cause the CertVerifier to treat all certificates as
2460 // expired.
2461 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2463 CertificateList unverified_certs = CreateCertificateListFromFile(
2464 GetTestCertsDirectory(), "redundant-server-chain.pem",
2465 X509Certificate::FORMAT_AUTO);
2466 ASSERT_EQ(4u, unverified_certs.size());
2468 // We will expect SSLInfo to ultimately contain this chain.
2469 CertificateList certs =
2470 CreateCertificateListFromFile(GetTestCertsDirectory(),
2471 "redundant-validated-chain.pem",
2472 X509Certificate::FORMAT_AUTO);
2473 ASSERT_EQ(3U, certs.size());
2475 X509Certificate::OSCertHandles temp_intermediates;
2476 temp_intermediates.push_back(certs[1]->os_cert_handle());
2477 temp_intermediates.push_back(certs[2]->os_cert_handle());
2479 CertVerifyResult verify_result;
2480 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2481 certs[0]->os_cert_handle(), temp_intermediates);
2483 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2484 // rather than A->B->C.
2485 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2487 // Load and install the root for the validated chain.
2488 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2489 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2490 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2491 ScopedTestRoot scoped_root(root_cert.get());
2493 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2494 SpawnedTestServer::SSLOptions ssl_options(
2495 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2496 SpawnedTestServer test_server(
2497 SpawnedTestServer::TYPE_HTTPS,
2498 ssl_options,
2499 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2500 ASSERT_TRUE(test_server.Start());
2502 AddressList addr;
2503 ASSERT_TRUE(test_server.GetAddressList(&addr));
2505 TestCompletionCallback callback;
2506 TestNetLog log;
2507 scoped_ptr<StreamSocket> transport(
2508 new TCPClientSocket(addr, &log, NetLog::Source()));
2509 int rv = transport->Connect(callback.callback());
2510 if (rv == ERR_IO_PENDING)
2511 rv = callback.WaitForResult();
2512 EXPECT_EQ(OK, rv);
2514 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2515 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2516 EXPECT_FALSE(sock->IsConnected());
2517 rv = sock->Connect(callback.callback());
2519 TestNetLogEntry::List entries;
2520 log.GetEntries(&entries);
2521 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2522 if (rv == ERR_IO_PENDING)
2523 rv = callback.WaitForResult();
2525 EXPECT_EQ(OK, rv);
2526 EXPECT_TRUE(sock->IsConnected());
2527 log.GetEntries(&entries);
2528 EXPECT_TRUE(LogContainsEndEvent(entries, -1, NetLog::TYPE_SSL_CONNECT));
2530 SSLInfo ssl_info;
2531 sock->GetSSLInfo(&ssl_info);
2533 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2534 // -> C2.
2535 const X509Certificate::OSCertHandles& intermediates =
2536 ssl_info.cert->GetIntermediateCertificates();
2537 ASSERT_EQ(2U, intermediates.size());
2538 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2539 certs[0]->os_cert_handle()));
2540 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2541 certs[1]->os_cert_handle()));
2542 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2543 certs[2]->os_cert_handle()));
2545 // Verify that SSLInfo also contains the chain as received from the server.
2546 const X509Certificate::OSCertHandles& served_intermediates =
2547 ssl_info.unverified_cert->GetIntermediateCertificates();
2548 ASSERT_EQ(3U, served_intermediates.size());
2549 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2550 ssl_info.cert->os_cert_handle(), unverified_certs[0]->os_cert_handle()));
2551 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2552 served_intermediates[0], unverified_certs[1]->os_cert_handle()));
2553 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2554 served_intermediates[1], unverified_certs[2]->os_cert_handle()));
2555 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2556 served_intermediates[2], unverified_certs[3]->os_cert_handle()));
2558 sock->Disconnect();
2559 EXPECT_FALSE(sock->IsConnected());
2562 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2563 SpawnedTestServer::SSLOptions ssl_options;
2564 ssl_options.request_client_certificate = true;
2565 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2566 ASSERT_TRUE(request_info.get());
2567 EXPECT_EQ(0u, request_info->cert_authorities.size());
2570 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2571 const base::FilePath::CharType kThawteFile[] =
2572 FILE_PATH_LITERAL("thawte.single.pem");
2573 const unsigned char kThawteDN[] = {
2574 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2575 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2576 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2577 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2578 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2579 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2580 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2581 const size_t kThawteLen = sizeof(kThawteDN);
2583 const base::FilePath::CharType kDiginotarFile[] =
2584 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2585 const unsigned char kDiginotarDN[] = {
2586 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2587 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2588 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2589 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2590 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2591 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2592 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2593 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2594 0x6c};
2595 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2597 SpawnedTestServer::SSLOptions ssl_options;
2598 ssl_options.request_client_certificate = true;
2599 ssl_options.client_authorities.push_back(
2600 GetTestClientCertsDirectory().Append(kThawteFile));
2601 ssl_options.client_authorities.push_back(
2602 GetTestClientCertsDirectory().Append(kDiginotarFile));
2603 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2604 ASSERT_TRUE(request_info.get());
2605 ASSERT_EQ(2u, request_info->cert_authorities.size());
2606 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2607 request_info->cert_authorities[0]);
2608 EXPECT_EQ(
2609 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2610 request_info->cert_authorities[1]);
2613 // cert_key_types is currently only populated on OpenSSL.
2614 #if defined(USE_OPENSSL)
2615 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2616 SpawnedTestServer::SSLOptions ssl_options;
2617 ssl_options.request_client_certificate = true;
2618 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2619 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2620 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2621 ASSERT_TRUE(request_info.get());
2622 ASSERT_EQ(2u, request_info->cert_key_types.size());
2623 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2624 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2626 #endif // defined(USE_OPENSSL)
2628 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2629 SpawnedTestServer::SSLOptions ssl_options;
2630 ssl_options.signed_cert_timestamps_tls_ext = "test";
2632 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2633 ssl_options,
2634 base::FilePath());
2635 ASSERT_TRUE(test_server.Start());
2637 AddressList addr;
2638 ASSERT_TRUE(test_server.GetAddressList(&addr));
2640 TestCompletionCallback callback;
2641 scoped_ptr<StreamSocket> transport(
2642 new TCPClientSocket(addr, &log_, NetLog::Source()));
2643 int rv = callback.GetResult(transport->Connect(callback.callback()));
2644 EXPECT_EQ(OK, rv);
2646 SSLConfig ssl_config;
2647 ssl_config.signed_cert_timestamps_enabled = true;
2649 MockCTVerifier ct_verifier;
2650 SetCTVerifier(&ct_verifier);
2652 // Check that the SCT list is extracted as expected.
2653 EXPECT_CALL(ct_verifier, Verify(_, "", "test", _, _)).WillRepeatedly(
2654 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2656 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2657 transport.Pass(), test_server.host_port_pair(), ssl_config));
2658 rv = callback.GetResult(sock->Connect(callback.callback()));
2659 EXPECT_EQ(OK, rv);
2661 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2664 namespace {
2666 bool IsValidOCSPResponse(const base::StringPiece& input) {
2667 base::StringPiece ocsp_response = input;
2668 base::StringPiece sequence, response_status, response_bytes;
2669 return asn1::GetElement(&ocsp_response, asn1::kSEQUENCE, &sequence) &&
2670 ocsp_response.empty() &&
2671 asn1::GetElement(&sequence, asn1::kENUMERATED, &response_status) &&
2672 asn1::GetElement(&sequence,
2673 asn1::kContextSpecific | asn1::kConstructed | 0,
2674 &response_status) &&
2675 sequence.empty();
2678 } // namespace
2680 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2681 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2682 SpawnedTestServer::SSLOptions ssl_options;
2683 ssl_options.staple_ocsp_response = true;
2684 // The test server currently only knows how to generate OCSP responses
2685 // for a freshly minted certificate.
2686 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2688 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2689 ssl_options,
2690 base::FilePath());
2691 ASSERT_TRUE(test_server.Start());
2693 AddressList addr;
2694 ASSERT_TRUE(test_server.GetAddressList(&addr));
2696 TestCompletionCallback callback;
2697 scoped_ptr<StreamSocket> transport(
2698 new TCPClientSocket(addr, &log_, NetLog::Source()));
2699 int rv = callback.GetResult(transport->Connect(callback.callback()));
2700 EXPECT_EQ(OK, rv);
2702 SSLConfig ssl_config;
2703 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2704 // Certificate Transparency verification regardless of whether the platform
2705 // is able to process the OCSP status itself.
2706 ssl_config.signed_cert_timestamps_enabled = true;
2708 MockCTVerifier ct_verifier;
2709 SetCTVerifier(&ct_verifier);
2711 // Check that the OCSP response is extracted and well-formed. It should be the
2712 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2713 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2714 // particular, it should not include the overall two-byte length prefix from
2715 // TLS.
2716 EXPECT_CALL(ct_verifier,
2717 Verify(_, Truly(IsValidOCSPResponse), "", _, _)).WillRepeatedly(
2718 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2720 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2721 transport.Pass(), test_server.host_port_pair(), ssl_config));
2722 rv = callback.GetResult(sock->Connect(callback.callback()));
2723 EXPECT_EQ(OK, rv);
2725 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2728 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2729 SpawnedTestServer::SSLOptions ssl_options;
2730 ssl_options.signed_cert_timestamps_tls_ext = "test";
2732 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2733 ssl_options,
2734 base::FilePath());
2735 ASSERT_TRUE(test_server.Start());
2737 AddressList addr;
2738 ASSERT_TRUE(test_server.GetAddressList(&addr));
2740 TestCompletionCallback callback;
2741 scoped_ptr<StreamSocket> transport(
2742 new TCPClientSocket(addr, &log_, NetLog::Source()));
2743 int rv = callback.GetResult(transport->Connect(callback.callback()));
2744 EXPECT_EQ(OK, rv);
2746 SSLConfig ssl_config;
2747 ssl_config.signed_cert_timestamps_enabled = false;
2749 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2750 transport.Pass(), test_server.host_port_pair(), ssl_config));
2751 rv = callback.GetResult(sock->Connect(callback.callback()));
2752 EXPECT_EQ(OK, rv);
2754 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2757 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2758 TEST_F(SSLClientSocketTest, ReuseStates) {
2759 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2760 SpawnedTestServer::kLocalhost,
2761 base::FilePath());
2762 ASSERT_TRUE(test_server.Start());
2764 AddressList addr;
2765 ASSERT_TRUE(test_server.GetAddressList(&addr));
2767 TestCompletionCallback callback;
2768 scoped_ptr<StreamSocket> transport(
2769 new TCPClientSocket(addr, NULL, NetLog::Source()));
2770 int rv = transport->Connect(callback.callback());
2771 if (rv == ERR_IO_PENDING)
2772 rv = callback.WaitForResult();
2773 EXPECT_EQ(OK, rv);
2775 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2776 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2778 rv = sock->Connect(callback.callback());
2779 if (rv == ERR_IO_PENDING)
2780 rv = callback.WaitForResult();
2781 EXPECT_EQ(OK, rv);
2783 // The socket was just connected. It should be idle because it is speaking
2784 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2785 // returns false.
2786 EXPECT_TRUE(sock->IsConnected());
2787 EXPECT_TRUE(sock->IsConnectedAndIdle());
2788 EXPECT_FALSE(sock->WasEverUsed());
2790 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2791 const size_t kRequestLen = arraysize(kRequestText) - 1;
2792 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2793 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2795 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2796 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2798 if (rv == ERR_IO_PENDING)
2799 rv = callback.WaitForResult();
2800 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2802 // The socket has now been used.
2803 EXPECT_TRUE(sock->WasEverUsed());
2805 // TODO(davidben): Read one byte to ensure the test server has responded and
2806 // then assert IsConnectedAndIdle is false. This currently doesn't work
2807 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2808 // SSL implementation's internal buffers. Either call PR_Available and
2809 // SSL_pending, although the former isn't actually implemented or perhaps
2810 // attempt to read one byte extra.
2813 // Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
2814 // been flushed completely out of SSLClientSocket's internal buffers. This is a
2815 // regression test for https://crbug.com/466147.
2816 TEST_F(SSLClientSocketTest, ReusableAfterWrite) {
2817 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2818 SpawnedTestServer::kLocalhost,
2819 base::FilePath());
2820 ASSERT_TRUE(test_server.Start());
2822 AddressList addr;
2823 ASSERT_TRUE(test_server.GetAddressList(&addr));
2825 TestCompletionCallback callback;
2826 scoped_ptr<StreamSocket> real_transport(
2827 new TCPClientSocket(addr, NULL, NetLog::Source()));
2828 scoped_ptr<FakeBlockingStreamSocket> transport(
2829 new FakeBlockingStreamSocket(real_transport.Pass()));
2830 FakeBlockingStreamSocket* raw_transport = transport.get();
2831 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2833 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2834 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2835 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2837 // Block any application data from reaching the network.
2838 raw_transport->BlockWrite();
2840 // Write a partial HTTP request.
2841 const char kRequestText[] = "GET / HTTP/1.0";
2842 const size_t kRequestLen = arraysize(kRequestText) - 1;
2843 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2844 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2846 // Although transport writes are blocked, both SSLClientSocketOpenSSL and
2847 // SSLClientSocketNSS complete the outer Write operation.
2848 EXPECT_EQ(static_cast<int>(kRequestLen),
2849 callback.GetResult(sock->Write(request_buffer.get(), kRequestLen,
2850 callback.callback())));
2852 // The Write operation is complete, so the socket should be treated as
2853 // reusable, in case the server returns an HTTP response before completely
2854 // consuming the request body. In this case, we assume the server will
2855 // properly drain the request body before trying to read the next request.
2856 EXPECT_TRUE(sock->IsConnectedAndIdle());
2859 // Tests that basic session resumption works.
2860 TEST_F(SSLClientSocketTest, SessionResumption) {
2861 SpawnedTestServer::SSLOptions ssl_options;
2862 ASSERT_TRUE(StartTestServer(ssl_options));
2864 // First, perform a full handshake.
2865 SSLConfig ssl_config;
2866 TestCompletionCallback callback;
2867 scoped_ptr<StreamSocket> transport(
2868 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2869 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2870 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2871 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2872 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2873 SSLInfo ssl_info;
2874 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2875 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2877 // The next connection should resume.
2878 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2879 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2880 sock = CreateSSLClientSocket(transport.Pass(),
2881 test_server()->host_port_pair(), ssl_config);
2882 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2883 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2884 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2886 // Using a different HostPortPair uses a different session cache key.
2887 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2888 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2889 sock = CreateSSLClientSocket(transport.Pass(),
2890 HostPortPair("example.com", 443), ssl_config);
2891 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2892 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2893 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2895 SSLClientSocket::ClearSessionCache();
2897 // After clearing the session cache, the next handshake doesn't resume.
2898 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2899 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2900 sock = CreateSSLClientSocket(transport.Pass(),
2901 test_server()->host_port_pair(), ssl_config);
2902 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2903 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2904 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2907 // Tests that connections with certificate errors do not add entries to the
2908 // session cache.
2909 TEST_F(SSLClientSocketTest, CertificateErrorNoResume) {
2910 SpawnedTestServer::SSLOptions ssl_options;
2911 ASSERT_TRUE(StartTestServer(ssl_options));
2913 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
2915 SSLConfig ssl_config;
2916 TestCompletionCallback callback;
2917 scoped_ptr<StreamSocket> transport(
2918 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2919 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2920 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2921 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2922 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID,
2923 callback.GetResult(sock->Connect(callback.callback())));
2925 cert_verifier_->set_default_result(OK);
2927 // The next connection should perform a full handshake.
2928 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2929 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2930 sock = CreateSSLClientSocket(transport.Pass(),
2931 test_server()->host_port_pair(), ssl_config);
2932 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2933 SSLInfo ssl_info;
2934 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2935 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2938 // Tests that session caches are sharded by max_version.
2939 TEST_F(SSLClientSocketTest, FallbackShardSessionCache) {
2940 SpawnedTestServer::SSLOptions ssl_options;
2941 ASSERT_TRUE(StartTestServer(ssl_options));
2943 // Prepare a normal and fallback SSL config.
2944 SSLConfig ssl_config;
2945 SSLConfig fallback_ssl_config;
2946 fallback_ssl_config.version_max = SSL_PROTOCOL_VERSION_TLS1;
2947 fallback_ssl_config.version_fallback_min = SSL_PROTOCOL_VERSION_TLS1;
2948 fallback_ssl_config.version_fallback = true;
2950 // Connect with a fallback config from the test server to add an entry to the
2951 // session cache.
2952 TestCompletionCallback callback;
2953 scoped_ptr<StreamSocket> transport(
2954 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2955 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2956 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2957 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config));
2958 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2959 SSLInfo ssl_info;
2960 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2961 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2962 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
2963 SSLConnectionStatusToVersion(ssl_info.connection_status));
2965 // A non-fallback connection needs a full handshake.
2966 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2967 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2968 sock = CreateSSLClientSocket(transport.Pass(),
2969 test_server()->host_port_pair(), ssl_config);
2970 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2971 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2972 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2973 // This does not check for equality because TLS 1.2 support is conditional on
2974 // system NSS features.
2975 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
2976 SSLConnectionStatusToVersion(ssl_info.connection_status));
2978 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2979 // 1.2, the above test would not be sufficient to prove the session caches are
2980 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2981 // attempt to resume with two more connections.
2983 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2984 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2985 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2986 sock = CreateSSLClientSocket(transport.Pass(),
2987 test_server()->host_port_pair(), ssl_config);
2988 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2989 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2990 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2991 // This does not check for equality because TLS 1.2 support is conditional on
2992 // system NSS features.
2993 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
2994 SSLConnectionStatusToVersion(ssl_info.connection_status));
2996 // The fallback connection still resumes from its session cache. It cannot
2997 // offer the > TLS 1.0 session, so this must have been the session from the
2998 // first fallback connection.
2999 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3000 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3001 sock = CreateSSLClientSocket(
3002 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config);
3003 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3004 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3005 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3006 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
3007 SSLConnectionStatusToVersion(ssl_info.connection_status));
3010 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
3011 TEST_F(SSLClientSocketTest, DeprecatedRC4) {
3012 SpawnedTestServer::SSLOptions ssl_options;
3013 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
3014 ASSERT_TRUE(StartTestServer(ssl_options));
3016 // Normal handshakes with RC4 do not work.
3017 SSLConfig ssl_config;
3018 TestCompletionCallback callback;
3019 scoped_ptr<StreamSocket> transport(
3020 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3021 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3022 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
3023 transport.Pass(), test_server()->host_port_pair(), ssl_config));
3024 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH,
3025 callback.GetResult(sock->Connect(callback.callback())));
3027 // Enabling deprecated ciphers works fine.
3028 ssl_config.enable_deprecated_cipher_suites = true;
3029 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3030 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3031 sock = CreateSSLClientSocket(transport.Pass(),
3032 test_server()->host_port_pair(), ssl_config);
3033 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3036 // Tests that enabling deprecated ciphers shards the session cache.
3037 TEST_F(SSLClientSocketTest, DeprecatedShardSessionCache) {
3038 SpawnedTestServer::SSLOptions ssl_options;
3039 ASSERT_TRUE(StartTestServer(ssl_options));
3041 // Prepare a normal and deprecated SSL config.
3042 SSLConfig ssl_config;
3043 SSLConfig deprecated_ssl_config;
3044 deprecated_ssl_config.enable_deprecated_cipher_suites = true;
3046 // Connect with deprecated ciphers enabled to warm the session cache cache.
3047 TestCompletionCallback callback;
3048 scoped_ptr<StreamSocket> transport(
3049 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3050 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3051 scoped_ptr<SSLClientSocket> sock(
3052 CreateSSLClientSocket(transport.Pass(), test_server()->host_port_pair(),
3053 deprecated_ssl_config));
3054 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3055 SSLInfo ssl_info;
3056 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3057 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3059 // Test that re-connecting with deprecated ciphers enabled still resumes.
3060 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3061 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3062 sock = CreateSSLClientSocket(
3063 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3064 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3065 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3066 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3068 // However, a normal connection needs a full handshake.
3069 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3070 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3071 sock = CreateSSLClientSocket(transport.Pass(),
3072 test_server()->host_port_pair(), ssl_config);
3073 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3074 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3075 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3077 // Clear the session cache for the inverse test.
3078 SSLClientSocket::ClearSessionCache();
3080 // Now make a normal connection to prime the session cache.
3081 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3082 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3083 sock = CreateSSLClientSocket(transport.Pass(),
3084 test_server()->host_port_pair(), ssl_config);
3085 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3086 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3087 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3089 // A normal connection should be able to resume.
3090 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3091 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3092 sock = CreateSSLClientSocket(transport.Pass(),
3093 test_server()->host_port_pair(), ssl_config);
3094 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3095 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3096 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3098 // However, enabling deprecated ciphers connects fresh.
3099 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3100 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3101 sock = CreateSSLClientSocket(
3102 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3103 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3104 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3105 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3108 TEST_F(SSLClientSocketTest, RequireECDHE) {
3109 // Run test server without ECDHE.
3110 SpawnedTestServer::SSLOptions ssl_options;
3111 ssl_options.key_exchanges = SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
3112 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS, ssl_options,
3113 base::FilePath());
3114 ASSERT_TRUE(test_server.Start());
3116 AddressList addr;
3117 ASSERT_TRUE(test_server.GetAddressList(&addr));
3119 TestCompletionCallback callback;
3120 TestNetLog log;
3121 scoped_ptr<StreamSocket> transport(
3122 new TCPClientSocket(addr, &log, NetLog::Source()));
3123 int rv = transport->Connect(callback.callback());
3124 rv = callback.GetResult(rv);
3125 EXPECT_EQ(OK, rv);
3127 SSLConfig config;
3128 config.require_ecdhe = true;
3130 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
3131 transport.Pass(), test_server.host_port_pair(), config));
3133 rv = sock->Connect(callback.callback());
3134 rv = callback.GetResult(rv);
3136 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, rv);
3139 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
3140 if (!SupportsAESGCM()) {
3141 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3142 return;
3145 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
3146 SpawnedTestServer::SSLOptions server_options;
3147 server_options.key_exchanges =
3148 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3149 server_options.bulk_ciphers =
3150 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3151 server_options.enable_npn = true;
3152 SSLConfig client_config;
3153 client_config.next_protos.push_back(kProtoHTTP11);
3154 ASSERT_NO_FATAL_FAILURE(
3155 TestFalseStart(server_options, client_config, true));
3158 // Test that False Start is disabled without NPN.
3159 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
3160 if (!SupportsAESGCM()) {
3161 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3162 return;
3165 SpawnedTestServer::SSLOptions server_options;
3166 server_options.key_exchanges =
3167 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3168 server_options.bulk_ciphers =
3169 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3170 SSLConfig client_config;
3171 client_config.next_protos.clear();
3172 ASSERT_NO_FATAL_FAILURE(
3173 TestFalseStart(server_options, client_config, false));
3176 // Test that False Start is disabled with plain RSA ciphers.
3177 TEST_F(SSLClientSocketFalseStartTest, RSA) {
3178 if (!SupportsAESGCM()) {
3179 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3180 return;
3183 SpawnedTestServer::SSLOptions server_options;
3184 server_options.key_exchanges =
3185 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_RSA;
3186 server_options.bulk_ciphers =
3187 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3188 server_options.enable_npn = true;
3189 SSLConfig client_config;
3190 client_config.next_protos.push_back(kProtoHTTP11);
3191 ASSERT_NO_FATAL_FAILURE(
3192 TestFalseStart(server_options, client_config, false));
3195 // Test that False Start is disabled with DHE_RSA ciphers.
3196 TEST_F(SSLClientSocketFalseStartTest, DHE_RSA) {
3197 if (!SupportsAESGCM()) {
3198 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3199 return;
3202 SpawnedTestServer::SSLOptions server_options;
3203 server_options.key_exchanges =
3204 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
3205 server_options.bulk_ciphers =
3206 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3207 server_options.enable_npn = true;
3208 SSLConfig client_config;
3209 client_config.next_protos.push_back(kProtoHTTP11);
3210 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3213 // Test that False Start is disabled without an AEAD.
3214 TEST_F(SSLClientSocketFalseStartTest, NoAEAD) {
3215 SpawnedTestServer::SSLOptions server_options;
3216 server_options.key_exchanges =
3217 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3218 server_options.bulk_ciphers =
3219 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
3220 server_options.enable_npn = true;
3221 SSLConfig client_config;
3222 client_config.next_protos.push_back(kProtoHTTP11);
3223 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3226 // Test that sessions are resumable after receiving the server Finished message.
3227 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
3228 if (!SupportsAESGCM()) {
3229 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3230 return;
3233 // Start a server.
3234 SpawnedTestServer::SSLOptions server_options;
3235 server_options.key_exchanges =
3236 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3237 server_options.bulk_ciphers =
3238 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3239 server_options.enable_npn = true;
3240 SSLConfig client_config;
3241 client_config.next_protos.push_back(kProtoHTTP11);
3243 // Let a full handshake complete with False Start.
3244 ASSERT_NO_FATAL_FAILURE(
3245 TestFalseStart(server_options, client_config, true));
3247 // Make a second connection.
3248 TestCompletionCallback callback;
3249 scoped_ptr<StreamSocket> transport2(
3250 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3251 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3252 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3253 transport2.Pass(), test_server()->host_port_pair(), client_config);
3254 ASSERT_TRUE(sock2.get());
3255 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3257 // It should resume the session.
3258 SSLInfo ssl_info;
3259 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3260 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3263 // Test that False Started sessions are not resumable before receiving the
3264 // server Finished message.
3265 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinished) {
3266 if (!SupportsAESGCM()) {
3267 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3268 return;
3271 // Start a server.
3272 SpawnedTestServer::SSLOptions server_options;
3273 server_options.key_exchanges =
3274 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3275 server_options.bulk_ciphers =
3276 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3277 server_options.enable_npn = true;
3278 ASSERT_TRUE(StartTestServer(server_options));
3280 SSLConfig client_config;
3281 client_config.next_protos.push_back(kProtoHTTP11);
3283 // Start a handshake up to the server Finished message.
3284 TestCompletionCallback callback;
3285 FakeBlockingStreamSocket* raw_transport1 = NULL;
3286 scoped_ptr<SSLClientSocket> sock1;
3287 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3288 client_config, &callback, &raw_transport1, &sock1));
3289 // Although raw_transport1 has the server Finished blocked, the handshake
3290 // still completes.
3291 EXPECT_EQ(OK, callback.WaitForResult());
3293 // Continue to block the client (|sock1|) from processing the Finished
3294 // message, but allow it to arrive on the socket. This ensures that, from the
3295 // server's point of view, it has completed the handshake and added the
3296 // session to its session cache.
3298 // The actual read on |sock1| will not complete until the Finished message is
3299 // processed; however, pump the underlying transport so that it is read from
3300 // the socket. NOTE: This may flakily pass if the server's final flight
3301 // doesn't come in one Read.
3302 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3303 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3304 EXPECT_EQ(ERR_IO_PENDING, rv);
3305 raw_transport1->WaitForReadResult();
3307 // Drop the old socket. This is needed because the Python test server can't
3308 // service two sockets in parallel.
3309 sock1.reset();
3311 // Start a second connection.
3312 scoped_ptr<StreamSocket> transport2(
3313 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3314 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3315 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3316 transport2.Pass(), test_server()->host_port_pair(), client_config);
3317 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3319 // No session resumption because the first connection never received a server
3320 // Finished message.
3321 SSLInfo ssl_info;
3322 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3323 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3326 // Test that False Started sessions are not resumable if the server Finished
3327 // message was bad.
3328 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBadFinished) {
3329 if (!SupportsAESGCM()) {
3330 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3331 return;
3334 // Start a server.
3335 SpawnedTestServer::SSLOptions server_options;
3336 server_options.key_exchanges =
3337 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3338 server_options.bulk_ciphers =
3339 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3340 server_options.enable_npn = true;
3341 ASSERT_TRUE(StartTestServer(server_options));
3343 SSLConfig client_config;
3344 client_config.next_protos.push_back(kProtoHTTP11);
3346 // Start a handshake up to the server Finished message.
3347 TestCompletionCallback callback;
3348 FakeBlockingStreamSocket* raw_transport1 = NULL;
3349 scoped_ptr<SSLClientSocket> sock1;
3350 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3351 client_config, &callback, &raw_transport1, &sock1));
3352 // Although raw_transport1 has the server Finished blocked, the handshake
3353 // still completes.
3354 EXPECT_EQ(OK, callback.WaitForResult());
3356 // Continue to block the client (|sock1|) from processing the Finished
3357 // message, but allow it to arrive on the socket. This ensures that, from the
3358 // server's point of view, it has completed the handshake and added the
3359 // session to its session cache.
3361 // The actual read on |sock1| will not complete until the Finished message is
3362 // processed; however, pump the underlying transport so that it is read from
3363 // the socket.
3364 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3365 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3366 EXPECT_EQ(ERR_IO_PENDING, rv);
3367 raw_transport1->WaitForReadResult();
3369 // The server's second leg, or part of it, is now received but not yet sent to
3370 // |sock1|. Before doing so, break the server's second leg.
3371 int bytes_read = raw_transport1->pending_read_result();
3372 ASSERT_LT(0, bytes_read);
3373 raw_transport1->pending_read_buf()->data()[bytes_read - 1]++;
3375 // Unblock the Finished message. |sock1->Read| should now fail.
3376 raw_transport1->UnblockReadResult();
3377 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(rv));
3379 // Drop the old socket. This is needed because the Python test server can't
3380 // service two sockets in parallel.
3381 sock1.reset();
3383 // Start a second connection.
3384 scoped_ptr<StreamSocket> transport2(
3385 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3386 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3387 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3388 transport2.Pass(), test_server()->host_port_pair(), client_config);
3389 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3391 // No session resumption because the first connection never received a server
3392 // Finished message.
3393 SSLInfo ssl_info;
3394 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3395 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3398 // Connect to a server using channel id. It should allow the connection.
3399 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
3400 SpawnedTestServer::SSLOptions ssl_options;
3402 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3404 EnableChannelID();
3405 SSLConfig ssl_config;
3406 ssl_config.channel_id_enabled = true;
3408 int rv;
3409 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3411 EXPECT_EQ(OK, rv);
3412 EXPECT_TRUE(sock_->IsConnected());
3413 SSLInfo ssl_info;
3414 ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
3415 EXPECT_TRUE(ssl_info.channel_id_sent);
3417 sock_->Disconnect();
3418 EXPECT_FALSE(sock_->IsConnected());
3421 // Connect to a server using Channel ID but failing to look up the Channel
3422 // ID. It should fail.
3423 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
3424 SpawnedTestServer::SSLOptions ssl_options;
3426 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3428 EnableFailingChannelID();
3429 SSLConfig ssl_config;
3430 ssl_config.channel_id_enabled = true;
3432 int rv;
3433 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3435 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3436 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3437 // error codes for now.
3438 // http://crbug.com/373670
3439 EXPECT_NE(OK, rv);
3440 EXPECT_FALSE(sock_->IsConnected());
3443 // Connect to a server using Channel ID but asynchronously failing to look up
3444 // the Channel ID. It should fail.
3445 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
3446 SpawnedTestServer::SSLOptions ssl_options;
3448 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3450 EnableAsyncFailingChannelID();
3451 SSLConfig ssl_config;
3452 ssl_config.channel_id_enabled = true;
3454 int rv;
3455 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3457 EXPECT_EQ(ERR_UNEXPECTED, rv);
3458 EXPECT_FALSE(sock_->IsConnected());
3461 } // namespace net