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 "net/base/address_list.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/net_errors.h"
12 #include "net/base/net_log.h"
13 #include "net/base/net_log_unittest.h"
14 #include "net/base/test_completion_callback.h"
15 #include "net/base/test_data_directory.h"
16 #include "net/cert/mock_cert_verifier.h"
17 #include "net/cert/test_root_certs.h"
18 #include "net/dns/host_resolver.h"
19 #include "net/http/transport_security_state.h"
20 #include "net/socket/client_socket_factory.h"
21 #include "net/socket/client_socket_handle.h"
22 #include "net/socket/socket_test_util.h"
23 #include "net/socket/tcp_client_socket.h"
24 #include "net/ssl/ssl_cert_request_info.h"
25 #include "net/ssl/ssl_config_service.h"
26 #include "net/test/cert_test_util.h"
27 #include "net/test/spawned_test_server/spawned_test_server.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "testing/platform_test.h"
31 //-----------------------------------------------------------------------------
37 const SSLConfig kDefaultSSLConfig;
39 // WrappedStreamSocket is a base class that wraps an existing StreamSocket,
40 // forwarding the Socket and StreamSocket interfaces to the underlying
42 // This is to provide a common base class for subclasses to override specific
43 // StreamSocket methods for testing, while still communicating with a 'real'
45 class WrappedStreamSocket : public StreamSocket {
47 explicit WrappedStreamSocket(scoped_ptr<StreamSocket> transport)
48 : transport_(transport.Pass()) {}
49 virtual ~WrappedStreamSocket() {}
51 // StreamSocket implementation:
52 virtual int Connect(const CompletionCallback& callback) OVERRIDE {
53 return transport_->Connect(callback);
55 virtual void Disconnect() OVERRIDE { transport_->Disconnect(); }
56 virtual bool IsConnected() const OVERRIDE {
57 return transport_->IsConnected();
59 virtual bool IsConnectedAndIdle() const OVERRIDE {
60 return transport_->IsConnectedAndIdle();
62 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE {
63 return transport_->GetPeerAddress(address);
65 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE {
66 return transport_->GetLocalAddress(address);
68 virtual const BoundNetLog& NetLog() const OVERRIDE {
69 return transport_->NetLog();
71 virtual void SetSubresourceSpeculation() OVERRIDE {
72 transport_->SetSubresourceSpeculation();
74 virtual void SetOmniboxSpeculation() OVERRIDE {
75 transport_->SetOmniboxSpeculation();
77 virtual bool WasEverUsed() const OVERRIDE {
78 return transport_->WasEverUsed();
80 virtual bool UsingTCPFastOpen() const OVERRIDE {
81 return transport_->UsingTCPFastOpen();
83 virtual bool WasNpnNegotiated() const OVERRIDE {
84 return transport_->WasNpnNegotiated();
86 virtual NextProto GetNegotiatedProtocol() const OVERRIDE {
87 return transport_->GetNegotiatedProtocol();
89 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE {
90 return transport_->GetSSLInfo(ssl_info);
93 // Socket implementation:
94 virtual int Read(IOBuffer* buf,
96 const CompletionCallback& callback) OVERRIDE {
97 return transport_->Read(buf, buf_len, callback);
99 virtual int Write(IOBuffer* buf,
101 const CompletionCallback& callback) OVERRIDE {
102 return transport_->Write(buf, buf_len, callback);
104 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE {
105 return transport_->SetReceiveBufferSize(size);
107 virtual bool SetSendBufferSize(int32 size) OVERRIDE {
108 return transport_->SetSendBufferSize(size);
112 scoped_ptr<StreamSocket> transport_;
115 // ReadBufferingStreamSocket is a wrapper for an existing StreamSocket that
116 // will ensure a certain amount of data is internally buffered before
117 // satisfying a Read() request. It exists to mimic OS-level internal
118 // buffering, but in a way to guarantee that X number of bytes will be
119 // returned to callers of Read(), regardless of how quickly the OS receives
120 // them from the TestServer.
121 class ReadBufferingStreamSocket : public WrappedStreamSocket {
123 explicit ReadBufferingStreamSocket(scoped_ptr<StreamSocket> transport);
124 virtual ~ReadBufferingStreamSocket() {}
126 // Socket implementation:
127 virtual int Read(IOBuffer* buf,
129 const CompletionCallback& callback) OVERRIDE;
131 // Sets the internal buffer to |size|. This must not be greater than
132 // the largest value supplied to Read() - that is, it does not handle
133 // having "leftovers" at the end of Read().
134 // Each call to Read() will be prevented from completion until at least
135 // |size| data has been read.
136 // Set to 0 to turn off buffering, causing Read() to transparently
137 // read via the underlying transport.
138 void SetBufferSize(int size);
147 int DoLoop(int result);
149 int DoReadComplete(int result);
150 void OnReadCompleted(int result);
153 scoped_refptr<GrowableIOBuffer> read_buffer_;
156 scoped_refptr<IOBuffer> user_read_buf_;
157 CompletionCallback user_read_callback_;
160 ReadBufferingStreamSocket::ReadBufferingStreamSocket(
161 scoped_ptr<StreamSocket> transport)
162 : WrappedStreamSocket(transport.Pass()),
163 read_buffer_(new GrowableIOBuffer()),
166 void ReadBufferingStreamSocket::SetBufferSize(int size) {
167 DCHECK(!user_read_buf_.get());
169 read_buffer_->SetCapacity(size);
172 int ReadBufferingStreamSocket::Read(IOBuffer* buf,
174 const CompletionCallback& callback) {
175 if (buffer_size_ == 0)
176 return transport_->Read(buf, buf_len, callback);
178 if (buf_len < buffer_size_)
179 return ERR_UNEXPECTED;
182 user_read_buf_ = buf;
183 int result = DoLoop(OK);
184 if (result == ERR_IO_PENDING)
185 user_read_callback_ = callback;
187 user_read_buf_ = NULL;
191 int ReadBufferingStreamSocket::DoLoop(int result) {
194 State current_state = state_;
196 switch (current_state) {
200 case STATE_READ_COMPLETE:
201 rv = DoReadComplete(rv);
205 NOTREACHED() << "Unexpected state: " << current_state;
209 } while (rv != ERR_IO_PENDING && state_ != STATE_NONE);
213 int ReadBufferingStreamSocket::DoRead() {
214 state_ = STATE_READ_COMPLETE;
216 transport_->Read(read_buffer_.get(),
217 read_buffer_->RemainingCapacity(),
218 base::Bind(&ReadBufferingStreamSocket::OnReadCompleted,
219 base::Unretained(this)));
223 int ReadBufferingStreamSocket::DoReadComplete(int result) {
228 read_buffer_->set_offset(read_buffer_->offset() + result);
229 if (read_buffer_->RemainingCapacity() > 0) {
234 memcpy(user_read_buf_->data(),
235 read_buffer_->StartOfBuffer(),
236 read_buffer_->capacity());
237 read_buffer_->set_offset(0);
238 return read_buffer_->capacity();
241 void ReadBufferingStreamSocket::OnReadCompleted(int result) {
242 result = DoLoop(result);
243 if (result == ERR_IO_PENDING)
246 user_read_buf_ = NULL;
247 base::ResetAndReturn(&user_read_callback_).Run(result);
250 // Simulates synchronously receiving an error during Read() or Write()
251 class SynchronousErrorStreamSocket : public WrappedStreamSocket {
253 explicit SynchronousErrorStreamSocket(scoped_ptr<StreamSocket> transport);
254 virtual ~SynchronousErrorStreamSocket() {}
256 // Socket implementation:
257 virtual int Read(IOBuffer* buf,
259 const CompletionCallback& callback) OVERRIDE;
260 virtual int Write(IOBuffer* buf,
262 const CompletionCallback& callback) OVERRIDE;
264 // Sets the next Read() call and all future calls to return |error|.
265 // If there is already a pending asynchronous read, the configured error
266 // will not be returned until that asynchronous read has completed and Read()
268 void SetNextReadError(Error error) {
270 have_read_error_ = true;
271 pending_read_error_ = error;
274 // Sets the next Write() call and all future calls to return |error|.
275 // If there is already a pending asynchronous write, the configured error
276 // will not be returned until that asynchronous write has completed and
277 // Write() is called again.
278 void SetNextWriteError(Error error) {
280 have_write_error_ = true;
281 pending_write_error_ = error;
285 bool have_read_error_;
286 int pending_read_error_;
288 bool have_write_error_;
289 int pending_write_error_;
291 DISALLOW_COPY_AND_ASSIGN(SynchronousErrorStreamSocket);
294 SynchronousErrorStreamSocket::SynchronousErrorStreamSocket(
295 scoped_ptr<StreamSocket> transport)
296 : WrappedStreamSocket(transport.Pass()),
297 have_read_error_(false),
298 pending_read_error_(OK),
299 have_write_error_(false),
300 pending_write_error_(OK) {}
302 int SynchronousErrorStreamSocket::Read(IOBuffer* buf,
304 const CompletionCallback& callback) {
305 if (have_read_error_)
306 return pending_read_error_;
307 return transport_->Read(buf, buf_len, callback);
310 int SynchronousErrorStreamSocket::Write(IOBuffer* buf,
312 const CompletionCallback& callback) {
313 if (have_write_error_)
314 return pending_write_error_;
315 return transport_->Write(buf, buf_len, callback);
318 // FakeBlockingStreamSocket wraps an existing StreamSocket and simulates the
319 // underlying transport needing to complete things asynchronously in a
320 // deterministic manner (e.g.: independent of the TestServer and the OS's
322 class FakeBlockingStreamSocket : public WrappedStreamSocket {
324 explicit FakeBlockingStreamSocket(scoped_ptr<StreamSocket> transport);
325 virtual ~FakeBlockingStreamSocket() {}
327 // Socket implementation:
328 virtual int Read(IOBuffer* buf,
330 const CompletionCallback& callback) OVERRIDE {
331 return read_state_.RunWrappedFunction(buf, buf_len, callback);
333 virtual int Write(IOBuffer* buf,
335 const CompletionCallback& callback) OVERRIDE {
336 return write_state_.RunWrappedFunction(buf, buf_len, callback);
339 // Causes the next call to Read() to return ERR_IO_PENDING, not completing
340 // (invoking the callback) until UnblockRead() has been called and the
341 // underlying transport has completed.
342 void SetNextReadShouldBlock() { read_state_.SetShouldBlock(); }
343 void UnblockRead() { read_state_.Unblock(); }
345 // Causes the next call to Write() to return ERR_IO_PENDING, not completing
346 // (invoking the callback) until UnblockWrite() has been called and the
347 // underlying transport has completed.
348 void SetNextWriteShouldBlock() { write_state_.SetShouldBlock(); }
349 void UnblockWrite() { write_state_.Unblock(); }
352 // Tracks the state for simulating a blocking Read/Write operation.
353 class BlockingState {
355 // Wrapper for the underlying Socket function to call (ie: Read/Write).
356 typedef base::Callback<int(IOBuffer*, int, const CompletionCallback&)>
357 WrappedSocketFunction;
359 explicit BlockingState(const WrappedSocketFunction& function);
362 // Sets the next call to RunWrappedFunction() to block, returning
363 // ERR_IO_PENDING and not invoking the user callback until Unblock() is
365 void SetShouldBlock();
367 // Unblocks the currently blocked pending function, invoking the user
368 // callback if the results are immediately available.
369 // Note: It's not valid to call this unless SetShouldBlock() has been
370 // called beforehand.
373 // Performs the wrapped socket function on the underlying transport. If
374 // configured to block via SetShouldBlock(), then |user_callback| will not
375 // be invoked until Unblock() has been called.
376 int RunWrappedFunction(IOBuffer* buf,
378 const CompletionCallback& user_callback);
381 // Handles completion from the underlying wrapped socket function.
382 void OnCompleted(int result);
384 WrappedSocketFunction wrapped_function_;
388 CompletionCallback user_callback_;
391 BlockingState read_state_;
392 BlockingState write_state_;
394 DISALLOW_COPY_AND_ASSIGN(FakeBlockingStreamSocket);
397 FakeBlockingStreamSocket::FakeBlockingStreamSocket(
398 scoped_ptr<StreamSocket> transport)
399 : WrappedStreamSocket(transport.Pass()),
400 read_state_(base::Bind(&Socket::Read,
401 base::Unretained(transport_.get()))),
402 write_state_(base::Bind(&Socket::Write,
403 base::Unretained(transport_.get()))) {}
405 FakeBlockingStreamSocket::BlockingState::BlockingState(
406 const WrappedSocketFunction& function)
407 : wrapped_function_(function),
408 should_block_(false),
410 pending_result_(OK) {}
412 void FakeBlockingStreamSocket::BlockingState::SetShouldBlock() {
413 DCHECK(!should_block_);
414 should_block_ = true;
417 void FakeBlockingStreamSocket::BlockingState::Unblock() {
418 DCHECK(should_block_);
419 should_block_ = false;
421 // If the operation is still pending in the underlying transport, immediately
422 // return - OnCompleted() will handle invoking the callback once the transport
427 have_result_ = false;
429 base::ResetAndReturn(&user_callback_).Run(pending_result_);
432 int FakeBlockingStreamSocket::BlockingState::RunWrappedFunction(
435 const CompletionCallback& callback) {
437 // The callback to be called by the underlying transport. Either forward
438 // directly to the user's callback if not set to block, or intercept it with
439 // OnCompleted so that the user's callback is not invoked until Unblock() is
441 CompletionCallback transport_callback =
442 !should_block_ ? callback : base::Bind(&BlockingState::OnCompleted,
443 base::Unretained(this));
444 int rv = wrapped_function_.Run(buf, len, transport_callback);
446 user_callback_ = callback;
447 // May have completed synchronously.
448 have_result_ = (rv != ERR_IO_PENDING);
449 pending_result_ = rv;
450 return ERR_IO_PENDING;
456 void FakeBlockingStreamSocket::BlockingState::OnCompleted(int result) {
458 // Store the result so that the callback can be invoked once Unblock() is
461 pending_result_ = result;
465 // Otherwise, the Unblock() function was called before the underlying
466 // transport completed, so run the user's callback immediately.
467 base::ResetAndReturn(&user_callback_).Run(result);
470 // CompletionCallback that will delete the associated StreamSocket when
471 // the callback is invoked.
472 class DeleteSocketCallback : public TestCompletionCallbackBase {
474 explicit DeleteSocketCallback(StreamSocket* socket)
476 callback_(base::Bind(&DeleteSocketCallback::OnComplete,
477 base::Unretained(this))) {}
478 virtual ~DeleteSocketCallback() {}
480 const CompletionCallback& callback() const { return callback_; }
483 void OnComplete(int result) {
488 ADD_FAILURE() << "Deleting socket twice";
493 StreamSocket* socket_;
494 CompletionCallback callback_;
496 DISALLOW_COPY_AND_ASSIGN(DeleteSocketCallback);
499 class SSLClientSocketTest : public PlatformTest {
501 SSLClientSocketTest()
502 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
503 cert_verifier_(new MockCertVerifier),
504 transport_security_state_(new TransportSecurityState) {
505 cert_verifier_->set_default_result(OK);
506 context_.cert_verifier = cert_verifier_.get();
507 context_.transport_security_state = transport_security_state_.get();
511 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
512 scoped_ptr<StreamSocket> transport_socket,
513 const HostPortPair& host_and_port,
514 const SSLConfig& ssl_config) {
515 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
516 connection->SetSocket(transport_socket.Pass());
517 return socket_factory_->CreateSSLClientSocket(
518 connection.Pass(), host_and_port, ssl_config, context_);
521 ClientSocketFactory* socket_factory_;
522 scoped_ptr<MockCertVerifier> cert_verifier_;
523 scoped_ptr<TransportSecurityState> transport_security_state_;
524 SSLClientSocketContext context_;
527 // Verifies the correctness of GetSSLCertRequestInfo.
528 class SSLClientSocketCertRequestInfoTest : public SSLClientSocketTest {
530 // Creates a test server with the given SSLOptions, connects to it and returns
531 // the SSLCertRequestInfo reported by the socket.
532 scoped_refptr<SSLCertRequestInfo> GetCertRequest(
533 SpawnedTestServer::SSLOptions ssl_options) {
534 SpawnedTestServer test_server(
535 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
536 if (!test_server.Start())
540 if (!test_server.GetAddressList(&addr))
543 TestCompletionCallback callback;
545 scoped_ptr<StreamSocket> transport(
546 new TCPClientSocket(addr, &log, NetLog::Source()));
547 int rv = transport->Connect(callback.callback());
548 if (rv == ERR_IO_PENDING)
549 rv = callback.WaitForResult();
552 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
553 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
554 EXPECT_FALSE(sock->IsConnected());
556 rv = sock->Connect(callback.callback());
557 if (rv == ERR_IO_PENDING)
558 rv = callback.WaitForResult();
559 scoped_refptr<SSLCertRequestInfo> request_info = new SSLCertRequestInfo();
560 sock->GetSSLCertRequestInfo(request_info.get());
562 EXPECT_FALSE(sock->IsConnected());
568 //-----------------------------------------------------------------------------
570 // LogContainsSSLConnectEndEvent returns true if the given index in the given
571 // log is an SSL connect end event. The NSS sockets will cork in an attempt to
572 // merge the first application data record with the Finished message when false
573 // starting. However, in order to avoid the server timing out the handshake,
574 // they'll give up waiting for application data and send the Finished after a
575 // timeout. This means that an SSL connect end event may appear as a socket
577 static bool LogContainsSSLConnectEndEvent(
578 const CapturingNetLog::CapturedEntryList& log,
580 return LogContainsEndEvent(log, i, NetLog::TYPE_SSL_CONNECT) ||
582 log, i, NetLog::TYPE_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
587 TEST_F(SSLClientSocketTest, Connect) {
588 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
589 SpawnedTestServer::kLocalhost,
591 ASSERT_TRUE(test_server.Start());
594 ASSERT_TRUE(test_server.GetAddressList(&addr));
596 TestCompletionCallback callback;
598 scoped_ptr<StreamSocket> transport(
599 new TCPClientSocket(addr, &log, NetLog::Source()));
600 int rv = transport->Connect(callback.callback());
601 if (rv == ERR_IO_PENDING)
602 rv = callback.WaitForResult();
605 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
606 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
608 EXPECT_FALSE(sock->IsConnected());
610 rv = sock->Connect(callback.callback());
612 CapturingNetLog::CapturedEntryList entries;
613 log.GetEntries(&entries);
614 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
615 if (rv == ERR_IO_PENDING)
616 rv = callback.WaitForResult();
618 EXPECT_TRUE(sock->IsConnected());
619 log.GetEntries(&entries);
620 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
623 EXPECT_FALSE(sock->IsConnected());
626 TEST_F(SSLClientSocketTest, ConnectExpired) {
627 SpawnedTestServer::SSLOptions ssl_options(
628 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
629 SpawnedTestServer test_server(
630 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
631 ASSERT_TRUE(test_server.Start());
633 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
636 ASSERT_TRUE(test_server.GetAddressList(&addr));
638 TestCompletionCallback callback;
640 scoped_ptr<StreamSocket> transport(
641 new TCPClientSocket(addr, &log, NetLog::Source()));
642 int rv = transport->Connect(callback.callback());
643 if (rv == ERR_IO_PENDING)
644 rv = callback.WaitForResult();
647 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
648 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
650 EXPECT_FALSE(sock->IsConnected());
652 rv = sock->Connect(callback.callback());
654 CapturingNetLog::CapturedEntryList entries;
655 log.GetEntries(&entries);
656 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
657 if (rv == ERR_IO_PENDING)
658 rv = callback.WaitForResult();
660 EXPECT_EQ(ERR_CERT_DATE_INVALID, rv);
662 // Rather than testing whether or not the underlying socket is connected,
663 // test that the handshake has finished. This is because it may be
664 // desirable to disconnect the socket before showing a user prompt, since
665 // the user may take indefinitely long to respond.
666 log.GetEntries(&entries);
667 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
670 TEST_F(SSLClientSocketTest, ConnectMismatched) {
671 SpawnedTestServer::SSLOptions ssl_options(
672 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
673 SpawnedTestServer test_server(
674 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
675 ASSERT_TRUE(test_server.Start());
677 cert_verifier_->set_default_result(ERR_CERT_COMMON_NAME_INVALID);
680 ASSERT_TRUE(test_server.GetAddressList(&addr));
682 TestCompletionCallback callback;
684 scoped_ptr<StreamSocket> transport(
685 new TCPClientSocket(addr, &log, NetLog::Source()));
686 int rv = transport->Connect(callback.callback());
687 if (rv == ERR_IO_PENDING)
688 rv = callback.WaitForResult();
691 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
692 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
694 EXPECT_FALSE(sock->IsConnected());
696 rv = sock->Connect(callback.callback());
698 CapturingNetLog::CapturedEntryList entries;
699 log.GetEntries(&entries);
700 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
701 if (rv == ERR_IO_PENDING)
702 rv = callback.WaitForResult();
704 EXPECT_EQ(ERR_CERT_COMMON_NAME_INVALID, rv);
706 // Rather than testing whether or not the underlying socket is connected,
707 // test that the handshake has finished. This is because it may be
708 // desirable to disconnect the socket before showing a user prompt, since
709 // the user may take indefinitely long to respond.
710 log.GetEntries(&entries);
711 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
714 // Attempt to connect to a page which requests a client certificate. It should
715 // return an error code on connect.
716 TEST_F(SSLClientSocketTest, ConnectClientAuthCertRequested) {
717 SpawnedTestServer::SSLOptions ssl_options;
718 ssl_options.request_client_certificate = true;
719 SpawnedTestServer test_server(
720 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
721 ASSERT_TRUE(test_server.Start());
724 ASSERT_TRUE(test_server.GetAddressList(&addr));
726 TestCompletionCallback callback;
728 scoped_ptr<StreamSocket> transport(
729 new TCPClientSocket(addr, &log, NetLog::Source()));
730 int rv = transport->Connect(callback.callback());
731 if (rv == ERR_IO_PENDING)
732 rv = callback.WaitForResult();
735 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
736 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
738 EXPECT_FALSE(sock->IsConnected());
740 rv = sock->Connect(callback.callback());
742 CapturingNetLog::CapturedEntryList entries;
743 log.GetEntries(&entries);
744 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
745 if (rv == ERR_IO_PENDING)
746 rv = callback.WaitForResult();
748 log.GetEntries(&entries);
749 // Because we prematurely kill the handshake at CertificateRequest,
750 // the server may still send data (notably the ServerHelloDone)
751 // after the error is returned. As a result, the SSL_CONNECT may not
752 // be the last entry. See http://crbug.com/54445. We use
753 // ExpectLogContainsSomewhere instead of
754 // LogContainsSSLConnectEndEvent to avoid assuming, e.g., only one
755 // extra read instead of two. This occurs before the handshake ends,
756 // so the corking logic of LogContainsSSLConnectEndEvent isn't
759 // TODO(davidben): When SSL_RestartHandshakeAfterCertReq in NSS is
760 // fixed and we can respond to the first CertificateRequest
761 // without closing the socket, add a unit test for sending the
762 // certificate. This test may still be useful as we'll want to close
763 // the socket on a timeout if the user takes a long time to pick a
764 // cert. Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=542832
765 ExpectLogContainsSomewhere(
766 entries, 0, NetLog::TYPE_SSL_CONNECT, NetLog::PHASE_END);
767 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
768 EXPECT_FALSE(sock->IsConnected());
771 // Connect to a server requesting optional client authentication. Send it a
772 // null certificate. It should allow the connection.
774 // TODO(davidben): Also test providing an actual certificate.
775 TEST_F(SSLClientSocketTest, ConnectClientAuthSendNullCert) {
776 SpawnedTestServer::SSLOptions ssl_options;
777 ssl_options.request_client_certificate = true;
778 SpawnedTestServer test_server(
779 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
780 ASSERT_TRUE(test_server.Start());
783 ASSERT_TRUE(test_server.GetAddressList(&addr));
785 TestCompletionCallback callback;
787 scoped_ptr<StreamSocket> transport(
788 new TCPClientSocket(addr, &log, NetLog::Source()));
789 int rv = transport->Connect(callback.callback());
790 if (rv == ERR_IO_PENDING)
791 rv = callback.WaitForResult();
794 SSLConfig ssl_config = kDefaultSSLConfig;
795 ssl_config.send_client_cert = true;
796 ssl_config.client_cert = NULL;
798 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
799 transport.Pass(), test_server.host_port_pair(), ssl_config));
801 EXPECT_FALSE(sock->IsConnected());
803 // Our test server accepts certificate-less connections.
804 // TODO(davidben): Add a test which requires them and verify the error.
805 rv = sock->Connect(callback.callback());
807 CapturingNetLog::CapturedEntryList entries;
808 log.GetEntries(&entries);
809 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
810 if (rv == ERR_IO_PENDING)
811 rv = callback.WaitForResult();
814 EXPECT_TRUE(sock->IsConnected());
815 log.GetEntries(&entries);
816 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
818 // We responded to the server's certificate request with a Certificate
819 // message with no client certificate in it. ssl_info.client_cert_sent
820 // should be false in this case.
822 sock->GetSSLInfo(&ssl_info);
823 EXPECT_FALSE(ssl_info.client_cert_sent);
826 EXPECT_FALSE(sock->IsConnected());
829 // TODO(wtc): Add unit tests for IsConnectedAndIdle:
830 // - Server closes an SSL connection (with a close_notify alert message).
831 // - Server closes the underlying TCP connection directly.
832 // - Server sends data unexpectedly.
834 TEST_F(SSLClientSocketTest, Read) {
835 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
836 SpawnedTestServer::kLocalhost,
838 ASSERT_TRUE(test_server.Start());
841 ASSERT_TRUE(test_server.GetAddressList(&addr));
843 TestCompletionCallback callback;
844 scoped_ptr<StreamSocket> transport(
845 new TCPClientSocket(addr, NULL, NetLog::Source()));
846 int rv = transport->Connect(callback.callback());
847 if (rv == ERR_IO_PENDING)
848 rv = callback.WaitForResult();
851 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
852 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
854 rv = sock->Connect(callback.callback());
855 if (rv == ERR_IO_PENDING)
856 rv = callback.WaitForResult();
858 EXPECT_TRUE(sock->IsConnected());
860 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
861 scoped_refptr<IOBuffer> request_buffer(
862 new IOBuffer(arraysize(request_text) - 1));
863 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
866 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
867 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
869 if (rv == ERR_IO_PENDING)
870 rv = callback.WaitForResult();
871 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
873 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
875 rv = sock->Read(buf.get(), 4096, callback.callback());
876 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
878 if (rv == ERR_IO_PENDING)
879 rv = callback.WaitForResult();
887 // Tests that the SSLClientSocket properly handles when the underlying transport
888 // synchronously returns an error code - such as if an intermediary terminates
889 // the socket connection uncleanly.
890 // This is a regression test for http://crbug.com/238536
891 TEST_F(SSLClientSocketTest, Read_WithSynchronousError) {
892 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
893 SpawnedTestServer::kLocalhost,
895 ASSERT_TRUE(test_server.Start());
898 ASSERT_TRUE(test_server.GetAddressList(&addr));
900 TestCompletionCallback callback;
901 scoped_ptr<StreamSocket> real_transport(
902 new TCPClientSocket(addr, NULL, NetLog::Source()));
903 scoped_ptr<SynchronousErrorStreamSocket> transport(
904 new SynchronousErrorStreamSocket(real_transport.Pass()));
905 int rv = callback.GetResult(transport->Connect(callback.callback()));
908 // Disable TLS False Start to avoid handshake non-determinism.
909 SSLConfig ssl_config;
910 ssl_config.false_start_enabled = false;
912 SynchronousErrorStreamSocket* raw_transport = transport.get();
913 scoped_ptr<SSLClientSocket> sock(
914 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
915 test_server.host_port_pair(),
918 rv = callback.GetResult(sock->Connect(callback.callback()));
920 EXPECT_TRUE(sock->IsConnected());
922 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
923 static const int kRequestTextSize =
924 static_cast<int>(arraysize(request_text) - 1);
925 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
926 memcpy(request_buffer->data(), request_text, kRequestTextSize);
928 rv = callback.GetResult(
929 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
930 EXPECT_EQ(kRequestTextSize, rv);
932 // Simulate an unclean/forcible shutdown.
933 raw_transport->SetNextReadError(ERR_CONNECTION_RESET);
935 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
937 // Note: This test will hang if this bug has regressed. Simply checking that
938 // rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING is a legitimate
939 // result when using a dedicated task runner for NSS.
940 rv = callback.GetResult(sock->Read(buf.get(), 4096, callback.callback()));
942 #if !defined(USE_OPENSSL)
943 // SSLClientSocketNSS records the error exactly
944 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
946 // SSLClientSocketOpenSSL treats any errors as a simple EOF.
951 // Tests that the SSLClientSocket properly handles when the underlying transport
952 // asynchronously returns an error code while writing data - such as if an
953 // intermediary terminates the socket connection uncleanly.
954 // This is a regression test for http://crbug.com/249848
955 TEST_F(SSLClientSocketTest, Write_WithSynchronousError) {
956 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
957 SpawnedTestServer::kLocalhost,
959 ASSERT_TRUE(test_server.Start());
962 ASSERT_TRUE(test_server.GetAddressList(&addr));
964 TestCompletionCallback callback;
965 scoped_ptr<StreamSocket> real_transport(
966 new TCPClientSocket(addr, NULL, NetLog::Source()));
967 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
968 // is retained in order to configure additional errors.
969 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
970 new SynchronousErrorStreamSocket(real_transport.Pass()));
971 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
972 scoped_ptr<FakeBlockingStreamSocket> transport(
973 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
974 FakeBlockingStreamSocket* raw_transport = transport.get();
975 int rv = callback.GetResult(transport->Connect(callback.callback()));
978 // Disable TLS False Start to avoid handshake non-determinism.
979 SSLConfig ssl_config;
980 ssl_config.false_start_enabled = false;
982 scoped_ptr<SSLClientSocket> sock(
983 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
984 test_server.host_port_pair(),
987 rv = callback.GetResult(sock->Connect(callback.callback()));
989 EXPECT_TRUE(sock->IsConnected());
991 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
992 static const int kRequestTextSize =
993 static_cast<int>(arraysize(request_text) - 1);
994 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
995 memcpy(request_buffer->data(), request_text, kRequestTextSize);
997 // Simulate an unclean/forcible shutdown on the underlying socket.
998 // However, simulate this error asynchronously.
999 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1000 raw_transport->SetNextWriteShouldBlock();
1002 // This write should complete synchronously, because the TLS ciphertext
1003 // can be created and placed into the outgoing buffers independent of the
1004 // underlying transport.
1005 rv = callback.GetResult(
1006 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1007 EXPECT_EQ(kRequestTextSize, rv);
1009 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1011 rv = sock->Read(buf.get(), 4096, callback.callback());
1012 EXPECT_EQ(ERR_IO_PENDING, rv);
1014 // Now unblock the outgoing request, having it fail with the connection
1016 raw_transport->UnblockWrite();
1018 // Note: This will cause an inifite loop if this bug has regressed. Simply
1019 // checking that rv != ERR_IO_PENDING is insufficient, as ERR_IO_PENDING
1020 // is a legitimate result when using a dedicated task runner for NSS.
1021 rv = callback.GetResult(rv);
1023 #if !defined(USE_OPENSSL)
1024 // SSLClientSocketNSS records the error exactly
1025 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1027 // SSLClientSocketOpenSSL treats any errors as a simple EOF.
1032 // Test the full duplex mode, with Read and Write pending at the same time.
1033 // This test also serves as a regression test for http://crbug.com/29815.
1034 TEST_F(SSLClientSocketTest, Read_FullDuplex) {
1035 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1036 SpawnedTestServer::kLocalhost,
1038 ASSERT_TRUE(test_server.Start());
1041 ASSERT_TRUE(test_server.GetAddressList(&addr));
1043 TestCompletionCallback callback; // Used for everything except Write.
1045 scoped_ptr<StreamSocket> transport(
1046 new TCPClientSocket(addr, NULL, NetLog::Source()));
1047 int rv = transport->Connect(callback.callback());
1048 if (rv == ERR_IO_PENDING)
1049 rv = callback.WaitForResult();
1052 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1053 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1055 rv = sock->Connect(callback.callback());
1056 if (rv == ERR_IO_PENDING)
1057 rv = callback.WaitForResult();
1059 EXPECT_TRUE(sock->IsConnected());
1061 // Issue a "hanging" Read first.
1062 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1063 rv = sock->Read(buf.get(), 4096, callback.callback());
1064 // We haven't written the request, so there should be no response yet.
1065 ASSERT_EQ(ERR_IO_PENDING, rv);
1067 // Write the request.
1068 // The request is padded with a User-Agent header to a size that causes the
1069 // memio circular buffer (4k bytes) in SSLClientSocketNSS to wrap around.
1070 // This tests the fix for http://crbug.com/29815.
1071 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1072 for (int i = 0; i < 3770; ++i)
1073 request_text.push_back('*');
1074 request_text.append("\r\n\r\n");
1075 scoped_refptr<IOBuffer> request_buffer(new StringIOBuffer(request_text));
1077 TestCompletionCallback callback2; // Used for Write only.
1079 request_buffer.get(), request_text.size(), callback2.callback());
1080 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1082 if (rv == ERR_IO_PENDING)
1083 rv = callback2.WaitForResult();
1084 EXPECT_EQ(static_cast<int>(request_text.size()), rv);
1086 // Now get the Read result.
1087 rv = callback.WaitForResult();
1091 // Attempts to Read() and Write() from an SSLClientSocketNSS in full duplex
1092 // mode when the underlying transport is blocked on sending data. When the
1093 // underlying transport completes due to an error, it should invoke both the
1094 // Read() and Write() callbacks. If the socket is deleted by the Read()
1095 // callback, the Write() callback should not be invoked.
1096 // Regression test for http://crbug.com/232633
1097 TEST_F(SSLClientSocketTest, Read_DeleteWhilePendingFullDuplex) {
1098 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1099 SpawnedTestServer::kLocalhost,
1101 ASSERT_TRUE(test_server.Start());
1104 ASSERT_TRUE(test_server.GetAddressList(&addr));
1106 TestCompletionCallback callback;
1107 scoped_ptr<StreamSocket> real_transport(
1108 new TCPClientSocket(addr, NULL, NetLog::Source()));
1109 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1110 // is retained in order to configure additional errors.
1111 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1112 new SynchronousErrorStreamSocket(real_transport.Pass()));
1113 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1114 scoped_ptr<FakeBlockingStreamSocket> transport(
1115 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1116 FakeBlockingStreamSocket* raw_transport = transport.get();
1118 int rv = callback.GetResult(transport->Connect(callback.callback()));
1121 // Disable TLS False Start to avoid handshake non-determinism.
1122 SSLConfig ssl_config;
1123 ssl_config.false_start_enabled = false;
1125 scoped_ptr<SSLClientSocket> sock =
1126 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1127 test_server.host_port_pair(),
1130 rv = callback.GetResult(sock->Connect(callback.callback()));
1132 EXPECT_TRUE(sock->IsConnected());
1134 std::string request_text = "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1135 request_text.append(20 * 1024, '*');
1136 request_text.append("\r\n\r\n");
1137 scoped_refptr<DrainableIOBuffer> request_buffer(new DrainableIOBuffer(
1138 new StringIOBuffer(request_text), request_text.size()));
1140 // Simulate errors being returned from the underlying Read() and Write() ...
1141 raw_error_socket->SetNextReadError(ERR_CONNECTION_RESET);
1142 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1143 // ... but have those errors returned asynchronously. Because the Write() will
1144 // return first, this will trigger the error.
1145 raw_transport->SetNextReadShouldBlock();
1146 raw_transport->SetNextWriteShouldBlock();
1148 // Enqueue a Read() before calling Write(), which should "hang" due to
1149 // the ERR_IO_PENDING caused by SetReadShouldBlock() and thus return.
1150 SSLClientSocket* raw_sock = sock.get();
1151 DeleteSocketCallback read_callback(sock.release());
1152 scoped_refptr<IOBuffer> read_buf(new IOBuffer(4096));
1153 rv = raw_sock->Read(read_buf.get(), 4096, read_callback.callback());
1155 // Ensure things didn't complete synchronously, otherwise |sock| is invalid.
1156 ASSERT_EQ(ERR_IO_PENDING, rv);
1157 ASSERT_FALSE(read_callback.have_result());
1159 #if !defined(USE_OPENSSL)
1160 // NSS follows a pattern where a call to PR_Write will only consume as
1161 // much data as it can encode into application data records before the
1162 // internal memio buffer is full, which should only fill if writing a large
1163 // amount of data and the underlying transport is blocked. Once this happens,
1164 // NSS will return (total size of all application data records it wrote) - 1,
1165 // with the caller expected to resume with the remaining unsent data.
1167 // This causes SSLClientSocketNSS::Write to return that it wrote some data
1168 // before it will return ERR_IO_PENDING, so make an extra call to Write() to
1169 // get the socket in the state needed for the test below.
1171 // This is not needed for OpenSSL, because for OpenSSL,
1172 // SSL_MODE_ENABLE_PARTIAL_WRITE is not specified - thus
1173 // SSLClientSocketOpenSSL::Write() will not return until all of
1174 // |request_buffer| has been written to the underlying BIO (although not
1175 // necessarily the underlying transport).
1176 rv = callback.GetResult(raw_sock->Write(request_buffer.get(),
1177 request_buffer->BytesRemaining(),
1178 callback.callback()));
1180 request_buffer->DidConsume(rv);
1182 // Guard to ensure that |request_buffer| was larger than all of the internal
1183 // buffers (transport, memio, NSS) along the way - otherwise the next call
1184 // to Write() will crash with an invalid buffer.
1185 ASSERT_LT(0, request_buffer->BytesRemaining());
1188 // Attempt to write the remaining data. NSS will not be able to consume the
1189 // application data because the internal buffers are full, while OpenSSL will
1190 // return that its blocked because the underlying transport is blocked.
1191 rv = raw_sock->Write(request_buffer.get(),
1192 request_buffer->BytesRemaining(),
1193 callback.callback());
1194 ASSERT_EQ(ERR_IO_PENDING, rv);
1195 ASSERT_FALSE(callback.have_result());
1197 // Now unblock Write(), which will invoke OnSendComplete and (eventually)
1198 // call the Read() callback, deleting the socket and thus aborting calling
1199 // the Write() callback.
1200 raw_transport->UnblockWrite();
1202 rv = read_callback.WaitForResult();
1204 #if !defined(USE_OPENSSL)
1205 // NSS records the error exactly.
1206 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1208 // OpenSSL treats any errors as a simple EOF.
1212 // The Write callback should not have been called.
1213 EXPECT_FALSE(callback.have_result());
1216 // Tests that the SSLClientSocket does not crash if data is received on the
1217 // transport socket after a failing write. This can occur if we have a Write
1218 // error in a SPDY socket.
1219 // Regression test for http://crbug.com/335557
1220 TEST_F(SSLClientSocketTest, Read_WithWriteError) {
1221 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1222 SpawnedTestServer::kLocalhost,
1224 ASSERT_TRUE(test_server.Start());
1227 ASSERT_TRUE(test_server.GetAddressList(&addr));
1229 TestCompletionCallback callback;
1230 scoped_ptr<StreamSocket> real_transport(
1231 new TCPClientSocket(addr, NULL, NetLog::Source()));
1232 // Note: |error_socket|'s ownership is handed to |transport|, but a pointer
1233 // is retained in order to configure additional errors.
1234 scoped_ptr<SynchronousErrorStreamSocket> error_socket(
1235 new SynchronousErrorStreamSocket(real_transport.Pass()));
1236 SynchronousErrorStreamSocket* raw_error_socket = error_socket.get();
1237 scoped_ptr<FakeBlockingStreamSocket> transport(
1238 new FakeBlockingStreamSocket(error_socket.PassAs<StreamSocket>()));
1239 FakeBlockingStreamSocket* raw_transport = transport.get();
1241 int rv = callback.GetResult(transport->Connect(callback.callback()));
1244 // Disable TLS False Start to avoid handshake non-determinism.
1245 SSLConfig ssl_config;
1246 ssl_config.false_start_enabled = false;
1248 scoped_ptr<SSLClientSocket> sock(
1249 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1250 test_server.host_port_pair(),
1253 rv = callback.GetResult(sock->Connect(callback.callback()));
1255 EXPECT_TRUE(sock->IsConnected());
1257 // Send a request so there is something to read from the socket.
1258 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1259 static const int kRequestTextSize =
1260 static_cast<int>(arraysize(request_text) - 1);
1261 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestTextSize));
1262 memcpy(request_buffer->data(), request_text, kRequestTextSize);
1264 rv = callback.GetResult(
1265 sock->Write(request_buffer.get(), kRequestTextSize, callback.callback()));
1266 EXPECT_EQ(kRequestTextSize, rv);
1268 // Start a hanging read.
1269 TestCompletionCallback read_callback;
1270 raw_transport->SetNextReadShouldBlock();
1271 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1272 rv = sock->Read(buf.get(), 4096, read_callback.callback());
1273 EXPECT_EQ(ERR_IO_PENDING, rv);
1275 // Perform another write, but have it fail. Write a request larger than the
1276 // internal socket buffers so that the request hits the underlying transport
1277 // socket and detects the error.
1278 std::string long_request_text =
1279 "GET / HTTP/1.1\r\nUser-Agent: long browser name ";
1280 long_request_text.append(20 * 1024, '*');
1281 long_request_text.append("\r\n\r\n");
1282 scoped_refptr<DrainableIOBuffer> long_request_buffer(new DrainableIOBuffer(
1283 new StringIOBuffer(long_request_text), long_request_text.size()));
1285 raw_error_socket->SetNextWriteError(ERR_CONNECTION_RESET);
1287 // Write as much data as possible until hitting an error. This is necessary
1288 // for NSS. PR_Write will only consume as much data as it can encode into
1289 // application data records before the internal memio buffer is full, which
1290 // should only fill if writing a large amount of data and the underlying
1291 // transport is blocked. Once this happens, NSS will return (total size of all
1292 // application data records it wrote) - 1, with the caller expected to resume
1293 // with the remaining unsent data.
1295 rv = callback.GetResult(sock->Write(long_request_buffer.get(),
1296 long_request_buffer->BytesRemaining(),
1297 callback.callback()));
1299 long_request_buffer->DidConsume(rv);
1300 // Abort if the entire buffer is ever consumed.
1301 ASSERT_LT(0, long_request_buffer->BytesRemaining());
1305 #if !defined(USE_OPENSSL)
1306 // NSS records the error exactly.
1307 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1309 // OpenSSL treats the reset as a generic protocol error.
1310 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
1313 // Release the read. Some bytes should go through.
1314 raw_transport->UnblockRead();
1315 rv = read_callback.WaitForResult();
1317 // Per the fix for http://crbug.com/249848, write failures currently break
1318 // reads. Change this assertion if they're changed to not collide.
1319 EXPECT_EQ(ERR_CONNECTION_RESET, rv);
1322 TEST_F(SSLClientSocketTest, Read_SmallChunks) {
1323 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1324 SpawnedTestServer::kLocalhost,
1326 ASSERT_TRUE(test_server.Start());
1329 ASSERT_TRUE(test_server.GetAddressList(&addr));
1331 TestCompletionCallback callback;
1332 scoped_ptr<StreamSocket> transport(
1333 new TCPClientSocket(addr, NULL, NetLog::Source()));
1334 int rv = transport->Connect(callback.callback());
1335 if (rv == ERR_IO_PENDING)
1336 rv = callback.WaitForResult();
1339 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1340 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1342 rv = sock->Connect(callback.callback());
1343 if (rv == ERR_IO_PENDING)
1344 rv = callback.WaitForResult();
1347 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1348 scoped_refptr<IOBuffer> request_buffer(
1349 new IOBuffer(arraysize(request_text) - 1));
1350 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1353 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1354 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1356 if (rv == ERR_IO_PENDING)
1357 rv = callback.WaitForResult();
1358 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1360 scoped_refptr<IOBuffer> buf(new IOBuffer(1));
1362 rv = sock->Read(buf.get(), 1, callback.callback());
1363 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1365 if (rv == ERR_IO_PENDING)
1366 rv = callback.WaitForResult();
1374 TEST_F(SSLClientSocketTest, Read_ManySmallRecords) {
1375 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1376 SpawnedTestServer::kLocalhost,
1378 ASSERT_TRUE(test_server.Start());
1381 ASSERT_TRUE(test_server.GetAddressList(&addr));
1383 TestCompletionCallback callback;
1385 scoped_ptr<StreamSocket> real_transport(
1386 new TCPClientSocket(addr, NULL, NetLog::Source()));
1387 scoped_ptr<ReadBufferingStreamSocket> transport(
1388 new ReadBufferingStreamSocket(real_transport.Pass()));
1389 ReadBufferingStreamSocket* raw_transport = transport.get();
1390 int rv = callback.GetResult(transport->Connect(callback.callback()));
1393 scoped_ptr<SSLClientSocket> sock(
1394 CreateSSLClientSocket(transport.PassAs<StreamSocket>(),
1395 test_server.host_port_pair(),
1396 kDefaultSSLConfig));
1398 rv = callback.GetResult(sock->Connect(callback.callback()));
1400 ASSERT_TRUE(sock->IsConnected());
1402 const char request_text[] = "GET /ssl-many-small-records HTTP/1.0\r\n\r\n";
1403 scoped_refptr<IOBuffer> request_buffer(
1404 new IOBuffer(arraysize(request_text) - 1));
1405 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1407 rv = callback.GetResult(sock->Write(
1408 request_buffer.get(), arraysize(request_text) - 1, callback.callback()));
1410 ASSERT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1412 // Note: This relies on SSLClientSocketNSS attempting to read up to 17K of
1413 // data (the max SSL record size) at a time. Ensure that at least 15K worth
1414 // of SSL data is buffered first. The 15K of buffered data is made up of
1415 // many smaller SSL records (the TestServer writes along 1350 byte
1416 // plaintext boundaries), although there may also be a few records that are
1417 // smaller or larger, due to timing and SSL False Start.
1418 // 15K was chosen because 15K is smaller than the 17K (max) read issued by
1419 // the SSLClientSocket implementation, and larger than the minimum amount
1420 // of ciphertext necessary to contain the 8K of plaintext requested below.
1421 raw_transport->SetBufferSize(15000);
1423 scoped_refptr<IOBuffer> buffer(new IOBuffer(8192));
1424 rv = callback.GetResult(sock->Read(buffer.get(), 8192, callback.callback()));
1425 ASSERT_EQ(rv, 8192);
1428 TEST_F(SSLClientSocketTest, Read_Interrupted) {
1429 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1430 SpawnedTestServer::kLocalhost,
1432 ASSERT_TRUE(test_server.Start());
1435 ASSERT_TRUE(test_server.GetAddressList(&addr));
1437 TestCompletionCallback callback;
1438 scoped_ptr<StreamSocket> transport(
1439 new TCPClientSocket(addr, NULL, NetLog::Source()));
1440 int rv = transport->Connect(callback.callback());
1441 if (rv == ERR_IO_PENDING)
1442 rv = callback.WaitForResult();
1445 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1446 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1448 rv = sock->Connect(callback.callback());
1449 if (rv == ERR_IO_PENDING)
1450 rv = callback.WaitForResult();
1453 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1454 scoped_refptr<IOBuffer> request_buffer(
1455 new IOBuffer(arraysize(request_text) - 1));
1456 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1459 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1460 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1462 if (rv == ERR_IO_PENDING)
1463 rv = callback.WaitForResult();
1464 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1466 // Do a partial read and then exit. This test should not crash!
1467 scoped_refptr<IOBuffer> buf(new IOBuffer(512));
1468 rv = sock->Read(buf.get(), 512, callback.callback());
1469 EXPECT_TRUE(rv > 0 || rv == ERR_IO_PENDING);
1471 if (rv == ERR_IO_PENDING)
1472 rv = callback.WaitForResult();
1477 TEST_F(SSLClientSocketTest, Read_FullLogging) {
1478 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1479 SpawnedTestServer::kLocalhost,
1481 ASSERT_TRUE(test_server.Start());
1484 ASSERT_TRUE(test_server.GetAddressList(&addr));
1486 TestCompletionCallback callback;
1487 CapturingNetLog log;
1488 log.SetLogLevel(NetLog::LOG_ALL);
1489 scoped_ptr<StreamSocket> transport(
1490 new TCPClientSocket(addr, &log, NetLog::Source()));
1491 int rv = transport->Connect(callback.callback());
1492 if (rv == ERR_IO_PENDING)
1493 rv = callback.WaitForResult();
1496 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1497 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1499 rv = sock->Connect(callback.callback());
1500 if (rv == ERR_IO_PENDING)
1501 rv = callback.WaitForResult();
1503 EXPECT_TRUE(sock->IsConnected());
1505 const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
1506 scoped_refptr<IOBuffer> request_buffer(
1507 new IOBuffer(arraysize(request_text) - 1));
1508 memcpy(request_buffer->data(), request_text, arraysize(request_text) - 1);
1511 request_buffer.get(), arraysize(request_text) - 1, callback.callback());
1512 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1514 if (rv == ERR_IO_PENDING)
1515 rv = callback.WaitForResult();
1516 EXPECT_EQ(static_cast<int>(arraysize(request_text) - 1), rv);
1518 CapturingNetLog::CapturedEntryList entries;
1519 log.GetEntries(&entries);
1520 size_t last_index = ExpectLogContainsSomewhereAfter(
1521 entries, 5, NetLog::TYPE_SSL_SOCKET_BYTES_SENT, NetLog::PHASE_NONE);
1523 scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
1525 rv = sock->Read(buf.get(), 4096, callback.callback());
1526 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
1528 if (rv == ERR_IO_PENDING)
1529 rv = callback.WaitForResult();
1535 log.GetEntries(&entries);
1537 ExpectLogContainsSomewhereAfter(entries,
1539 NetLog::TYPE_SSL_SOCKET_BYTES_RECEIVED,
1540 NetLog::PHASE_NONE);
1544 // Regression test for http://crbug.com/42538
1545 TEST_F(SSLClientSocketTest, PrematureApplicationData) {
1546 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1547 SpawnedTestServer::kLocalhost,
1549 ASSERT_TRUE(test_server.Start());
1552 TestCompletionCallback callback;
1554 static const unsigned char application_data[] = {
1555 0x17, 0x03, 0x01, 0x00, 0x4a, 0x02, 0x00, 0x00, 0x46, 0x03, 0x01, 0x4b,
1556 0xc2, 0xf8, 0xb2, 0xc1, 0x56, 0x42, 0xb9, 0x57, 0x7f, 0xde, 0x87, 0x46,
1557 0xf7, 0xa3, 0x52, 0x42, 0x21, 0xf0, 0x13, 0x1c, 0x9c, 0x83, 0x88, 0xd6,
1558 0x93, 0x0c, 0xf6, 0x36, 0x30, 0x05, 0x7e, 0x20, 0xb5, 0xb5, 0x73, 0x36,
1559 0x53, 0x83, 0x0a, 0xfc, 0x17, 0x63, 0xbf, 0xa0, 0xe4, 0x42, 0x90, 0x0d,
1560 0x2f, 0x18, 0x6d, 0x20, 0xd8, 0x36, 0x3f, 0xfc, 0xe6, 0x01, 0xfa, 0x0f,
1561 0xa5, 0x75, 0x7f, 0x09, 0x00, 0x04, 0x00, 0x16, 0x03, 0x01, 0x11, 0x57,
1562 0x0b, 0x00, 0x11, 0x53, 0x00, 0x11, 0x50, 0x00, 0x06, 0x22, 0x30, 0x82,
1563 0x06, 0x1e, 0x30, 0x82, 0x05, 0x06, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02,
1566 // All reads and writes complete synchronously (async=false).
1567 MockRead data_reads[] = {
1568 MockRead(SYNCHRONOUS,
1569 reinterpret_cast<const char*>(application_data),
1570 arraysize(application_data)),
1571 MockRead(SYNCHRONOUS, OK), };
1573 StaticSocketDataProvider data(data_reads, arraysize(data_reads), NULL, 0);
1575 scoped_ptr<StreamSocket> transport(
1576 new MockTCPClientSocket(addr, NULL, &data));
1577 int rv = transport->Connect(callback.callback());
1578 if (rv == ERR_IO_PENDING)
1579 rv = callback.WaitForResult();
1582 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1583 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1585 rv = sock->Connect(callback.callback());
1586 if (rv == ERR_IO_PENDING)
1587 rv = callback.WaitForResult();
1588 EXPECT_EQ(ERR_SSL_PROTOCOL_ERROR, rv);
1591 TEST_F(SSLClientSocketTest, CipherSuiteDisables) {
1592 // Rather than exhaustively disabling every RC4 ciphersuite defined at
1593 // http://www.iana.org/assignments/tls-parameters/tls-parameters.xml,
1594 // only disabling those cipher suites that the test server actually
1596 const uint16 kCiphersToDisable[] = {0x0005, // TLS_RSA_WITH_RC4_128_SHA
1599 SpawnedTestServer::SSLOptions ssl_options;
1600 // Enable only RC4 on the test server.
1601 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
1602 SpawnedTestServer test_server(
1603 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1604 ASSERT_TRUE(test_server.Start());
1607 ASSERT_TRUE(test_server.GetAddressList(&addr));
1609 TestCompletionCallback callback;
1610 CapturingNetLog log;
1611 scoped_ptr<StreamSocket> transport(
1612 new TCPClientSocket(addr, &log, NetLog::Source()));
1613 int rv = transport->Connect(callback.callback());
1614 if (rv == ERR_IO_PENDING)
1615 rv = callback.WaitForResult();
1618 SSLConfig ssl_config;
1619 for (size_t i = 0; i < arraysize(kCiphersToDisable); ++i)
1620 ssl_config.disabled_cipher_suites.push_back(kCiphersToDisable[i]);
1622 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1623 transport.Pass(), test_server.host_port_pair(), ssl_config));
1625 EXPECT_FALSE(sock->IsConnected());
1627 rv = sock->Connect(callback.callback());
1628 CapturingNetLog::CapturedEntryList entries;
1629 log.GetEntries(&entries);
1630 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1632 // NSS has special handling that maps a handshake_failure alert received
1633 // immediately after a client_hello to be a mismatched cipher suite error,
1634 // leading to ERR_SSL_VERSION_OR_CIPHER_MISMATCH. When using OpenSSL or
1635 // Secure Transport (OS X), the handshake_failure is bubbled up without any
1636 // interpretation, leading to ERR_SSL_PROTOCOL_ERROR. Either way, a failure
1637 // indicates that no cipher suite was negotiated with the test server.
1638 if (rv == ERR_IO_PENDING)
1639 rv = callback.WaitForResult();
1640 EXPECT_TRUE(rv == ERR_SSL_VERSION_OR_CIPHER_MISMATCH ||
1641 rv == ERR_SSL_PROTOCOL_ERROR);
1642 // The exact ordering differs between SSLClientSocketNSS (which issues an
1643 // extra read) and SSLClientSocketMac (which does not). Just make sure the
1644 // error appears somewhere in the log.
1645 log.GetEntries(&entries);
1646 ExpectLogContainsSomewhere(
1647 entries, 0, NetLog::TYPE_SSL_HANDSHAKE_ERROR, NetLog::PHASE_NONE);
1649 // We cannot test sock->IsConnected(), as the NSS implementation disconnects
1650 // the socket when it encounters an error, whereas other implementations
1651 // leave it connected.
1652 // Because this an error that the test server is mutually aware of, as opposed
1653 // to being an error such as a certificate name mismatch, which is
1654 // client-only, the exact index of the SSL connect end depends on how
1655 // quickly the test server closes the underlying socket. If the test server
1656 // closes before the IO message loop pumps messages, there may be a 0-byte
1657 // Read event in the NetLog due to TCPClientSocket picking up the EOF. As a
1658 // result, the SSL connect end event will be the second-to-last entry,
1659 // rather than the last entry.
1660 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1) ||
1661 LogContainsSSLConnectEndEvent(entries, -2));
1664 // When creating an SSLClientSocket, it is allowed to pass in a
1665 // ClientSocketHandle that is not obtained from a client socket pool.
1666 // Here we verify that such a simple ClientSocketHandle, not associated with any
1667 // client socket pool, can be destroyed safely.
1668 TEST_F(SSLClientSocketTest, ClientSocketHandleNotFromPool) {
1669 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1670 SpawnedTestServer::kLocalhost,
1672 ASSERT_TRUE(test_server.Start());
1675 ASSERT_TRUE(test_server.GetAddressList(&addr));
1677 TestCompletionCallback callback;
1678 scoped_ptr<StreamSocket> transport(
1679 new TCPClientSocket(addr, NULL, NetLog::Source()));
1680 int rv = transport->Connect(callback.callback());
1681 if (rv == ERR_IO_PENDING)
1682 rv = callback.WaitForResult();
1685 scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle());
1686 socket_handle->SetSocket(transport.Pass());
1688 scoped_ptr<SSLClientSocket> sock(
1689 socket_factory_->CreateSSLClientSocket(socket_handle.Pass(),
1690 test_server.host_port_pair(),
1694 EXPECT_FALSE(sock->IsConnected());
1695 rv = sock->Connect(callback.callback());
1696 if (rv == ERR_IO_PENDING)
1697 rv = callback.WaitForResult();
1701 // Verifies that SSLClientSocket::ExportKeyingMaterial return a success
1702 // code and different keying label results in different keying material.
1703 TEST_F(SSLClientSocketTest, ExportKeyingMaterial) {
1704 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1705 SpawnedTestServer::kLocalhost,
1707 ASSERT_TRUE(test_server.Start());
1710 ASSERT_TRUE(test_server.GetAddressList(&addr));
1712 TestCompletionCallback callback;
1714 scoped_ptr<StreamSocket> transport(
1715 new TCPClientSocket(addr, NULL, NetLog::Source()));
1716 int rv = transport->Connect(callback.callback());
1717 if (rv == ERR_IO_PENDING)
1718 rv = callback.WaitForResult();
1721 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1722 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1724 rv = sock->Connect(callback.callback());
1725 if (rv == ERR_IO_PENDING)
1726 rv = callback.WaitForResult();
1728 EXPECT_TRUE(sock->IsConnected());
1730 const int kKeyingMaterialSize = 32;
1731 const char* kKeyingLabel1 = "client-socket-test-1";
1732 const char* kKeyingContext = "";
1733 unsigned char client_out1[kKeyingMaterialSize];
1734 memset(client_out1, 0, sizeof(client_out1));
1735 rv = sock->ExportKeyingMaterial(
1736 kKeyingLabel1, false, kKeyingContext, client_out1, sizeof(client_out1));
1739 const char* kKeyingLabel2 = "client-socket-test-2";
1740 unsigned char client_out2[kKeyingMaterialSize];
1741 memset(client_out2, 0, sizeof(client_out2));
1742 rv = sock->ExportKeyingMaterial(
1743 kKeyingLabel2, false, kKeyingContext, client_out2, sizeof(client_out2));
1745 EXPECT_NE(memcmp(client_out1, client_out2, kKeyingMaterialSize), 0);
1748 // Verifies that SSLClientSocket::ClearSessionCache can be called without
1749 // explicit NSS initialization.
1750 TEST(SSLClientSocket, ClearSessionCache) {
1751 SSLClientSocket::ClearSessionCache();
1754 // Test that the server certificates are properly retrieved from the underlying
1756 TEST_F(SSLClientSocketTest, VerifyServerChainProperlyOrdered) {
1757 // The connection does not have to be successful.
1758 cert_verifier_->set_default_result(ERR_CERT_INVALID);
1760 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
1761 // This makes the server present redundant-server-chain.pem, which contains
1762 // intermediate certificates.
1763 SpawnedTestServer::SSLOptions ssl_options(
1764 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
1765 SpawnedTestServer test_server(
1766 SpawnedTestServer::TYPE_HTTPS, ssl_options, base::FilePath());
1767 ASSERT_TRUE(test_server.Start());
1770 ASSERT_TRUE(test_server.GetAddressList(&addr));
1772 TestCompletionCallback callback;
1773 scoped_ptr<StreamSocket> transport(
1774 new TCPClientSocket(addr, NULL, NetLog::Source()));
1775 int rv = transport->Connect(callback.callback());
1776 rv = callback.GetResult(rv);
1779 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1780 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1781 EXPECT_FALSE(sock->IsConnected());
1782 rv = sock->Connect(callback.callback());
1783 rv = callback.GetResult(rv);
1785 EXPECT_EQ(ERR_CERT_INVALID, rv);
1786 EXPECT_TRUE(sock->IsConnected());
1788 // When given option CERT_CHAIN_WRONG_ROOT, SpawnedTestServer will present
1789 // certs from redundant-server-chain.pem.
1790 CertificateList server_certs =
1791 CreateCertificateListFromFile(GetTestCertsDirectory(),
1792 "redundant-server-chain.pem",
1793 X509Certificate::FORMAT_AUTO);
1795 // Get the server certificate as received client side.
1796 scoped_refptr<X509Certificate> server_certificate =
1797 sock->GetUnverifiedServerCertificateChain();
1799 // Get the intermediates as received client side.
1800 const X509Certificate::OSCertHandles& server_intermediates =
1801 server_certificate->GetIntermediateCertificates();
1803 // Check that the unverified server certificate chain is properly retrieved
1804 // from the underlying ssl stack.
1805 ASSERT_EQ(4U, server_certs.size());
1807 EXPECT_TRUE(X509Certificate::IsSameOSCert(
1808 server_certificate->os_cert_handle(), server_certs[0]->os_cert_handle()));
1810 ASSERT_EQ(3U, server_intermediates.size());
1812 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[0],
1813 server_certs[1]->os_cert_handle()));
1814 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[1],
1815 server_certs[2]->os_cert_handle()));
1816 EXPECT_TRUE(X509Certificate::IsSameOSCert(server_intermediates[2],
1817 server_certs[3]->os_cert_handle()));
1820 EXPECT_FALSE(sock->IsConnected());
1823 // This tests that SSLInfo contains a properly re-constructed certificate
1824 // chain. That, in turn, verifies that GetSSLInfo is giving us the chain as
1825 // verified, not the chain as served by the server. (They may be different.)
1827 // CERT_CHAIN_WRONG_ROOT is redundant-server-chain.pem. It contains A
1828 // (end-entity) -> B -> C, and C is signed by D. redundant-validated-chain.pem
1829 // contains a chain of A -> B -> C2, where C2 is the same public key as C, but
1830 // a self-signed root. Such a situation can occur when a new root (C2) is
1831 // cross-certified by an old root (D) and has two different versions of its
1832 // floating around. Servers may supply C2 as an intermediate, but the
1833 // SSLClientSocket should return the chain that was verified, from
1834 // verify_result, instead.
1835 TEST_F(SSLClientSocketTest, VerifyReturnChainProperlyOrdered) {
1836 // By default, cause the CertVerifier to treat all certificates as
1838 cert_verifier_->set_default_result(ERR_CERT_DATE_INVALID);
1840 // We will expect SSLInfo to ultimately contain this chain.
1841 CertificateList certs =
1842 CreateCertificateListFromFile(GetTestCertsDirectory(),
1843 "redundant-validated-chain.pem",
1844 X509Certificate::FORMAT_AUTO);
1845 ASSERT_EQ(3U, certs.size());
1847 X509Certificate::OSCertHandles temp_intermediates;
1848 temp_intermediates.push_back(certs[1]->os_cert_handle());
1849 temp_intermediates.push_back(certs[2]->os_cert_handle());
1851 CertVerifyResult verify_result;
1852 verify_result.verified_cert = X509Certificate::CreateFromHandle(
1853 certs[0]->os_cert_handle(), temp_intermediates);
1855 // Add a rule that maps the server cert (A) to the chain of A->B->C2
1856 // rather than A->B->C.
1857 cert_verifier_->AddResultForCert(certs[0].get(), verify_result, OK);
1859 // Load and install the root for the validated chain.
1860 scoped_refptr<X509Certificate> root_cert = ImportCertFromFile(
1861 GetTestCertsDirectory(), "redundant-validated-chain-root.pem");
1862 ASSERT_NE(static_cast<X509Certificate*>(NULL), root_cert);
1863 ScopedTestRoot scoped_root(root_cert.get());
1865 // Set up a test server with CERT_CHAIN_WRONG_ROOT.
1866 SpawnedTestServer::SSLOptions ssl_options(
1867 SpawnedTestServer::SSLOptions::CERT_CHAIN_WRONG_ROOT);
1868 SpawnedTestServer test_server(
1869 SpawnedTestServer::TYPE_HTTPS,
1871 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
1872 ASSERT_TRUE(test_server.Start());
1875 ASSERT_TRUE(test_server.GetAddressList(&addr));
1877 TestCompletionCallback callback;
1878 CapturingNetLog log;
1879 scoped_ptr<StreamSocket> transport(
1880 new TCPClientSocket(addr, &log, NetLog::Source()));
1881 int rv = transport->Connect(callback.callback());
1882 if (rv == ERR_IO_PENDING)
1883 rv = callback.WaitForResult();
1886 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1887 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
1888 EXPECT_FALSE(sock->IsConnected());
1889 rv = sock->Connect(callback.callback());
1891 CapturingNetLog::CapturedEntryList entries;
1892 log.GetEntries(&entries);
1893 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
1894 if (rv == ERR_IO_PENDING)
1895 rv = callback.WaitForResult();
1898 EXPECT_TRUE(sock->IsConnected());
1899 log.GetEntries(&entries);
1900 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
1903 sock->GetSSLInfo(&ssl_info);
1905 // Verify that SSLInfo contains the corrected re-constructed chain A -> B
1907 const X509Certificate::OSCertHandles& intermediates =
1908 ssl_info.cert->GetIntermediateCertificates();
1909 ASSERT_EQ(2U, intermediates.size());
1910 EXPECT_TRUE(X509Certificate::IsSameOSCert(ssl_info.cert->os_cert_handle(),
1911 certs[0]->os_cert_handle()));
1912 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[0],
1913 certs[1]->os_cert_handle()));
1914 EXPECT_TRUE(X509Certificate::IsSameOSCert(intermediates[1],
1915 certs[2]->os_cert_handle()));
1918 EXPECT_FALSE(sock->IsConnected());
1921 TEST_F(SSLClientSocketCertRequestInfoTest, NoAuthorities) {
1922 SpawnedTestServer::SSLOptions ssl_options;
1923 ssl_options.request_client_certificate = true;
1924 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
1925 ASSERT_TRUE(request_info.get());
1926 EXPECT_EQ(0u, request_info->cert_authorities.size());
1929 TEST_F(SSLClientSocketCertRequestInfoTest, TwoAuthorities) {
1930 const base::FilePath::CharType kThawteFile[] =
1931 FILE_PATH_LITERAL("thawte.single.pem");
1932 const unsigned char kThawteDN[] = {
1933 0x30, 0x4c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1934 0x02, 0x5a, 0x41, 0x31, 0x25, 0x30, 0x23, 0x06, 0x03, 0x55, 0x04, 0x0a,
1935 0x13, 0x1c, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20, 0x43, 0x6f, 0x6e,
1936 0x73, 0x75, 0x6c, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x28, 0x50, 0x74, 0x79,
1937 0x29, 0x20, 0x4c, 0x74, 0x64, 0x2e, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03,
1938 0x55, 0x04, 0x03, 0x13, 0x0d, 0x54, 0x68, 0x61, 0x77, 0x74, 0x65, 0x20,
1939 0x53, 0x47, 0x43, 0x20, 0x43, 0x41};
1940 const size_t kThawteLen = sizeof(kThawteDN);
1942 const base::FilePath::CharType kDiginotarFile[] =
1943 FILE_PATH_LITERAL("diginotar_root_ca.pem");
1944 const unsigned char kDiginotarDN[] = {
1945 0x30, 0x5f, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
1946 0x02, 0x4e, 0x4c, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0a,
1947 0x13, 0x09, 0x44, 0x69, 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x31,
1948 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x44, 0x69,
1949 0x67, 0x69, 0x4e, 0x6f, 0x74, 0x61, 0x72, 0x20, 0x52, 0x6f, 0x6f, 0x74,
1950 0x20, 0x43, 0x41, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48,
1951 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x11, 0x69, 0x6e, 0x66, 0x6f,
1952 0x40, 0x64, 0x69, 0x67, 0x69, 0x6e, 0x6f, 0x74, 0x61, 0x72, 0x2e, 0x6e,
1954 const size_t kDiginotarLen = sizeof(kDiginotarDN);
1956 SpawnedTestServer::SSLOptions ssl_options;
1957 ssl_options.request_client_certificate = true;
1958 ssl_options.client_authorities.push_back(
1959 GetTestClientCertsDirectory().Append(kThawteFile));
1960 ssl_options.client_authorities.push_back(
1961 GetTestClientCertsDirectory().Append(kDiginotarFile));
1962 scoped_refptr<SSLCertRequestInfo> request_info = GetCertRequest(ssl_options);
1963 ASSERT_TRUE(request_info.get());
1964 ASSERT_EQ(2u, request_info->cert_authorities.size());
1965 EXPECT_EQ(std::string(reinterpret_cast<const char*>(kThawteDN), kThawteLen),
1966 request_info->cert_authorities[0]);
1968 std::string(reinterpret_cast<const char*>(kDiginotarDN), kDiginotarLen),
1969 request_info->cert_authorities[1]);
1972 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledTLSExtension) {
1973 SpawnedTestServer::SSLOptions ssl_options;
1974 ssl_options.signed_cert_timestamps_tls_ext = "test";
1976 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
1979 ASSERT_TRUE(test_server.Start());
1982 ASSERT_TRUE(test_server.GetAddressList(&addr));
1984 TestCompletionCallback callback;
1985 CapturingNetLog log;
1986 scoped_ptr<StreamSocket> transport(
1987 new TCPClientSocket(addr, &log, NetLog::Source()));
1988 int rv = transport->Connect(callback.callback());
1989 if (rv == ERR_IO_PENDING)
1990 rv = callback.WaitForResult();
1993 SSLConfig ssl_config;
1994 ssl_config.signed_cert_timestamps_enabled = true;
1996 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
1997 transport.Pass(), test_server.host_port_pair(), ssl_config));
1999 EXPECT_FALSE(sock->IsConnected());
2001 rv = sock->Connect(callback.callback());
2003 CapturingNetLog::CapturedEntryList entries;
2004 log.GetEntries(&entries);
2005 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2006 if (rv == ERR_IO_PENDING)
2007 rv = callback.WaitForResult();
2009 EXPECT_TRUE(sock->IsConnected());
2010 log.GetEntries(&entries);
2011 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2013 #if !defined(USE_OPENSSL)
2014 EXPECT_TRUE(sock->signed_cert_timestamps_received_);
2016 // Enabling CT for OpenSSL is currently a noop.
2017 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2021 EXPECT_FALSE(sock->IsConnected());
2024 // Test that enabling Signed Certificate Timestamps enables OCSP stapling.
2025 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsEnabledOCSP) {
2026 SpawnedTestServer::SSLOptions ssl_options;
2027 ssl_options.staple_ocsp_response = true;
2028 // The test server currently only knows how to generate OCSP responses
2029 // for a freshly minted certificate.
2030 ssl_options.server_certificate = SpawnedTestServer::SSLOptions::CERT_AUTO;
2032 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2035 ASSERT_TRUE(test_server.Start());
2038 ASSERT_TRUE(test_server.GetAddressList(&addr));
2040 TestCompletionCallback callback;
2041 CapturingNetLog log;
2042 scoped_ptr<StreamSocket> transport(
2043 new TCPClientSocket(addr, &log, NetLog::Source()));
2044 int rv = transport->Connect(callback.callback());
2045 if (rv == ERR_IO_PENDING)
2046 rv = callback.WaitForResult();
2049 SSLConfig ssl_config;
2050 // Enabling Signed Cert Timestamps ensures we request OCSP stapling for
2051 // Certificate Transparency verification regardless of whether the platform
2052 // is able to process the OCSP status itself.
2053 ssl_config.signed_cert_timestamps_enabled = true;
2055 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2056 transport.Pass(), test_server.host_port_pair(), ssl_config));
2058 EXPECT_FALSE(sock->IsConnected());
2060 rv = sock->Connect(callback.callback());
2062 CapturingNetLog::CapturedEntryList entries;
2063 log.GetEntries(&entries);
2064 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2065 if (rv == ERR_IO_PENDING)
2066 rv = callback.WaitForResult();
2068 EXPECT_TRUE(sock->IsConnected());
2069 log.GetEntries(&entries);
2070 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2072 #if !defined(USE_OPENSSL)
2073 EXPECT_TRUE(sock->stapled_ocsp_response_received_);
2075 // OCSP stapling isn't currently supported in the OpenSSL socket.
2076 EXPECT_FALSE(sock->stapled_ocsp_response_received_);
2080 EXPECT_FALSE(sock->IsConnected());
2083 TEST_F(SSLClientSocketTest, ConnectSignedCertTimestampsDisabled) {
2084 SpawnedTestServer::SSLOptions ssl_options;
2085 ssl_options.signed_cert_timestamps_tls_ext = "test";
2087 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2090 ASSERT_TRUE(test_server.Start());
2093 ASSERT_TRUE(test_server.GetAddressList(&addr));
2095 TestCompletionCallback callback;
2096 CapturingNetLog log;
2097 scoped_ptr<StreamSocket> transport(
2098 new TCPClientSocket(addr, &log, NetLog::Source()));
2099 int rv = transport->Connect(callback.callback());
2100 if (rv == ERR_IO_PENDING)
2101 rv = callback.WaitForResult();
2104 SSLConfig ssl_config;
2105 ssl_config.signed_cert_timestamps_enabled = false;
2107 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2108 transport.Pass(), test_server.host_port_pair(), ssl_config));
2110 EXPECT_FALSE(sock->IsConnected());
2112 rv = sock->Connect(callback.callback());
2114 CapturingNetLog::CapturedEntryList entries;
2115 log.GetEntries(&entries);
2116 EXPECT_TRUE(LogContainsBeginEvent(entries, 5, NetLog::TYPE_SSL_CONNECT));
2117 if (rv == ERR_IO_PENDING)
2118 rv = callback.WaitForResult();
2120 EXPECT_TRUE(sock->IsConnected());
2121 log.GetEntries(&entries);
2122 EXPECT_TRUE(LogContainsSSLConnectEndEvent(entries, -1));
2124 EXPECT_FALSE(sock->signed_cert_timestamps_received_);
2127 EXPECT_FALSE(sock->IsConnected());
2130 // Tests that IsConnectedAndIdle and WasEverUsed behave as expected.
2131 TEST_F(SSLClientSocketTest, ReuseStates) {
2132 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTPS,
2133 SpawnedTestServer::kLocalhost,
2135 ASSERT_TRUE(test_server.Start());
2138 ASSERT_TRUE(test_server.GetAddressList(&addr));
2140 TestCompletionCallback callback;
2141 scoped_ptr<StreamSocket> transport(
2142 new TCPClientSocket(addr, NULL, NetLog::Source()));
2143 int rv = transport->Connect(callback.callback());
2144 if (rv == ERR_IO_PENDING)
2145 rv = callback.WaitForResult();
2148 scoped_ptr<SSLClientSocket> sock(CreateSSLClientSocket(
2149 transport.Pass(), test_server.host_port_pair(), kDefaultSSLConfig));
2151 rv = sock->Connect(callback.callback());
2152 if (rv == ERR_IO_PENDING)
2153 rv = callback.WaitForResult();
2156 // The socket was just connected. It should be idle because it is speaking
2157 // HTTP. Although the transport has been used for the handshake, WasEverUsed()
2159 EXPECT_TRUE(sock->IsConnected());
2160 EXPECT_TRUE(sock->IsConnectedAndIdle());
2161 EXPECT_FALSE(sock->WasEverUsed());
2163 const char kRequestText[] = "GET / HTTP/1.0\r\n\r\n";
2164 const size_t kRequestLen = arraysize(kRequestText) - 1;
2165 scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kRequestLen));
2166 memcpy(request_buffer->data(), kRequestText, kRequestLen);
2168 rv = sock->Write(request_buffer.get(), kRequestLen, callback.callback());
2169 EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
2171 if (rv == ERR_IO_PENDING)
2172 rv = callback.WaitForResult();
2173 EXPECT_EQ(static_cast<int>(kRequestLen), rv);
2175 // The socket has now been used.
2176 EXPECT_TRUE(sock->WasEverUsed());
2178 // TODO(davidben): Read one byte to ensure the test server has responded and
2179 // then assert IsConnectedAndIdle is false. This currently doesn't work
2180 // because neither SSLClientSocketNSS nor SSLClientSocketOpenSSL check their
2181 // SSL implementation's internal buffers. Either call PR_Available and
2182 // SSL_pending, although the former isn't actually implemented or perhaps
2183 // attempt to read one byte extra.