Material throbber: use in tabstrip
[chromium-blink-merge.git] / net / socket / ssl_client_socket_unittest.cc
blob9b90ae8915ffcc98b65a2fad87c8bbf3b1861756
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/socket/ssl_client_socket.h"
7 #include "base/callback_helpers.h"
8 #include "base/memory/ref_counted.h"
9 #include "base/run_loop.h"
10 #include "base/time/time.h"
11 #include "net/base/address_list.h"
12 #include "net/base/io_buffer.h"
13 #include "net/base/net_errors.h"
14 #include "net/base/test_completion_callback.h"
15 #include "net/base/test_data_directory.h"
16 #include "net/cert/asn1_util.h"
17 #include "net/cert/ct_verifier.h"
18 #include "net/cert/mock_cert_verifier.h"
19 #include "net/cert/test_root_certs.h"
20 #include "net/dns/host_resolver.h"
21 #include "net/http/transport_security_state.h"
22 #include "net/log/captured_net_log_entry.h"
23 #include "net/log/net_log.h"
24 #include "net/log/net_log_unittest.h"
25 #include "net/log/test_net_log.h"
26 #include "net/socket/client_socket_factory.h"
27 #include "net/socket/client_socket_handle.h"
28 #include "net/socket/socket_test_util.h"
29 #include "net/socket/tcp_client_socket.h"
30 #include "net/ssl/channel_id_service.h"
31 #include "net/ssl/default_channel_id_store.h"
32 #include "net/ssl/ssl_cert_request_info.h"
33 #include "net/ssl/ssl_config_service.h"
34 #include "net/ssl/ssl_connection_status_flags.h"
35 #include "net/ssl/ssl_info.h"
36 #include "net/test/cert_test_util.h"
37 #include "net/test/spawned_test_server/spawned_test_server.h"
38 #include "testing/gmock/include/gmock/gmock.h"
39 #include "testing/gtest/include/gtest/gtest.h"
40 #include "testing/platform_test.h"
42 #if !defined(USE_OPENSSL)
43 #include <pk11pub.h>
44 #include "crypto/nss_util.h"
46 #if !defined(CKM_AES_GCM)
47 #define CKM_AES_GCM 0x00001087
48 #endif
50 #if !defined(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256)
51 #define CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256 (CKM_NSS + 24)
52 #endif
53 #endif
55 //-----------------------------------------------------------------------------
57 using testing::_;
58 using testing::Return;
59 using testing::Truly;
61 namespace net {
63 namespace {
65 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
66 // forwarding the Socket and StreamSocket interfaces to the underlying
67 // transport.
68 // This is to provide a common base class for subclasses to override specific
69 // StreamSocket methods for testing, while still communicating with a 'real'
70 // StreamSocket.
71 class WrappedStreamSocket : public StreamSocket {
72 public:
73 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
74 : transport_(transport.Pass()) {}
75 ~WrappedStreamSocket() override {}
77 // StreamSocket implementation:
78 int Connect(const CompletionCallback& callback) override {
79 return transport_->Connect(callback);
81 void Disconnect() override { transport_->Disconnect(); }
82 bool IsConnected() const override { return transport_->IsConnected(); }
83 bool IsConnectedAndIdle() const override {
84 return transport_->IsConnectedAndIdle();
86 int GetPeerAddress(IPEndPoint* address) const override {
87 return transport_->GetPeerAddress(address);
89 int GetLocalAddress(IPEndPoint* address) const override {
90 return transport_->GetLocalAddress(address);
92 const BoundNetLog& NetLog() const override { return transport_->NetLog(); }
93 void SetSubresourceSpeculation() override {
94 transport_->SetSubresourceSpeculation();
96 void SetOmniboxSpeculation() override { transport_->SetOmniboxSpeculation(); }
97 bool WasEverUsed() const override { return transport_->WasEverUsed(); }
98 bool UsingTCPFastOpen() const override {
99 return transport_->UsingTCPFastOpen();
101 bool WasNpnNegotiated() const override {
102 return transport_->WasNpnNegotiated();
104 NextProto GetNegotiatedProtocol() const override {
105 return transport_->GetNegotiatedProtocol();
107 bool GetSSLInfo(SSLInfo* ssl_info) override {
108 return transport_->GetSSLInfo(ssl_info);
111 // Socket implementation:
112 int Read(IOBuffer* buf,
113 int buf_len,
114 const CompletionCallback& callback) override {
115 return transport_->Read(buf, buf_len, callback);
117 int Write(IOBuffer* buf,
118 int buf_len,
119 const CompletionCallback& callback) override {
120 return transport_->Write(buf, buf_len, callback);
122 int SetReceiveBufferSize(int32 size) override {
123 return transport_->SetReceiveBufferSize(size);
125 int SetSendBufferSize(int32 size) override {
126 return transport_->SetSendBufferSize(size);
129 protected:
130 scoped_ptr<StreamSocket> transport_;
133 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
134 // will ensure a certain amount of data is internally buffered before
135 // satisfying a Read() request. It exists to mimic OS-level internal
136 // buffering, but in a way to guarantee that X number of bytes will be
137 // returned to callers of Read(), regardless of how quickly the OS receives
138 // them from the TestServer.
139 class ReadBufferingStreamSocket : public WrappedStreamSocket {
140 public:
141 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
142 ~ReadBufferingStreamSocket() override {}
144 // Socket implementation:
145 int Read(IOBuffer* buf,
146 int buf_len,
147 const CompletionCallback& callback) override;
149 // Sets the internal buffer to |size|. This must not be greater than
150 // the largest value supplied to Read() - that is, it does not handle
151 // having "leftovers" at the end of Read().
152 // Each call to Read() will be prevented from completion until at least
153 // |size| data has been read.
154 // Set to 0 to turn off buffering, causing Read() to transparently
155 // read via the underlying transport.
156 void SetBufferSize(int size);
158 private:
159 enum State {
160 STATE_NONE,
161 STATE_READ,
162 STATE_READ_COMPLETE,
165 int DoLoop(int result);
166 int DoRead();
167 int DoReadComplete(int result);
168 void OnReadCompleted(int result);
170 State state_;
171 scoped_refptr<GrowableIOBuffer> read_buffer_;
172 int buffer_size_;
174 scoped_refptr<IOBuffer> user_read_buf_;
175 CompletionCallback user_read_callback_;
178 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
179 scoped_ptr<StreamSocket> transport)
180 : WrappedStreamSocket(transport.Pass()),
181 read_buffer_(new GrowableIOBuffer()),
182 buffer_size_(0) {}
184 void ReadBufferingStreamSocket::SetBufferSize(int size) {
185 DCHECK(!user_read_buf_.get());
186 buffer_size_ = size;
187 read_buffer_->SetCapacity(size);
190 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
191 int buf_len,
192 const CompletionCallback& callback) {
193 if (buffer_size_ == 0)
194 return transport_->Read(buf, buf_len, callback);
196 if (buf_len < buffer_size_)
197 return ERR_UNEXPECTED;
199 state_ = STATE_READ;
200 user_read_buf_ = buf;
201 int result = DoLoop(OK);
202 if (result == ERR_IO_PENDING)
203 user_read_callback_ = callback;
204 else
205 user_read_buf_ = NULL;
206 return result;
209 int ReadBufferingStreamSocket::DoLoop(int result) {
210 int rv = result;
211 do {
212 State current_state = state_;
213 state_ = STATE_NONE;
214 switch (current_state) {
215 case STATE_READ:
216 rv = DoRead();
217 break;
218 case STATE_READ_COMPLETE:
219 rv = DoReadComplete(rv);
220 break;
221 case STATE_NONE:
222 default:
223 NOTREACHED() << "Unexpected state: " << current_state;
224 rv = ERR_UNEXPECTED;
225 break;
227 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
228 return rv;
231 int ReadBufferingStreamSocket::DoRead() {
232 state_ = STATE_READ_COMPLETE;
233 int rv =
234 transport_->Read(read_buffer_.get(),
235 read_buffer_->RemainingCapacity(),
236 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
237 base::Unretained(this)));
238 return rv;
241 int ReadBufferingStreamSocket::DoReadComplete(int result) {
242 state_ = STATE_NONE;
243 if (result <= 0)
244 return result;
246 read_buffer_->set_offset(read_buffer_->offset() + result);
247 if (read_buffer_->RemainingCapacity() > 0) {
248 state_ = STATE_READ;
249 return OK;
252 memcpy(user_read_buf_->data(),
253 read_buffer_->StartOfBuffer(),
254 read_buffer_->capacity());
255 read_buffer_->set_offset(0);
256 return read_buffer_->capacity();
259 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
260 result = DoLoop(result);
261 if (result == ERR_IO_PENDING)
262 return;
264 user_read_buf_ = NULL;
265 base::ResetAndReturn(&user_read_callback_).Run(result);
268 // Simulates synchronously receiving an error during Read() or Write()
269 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
270 public:
271 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
272 ~SynchronousErrorStreamSocket() override {}
274 // Socket implementation:
275 int Read(IOBuffer* buf,
276 int buf_len,
277 const CompletionCallback& callback) override;
278 int Write(IOBuffer* buf,
279 int buf_len,
280 const CompletionCallback& callback) override;
282 // Sets the next Read() call and all future calls to return |error|.
283 // If there is already a pending asynchronous read, the configured error
284 // will not be returned until that asynchronous read has completed and Read()
285 // is called again.
286 void SetNextReadError(int error) {
287 DCHECK_GE(0, error);
288 have_read_error_ = true;
289 pending_read_error_ = error;
292 // Sets the next Write() call and all future calls to return |error|.
293 // If there is already a pending asynchronous write, the configured error
294 // will not be returned until that asynchronous write has completed and
295 // Write() is called again.
296 void SetNextWriteError(int error) {
297 DCHECK_GE(0, error);
298 have_write_error_ = true;
299 pending_write_error_ = error;
302 private:
303 bool have_read_error_;
304 int pending_read_error_;
306 bool have_write_error_;
307 int pending_write_error_;
309 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
312 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
313 scoped_ptr<StreamSocket> transport)
314 : WrappedStreamSocket(transport.Pass()),
315 have_read_error_(false),
316 pending_read_error_(OK),
317 have_write_error_(false),
318 pending_write_error_(OK) {}
320 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
321 int buf_len,
322 const CompletionCallback& callback) {
323 if (have_read_error_)
324 return pending_read_error_;
325 return transport_->Read(buf, buf_len, callback);
328 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
329 int buf_len,
330 const CompletionCallback& callback) {
331 if (have_write_error_)
332 return pending_write_error_;
333 return transport_->Write(buf, buf_len, callback);
336 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
337 // underlying transport needing to complete things asynchronously in a
338 // deterministic manner (e.g.: independent of the TestServer and the OS's
339 // semantics).
340 class FakeBlockingStreamSocket : public WrappedStreamSocket {
341 public:
342 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
343 ~FakeBlockingStreamSocket() override {}
345 // Socket implementation:
346 int Read(IOBuffer* buf,
347 int buf_len,
348 const CompletionCallback& callback) override;
349 int Write(IOBuffer* buf,
350 int buf_len,
351 const CompletionCallback& callback) override;
353 int pending_read_result() const { return pending_read_result_; }
354 IOBuffer* pending_read_buf() const { return pending_read_buf_.get(); }
356 // Blocks read results on the socket. Reads will not complete until
357 // UnblockReadResult() has been called and a result is ready from the
358 // underlying transport. Note: if BlockReadResult() is called while there is a
359 // hanging asynchronous Read(), that Read is blocked.
360 void BlockReadResult();
361 void UnblockReadResult();
363 // Waits for the blocked Read() call to be complete at the underlying
364 // transport.
365 void WaitForReadResult();
367 // Causes the next call to Write() to return ERR_IO_PENDING, not beginning the
368 // underlying transport until UnblockWrite() has been called. Note: if there
369 // is a pending asynchronous write, it is NOT blocked. For purposes of
370 // blocking writes, data is considered to have reached the underlying
371 // transport as soon as Write() is called.
372 void BlockWrite();
373 void UnblockWrite();
375 // Waits for the blocked Write() call to be scheduled.
376 void WaitForWrite();
378 private:
379 // Handles completion from the underlying transport read.
380 void OnReadCompleted(int result);
382 // True if read callbacks are blocked.
383 bool should_block_read_;
385 // The buffer for the pending read, or NULL if not consumed.
386 scoped_refptr<IOBuffer> pending_read_buf_;
388 // The user callback for the pending read call.
389 CompletionCallback pending_read_callback_;
391 // The result for the blocked read callback, or ERR_IO_PENDING if not
392 // completed.
393 int pending_read_result_;
395 // WaitForReadResult() wait loop.
396 scoped_ptr<base::RunLoop> read_loop_;
398 // True if write calls are blocked.
399 bool should_block_write_;
401 // The buffer for the pending write, or NULL if not scheduled.
402 scoped_refptr<IOBuffer> pending_write_buf_;
404 // The callback for the pending write call.
405 CompletionCallback pending_write_callback_;
407 // The length for the pending write, or -1 if not scheduled.
408 int pending_write_len_;
410 // WaitForWrite() wait loop.
411 scoped_ptr<base::RunLoop> write_loop_;
414 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
415 scoped_ptr<StreamSocket> transport)
416 : WrappedStreamSocket(transport.Pass()),
417 should_block_read_(false),
418 pending_read_result_(ERR_IO_PENDING),
419 should_block_write_(false),
420 pending_write_len_(-1) {}
422 int FakeBlockingStreamSocket::Read(IOBuffer* buf,
423 int len,
424 const CompletionCallback& callback) {
425 DCHECK(!pending_read_buf_);
426 DCHECK(pending_read_callback_.is_null());
427 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
428 DCHECK(!callback.is_null());
430 int rv = transport_->Read(buf, len, base::Bind(
431 &FakeBlockingStreamSocket::OnReadCompleted, base::Unretained(this)));
432 if (rv == ERR_IO_PENDING) {
433 // Save the callback to be called later.
434 pending_read_buf_ = buf;
435 pending_read_callback_ = callback;
436 } else if (should_block_read_) {
437 // Save the callback and read result to be called later.
438 pending_read_buf_ = buf;
439 pending_read_callback_ = callback;
440 OnReadCompleted(rv);
441 rv = ERR_IO_PENDING;
443 return rv;
446 int FakeBlockingStreamSocket::Write(IOBuffer* buf,
447 int len,
448 const CompletionCallback& callback) {
449 DCHECK(buf);
450 DCHECK_LE(0, len);
452 if (!should_block_write_)
453 return transport_->Write(buf, len, callback);
455 // Schedule the write, but do nothing.
456 DCHECK(!pending_write_buf_.get());
457 DCHECK_EQ(-1, pending_write_len_);
458 DCHECK(pending_write_callback_.is_null());
459 DCHECK(!callback.is_null());
460 pending_write_buf_ = buf;
461 pending_write_len_ = len;
462 pending_write_callback_ = callback;
464 // Stop the write loop, if any.
465 if (write_loop_)
466 write_loop_->Quit();
467 return ERR_IO_PENDING;
470 void FakeBlockingStreamSocket::BlockReadResult() {
471 DCHECK(!should_block_read_);
472 should_block_read_ = true;
475 void FakeBlockingStreamSocket::UnblockReadResult() {
476 DCHECK(should_block_read_);
477 should_block_read_ = false;
479 // If the operation is still pending in the underlying transport, immediately
480 // return - OnReadCompleted() will handle invoking the callback once the
481 // transport has completed.
482 if (pending_read_result_ == ERR_IO_PENDING)
483 return;
484 int result = pending_read_result_;
485 pending_read_buf_ = nullptr;
486 pending_read_result_ = ERR_IO_PENDING;
487 base::ResetAndReturn(&pending_read_callback_).Run(result);
490 void FakeBlockingStreamSocket::WaitForReadResult() {
491 DCHECK(should_block_read_);
492 DCHECK(!read_loop_);
494 if (pending_read_result_ != ERR_IO_PENDING)
495 return;
496 read_loop_.reset(new base::RunLoop);
497 read_loop_->Run();
498 read_loop_.reset();
499 DCHECK_NE(ERR_IO_PENDING, pending_read_result_);
502 void FakeBlockingStreamSocket::BlockWrite() {
503 DCHECK(!should_block_write_);
504 should_block_write_ = true;
507 void FakeBlockingStreamSocket::UnblockWrite() {
508 DCHECK(should_block_write_);
509 should_block_write_ = false;
511 // Do nothing if UnblockWrite() was called after BlockWrite(),
512 // without a Write() in between.
513 if (!pending_write_buf_.get())
514 return;
516 int rv = transport_->Write(
517 pending_write_buf_.get(), pending_write_len_, pending_write_callback_);
518 pending_write_buf_ = NULL;
519 pending_write_len_ = -1;
520 if (rv == ERR_IO_PENDING) {
521 pending_write_callback_.Reset();
522 } else {
523 base::ResetAndReturn(&pending_write_callback_).Run(rv);
527 void FakeBlockingStreamSocket::WaitForWrite() {
528 DCHECK(should_block_write_);
529 DCHECK(!write_loop_);
531 if (pending_write_buf_.get())
532 return;
533 write_loop_.reset(new base::RunLoop);
534 write_loop_->Run();
535 write_loop_.reset();
536 DCHECK(pending_write_buf_.get());
539 void FakeBlockingStreamSocket::OnReadCompleted(int result) {
540 DCHECK_EQ(ERR_IO_PENDING, pending_read_result_);
541 DCHECK(!pending_read_callback_.is_null());
543 if (should_block_read_) {
544 // Store the result so that the callback can be invoked once Unblock() is
545 // called.
546 pending_read_result_ = result;
548 // Stop the WaitForReadResult() call if any.
549 if (read_loop_)
550 read_loop_->Quit();
551 } else {
552 // Either the Read() was never blocked or UnblockReadResult() was called
553 // before the Read() completed. Either way, return the result to the caller.
554 pending_read_buf_ = nullptr;
555 base::ResetAndReturn(&pending_read_callback_).Run(result);
559 // CountingStreamSocket wraps an existing StreamSocket and maintains a count of
560 // reads and writes on the socket.
561 class CountingStreamSocket : public WrappedStreamSocket {
562 public:
563 explicit CountingStreamSocket(scoped_ptr<StreamSocket> transport)
564 : WrappedStreamSocket(transport.Pass()),
565 read_count_(0),
566 write_count_(0) {}
567 ~CountingStreamSocket() override {}
569 // Socket implementation:
570 int Read(IOBuffer* buf,
571 int buf_len,
572 const CompletionCallback& callback) override {
573 read_count_++;
574 return transport_->Read(buf, buf_len, callback);
576 int Write(IOBuffer* buf,
577 int buf_len,
578 const CompletionCallback& callback) override {
579 write_count_++;
580 return transport_->Write(buf, buf_len, callback);
583 int read_count() const { return read_count_; }
584 int write_count() const { return write_count_; }
586 private:
587 int read_count_;
588 int write_count_;
591 // CompletionCallback that will delete the associated StreamSocket when
592 // the callback is invoked.
593 class DeleteSocketCallback : public TestCompletionCallbackBase {
594 public:
595 explicit DeleteSocketCallback(StreamSocket* socket)
596 : socket_(socket),
597 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
598 base::Unretained(this))) {}
599 ~DeleteSocketCallback() override {}
601 const CompletionCallback& callback() const { return callback_; }
603 private:
604 void OnComplete(int result) {
605 if (socket_) {
606 delete socket_;
607 socket_ = NULL;
608 } else {
609 ADD_FAILURE() << "Deleting socket twice";
611 SetResult(result);
614 StreamSocket* socket_;
615 CompletionCallback callback_;
617 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
620 // A ChannelIDStore that always returns an error when asked for a
621 // channel id.
622 class FailingChannelIDStore : public ChannelIDStore {
623 int GetChannelID(const std::string& server_identifier,
624 base::Time* expiration_time,
625 std::string* private_key_result,
626 std::string* cert_result,
627 const GetChannelIDCallback& callback) override {
628 return ERR_UNEXPECTED;
630 void SetChannelID(const std::string& server_identifier,
631 base::Time creation_time,
632 base::Time expiration_time,
633 const std::string& private_key,
634 const std::string& cert) override {}
635 void DeleteChannelID(const std::string& server_identifier,
636 const base::Closure& completion_callback) override {}
637 void DeleteAllCreatedBetween(
638 base::Time delete_begin,
639 base::Time delete_end,
640 const base::Closure& completion_callback) override {}
641 void DeleteAll(const base::Closure& completion_callback) override {}
642 void GetAllChannelIDs(const GetChannelIDListCallback& callback) override {}
643 int GetChannelIDCount() override { return 0; }
644 void SetForceKeepSessionState() override {}
647 // A ChannelIDStore that asynchronously returns an error when asked for a
648 // channel id.
649 class AsyncFailingChannelIDStore : public ChannelIDStore {
650 int GetChannelID(const std::string& server_identifier,
651 base::Time* expiration_time,
652 std::string* private_key_result,
653 std::string* cert_result,
654 const GetChannelIDCallback& callback) override {
655 base::MessageLoop::current()->PostTask(
656 FROM_HERE, base::Bind(callback, ERR_UNEXPECTED,
657 server_identifier, base::Time(), "", ""));
658 return ERR_IO_PENDING;
660 void SetChannelID(const std::string& server_identifier,
661 base::Time creation_time,
662 base::Time expiration_time,
663 const std::string& private_key,
664 const std::string& cert) 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(
943 new ChannelIDService(new DefaultChannelIDStore(NULL),
944 base::MessageLoopProxy::current()));
945 context_.channel_id_service = channel_id_service_.get();
948 void EnableFailingChannelID() {
949 channel_id_service_.reset(new ChannelIDService(
950 new FailingChannelIDStore(), base::MessageLoopProxy::current()));
951 context_.channel_id_service = channel_id_service_.get();
954 void EnableAsyncFailingChannelID() {
955 channel_id_service_.reset(new ChannelIDService(
956 new AsyncFailingChannelIDStore(),
957 base::MessageLoopProxy::current()));
958 context_.channel_id_service = channel_id_service_.get();
961 private:
962 scoped_ptr<ChannelIDService> channel_id_service_;
965 //-----------------------------------------------------------------------------
967 // LogContainsSSLConnectEndEvent returns true if the given index in the given
968 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
969 // merge the first application data record with the Finished message when false
970 // starting. However, in order to avoid the server timing out the handshake,
971 // they'll give up waiting for application data and send the Finished after a
972 // timeout. This means that an SSL connect end event may appear as a socket
973 // write.
974 static bool LogContainsSSLConnectEndEvent(const CapturedNetLogEntry::List& log,
975 int i) {
976 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
977 LogContainsEvent(
978 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
981 bool SupportsAESGCM() {
982 #if defined(USE_OPENSSL)
983 return true;
984 #else
985 crypto::EnsureNSSInit();
986 return PK11_TokenExists(CKM_AES_GCM) &&
987 PK11_TokenExists(CKM_NSS_TLS_MASTER_KEY_DERIVE_DH_SHA256);
988 #endif
991 } // namespace
993 TEST_F(SSLClientSocketTest, Connect) {
994 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
995 SpawnedTestServer::kLocalhost,
996 base::FilePath());
997 ASSERT_TRUE(test_server.Start());
999 AddressList addr;
1000 ASSERT_TRUE(test_server.GetAddressList(&addr));
1002 TestCompletionCallback callback;
1003 TestNetLog log;
1004 scoped_ptr<StreamSocket> transport(
1005 new TCPClientSocket(addr, &log, NetLog::Source()));
1006 int rv = transport->Connect(callback.callback());
1007 if (rv == ERR_IO_PENDING)
1008 rv = callback.WaitForResult();
1009 EXPECT_EQ(OK, rv);
1011 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1012 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1014 EXPECT_FALSE(sock->IsConnected());
1016 rv = sock->Connect(callback.callback());
1018 CapturedNetLogEntry::List entries;
1019 log.GetEntries(&entries);
1020 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1021 if (rv == ERR_IO_PENDING)
1022 rv = callback.WaitForResult();
1023 EXPECT_EQ(OK, rv);
1024 EXPECT_TRUE(sock->IsConnected());
1025 log.GetEntries(&entries);
1026 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1028 sock->Disconnect();
1029 EXPECT_FALSE(sock->IsConnected());
1032 TEST_F(SSLClientSocketTest, ConnectExpired) {
1033 SpawnedTestServer::SSLOptions ssl_options(
1034 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
1035 SpawnedTestServer test_server(
1036 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1037 ASSERT_TRUE(test_server.Start());
1039 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1041 AddressList addr;
1042 ASSERT_TRUE(test_server.GetAddressList(&addr));
1044 TestCompletionCallback callback;
1045 TestNetLog log;
1046 scoped_ptr<StreamSocket> transport(
1047 new TCPClientSocket(addr, &log, NetLog::Source()));
1048 int rv = transport->Connect(callback.callback());
1049 if (rv == ERR_IO_PENDING)
1050 rv = callback.WaitForResult();
1051 EXPECT_EQ(OK, rv);
1053 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1054 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1056 EXPECT_FALSE(sock->IsConnected());
1058 rv = sock->Connect(callback.callback());
1060 CapturedNetLogEntry::List entries;
1061 log.GetEntries(&entries);
1062 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1063 if (rv == ERR_IO_PENDING)
1064 rv = callback.WaitForResult();
1066 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
1068 // Rather than testing whether or not the underlying socket is connected,
1069 // test that the handshake has finished. This is because it may be
1070 // desirable to disconnect the socket before showing a user prompt, since
1071 // the user may take indefinitely long to respond.
1072 log.GetEntries(&entries);
1073 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1076 TEST_F(SSLClientSocketTest, ConnectMismatched) {
1077 SpawnedTestServer::SSLOptions ssl_options(
1078 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
1079 SpawnedTestServer test_server(
1080 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1081 ASSERT_TRUE(test_server.Start());
1083 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
1085 AddressList addr;
1086 ASSERT_TRUE(test_server.GetAddressList(&addr));
1088 TestCompletionCallback callback;
1089 TestNetLog log;
1090 scoped_ptr<StreamSocket> transport(
1091 new TCPClientSocket(addr, &log, NetLog::Source()));
1092 int rv = transport->Connect(callback.callback());
1093 if (rv == ERR_IO_PENDING)
1094 rv = callback.WaitForResult();
1095 EXPECT_EQ(OK, rv);
1097 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1098 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1100 EXPECT_FALSE(sock->IsConnected());
1102 rv = sock->Connect(callback.callback());
1104 CapturedNetLogEntry::List entries;
1105 log.GetEntries(&entries);
1106 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1107 if (rv == ERR_IO_PENDING)
1108 rv = callback.WaitForResult();
1110 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
1112 // Rather than testing whether or not the underlying socket is connected,
1113 // test that the handshake has finished. This is because it may be
1114 // desirable to disconnect the socket before showing a user prompt, since
1115 // the user may take indefinitely long to respond.
1116 log.GetEntries(&entries);
1117 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1120 // Attempt to connect to a page which requests a client certificate. It should
1121 // return an error code on connect.
1122 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
1123 SpawnedTestServer::SSLOptions ssl_options;
1124 ssl_options.request_client_certificate = true;
1125 SpawnedTestServer test_server(
1126 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1127 ASSERT_TRUE(test_server.Start());
1129 AddressList addr;
1130 ASSERT_TRUE(test_server.GetAddressList(&addr));
1132 TestCompletionCallback callback;
1133 TestNetLog log;
1134 scoped_ptr<StreamSocket> transport(
1135 new TCPClientSocket(addr, &log, NetLog::Source()));
1136 int rv = transport->Connect(callback.callback());
1137 if (rv == ERR_IO_PENDING)
1138 rv = callback.WaitForResult();
1139 EXPECT_EQ(OK, rv);
1141 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1142 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1144 EXPECT_FALSE(sock->IsConnected());
1146 rv = sock->Connect(callback.callback());
1148 CapturedNetLogEntry::List entries;
1149 log.GetEntries(&entries);
1150 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1151 if (rv == ERR_IO_PENDING)
1152 rv = callback.WaitForResult();
1154 log.GetEntries(&entries);
1155 // Because we prematurely kill the handshake at CertificateRequest,
1156 // the server may still send data (notably the ServerHelloDone)
1157 // after the error is returned. As a result, the SSL_CONNECT may not
1158 // be the last entry. See http://crbug.com/54445. We use
1159 // ExpectLogContainsSomewhere instead of
1160 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
1161 // extra read instead of two. This occurs before the handshake ends,
1162 // so the corking logic of LogContainsSSLConnectEndEvent isn't
1163 // necessary.
1165 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
1166 // fixed and we can respond to the first CertificateRequest
1167 // without closing the socket, add a unit test for sending the
1168 // certificate. This test may still be useful as we'll want to close
1169 // the socket on a timeout if the user takes a long time to pick a
1170 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
1171 ExpectLogContainsSomewhere(
1172 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
1173 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
1174 EXPECT_FALSE(sock->IsConnected());
1177 // Connect to a server requesting optional client authentication. Send it a
1178 // null certificate. It should allow the connection.
1180 // TODO(davidben): Also test providing an actual certificate.
1181 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
1182 SpawnedTestServer::SSLOptions ssl_options;
1183 ssl_options.request_client_certificate = true;
1184 SpawnedTestServer test_server(
1185 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1186 ASSERT_TRUE(test_server.Start());
1188 AddressList addr;
1189 ASSERT_TRUE(test_server.GetAddressList(&addr));
1191 TestCompletionCallback callback;
1192 TestNetLog log;
1193 scoped_ptr<StreamSocket> transport(
1194 new TCPClientSocket(addr, &log, NetLog::Source()));
1195 int rv = transport->Connect(callback.callback());
1196 if (rv == ERR_IO_PENDING)
1197 rv = callback.WaitForResult();
1198 EXPECT_EQ(OK, rv);
1200 SSLConfig ssl_config;
1201 ssl_config.send_client_cert = true;
1202 ssl_config.client_cert = NULL;
1204 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1205 transport.Pass(), test_server.host_port_pair(), ssl_config));
1207 EXPECT_FALSE(sock->IsConnected());
1209 // Our test server accepts certificate-less connections.
1210 // TODO(davidben): Add a test which requires them and verify the error.
1211 rv = sock->Connect(callback.callback());
1213 CapturedNetLogEntry::List entries;
1214 log.GetEntries(&entries);
1215 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1216 if (rv == ERR_IO_PENDING)
1217 rv = callback.WaitForResult();
1219 EXPECT_EQ(OK, rv);
1220 EXPECT_TRUE(sock->IsConnected());
1221 log.GetEntries(&entries);
1222 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1224 // We responded to the server's certificate request with a Certificate
1225 // message with no client certificate in it. ssl_info.client_cert_sent
1226 // should be false in this case.
1227 SSLInfo ssl_info;
1228 sock->GetSSLInfo(&ssl_info);
1229 EXPECT_FALSE(ssl_info.client_cert_sent);
1231 sock->Disconnect();
1232 EXPECT_FALSE(sock->IsConnected());
1235 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
1236 // - Server closes an SSL connection (with a close_notify alert message).
1237 // - Server closes the underlying TCP connection directly.
1238 // - Server sends data unexpectedly.
1240 // Tests that the socket can be read from successfully. Also test that a peer's
1241 // close_notify alert is successfully processed without error.
1242 TEST_F(SSLClientSocketTest, Read) {
1243 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1244 SpawnedTestServer::kLocalhost,
1245 base::FilePath());
1246 ASSERT_TRUE(test_server.Start());
1248 AddressList addr;
1249 ASSERT_TRUE(test_server.GetAddressList(&addr));
1251 TestCompletionCallback callback;
1252 scoped_ptr<StreamSocket> transport(
1253 new TCPClientSocket(addr, NULL, NetLog::Source()));
1254 int rv = transport->Connect(callback.callback());
1255 if (rv == ERR_IO_PENDING)
1256 rv = callback.WaitForResult();
1257 EXPECT_EQ(OK, rv);
1259 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1260 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1262 rv = sock->Connect(callback.callback());
1263 if (rv == ERR_IO_PENDING)
1264 rv = callback.WaitForResult();
1265 EXPECT_EQ(OK, rv);
1266 EXPECT_TRUE(sock->IsConnected());
1268 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1269 scoped_refptr<IOBuffer> request_buffer(
1270 new IOBuffer(arraysize(request_text) - 1));
1271 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1273 rv = sock->Write(
1274 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1275 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1277 if (rv == ERR_IO_PENDING)
1278 rv = callback.WaitForResult();
1279 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1281 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1282 for (;;) {
1283 rv = sock->Read(buf.get(), 4096, callback.callback());
1284 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1286 if (rv == ERR_IO_PENDING)
1287 rv = callback.WaitForResult();
1289 EXPECT_GE(rv, 0);
1290 if (rv <= 0)
1291 break;
1294 // The peer should have cleanly closed the connection with a close_notify.
1295 EXPECT_EQ(0, rv);
1298 // Tests that SSLClientSocket properly handles when the underlying transport
1299 // synchronously fails a transport read in during the handshake. The error code
1300 // should be preserved so SSLv3 fallback logic can condition on it.
1301 TEST_F(SSLClientSocketTest, Connect_WithSynchronousError) {
1302 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1303 SpawnedTestServer::kLocalhost,
1304 base::FilePath());
1305 ASSERT_TRUE(test_server.Start());
1307 AddressList addr;
1308 ASSERT_TRUE(test_server.GetAddressList(&addr));
1310 TestCompletionCallback callback;
1311 scoped_ptr<StreamSocket> real_transport(
1312 new TCPClientSocket(addr, NULL, NetLog::Source()));
1313 scoped_ptr<SynchronousErrorStreamSocket> transport(
1314 new SynchronousErrorStreamSocket(real_transport.Pass()));
1315 int rv = callback.GetResult(transport->Connect(callback.callback()));
1316 EXPECT_EQ(OK, rv);
1318 // Disable TLS False Start to avoid handshake non-determinism.
1319 SSLConfig ssl_config;
1320 ssl_config.false_start_enabled = false;
1322 SynchronousErrorStreamSocket* raw_transport = transport.get();
1323 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1324 transport.Pass(), test_server.host_port_pair(), ssl_config));
1326 raw_transport->SetNextWriteError(ERR_CONNECTION_RESET);
1328 rv = callback.GetResult(sock->Connect(callback.callback()));
1329 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1330 EXPECT_FALSE(sock->IsConnected());
1333 // Tests that the SSLClientSocket properly handles when the underlying transport
1334 // synchronously returns an error code - such as if an intermediary terminates
1335 // the socket connection uncleanly.
1336 // This is a regression test for http://crbug.com/238536
1337 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
1338 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1339 SpawnedTestServer::kLocalhost,
1340 base::FilePath());
1341 ASSERT_TRUE(test_server.Start());
1343 AddressList addr;
1344 ASSERT_TRUE(test_server.GetAddressList(&addr));
1346 TestCompletionCallback callback;
1347 scoped_ptr<StreamSocket> real_transport(
1348 new TCPClientSocket(addr, NULL, NetLog::Source()));
1349 scoped_ptr<SynchronousErrorStreamSocket> transport(
1350 new SynchronousErrorStreamSocket(real_transport.Pass()));
1351 int rv = callback.GetResult(transport->Connect(callback.callback()));
1352 EXPECT_EQ(OK, rv);
1354 // Disable TLS False Start to avoid handshake non-determinism.
1355 SSLConfig ssl_config;
1356 ssl_config.false_start_enabled = false;
1358 SynchronousErrorStreamSocket* raw_transport = transport.get();
1359 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1360 transport.Pass(), test_server.host_port_pair(), ssl_config));
1362 rv = callback.GetResult(sock->Connect(callback.callback()));
1363 EXPECT_EQ(OK, rv);
1364 EXPECT_TRUE(sock->IsConnected());
1366 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1367 static const int kRequestTextSize =
1368 static_cast<int>(arraysize(request_text) - 1);
1369 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1370 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1372 rv = callback.GetResult(
1373 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1374 EXPECT_EQ(kRequestTextSize, rv);
1376 // Simulate an unclean/forcible shutdown.
1377 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
1379 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1381 // Note: This test will hang if this bug has regressed. Simply checking that
1382 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
1383 // result when using a dedicated task runner for NSS.
1384 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1385 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1388 // Tests that the SSLClientSocket properly handles when the underlying transport
1389 // asynchronously returns an error code while writing data - such as if an
1390 // intermediary terminates the socket connection uncleanly.
1391 // This is a regression test for http://crbug.com/249848
1392 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
1393 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1394 SpawnedTestServer::kLocalhost,
1395 base::FilePath());
1396 ASSERT_TRUE(test_server.Start());
1398 AddressList addr;
1399 ASSERT_TRUE(test_server.GetAddressList(&addr));
1401 TestCompletionCallback callback;
1402 scoped_ptr<StreamSocket> real_transport(
1403 new TCPClientSocket(addr, NULL, NetLog::Source()));
1404 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1405 // is retained in order to configure additional errors.
1406 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1407 new SynchronousErrorStreamSocket(real_transport.Pass()));
1408 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1409 scoped_ptr<FakeBlockingStreamSocket> transport(
1410 new FakeBlockingStreamSocket(error_socket.Pass()));
1411 FakeBlockingStreamSocket* raw_transport = transport.get();
1412 int rv = callback.GetResult(transport->Connect(callback.callback()));
1413 EXPECT_EQ(OK, rv);
1415 // Disable TLS False Start to avoid handshake non-determinism.
1416 SSLConfig ssl_config;
1417 ssl_config.false_start_enabled = false;
1419 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1420 transport.Pass(), test_server.host_port_pair(), ssl_config));
1422 rv = callback.GetResult(sock->Connect(callback.callback()));
1423 EXPECT_EQ(OK, rv);
1424 EXPECT_TRUE(sock->IsConnected());
1426 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1427 static const int kRequestTextSize =
1428 static_cast<int>(arraysize(request_text) - 1);
1429 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1430 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1432 // Simulate an unclean/forcible shutdown on the underlying socket.
1433 // However, simulate this error asynchronously.
1434 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1435 raw_transport->BlockWrite();
1437 // This write should complete synchronously, because the TLS ciphertext
1438 // can be created and placed into the outgoing buffers independent of the
1439 // underlying transport.
1440 rv = callback.GetResult(
1441 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1442 EXPECT_EQ(kRequestTextSize, rv);
1444 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1446 rv = sock->Read(buf.get(), 4096, callback.callback());
1447 EXPECT_EQ(ERR_IO_PENDING, rv);
1449 // Now unblock the outgoing request, having it fail with the connection
1450 // being reset.
1451 raw_transport->UnblockWrite();
1453 // Note: This will cause an inifite loop if this bug has regressed. Simply
1454 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1455 // is a legitimate result when using a dedicated task runner for NSS.
1456 rv = callback.GetResult(rv);
1457 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1460 // If there is a Write failure at the transport with no follow-up Read, although
1461 // the write error will not be returned to the client until a future Read or
1462 // Write operation, SSLClientSocket should not spin attempting to re-write on
1463 // the socket. This is a regression test for part of https://crbug.com/381160.
1464 TEST_F(SSLClientSocketTest, Write_WithSynchronousErrorNoRead) {
1465 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1466 SpawnedTestServer::kLocalhost,
1467 base::FilePath());
1468 ASSERT_TRUE(test_server.Start());
1470 AddressList addr;
1471 ASSERT_TRUE(test_server.GetAddressList(&addr));
1473 TestCompletionCallback callback;
1474 scoped_ptr<StreamSocket> real_transport(
1475 new TCPClientSocket(addr, NULL, NetLog::Source()));
1476 // Note: intermediate sockets' ownership are handed to |sock|, but a pointer
1477 // is retained in order to query them.
1478 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1479 new SynchronousErrorStreamSocket(real_transport.Pass()));
1480 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1481 scoped_ptr<CountingStreamSocket> counting_socket(
1482 new CountingStreamSocket(error_socket.Pass()));
1483 CountingStreamSocket* raw_counting_socket = counting_socket.get();
1484 int rv = callback.GetResult(counting_socket->Connect(callback.callback()));
1485 ASSERT_EQ(OK, rv);
1487 // Disable TLS False Start to avoid handshake non-determinism.
1488 SSLConfig ssl_config;
1489 ssl_config.false_start_enabled = false;
1491 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1492 counting_socket.Pass(), test_server.host_port_pair(), ssl_config));
1494 rv = callback.GetResult(sock->Connect(callback.callback()));
1495 ASSERT_EQ(OK, rv);
1496 ASSERT_TRUE(sock->IsConnected());
1498 // Simulate an unclean/forcible shutdown on the underlying socket.
1499 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1501 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1502 static const int kRequestTextSize =
1503 static_cast<int>(arraysize(request_text) - 1);
1504 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1505 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1507 // This write should complete synchronously, because the TLS ciphertext
1508 // can be created and placed into the outgoing buffers independent of the
1509 // underlying transport.
1510 rv = callback.GetResult(
1511 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1512 ASSERT_EQ(kRequestTextSize, rv);
1514 // Let the event loop spin for a little bit of time. Even on platforms where
1515 // pumping the state machine involve thread hops, there should be no further
1516 // writes on the transport socket.
1518 // TODO(davidben): Avoid the arbitrary timeout?
1519 int old_write_count = raw_counting_socket->write_count();
1520 base::RunLoop loop;
1521 base::MessageLoop::current()->PostDelayedTask(
1522 FROM_HERE, loop.QuitClosure(), base::TimeDelta::FromMilliseconds(100));
1523 loop.Run();
1524 EXPECT_EQ(old_write_count, raw_counting_socket->write_count());
1527 // Test the full duplex mode, with Read and Write pending at the same time.
1528 // This test also serves as a regression test for http://crbug.com/29815.
1529 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1530 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1531 SpawnedTestServer::kLocalhost,
1532 base::FilePath());
1533 ASSERT_TRUE(test_server.Start());
1535 AddressList addr;
1536 ASSERT_TRUE(test_server.GetAddressList(&addr));
1538 TestCompletionCallback callback; // Used for everything except Write.
1540 scoped_ptr<StreamSocket> transport(
1541 new TCPClientSocket(addr, NULL, NetLog::Source()));
1542 int rv = transport->Connect(callback.callback());
1543 if (rv == ERR_IO_PENDING)
1544 rv = callback.WaitForResult();
1545 EXPECT_EQ(OK, rv);
1547 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1548 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1550 rv = sock->Connect(callback.callback());
1551 if (rv == ERR_IO_PENDING)
1552 rv = callback.WaitForResult();
1553 EXPECT_EQ(OK, rv);
1554 EXPECT_TRUE(sock->IsConnected());
1556 // Issue a "hanging" Read first.
1557 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1558 rv = sock->Read(buf.get(), 4096, callback.callback());
1559 // We haven't written the request, so there should be no response yet.
1560 ASSERT_EQ(ERR_IO_PENDING, rv);
1562 // Write the request.
1563 // The request is padded with a User-Agent header to a size that causes the
1564 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1565 // This tests the fix for http://crbug.com/29815.
1566 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1567 for (int i = 0; i < 3770; ++i)
1568 request_text.push_back('*');
1569 request_text.append("\r\n\r\n");
1570 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1572 TestCompletionCallback callback2; // Used for Write only.
1573 rv = sock->Write(
1574 request_buffer.get(), request_text.size(), callback2.callback());
1575 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1577 if (rv == ERR_IO_PENDING)
1578 rv = callback2.WaitForResult();
1579 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1581 // Now get the Read result.
1582 rv = callback.WaitForResult();
1583 EXPECT_GT(rv, 0);
1586 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1587 // mode when the underlying transport is blocked on sending data. When the
1588 // underlying transport completes due to an error, it should invoke both the
1589 // Read() and Write() callbacks. If the socket is deleted by the Read()
1590 // callback, the Write() callback should not be invoked.
1591 // Regression test for http://crbug.com/232633
1592 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1593 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1594 SpawnedTestServer::kLocalhost,
1595 base::FilePath());
1596 ASSERT_TRUE(test_server.Start());
1598 AddressList addr;
1599 ASSERT_TRUE(test_server.GetAddressList(&addr));
1601 TestCompletionCallback callback;
1602 scoped_ptr<StreamSocket> real_transport(
1603 new TCPClientSocket(addr, NULL, NetLog::Source()));
1604 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1605 // is retained in order to configure additional errors.
1606 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1607 new SynchronousErrorStreamSocket(real_transport.Pass()));
1608 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1609 scoped_ptr<FakeBlockingStreamSocket> transport(
1610 new FakeBlockingStreamSocket(error_socket.Pass()));
1611 FakeBlockingStreamSocket* raw_transport = transport.get();
1613 int rv = callback.GetResult(transport->Connect(callback.callback()));
1614 EXPECT_EQ(OK, rv);
1616 // Disable TLS False Start to avoid handshake non-determinism.
1617 SSLConfig ssl_config;
1618 ssl_config.false_start_enabled = false;
1620 scoped_ptr<SSLClientSocket> sock = CreateSSLClientSocket(
1621 transport.Pass(), test_server.host_port_pair(), ssl_config);
1623 rv = callback.GetResult(sock->Connect(callback.callback()));
1624 EXPECT_EQ(OK, rv);
1625 EXPECT_TRUE(sock->IsConnected());
1627 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1628 request_text.append(20 * 1024, '*');
1629 request_text.append("\r\n\r\n");
1630 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1631 new StringIOBuffer(request_text), request_text.size()));
1633 // Simulate errors being returned from the underlying Read() and Write() ...
1634 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1635 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1636 // ... but have those errors returned asynchronously. Because the Write() will
1637 // return first, this will trigger the error.
1638 raw_transport->BlockReadResult();
1639 raw_transport->BlockWrite();
1641 // Enqueue a Read() before calling Write(), which should "hang" due to
1642 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1643 SSLClientSocket* raw_sock = sock.get();
1644 DeleteSocketCallback read_callback(sock.release());
1645 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1646 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1648 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1649 ASSERT_EQ(ERR_IO_PENDING, rv);
1650 ASSERT_FALSE(read_callback.have_result());
1652 #if !defined(USE_OPENSSL)
1653 // NSS follows a pattern where a call to PR_Write will only consume as
1654 // much data as it can encode into application data records before the
1655 // internal memio buffer is full, which should only fill if writing a large
1656 // amount of data and the underlying transport is blocked. Once this happens,
1657 // NSS will return (total size of all application data records it wrote) - 1,
1658 // with the caller expected to resume with the remaining unsent data.
1660 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1661 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1662 // get the socket in the state needed for the test below.
1664 // This is not needed for OpenSSL, because for OpenSSL,
1665 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1666 // SSLClientSocketOpenSSL::Write() will not return until all of
1667 // |request_buffer| has been written to the underlying BIO (although not
1668 // necessarily the underlying transport).
1669 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1670 request_buffer->BytesRemaining(),
1671 callback.callback()));
1672 ASSERT_LT(0, rv);
1673 request_buffer->DidConsume(rv);
1675 // Guard to ensure that |request_buffer| was larger than all of the internal
1676 // buffers (transport, memio, NSS) along the way - otherwise the next call
1677 // to Write() will crash with an invalid buffer.
1678 ASSERT_LT(0, request_buffer->BytesRemaining());
1679 #endif
1681 // Attempt to write the remaining data. NSS will not be able to consume the
1682 // application data because the internal buffers are full, while OpenSSL will
1683 // return that its blocked because the underlying transport is blocked.
1684 rv = raw_sock->Write(request_buffer.get(),
1685 request_buffer->BytesRemaining(),
1686 callback.callback());
1687 ASSERT_EQ(ERR_IO_PENDING, rv);
1688 ASSERT_FALSE(callback.have_result());
1690 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1691 // call the Read() callback, deleting the socket and thus aborting calling
1692 // the Write() callback.
1693 raw_transport->UnblockWrite();
1695 rv = read_callback.WaitForResult();
1696 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1698 // The Write callback should not have been called.
1699 EXPECT_FALSE(callback.have_result());
1702 // Tests that the SSLClientSocket does not crash if data is received on the
1703 // transport socket after a failing write. This can occur if we have a Write
1704 // error in a SPDY socket.
1705 // Regression test for http://crbug.com/335557
1706 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1707 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1708 SpawnedTestServer::kLocalhost,
1709 base::FilePath());
1710 ASSERT_TRUE(test_server.Start());
1712 AddressList addr;
1713 ASSERT_TRUE(test_server.GetAddressList(&addr));
1715 TestCompletionCallback callback;
1716 scoped_ptr<StreamSocket> real_transport(
1717 new TCPClientSocket(addr, NULL, NetLog::Source()));
1718 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1719 // is retained in order to configure additional errors.
1720 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1721 new SynchronousErrorStreamSocket(real_transport.Pass()));
1722 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1723 scoped_ptr<FakeBlockingStreamSocket> transport(
1724 new FakeBlockingStreamSocket(error_socket.Pass()));
1725 FakeBlockingStreamSocket* raw_transport = transport.get();
1727 int rv = callback.GetResult(transport->Connect(callback.callback()));
1728 EXPECT_EQ(OK, rv);
1730 // Disable TLS False Start to avoid handshake non-determinism.
1731 SSLConfig ssl_config;
1732 ssl_config.false_start_enabled = false;
1734 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1735 transport.Pass(), test_server.host_port_pair(), ssl_config));
1737 rv = callback.GetResult(sock->Connect(callback.callback()));
1738 EXPECT_EQ(OK, rv);
1739 EXPECT_TRUE(sock->IsConnected());
1741 // Send a request so there is something to read from the socket.
1742 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1743 static const int kRequestTextSize =
1744 static_cast<int>(arraysize(request_text) - 1);
1745 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1746 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1748 rv = callback.GetResult(
1749 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1750 EXPECT_EQ(kRequestTextSize, rv);
1752 // Start a hanging read.
1753 TestCompletionCallback read_callback;
1754 raw_transport->BlockReadResult();
1755 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1756 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1757 EXPECT_EQ(ERR_IO_PENDING, rv);
1759 // Perform another write, but have it fail. Write a request larger than the
1760 // internal socket buffers so that the request hits the underlying transport
1761 // socket and detects the error.
1762 std::string long_request_text =
1763 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1764 long_request_text.append(20 * 1024, '*');
1765 long_request_text.append("\r\n\r\n");
1766 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1767 new StringIOBuffer(long_request_text), long_request_text.size()));
1769 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1771 // Write as much data as possible until hitting an error. This is necessary
1772 // for NSS. PR_Write will only consume as much data as it can encode into
1773 // application data records before the internal memio buffer is full, which
1774 // should only fill if writing a large amount of data and the underlying
1775 // transport is blocked. Once this happens, NSS will return (total size of all
1776 // application data records it wrote) - 1, with the caller expected to resume
1777 // with the remaining unsent data.
1778 do {
1779 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1780 long_request_buffer->BytesRemaining(),
1781 callback.callback()));
1782 if (rv > 0) {
1783 long_request_buffer->DidConsume(rv);
1784 // Abort if the entire buffer is ever consumed.
1785 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1787 } while (rv > 0);
1789 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1791 // Release the read.
1792 raw_transport->UnblockReadResult();
1793 rv = read_callback.WaitForResult();
1795 #if defined(USE_OPENSSL)
1796 // Should still read bytes despite the write error.
1797 EXPECT_LT(0, rv);
1798 #else
1799 // NSS attempts to flush the write buffer in PR_Read on an SSL socket before
1800 // pumping the read state machine, unless configured with SSL_ENABLE_FDX, so
1801 // the write error stops future reads.
1802 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1803 #endif
1806 // Tests that SSLClientSocket fails the handshake if the underlying
1807 // transport is cleanly closed.
1808 TEST_F(SSLClientSocketTest, Connect_WithZeroReturn) {
1809 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1810 SpawnedTestServer::kLocalhost,
1811 base::FilePath());
1812 ASSERT_TRUE(test_server.Start());
1814 AddressList addr;
1815 ASSERT_TRUE(test_server.GetAddressList(&addr));
1817 TestCompletionCallback callback;
1818 scoped_ptr<StreamSocket> real_transport(
1819 new TCPClientSocket(addr, NULL, NetLog::Source()));
1820 scoped_ptr<SynchronousErrorStreamSocket> transport(
1821 new SynchronousErrorStreamSocket(real_transport.Pass()));
1822 int rv = callback.GetResult(transport->Connect(callback.callback()));
1823 EXPECT_EQ(OK, rv);
1825 SynchronousErrorStreamSocket* raw_transport = transport.get();
1826 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1827 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1829 raw_transport->SetNextReadError(0);
1831 rv = callback.GetResult(sock->Connect(callback.callback()));
1832 EXPECT_EQ(ERR_CONNECTION_CLOSED, rv);
1833 EXPECT_FALSE(sock->IsConnected());
1836 // Tests that SSLClientSocket returns a Read of size 0 if the underlying socket
1837 // is cleanly closed, but the peer does not send close_notify.
1838 // This is a regression test for https://crbug.com/422246
1839 TEST_F(SSLClientSocketTest, Read_WithZeroReturn) {
1840 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1841 SpawnedTestServer::kLocalhost,
1842 base::FilePath());
1843 ASSERT_TRUE(test_server.Start());
1845 AddressList addr;
1846 ASSERT_TRUE(test_server.GetAddressList(&addr));
1848 TestCompletionCallback callback;
1849 scoped_ptr<StreamSocket> real_transport(
1850 new TCPClientSocket(addr, NULL, NetLog::Source()));
1851 scoped_ptr<SynchronousErrorStreamSocket> transport(
1852 new SynchronousErrorStreamSocket(real_transport.Pass()));
1853 int rv = callback.GetResult(transport->Connect(callback.callback()));
1854 EXPECT_EQ(OK, rv);
1856 // Disable TLS False Start to ensure the handshake has completed.
1857 SSLConfig ssl_config;
1858 ssl_config.false_start_enabled = false;
1860 SynchronousErrorStreamSocket* raw_transport = transport.get();
1861 scoped_ptr<SSLClientSocket> sock(
1862 CreateSSLClientSocket(transport.Pass(),
1863 test_server.host_port_pair(),
1864 ssl_config));
1866 rv = callback.GetResult(sock->Connect(callback.callback()));
1867 EXPECT_EQ(OK, rv);
1868 EXPECT_TRUE(sock->IsConnected());
1870 raw_transport->SetNextReadError(0);
1871 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1872 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
1873 EXPECT_EQ(0, rv);
1876 // Tests that SSLClientSocket cleanly returns a Read of size 0 if the
1877 // underlying socket is cleanly closed asynchronously.
1878 // This is a regression test for https://crbug.com/422246
1879 TEST_F(SSLClientSocketTest, Read_WithAsyncZeroReturn) {
1880 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1881 SpawnedTestServer::kLocalhost,
1882 base::FilePath());
1883 ASSERT_TRUE(test_server.Start());
1885 AddressList addr;
1886 ASSERT_TRUE(test_server.GetAddressList(&addr));
1888 TestCompletionCallback callback;
1889 scoped_ptr<StreamSocket> real_transport(
1890 new TCPClientSocket(addr, NULL, NetLog::Source()));
1891 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1892 new SynchronousErrorStreamSocket(real_transport.Pass()));
1893 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1894 scoped_ptr<FakeBlockingStreamSocket> transport(
1895 new FakeBlockingStreamSocket(error_socket.Pass()));
1896 FakeBlockingStreamSocket* raw_transport = transport.get();
1897 int rv = callback.GetResult(transport->Connect(callback.callback()));
1898 EXPECT_EQ(OK, rv);
1900 // Disable TLS False Start to ensure the handshake has completed.
1901 SSLConfig ssl_config;
1902 ssl_config.false_start_enabled = false;
1904 scoped_ptr<SSLClientSocket> sock(
1905 CreateSSLClientSocket(transport.Pass(),
1906 test_server.host_port_pair(),
1907 ssl_config));
1909 rv = callback.GetResult(sock->Connect(callback.callback()));
1910 EXPECT_EQ(OK, rv);
1911 EXPECT_TRUE(sock->IsConnected());
1913 raw_error_socket->SetNextReadError(0);
1914 raw_transport->BlockReadResult();
1915 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1916 rv = sock->Read(buf.get(), 4096, callback.callback());
1917 EXPECT_EQ(ERR_IO_PENDING, rv);
1919 raw_transport->UnblockReadResult();
1920 rv = callback.GetResult(rv);
1921 EXPECT_EQ(0, rv);
1924 // Tests that fatal alerts from the peer are processed. This is a regression
1925 // test for https://crbug.com/466303.
1926 TEST_F(SSLClientSocketTest, Read_WithFatalAlert) {
1927 SpawnedTestServer::SSLOptions ssl_options;
1928 ssl_options.alert_after_handshake = true;
1929 ASSERT_TRUE(StartTestServer(ssl_options));
1931 SSLConfig ssl_config;
1932 TestCompletionCallback callback;
1933 scoped_ptr<StreamSocket> transport(
1934 new TCPClientSocket(addr(), &log_, NetLog::Source()));
1935 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
1936 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1937 transport.Pass(), test_server()->host_port_pair(), ssl_config));
1938 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
1940 // Receive the fatal alert.
1941 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1942 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(sock->Read(
1943 buf.get(), 4096, callback.callback())));
1946 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1947 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1948 SpawnedTestServer::kLocalhost,
1949 base::FilePath());
1950 ASSERT_TRUE(test_server.Start());
1952 AddressList addr;
1953 ASSERT_TRUE(test_server.GetAddressList(&addr));
1955 TestCompletionCallback callback;
1956 scoped_ptr<StreamSocket> transport(
1957 new TCPClientSocket(addr, NULL, NetLog::Source()));
1958 int rv = transport->Connect(callback.callback());
1959 if (rv == ERR_IO_PENDING)
1960 rv = callback.WaitForResult();
1961 EXPECT_EQ(OK, rv);
1963 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1964 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
1966 rv = sock->Connect(callback.callback());
1967 if (rv == ERR_IO_PENDING)
1968 rv = callback.WaitForResult();
1969 EXPECT_EQ(OK, rv);
1971 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1972 scoped_refptr<IOBuffer> request_buffer(
1973 new IOBuffer(arraysize(request_text) - 1));
1974 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1976 rv = sock->Write(
1977 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1978 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1980 if (rv == ERR_IO_PENDING)
1981 rv = callback.WaitForResult();
1982 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1984 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1985 for (;;) {
1986 rv = sock->Read(buf.get(), 1, callback.callback());
1987 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1989 if (rv == ERR_IO_PENDING)
1990 rv = callback.WaitForResult();
1992 EXPECT_GE(rv, 0);
1993 if (rv <= 0)
1994 break;
1998 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1999 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2000 SpawnedTestServer::kLocalhost,
2001 base::FilePath());
2002 ASSERT_TRUE(test_server.Start());
2004 AddressList addr;
2005 ASSERT_TRUE(test_server.GetAddressList(&addr));
2007 TestCompletionCallback callback;
2009 scoped_ptr<StreamSocket> real_transport(
2010 new TCPClientSocket(addr, NULL, NetLog::Source()));
2011 scoped_ptr<ReadBufferingStreamSocket> transport(
2012 new ReadBufferingStreamSocket(real_transport.Pass()));
2013 ReadBufferingStreamSocket* raw_transport = transport.get();
2014 int rv = callback.GetResult(transport->Connect(callback.callback()));
2015 ASSERT_EQ(OK, rv);
2017 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2018 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2020 rv = callback.GetResult(sock->Connect(callback.callback()));
2021 ASSERT_EQ(OK, rv);
2022 ASSERT_TRUE(sock->IsConnected());
2024 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
2025 scoped_refptr<IOBuffer> request_buffer(
2026 new IOBuffer(arraysize(request_text) - 1));
2027 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2029 rv = callback.GetResult(sock->Write(
2030 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
2031 ASSERT_GT(rv, 0);
2032 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2034 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
2035 // data (the max SSL record size) at a time. Ensure that at least 15K worth
2036 // of SSL data is buffered first. The 15K of buffered data is made up of
2037 // many smaller SSL records (the TestServer writes along 1350 byte
2038 // plaintext boundaries), although there may also be a few records that are
2039 // smaller or larger, due to timing and SSL False Start.
2040 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
2041 // the SSLClientSocket implementation, and larger than the minimum amount
2042 // of ciphertext necessary to contain the 8K of plaintext requested below.
2043 raw_transport->SetBufferSize(15000);
2045 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
2046 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
2047 ASSERT_EQ(rv, 8192);
2050 TEST_F(SSLClientSocketTest, Read_Interrupted) {
2051 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2052 SpawnedTestServer::kLocalhost,
2053 base::FilePath());
2054 ASSERT_TRUE(test_server.Start());
2056 AddressList addr;
2057 ASSERT_TRUE(test_server.GetAddressList(&addr));
2059 TestCompletionCallback callback;
2060 scoped_ptr<StreamSocket> transport(
2061 new TCPClientSocket(addr, NULL, NetLog::Source()));
2062 int rv = transport->Connect(callback.callback());
2063 if (rv == ERR_IO_PENDING)
2064 rv = callback.WaitForResult();
2065 EXPECT_EQ(OK, rv);
2067 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2068 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2070 rv = sock->Connect(callback.callback());
2071 if (rv == ERR_IO_PENDING)
2072 rv = callback.WaitForResult();
2073 EXPECT_EQ(OK, rv);
2075 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2076 scoped_refptr<IOBuffer> request_buffer(
2077 new IOBuffer(arraysize(request_text) - 1));
2078 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2080 rv = sock->Write(
2081 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2082 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2084 if (rv == ERR_IO_PENDING)
2085 rv = callback.WaitForResult();
2086 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2088 // Do a partial read and then exit. This test should not crash!
2089 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
2090 rv = sock->Read(buf.get(), 512, callback.callback());
2091 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
2093 if (rv == ERR_IO_PENDING)
2094 rv = callback.WaitForResult();
2096 EXPECT_GT(rv, 0);
2099 TEST_F(SSLClientSocketTest, Read_FullLogging) {
2100 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2101 SpawnedTestServer::kLocalhost,
2102 base::FilePath());
2103 ASSERT_TRUE(test_server.Start());
2105 AddressList addr;
2106 ASSERT_TRUE(test_server.GetAddressList(&addr));
2108 TestCompletionCallback callback;
2109 TestNetLog log;
2110 log.SetCaptureMode(NetLogCaptureMode::IncludeSocketBytes());
2111 scoped_ptr<StreamSocket> transport(
2112 new TCPClientSocket(addr, &log, NetLog::Source()));
2113 int rv = transport->Connect(callback.callback());
2114 if (rv == ERR_IO_PENDING)
2115 rv = callback.WaitForResult();
2116 EXPECT_EQ(OK, rv);
2118 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2119 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2121 rv = sock->Connect(callback.callback());
2122 if (rv == ERR_IO_PENDING)
2123 rv = callback.WaitForResult();
2124 EXPECT_EQ(OK, rv);
2125 EXPECT_TRUE(sock->IsConnected());
2127 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
2128 scoped_refptr<IOBuffer> request_buffer(
2129 new IOBuffer(arraysize(request_text) - 1));
2130 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
2132 rv = sock->Write(
2133 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
2134 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2136 if (rv == ERR_IO_PENDING)
2137 rv = callback.WaitForResult();
2138 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
2140 CapturedNetLogEntry::List entries;
2141 log.GetEntries(&entries);
2142 size_t last_index = ExpectLogContainsSomewhereAfter(
2143 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
2145 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
2146 for (;;) {
2147 rv = sock->Read(buf.get(), 4096, callback.callback());
2148 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2150 if (rv == ERR_IO_PENDING)
2151 rv = callback.WaitForResult();
2153 EXPECT_GE(rv, 0);
2154 if (rv <= 0)
2155 break;
2157 log.GetEntries(&entries);
2158 last_index =
2159 ExpectLogContainsSomewhereAfter(entries,
2160 last_index + 1,
2161 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
2162 NetLog::PHASE_NONE);
2166 // Regression test for http://crbug.com/42538
2167 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
2168 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2169 SpawnedTestServer::kLocalhost,
2170 base::FilePath());
2171 ASSERT_TRUE(test_server.Start());
2173 AddressList addr;
2174 TestCompletionCallback callback;
2176 static const unsigned char application_data[] = {
2177 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
2178 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
2179 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
2180 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
2181 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
2182 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
2183 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
2184 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
2185 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
2186 0x0a};
2188 // All reads and writes complete synchronously (async=false).
2189 MockRead data_reads[] = {
2190 MockRead(SYNCHRONOUS,
2191 reinterpret_cast<const char*>(application_data),
2192 arraysize(application_data)),
2193 MockRead(SYNCHRONOUS, OK), };
2195 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
2197 scoped_ptr<StreamSocket> transport(
2198 new MockTCPClientSocket(addr, NULL, &data));
2199 int rv = transport->Connect(callback.callback());
2200 if (rv == ERR_IO_PENDING)
2201 rv = callback.WaitForResult();
2202 EXPECT_EQ(OK, rv);
2204 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2205 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2207 rv = sock->Connect(callback.callback());
2208 if (rv == ERR_IO_PENDING)
2209 rv = callback.WaitForResult();
2210 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
2213 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
2214 // Rather than exhaustively disabling every AES_128_CBC ciphersuite defined at
2215 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml, only
2216 // disabling those cipher suites that the test server actually implements.
2217 const uint16 kCiphersToDisable[] = {
2218 0x002f, // TLS_RSA_WITH_AES_128_CBC_SHA
2219 0x0033, // TLS_DHE_RSA_WITH_AES_128_CBC_SHA
2220 0xc013, // TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
2223 SpawnedTestServer::SSLOptions ssl_options;
2224 // Enable only AES_128_CBC on the test server.
2225 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
2226 SpawnedTestServer test_server(
2227 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2228 ASSERT_TRUE(test_server.Start());
2230 AddressList addr;
2231 ASSERT_TRUE(test_server.GetAddressList(&addr));
2233 TestCompletionCallback callback;
2234 TestNetLog log;
2235 scoped_ptr<StreamSocket> transport(
2236 new TCPClientSocket(addr, &log, NetLog::Source()));
2237 int rv = transport->Connect(callback.callback());
2238 if (rv == ERR_IO_PENDING)
2239 rv = callback.WaitForResult();
2240 EXPECT_EQ(OK, rv);
2242 SSLConfig ssl_config;
2243 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
2244 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
2246 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2247 transport.Pass(), test_server.host_port_pair(), ssl_config));
2249 EXPECT_FALSE(sock->IsConnected());
2251 rv = sock->Connect(callback.callback());
2252 CapturedNetLogEntry::List entries;
2253 log.GetEntries(&entries);
2254 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2256 if (rv == ERR_IO_PENDING)
2257 rv = callback.WaitForResult();
2258 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, rv);
2259 // The exact ordering depends no whether an extra read is issued. Just check
2260 // the error is somewhere in the log.
2261 log.GetEntries(&entries);
2262 ExpectLogContainsSomewhere(
2263 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
2265 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
2266 // the socket when it encounters an error, whereas other implementations
2267 // leave it connected.
2268 // Because this an error that the test server is mutually aware of, as opposed
2269 // to being an error such as a certificate name mismatch, which is
2270 // client-only, the exact index of the SSL connect end depends on how
2271 // quickly the test server closes the underlying socket. If the test server
2272 // closes before the IO message loop pumps messages, there may be a 0-byte
2273 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
2274 // result, the SSL connect end event will be the second-to-last entry,
2275 // rather than the last entry.
2276 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
2277 LogContainsSSLConnectEndEvent(entries, -2));
2280 // When creating an SSLClientSocket, it is allowed to pass in a
2281 // ClientSocketHandle that is not obtained from a client socket pool.
2282 // Here we verify that such a simple ClientSocketHandle, not associated with any
2283 // client socket pool, can be destroyed safely.
2284 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
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;
2294 scoped_ptr<StreamSocket> transport(
2295 new TCPClientSocket(addr, NULL, NetLog::Source()));
2296 int rv = transport->Connect(callback.callback());
2297 if (rv == ERR_IO_PENDING)
2298 rv = callback.WaitForResult();
2299 EXPECT_EQ(OK, rv);
2301 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
2302 socket_handle->SetSocket(transport.Pass());
2304 scoped_ptr<SSLClientSocket> sock(socket_factory_->CreateSSLClientSocket(
2305 socket_handle.Pass(), test_server.host_port_pair(), SSLConfig(),
2306 context_));
2308 EXPECT_FALSE(sock->IsConnected());
2309 rv = sock->Connect(callback.callback());
2310 if (rv == ERR_IO_PENDING)
2311 rv = callback.WaitForResult();
2312 EXPECT_EQ(OK, rv);
2315 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
2316 // code and different keying label results in different keying material.
2317 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
2318 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2319 SpawnedTestServer::kLocalhost,
2320 base::FilePath());
2321 ASSERT_TRUE(test_server.Start());
2323 AddressList addr;
2324 ASSERT_TRUE(test_server.GetAddressList(&addr));
2326 TestCompletionCallback callback;
2328 scoped_ptr<StreamSocket> transport(
2329 new TCPClientSocket(addr, NULL, NetLog::Source()));
2330 int rv = transport->Connect(callback.callback());
2331 if (rv == ERR_IO_PENDING)
2332 rv = callback.WaitForResult();
2333 EXPECT_EQ(OK, rv);
2335 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2336 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2338 rv = sock->Connect(callback.callback());
2339 if (rv == ERR_IO_PENDING)
2340 rv = callback.WaitForResult();
2341 EXPECT_EQ(OK, rv);
2342 EXPECT_TRUE(sock->IsConnected());
2344 const int kKeyingMaterialSize = 32;
2345 const char kKeyingLabel1[] = "client-socket-test-1";
2346 const char kKeyingContext1[] = "";
2347 unsigned char client_out1[kKeyingMaterialSize];
2348 memset(client_out1, 0, sizeof(client_out1));
2349 rv = sock->ExportKeyingMaterial(kKeyingLabel1, false, kKeyingContext1,
2350 client_out1, sizeof(client_out1));
2351 EXPECT_EQ(rv, OK);
2353 const char kKeyingLabel2[] = "client-socket-test-2";
2354 unsigned char client_out2[kKeyingMaterialSize];
2355 memset(client_out2, 0, sizeof(client_out2));
2356 rv = sock->ExportKeyingMaterial(kKeyingLabel2, false, kKeyingContext1,
2357 client_out2, sizeof(client_out2));
2358 EXPECT_EQ(rv, OK);
2359 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2361 const char kKeyingContext2[] = "context";
2362 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext2,
2363 client_out2, sizeof(client_out2));
2364 EXPECT_EQ(rv, OK);
2365 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2367 // Using an empty context should give different key material from not using a
2368 // context at all.
2369 memset(client_out2, 0, sizeof(client_out2));
2370 rv = sock->ExportKeyingMaterial(kKeyingLabel1, true, kKeyingContext1,
2371 client_out2, sizeof(client_out2));
2372 EXPECT_EQ(rv, OK);
2373 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
2376 // Verifies that SSLClientSocket::ClearSessionCache can be called without
2377 // explicit NSS initialization.
2378 TEST(SSLClientSocket, ClearSessionCache) {
2379 SSLClientSocket::ClearSessionCache();
2382 TEST(SSLClientSocket, SerializeNextProtos) {
2383 NextProtoVector next_protos;
2384 next_protos.push_back(kProtoHTTP11);
2385 next_protos.push_back(kProtoSPDY31);
2386 static std::vector<uint8_t> serialized =
2387 SSLClientSocket::SerializeNextProtos(next_protos, true);
2388 ASSERT_EQ(18u, serialized.size());
2389 EXPECT_EQ(8, serialized[0]); // length("http/1.1")
2390 EXPECT_EQ('h', serialized[1]);
2391 EXPECT_EQ('t', serialized[2]);
2392 EXPECT_EQ('t', serialized[3]);
2393 EXPECT_EQ('p', serialized[4]);
2394 EXPECT_EQ('/', serialized[5]);
2395 EXPECT_EQ('1', serialized[6]);
2396 EXPECT_EQ('.', serialized[7]);
2397 EXPECT_EQ('1', serialized[8]);
2398 EXPECT_EQ(8, serialized[9]); // length("spdy/3.1")
2399 EXPECT_EQ('s', serialized[10]);
2400 EXPECT_EQ('p', serialized[11]);
2401 EXPECT_EQ('d', serialized[12]);
2402 EXPECT_EQ('y', serialized[13]);
2403 EXPECT_EQ('/', serialized[14]);
2404 EXPECT_EQ('3', serialized[15]);
2405 EXPECT_EQ('.', serialized[16]);
2406 EXPECT_EQ('1', serialized[17]);
2409 // Test that the server certificates are properly retrieved from the underlying
2410 // SSL stack.
2411 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
2412 // The connection does not have to be successful.
2413 cert_verifier_->set_default_result(ERR_CERT_INVALID);
2415 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2416 // This makes the server present redundant-server-chain.pem, which contains
2417 // intermediate certificates.
2418 SpawnedTestServer::SSLOptions ssl_options(
2419 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2420 SpawnedTestServer test_server(
2421 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
2422 ASSERT_TRUE(test_server.Start());
2424 AddressList addr;
2425 ASSERT_TRUE(test_server.GetAddressList(&addr));
2427 TestCompletionCallback callback;
2428 scoped_ptr<StreamSocket> transport(
2429 new TCPClientSocket(addr, NULL, NetLog::Source()));
2430 int rv = transport->Connect(callback.callback());
2431 rv = callback.GetResult(rv);
2432 EXPECT_EQ(OK, rv);
2434 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2435 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2436 EXPECT_FALSE(sock->IsConnected());
2437 rv = sock->Connect(callback.callback());
2438 rv = callback.GetResult(rv);
2440 EXPECT_EQ(ERR_CERT_INVALID, rv);
2441 EXPECT_TRUE(sock->IsConnected());
2443 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
2444 // certs from redundant-server-chain.pem.
2445 CertificateList server_certs =
2446 CreateCertificateListFromFile(GetTestCertsDirectory(),
2447 "redundant-server-chain.pem",
2448 X509Certificate::FORMAT_AUTO);
2450 // Get the server certificate as received client side.
2451 scoped_refptr<X509Certificate> server_certificate =
2452 sock->GetUnverifiedServerCertificateChain();
2454 // Get the intermediates as received client side.
2455 const X509Certificate::OSCertHandles& server_intermediates =
2456 server_certificate->GetIntermediateCertificates();
2458 // Check that the unverified server certificate chain is properly retrieved
2459 // from the underlying ssl stack.
2460 ASSERT_EQ(4U, server_certs.size());
2462 EXPECT_TRUE(X509Certificate::IsSameOSCert(
2463 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
2465 ASSERT_EQ(3U, server_intermediates.size());
2467 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
2468 server_certs[1]->os_cert_handle()));
2469 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
2470 server_certs[2]->os_cert_handle()));
2471 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
2472 server_certs[3]->os_cert_handle()));
2474 sock->Disconnect();
2475 EXPECT_FALSE(sock->IsConnected());
2478 // This tests that SSLInfo contains a properly re-constructed certificate
2479 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
2480 // verified, not the chain as served by the server. (They may be different.)
2482 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
2483 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
2484 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
2485 // a self-signed root. Such a situation can occur when a new root (C2) is
2486 // cross-certified by an old root (D) and has two different versions of its
2487 // floating around. Servers may supply C2 as an intermediate, but the
2488 // SSLClientSocket should return the chain that was verified, from
2489 // verify_result, instead.
2490 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
2491 // By default, cause the CertVerifier to treat all certificates as
2492 // expired.
2493 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
2495 // We will expect SSLInfo to ultimately contain this chain.
2496 CertificateList certs =
2497 CreateCertificateListFromFile(GetTestCertsDirectory(),
2498 "redundant-validated-chain.pem",
2499 X509Certificate::FORMAT_AUTO);
2500 ASSERT_EQ(3U, certs.size());
2502 X509Certificate::OSCertHandles temp_intermediates;
2503 temp_intermediates.push_back(certs[1]->os_cert_handle());
2504 temp_intermediates.push_back(certs[2]->os_cert_handle());
2506 CertVerifyResult verify_result;
2507 verify_result.verified_cert = X509Certificate::CreateFromHandle(
2508 certs[0]->os_cert_handle(), temp_intermediates);
2510 // Add a rule that maps the server cert (A) to the chain of A->B->C2
2511 // rather than A->B->C.
2512 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
2514 // Load and install the root for the validated chain.
2515 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
2516 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
2517 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
2518 ScopedTestRoot scoped_root(root_cert.get());
2520 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
2521 SpawnedTestServer::SSLOptions ssl_options(
2522 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
2523 SpawnedTestServer test_server(
2524 SpawnedTestServer::TYPE_HTTPS,
2525 ssl_options,
2526 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2527 ASSERT_TRUE(test_server.Start());
2529 AddressList addr;
2530 ASSERT_TRUE(test_server.GetAddressList(&addr));
2532 TestCompletionCallback callback;
2533 TestNetLog log;
2534 scoped_ptr<StreamSocket> transport(
2535 new TCPClientSocket(addr, &log, NetLog::Source()));
2536 int rv = transport->Connect(callback.callback());
2537 if (rv == ERR_IO_PENDING)
2538 rv = callback.WaitForResult();
2539 EXPECT_EQ(OK, rv);
2541 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2542 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2543 EXPECT_FALSE(sock->IsConnected());
2544 rv = sock->Connect(callback.callback());
2546 CapturedNetLogEntry::List entries;
2547 log.GetEntries(&entries);
2548 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2549 if (rv == ERR_IO_PENDING)
2550 rv = callback.WaitForResult();
2552 EXPECT_EQ(OK, rv);
2553 EXPECT_TRUE(sock->IsConnected());
2554 log.GetEntries(&entries);
2555 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2557 SSLInfo ssl_info;
2558 sock->GetSSLInfo(&ssl_info);
2560 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
2561 // -> C2.
2562 const X509Certificate::OSCertHandles& intermediates =
2563 ssl_info.cert->GetIntermediateCertificates();
2564 ASSERT_EQ(2U, intermediates.size());
2565 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
2566 certs[0]->os_cert_handle()));
2567 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
2568 certs[1]->os_cert_handle()));
2569 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
2570 certs[2]->os_cert_handle()));
2572 sock->Disconnect();
2573 EXPECT_FALSE(sock->IsConnected());
2576 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
2577 SpawnedTestServer::SSLOptions ssl_options;
2578 ssl_options.request_client_certificate = true;
2579 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2580 ASSERT_TRUE(request_info.get());
2581 EXPECT_EQ(0u, request_info->cert_authorities.size());
2584 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
2585 const base::FilePath::CharType kThawteFile[] =
2586 FILE_PATH_LITERAL("thawte.single.pem");
2587 const unsigned char kThawteDN[] = {
2588 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2589 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
2590 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
2591 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
2592 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
2593 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
2594 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
2595 const size_t kThawteLen = sizeof(kThawteDN);
2597 const base::FilePath::CharType kDiginotarFile[] =
2598 FILE_PATH_LITERAL("diginotar_root_ca.pem");
2599 const unsigned char kDiginotarDN[] = {
2600 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
2601 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
2602 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
2603 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
2604 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
2605 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
2606 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
2607 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
2608 0x6c};
2609 const size_t kDiginotarLen = sizeof(kDiginotarDN);
2611 SpawnedTestServer::SSLOptions ssl_options;
2612 ssl_options.request_client_certificate = true;
2613 ssl_options.client_authorities.push_back(
2614 GetTestClientCertsDirectory().Append(kThawteFile));
2615 ssl_options.client_authorities.push_back(
2616 GetTestClientCertsDirectory().Append(kDiginotarFile));
2617 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2618 ASSERT_TRUE(request_info.get());
2619 ASSERT_EQ(2u, request_info->cert_authorities.size());
2620 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
2621 request_info->cert_authorities[0]);
2622 EXPECT_EQ(
2623 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
2624 request_info->cert_authorities[1]);
2627 // cert_key_types is currently only populated on OpenSSL.
2628 #if defined(USE_OPENSSL)
2629 TEST_F(SSLClientSocketCertRequestInfoTest, CertKeyTypes) {
2630 SpawnedTestServer::SSLOptions ssl_options;
2631 ssl_options.request_client_certificate = true;
2632 ssl_options.client_cert_types.push_back(CLIENT_CERT_RSA_SIGN);
2633 ssl_options.client_cert_types.push_back(CLIENT_CERT_ECDSA_SIGN);
2634 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
2635 ASSERT_TRUE(request_info.get());
2636 ASSERT_EQ(2u, request_info->cert_key_types.size());
2637 EXPECT_EQ(CLIENT_CERT_RSA_SIGN, request_info->cert_key_types[0]);
2638 EXPECT_EQ(CLIENT_CERT_ECDSA_SIGN, request_info->cert_key_types[1]);
2640 #endif // defined(USE_OPENSSL)
2642 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
2643 SpawnedTestServer::SSLOptions ssl_options;
2644 ssl_options.signed_cert_timestamps_tls_ext = "test";
2646 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2647 ssl_options,
2648 base::FilePath());
2649 ASSERT_TRUE(test_server.Start());
2651 AddressList addr;
2652 ASSERT_TRUE(test_server.GetAddressList(&addr));
2654 TestCompletionCallback callback;
2655 scoped_ptr<StreamSocket> transport(
2656 new TCPClientSocket(addr, &log_, NetLog::Source()));
2657 int rv = callback.GetResult(transport->Connect(callback.callback()));
2658 EXPECT_EQ(OK, rv);
2660 SSLConfig ssl_config;
2661 ssl_config.signed_cert_timestamps_enabled = true;
2663 MockCTVerifier ct_verifier;
2664 SetCTVerifier(&ct_verifier);
2666 // Check that the SCT list is extracted as expected.
2667 EXPECT_CALL(ct_verifier, Verify(_, "", "test", _, _)).WillRepeatedly(
2668 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2670 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2671 transport.Pass(), test_server.host_port_pair(), ssl_config));
2672 rv = callback.GetResult(sock->Connect(callback.callback()));
2673 EXPECT_EQ(OK, rv);
2675 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2678 namespace {
2680 bool IsValidOCSPResponse(const base::StringPiece& input) {
2681 base::StringPiece ocsp_response = input;
2682 base::StringPiece sequence, response_status, response_bytes;
2683 return asn1::GetElement(&ocsp_response, asn1::kSEQUENCE, &sequence) &&
2684 ocsp_response.empty() &&
2685 asn1::GetElement(&sequence, asn1::kENUMERATED, &response_status) &&
2686 asn1::GetElement(&sequence,
2687 asn1::kContextSpecific | asn1::kConstructed | 0,
2688 &response_status) &&
2689 sequence.empty();
2692 } // namespace
2694 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2695 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2696 SpawnedTestServer::SSLOptions ssl_options;
2697 ssl_options.staple_ocsp_response = true;
2698 // The test server currently only knows how to generate OCSP responses
2699 // for a freshly minted certificate.
2700 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2702 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2703 ssl_options,
2704 base::FilePath());
2705 ASSERT_TRUE(test_server.Start());
2707 AddressList addr;
2708 ASSERT_TRUE(test_server.GetAddressList(&addr));
2710 TestCompletionCallback callback;
2711 scoped_ptr<StreamSocket> transport(
2712 new TCPClientSocket(addr, &log_, NetLog::Source()));
2713 int rv = callback.GetResult(transport->Connect(callback.callback()));
2714 EXPECT_EQ(OK, rv);
2716 SSLConfig ssl_config;
2717 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2718 // Certificate Transparency verification regardless of whether the platform
2719 // is able to process the OCSP status itself.
2720 ssl_config.signed_cert_timestamps_enabled = true;
2722 MockCTVerifier ct_verifier;
2723 SetCTVerifier(&ct_verifier);
2725 // Check that the OCSP response is extracted and well-formed. It should be the
2726 // DER encoding of an OCSPResponse (RFC 2560), so check that it consists of a
2727 // SEQUENCE of an ENUMERATED type and an element tagged with [0] EXPLICIT. In
2728 // particular, it should not include the overall two-byte length prefix from
2729 // TLS.
2730 EXPECT_CALL(ct_verifier,
2731 Verify(_, Truly(IsValidOCSPResponse), "", _, _)).WillRepeatedly(
2732 Return(ERR_CT_NO_SCTS_VERIFIED_OK));
2734 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2735 transport.Pass(), test_server.host_port_pair(), ssl_config));
2736 rv = callback.GetResult(sock->Connect(callback.callback()));
2737 EXPECT_EQ(OK, rv);
2739 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2742 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2743 SpawnedTestServer::SSLOptions ssl_options;
2744 ssl_options.signed_cert_timestamps_tls_ext = "test";
2746 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2747 ssl_options,
2748 base::FilePath());
2749 ASSERT_TRUE(test_server.Start());
2751 AddressList addr;
2752 ASSERT_TRUE(test_server.GetAddressList(&addr));
2754 TestCompletionCallback callback;
2755 scoped_ptr<StreamSocket> transport(
2756 new TCPClientSocket(addr, &log_, NetLog::Source()));
2757 int rv = callback.GetResult(transport->Connect(callback.callback()));
2758 EXPECT_EQ(OK, rv);
2760 SSLConfig ssl_config;
2761 ssl_config.signed_cert_timestamps_enabled = false;
2763 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2764 transport.Pass(), test_server.host_port_pair(), ssl_config));
2765 rv = callback.GetResult(sock->Connect(callback.callback()));
2766 EXPECT_EQ(OK, rv);
2768 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2771 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2772 TEST_F(SSLClientSocketTest, ReuseStates) {
2773 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2774 SpawnedTestServer::kLocalhost,
2775 base::FilePath());
2776 ASSERT_TRUE(test_server.Start());
2778 AddressList addr;
2779 ASSERT_TRUE(test_server.GetAddressList(&addr));
2781 TestCompletionCallback callback;
2782 scoped_ptr<StreamSocket> transport(
2783 new TCPClientSocket(addr, NULL, NetLog::Source()));
2784 int rv = transport->Connect(callback.callback());
2785 if (rv == ERR_IO_PENDING)
2786 rv = callback.WaitForResult();
2787 EXPECT_EQ(OK, rv);
2789 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2790 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2792 rv = sock->Connect(callback.callback());
2793 if (rv == ERR_IO_PENDING)
2794 rv = callback.WaitForResult();
2795 EXPECT_EQ(OK, rv);
2797 // The socket was just connected. It should be idle because it is speaking
2798 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2799 // returns false.
2800 EXPECT_TRUE(sock->IsConnected());
2801 EXPECT_TRUE(sock->IsConnectedAndIdle());
2802 EXPECT_FALSE(sock->WasEverUsed());
2804 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2805 const size_t kRequestLen = arraysize(kRequestText) - 1;
2806 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2807 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2809 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2810 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2812 if (rv == ERR_IO_PENDING)
2813 rv = callback.WaitForResult();
2814 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2816 // The socket has now been used.
2817 EXPECT_TRUE(sock->WasEverUsed());
2819 // TODO(davidben): Read one byte to ensure the test server has responded and
2820 // then assert IsConnectedAndIdle is false. This currently doesn't work
2821 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2822 // SSL implementation's internal buffers. Either call PR_Available and
2823 // SSL_pending, although the former isn't actually implemented or perhaps
2824 // attempt to read one byte extra.
2827 // Tests that IsConnectedAndIdle treats a socket as idle even if a Write hasn't
2828 // been flushed completely out of SSLClientSocket's internal buffers. This is a
2829 // regression test for https://crbug.com/466147.
2830 TEST_F(SSLClientSocketTest, ReusableAfterWrite) {
2831 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2832 SpawnedTestServer::kLocalhost,
2833 base::FilePath());
2834 ASSERT_TRUE(test_server.Start());
2836 AddressList addr;
2837 ASSERT_TRUE(test_server.GetAddressList(&addr));
2839 TestCompletionCallback callback;
2840 scoped_ptr<StreamSocket> real_transport(
2841 new TCPClientSocket(addr, NULL, NetLog::Source()));
2842 scoped_ptr<FakeBlockingStreamSocket> transport(
2843 new FakeBlockingStreamSocket(real_transport.Pass()));
2844 FakeBlockingStreamSocket* raw_transport = transport.get();
2845 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2847 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2848 transport.Pass(), test_server.host_port_pair(), SSLConfig()));
2849 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2851 // Block any application data from reaching the network.
2852 raw_transport->BlockWrite();
2854 // Write a partial HTTP request.
2855 const char kRequestText[] = "GET / HTTP/1.0";
2856 const size_t kRequestLen = arraysize(kRequestText) - 1;
2857 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2858 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2860 // Although transport writes are blocked, both SSLClientSocketOpenSSL and
2861 // SSLClientSocketNSS complete the outer Write operation.
2862 EXPECT_EQ(static_cast<int>(kRequestLen),
2863 callback.GetResult(sock->Write(request_buffer.get(), kRequestLen,
2864 callback.callback())));
2866 // The Write operation is complete, so the socket should be treated as
2867 // reusable, in case the server returns an HTTP response before completely
2868 // consuming the request body. In this case, we assume the server will
2869 // properly drain the request body before trying to read the next request.
2870 EXPECT_TRUE(sock->IsConnectedAndIdle());
2873 // Tests that basic session resumption works.
2874 TEST_F(SSLClientSocketTest, SessionResumption) {
2875 SpawnedTestServer::SSLOptions ssl_options;
2876 ASSERT_TRUE(StartTestServer(ssl_options));
2878 // First, perform a full handshake.
2879 SSLConfig ssl_config;
2880 TestCompletionCallback callback;
2881 scoped_ptr<StreamSocket> transport(
2882 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2883 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2884 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2885 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2886 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2887 SSLInfo ssl_info;
2888 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2889 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2891 // The next connection should resume.
2892 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2893 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2894 sock = CreateSSLClientSocket(transport.Pass(),
2895 test_server()->host_port_pair(), ssl_config);
2896 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2897 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2898 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
2900 // Using a different HostPortPair uses a different session cache key.
2901 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2902 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2903 sock = CreateSSLClientSocket(transport.Pass(),
2904 HostPortPair("example.com", 443), ssl_config);
2905 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2906 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2907 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2909 SSLClientSocket::ClearSessionCache();
2911 // After clearing the session cache, the next handshake doesn't resume.
2912 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2913 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2914 sock = CreateSSLClientSocket(transport.Pass(),
2915 test_server()->host_port_pair(), ssl_config);
2916 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2917 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2918 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2921 // Tests that connections with certificate errors do not add entries to the
2922 // session cache.
2923 TEST_F(SSLClientSocketTest, CertificateErrorNoResume) {
2924 SpawnedTestServer::SSLOptions ssl_options;
2925 ASSERT_TRUE(StartTestServer(ssl_options));
2927 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
2929 SSLConfig ssl_config;
2930 TestCompletionCallback callback;
2931 scoped_ptr<StreamSocket> transport(
2932 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2933 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2934 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2935 transport.Pass(), test_server()->host_port_pair(), ssl_config));
2936 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID,
2937 callback.GetResult(sock->Connect(callback.callback())));
2939 cert_verifier_->set_default_result(OK);
2941 // The next connection should perform a full handshake.
2942 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2943 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2944 sock = CreateSSLClientSocket(transport.Pass(),
2945 test_server()->host_port_pair(), ssl_config);
2946 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2947 SSLInfo ssl_info;
2948 ASSERT_TRUE(sock->GetSSLInfo(&ssl_info));
2949 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2952 // Tests that session caches are sharded by max_version.
2953 TEST_F(SSLClientSocketTest, FallbackShardSessionCache) {
2954 SpawnedTestServer::SSLOptions ssl_options;
2955 ASSERT_TRUE(StartTestServer(ssl_options));
2957 // Prepare a normal and fallback SSL config.
2958 SSLConfig ssl_config;
2959 SSLConfig fallback_ssl_config;
2960 fallback_ssl_config.version_max = SSL_PROTOCOL_VERSION_TLS1;
2961 fallback_ssl_config.version_fallback = true;
2963 // Connect with a fallback config from the test server to add an entry to the
2964 // session cache.
2965 TestCompletionCallback callback;
2966 scoped_ptr<StreamSocket> transport(
2967 new TCPClientSocket(addr(), &log_, NetLog::Source()));
2968 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2969 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2970 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config));
2971 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2972 SSLInfo ssl_info;
2973 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2974 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2975 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
2976 SSLConnectionStatusToVersion(ssl_info.connection_status));
2978 // A non-fallback connection needs a full handshake.
2979 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2980 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2981 sock = CreateSSLClientSocket(transport.Pass(),
2982 test_server()->host_port_pair(), ssl_config);
2983 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
2984 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
2985 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
2986 // This does not check for equality because TLS 1.2 support is conditional on
2987 // system NSS features.
2988 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
2989 SSLConnectionStatusToVersion(ssl_info.connection_status));
2991 // Note: if the server (correctly) declines to resume a TLS 1.0 session at TLS
2992 // 1.2, the above test would not be sufficient to prove the session caches are
2993 // sharded. Implementations vary here, so, to avoid being sensitive to this,
2994 // attempt to resume with two more connections.
2996 // The non-fallback connection added a > TLS 1.0 entry to the session cache.
2997 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
2998 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
2999 sock = CreateSSLClientSocket(transport.Pass(),
3000 test_server()->host_port_pair(), ssl_config);
3001 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3002 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3003 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3004 // This does not check for equality because TLS 1.2 support is conditional on
3005 // system NSS features.
3006 EXPECT_LT(SSL_CONNECTION_VERSION_TLS1,
3007 SSLConnectionStatusToVersion(ssl_info.connection_status));
3009 // The fallback connection still resumes from its session cache. It cannot
3010 // offer the > TLS 1.0 session, so this must have been the session from the
3011 // first fallback connection.
3012 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3013 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3014 sock = CreateSSLClientSocket(
3015 transport.Pass(), test_server()->host_port_pair(), fallback_ssl_config);
3016 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3017 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3018 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3019 EXPECT_EQ(SSL_CONNECTION_VERSION_TLS1,
3020 SSLConnectionStatusToVersion(ssl_info.connection_status));
3023 // Test that RC4 is only enabled if enable_deprecated_cipher_suites is set.
3024 TEST_F(SSLClientSocketTest, DeprecatedRC4) {
3025 SpawnedTestServer::SSLOptions ssl_options;
3026 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
3027 ASSERT_TRUE(StartTestServer(ssl_options));
3029 // Normal handshakes with RC4 do not work.
3030 SSLConfig ssl_config;
3031 TestCompletionCallback callback;
3032 scoped_ptr<StreamSocket> transport(
3033 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3034 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3035 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
3036 transport.Pass(), test_server()->host_port_pair(), ssl_config));
3037 ASSERT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH,
3038 callback.GetResult(sock->Connect(callback.callback())));
3040 // Enabling deprecated ciphers works fine.
3041 ssl_config.enable_deprecated_cipher_suites = true;
3042 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3043 ASSERT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3044 sock = CreateSSLClientSocket(transport.Pass(),
3045 test_server()->host_port_pair(), ssl_config);
3046 ASSERT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3049 // Tests that enabling deprecated ciphers shards the session cache.
3050 TEST_F(SSLClientSocketTest, DeprecatedShardSessionCache) {
3051 SpawnedTestServer::SSLOptions ssl_options;
3052 ASSERT_TRUE(StartTestServer(ssl_options));
3054 // Prepare a normal and deprecated SSL config.
3055 SSLConfig ssl_config;
3056 SSLConfig deprecated_ssl_config;
3057 deprecated_ssl_config.enable_deprecated_cipher_suites = true;
3059 // Connect with deprecated ciphers enabled to warm the session cache cache.
3060 TestCompletionCallback callback;
3061 scoped_ptr<StreamSocket> transport(
3062 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3063 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3064 scoped_ptr<SSLClientSocket> sock(
3065 CreateSSLClientSocket(transport.Pass(), test_server()->host_port_pair(),
3066 deprecated_ssl_config));
3067 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3068 SSLInfo ssl_info;
3069 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3070 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3072 // Test that re-connecting with deprecated ciphers enabled still resumes.
3073 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3074 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3075 sock = CreateSSLClientSocket(
3076 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3077 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3078 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3079 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3081 // However, a normal connection needs a full handshake.
3082 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3083 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3084 sock = CreateSSLClientSocket(transport.Pass(),
3085 test_server()->host_port_pair(), ssl_config);
3086 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3087 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3088 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3090 // Clear the session cache for the inverse test.
3091 SSLClientSocket::ClearSessionCache();
3093 // Now make a normal connection to prime the session cache.
3094 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3095 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3096 sock = CreateSSLClientSocket(transport.Pass(),
3097 test_server()->host_port_pair(), ssl_config);
3098 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3099 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3100 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3102 // A normal connection should be able to resume.
3103 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3104 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3105 sock = CreateSSLClientSocket(transport.Pass(),
3106 test_server()->host_port_pair(), ssl_config);
3107 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3108 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3109 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3111 // However, enabling deprecated ciphers connects fresh.
3112 transport.reset(new TCPClientSocket(addr(), &log_, NetLog::Source()));
3113 EXPECT_EQ(OK, callback.GetResult(transport->Connect(callback.callback())));
3114 sock = CreateSSLClientSocket(
3115 transport.Pass(), test_server()->host_port_pair(), deprecated_ssl_config);
3116 EXPECT_EQ(OK, callback.GetResult(sock->Connect(callback.callback())));
3117 EXPECT_TRUE(sock->GetSSLInfo(&ssl_info));
3118 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3121 TEST_F(SSLClientSocketFalseStartTest, FalseStartEnabled) {
3122 if (!SupportsAESGCM()) {
3123 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3124 return;
3127 // False Start requires NPN/ALPN, ECDHE, and an AEAD.
3128 SpawnedTestServer::SSLOptions server_options;
3129 server_options.key_exchanges =
3130 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3131 server_options.bulk_ciphers =
3132 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3133 server_options.enable_npn = true;
3134 SSLConfig client_config;
3135 client_config.next_protos.push_back(kProtoHTTP11);
3136 ASSERT_NO_FATAL_FAILURE(
3137 TestFalseStart(server_options, client_config, true));
3140 // Test that False Start is disabled without NPN.
3141 TEST_F(SSLClientSocketFalseStartTest, NoNPN) {
3142 if (!SupportsAESGCM()) {
3143 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3144 return;
3147 SpawnedTestServer::SSLOptions server_options;
3148 server_options.key_exchanges =
3149 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3150 server_options.bulk_ciphers =
3151 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3152 SSLConfig client_config;
3153 client_config.next_protos.clear();
3154 ASSERT_NO_FATAL_FAILURE(
3155 TestFalseStart(server_options, client_config, false));
3158 // Test that False Start is disabled with plain RSA ciphers.
3159 TEST_F(SSLClientSocketFalseStartTest, RSA) {
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_RSA;
3168 server_options.bulk_ciphers =
3169 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3170 server_options.enable_npn = true;
3171 SSLConfig client_config;
3172 client_config.next_protos.push_back(kProtoHTTP11);
3173 ASSERT_NO_FATAL_FAILURE(
3174 TestFalseStart(server_options, client_config, false));
3177 // Test that False Start is disabled with DHE_RSA ciphers.
3178 TEST_F(SSLClientSocketFalseStartTest, DHE_RSA) {
3179 if (!SupportsAESGCM()) {
3180 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3181 return;
3184 SpawnedTestServer::SSLOptions server_options;
3185 server_options.key_exchanges =
3186 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
3187 server_options.bulk_ciphers =
3188 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3189 server_options.enable_npn = true;
3190 SSLConfig client_config;
3191 client_config.next_protos.push_back(kProtoHTTP11);
3192 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3195 // Test that False Start is disabled without an AEAD.
3196 TEST_F(SSLClientSocketFalseStartTest, NoAEAD) {
3197 SpawnedTestServer::SSLOptions server_options;
3198 server_options.key_exchanges =
3199 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3200 server_options.bulk_ciphers =
3201 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128;
3202 server_options.enable_npn = true;
3203 SSLConfig client_config;
3204 client_config.next_protos.push_back(kProtoHTTP11);
3205 ASSERT_NO_FATAL_FAILURE(TestFalseStart(server_options, client_config, false));
3208 // Test that sessions are resumable after receiving the server Finished message.
3209 TEST_F(SSLClientSocketFalseStartTest, SessionResumption) {
3210 if (!SupportsAESGCM()) {
3211 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3212 return;
3215 // Start a server.
3216 SpawnedTestServer::SSLOptions server_options;
3217 server_options.key_exchanges =
3218 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3219 server_options.bulk_ciphers =
3220 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3221 server_options.enable_npn = true;
3222 SSLConfig client_config;
3223 client_config.next_protos.push_back(kProtoHTTP11);
3225 // Let a full handshake complete with False Start.
3226 ASSERT_NO_FATAL_FAILURE(
3227 TestFalseStart(server_options, client_config, true));
3229 // Make a second connection.
3230 TestCompletionCallback callback;
3231 scoped_ptr<StreamSocket> transport2(
3232 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3233 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3234 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3235 transport2.Pass(), test_server()->host_port_pair(), client_config);
3236 ASSERT_TRUE(sock2.get());
3237 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3239 // It should resume the session.
3240 SSLInfo ssl_info;
3241 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3242 EXPECT_EQ(SSLInfo::HANDSHAKE_RESUME, ssl_info.handshake_type);
3245 // Test that False Started sessions are not resumable before receiving the
3246 // server Finished message.
3247 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBeforeFinished) {
3248 if (!SupportsAESGCM()) {
3249 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3250 return;
3253 // Start a server.
3254 SpawnedTestServer::SSLOptions server_options;
3255 server_options.key_exchanges =
3256 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3257 server_options.bulk_ciphers =
3258 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3259 server_options.enable_npn = true;
3260 ASSERT_TRUE(StartTestServer(server_options));
3262 SSLConfig client_config;
3263 client_config.next_protos.push_back(kProtoHTTP11);
3265 // Start a handshake up to the server Finished message.
3266 TestCompletionCallback callback;
3267 FakeBlockingStreamSocket* raw_transport1 = NULL;
3268 scoped_ptr<SSLClientSocket> sock1;
3269 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3270 client_config, &callback, &raw_transport1, &sock1));
3271 // Although raw_transport1 has the server Finished blocked, the handshake
3272 // still completes.
3273 EXPECT_EQ(OK, callback.WaitForResult());
3275 // Continue to block the client (|sock1|) from processing the Finished
3276 // message, but allow it to arrive on the socket. This ensures that, from the
3277 // server's point of view, it has completed the handshake and added the
3278 // session to its session cache.
3280 // The actual read on |sock1| will not complete until the Finished message is
3281 // processed; however, pump the underlying transport so that it is read from
3282 // the socket. NOTE: This may flakily pass if the server's final flight
3283 // doesn't come in one Read.
3284 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3285 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3286 EXPECT_EQ(ERR_IO_PENDING, rv);
3287 raw_transport1->WaitForReadResult();
3289 // Drop the old socket. This is needed because the Python test server can't
3290 // service two sockets in parallel.
3291 sock1.reset();
3293 // Start a second connection.
3294 scoped_ptr<StreamSocket> transport2(
3295 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3296 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3297 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3298 transport2.Pass(), test_server()->host_port_pair(), client_config);
3299 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3301 // No session resumption because the first connection never received a server
3302 // Finished message.
3303 SSLInfo ssl_info;
3304 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3305 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3308 // Test that False Started sessions are not resumable if the server Finished
3309 // message was bad.
3310 TEST_F(SSLClientSocketFalseStartTest, NoSessionResumptionBadFinished) {
3311 if (!SupportsAESGCM()) {
3312 LOG(WARNING) << "Skipping test because AES-GCM is not supported.";
3313 return;
3316 // Start a server.
3317 SpawnedTestServer::SSLOptions server_options;
3318 server_options.key_exchanges =
3319 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_ECDHE_RSA;
3320 server_options.bulk_ciphers =
3321 SpawnedTestServer::SSLOptions::BULK_CIPHER_AES128GCM;
3322 server_options.enable_npn = true;
3323 ASSERT_TRUE(StartTestServer(server_options));
3325 SSLConfig client_config;
3326 client_config.next_protos.push_back(kProtoHTTP11);
3328 // Start a handshake up to the server Finished message.
3329 TestCompletionCallback callback;
3330 FakeBlockingStreamSocket* raw_transport1 = NULL;
3331 scoped_ptr<SSLClientSocket> sock1;
3332 ASSERT_NO_FATAL_FAILURE(CreateAndConnectUntilServerFinishedReceived(
3333 client_config, &callback, &raw_transport1, &sock1));
3334 // Although raw_transport1 has the server Finished blocked, the handshake
3335 // still completes.
3336 EXPECT_EQ(OK, callback.WaitForResult());
3338 // Continue to block the client (|sock1|) from processing the Finished
3339 // message, but allow it to arrive on the socket. This ensures that, from the
3340 // server's point of view, it has completed the handshake and added the
3341 // session to its session cache.
3343 // The actual read on |sock1| will not complete until the Finished message is
3344 // processed; however, pump the underlying transport so that it is read from
3345 // the socket.
3346 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
3347 int rv = sock1->Read(buf.get(), 4096, callback.callback());
3348 EXPECT_EQ(ERR_IO_PENDING, rv);
3349 raw_transport1->WaitForReadResult();
3351 // The server's second leg, or part of it, is now received but not yet sent to
3352 // |sock1|. Before doing so, break the server's second leg.
3353 int bytes_read = raw_transport1->pending_read_result();
3354 ASSERT_LT(0, bytes_read);
3355 raw_transport1->pending_read_buf()->data()[bytes_read - 1]++;
3357 // Unblock the Finished message. |sock1->Read| should now fail.
3358 raw_transport1->UnblockReadResult();
3359 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, callback.GetResult(rv));
3361 // Drop the old socket. This is needed because the Python test server can't
3362 // service two sockets in parallel.
3363 sock1.reset();
3365 // Start a second connection.
3366 scoped_ptr<StreamSocket> transport2(
3367 new TCPClientSocket(addr(), &log_, NetLog::Source()));
3368 EXPECT_EQ(OK, callback.GetResult(transport2->Connect(callback.callback())));
3369 scoped_ptr<SSLClientSocket> sock2 = CreateSSLClientSocket(
3370 transport2.Pass(), test_server()->host_port_pair(), client_config);
3371 EXPECT_EQ(OK, callback.GetResult(sock2->Connect(callback.callback())));
3373 // No session resumption because the first connection never received a server
3374 // Finished message.
3375 SSLInfo ssl_info;
3376 EXPECT_TRUE(sock2->GetSSLInfo(&ssl_info));
3377 EXPECT_EQ(SSLInfo::HANDSHAKE_FULL, ssl_info.handshake_type);
3380 // Connect to a server using channel id. It should allow the connection.
3381 TEST_F(SSLClientSocketChannelIDTest, SendChannelID) {
3382 SpawnedTestServer::SSLOptions ssl_options;
3384 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3386 EnableChannelID();
3387 SSLConfig ssl_config;
3388 ssl_config.channel_id_enabled = true;
3390 int rv;
3391 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3393 EXPECT_EQ(OK, rv);
3394 EXPECT_TRUE(sock_->IsConnected());
3395 SSLInfo ssl_info;
3396 ASSERT_TRUE(sock_->GetSSLInfo(&ssl_info));
3397 EXPECT_TRUE(ssl_info.channel_id_sent);
3399 sock_->Disconnect();
3400 EXPECT_FALSE(sock_->IsConnected());
3403 // Connect to a server using Channel ID but failing to look up the Channel
3404 // ID. It should fail.
3405 TEST_F(SSLClientSocketChannelIDTest, FailingChannelID) {
3406 SpawnedTestServer::SSLOptions ssl_options;
3408 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3410 EnableFailingChannelID();
3411 SSLConfig ssl_config;
3412 ssl_config.channel_id_enabled = true;
3414 int rv;
3415 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3417 // TODO(haavardm@opera.com): Due to differences in threading, Linux returns
3418 // ERR_UNEXPECTED while Mac and Windows return ERR_PROTOCOL_ERROR. Accept all
3419 // error codes for now.
3420 // http://crbug.com/373670
3421 EXPECT_NE(OK, rv);
3422 EXPECT_FALSE(sock_->IsConnected());
3425 // Connect to a server using Channel ID but asynchronously failing to look up
3426 // the Channel ID. It should fail.
3427 TEST_F(SSLClientSocketChannelIDTest, FailingChannelIDAsync) {
3428 SpawnedTestServer::SSLOptions ssl_options;
3430 ASSERT_TRUE(ConnectToTestServer(ssl_options));
3432 EnableAsyncFailingChannelID();
3433 SSLConfig ssl_config;
3434 ssl_config.channel_id_enabled = true;
3436 int rv;
3437 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
3439 EXPECT_EQ(ERR_UNEXPECTED, rv);
3440 EXPECT_FALSE(sock_->IsConnected());
3443 } // namespace net