Convert raw pointers to scoped_ptr in net module.
[chromium-blink-merge.git] / net / socket / ssl_client_socket_openssl_unittest.cc
blob0a08f8c7562def9e6329243f1815ac0682777f2d
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 <errno.h>
8 #include <string.h>
10 #include <openssl/bio.h>
11 #include <openssl/bn.h>
12 #include <openssl/evp.h>
13 #include <openssl/pem.h>
14 #include <openssl/rsa.h>
16 #include "base/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/values.h"
21 #include "crypto/openssl_util.h"
22 #include "crypto/scoped_openssl_types.h"
23 #include "net/base/address_list.h"
24 #include "net/base/io_buffer.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/test_completion_callback.h"
27 #include "net/base/test_data_directory.h"
28 #include "net/cert/mock_cert_verifier.h"
29 #include "net/cert/test_root_certs.h"
30 #include "net/dns/host_resolver.h"
31 #include "net/http/transport_security_state.h"
32 #include "net/log/net_log.h"
33 #include "net/socket/client_socket_factory.h"
34 #include "net/socket/client_socket_handle.h"
35 #include "net/socket/socket_test_util.h"
36 #include "net/socket/tcp_client_socket.h"
37 #include "net/ssl/openssl_client_key_store.h"
38 #include "net/ssl/ssl_cert_request_info.h"
39 #include "net/ssl/ssl_config_service.h"
40 #include "net/test/cert_test_util.h"
41 #include "net/test/spawned_test_server/spawned_test_server.h"
42 #include "testing/gtest/include/gtest/gtest.h"
43 #include "testing/platform_test.h"
45 namespace net {
47 namespace {
49 // These client auth tests are currently dependent on OpenSSL's struct X509.
50 #if defined(USE_OPENSSL_CERTS)
52 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
53 // |filepath| is the private key file path.
54 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
55 // Returns true on success, false on failure.
56 bool LoadPrivateKeyOpenSSL(
57 const base::FilePath& filepath,
58 crypto::ScopedEVP_PKEY* pkey) {
59 std::string data;
60 if (!base::ReadFileToString(filepath, &data)) {
61 LOG(ERROR) << "Could not read private key file: "
62 << filepath.value() << ": " << strerror(errno);
63 return false;
65 crypto::ScopedBIO bio(BIO_new_mem_buf(
66 const_cast<char*>(reinterpret_cast<const char*>(data.data())),
67 static_cast<int>(data.size())));
68 if (!bio.get()) {
69 LOG(ERROR) << "Could not allocate BIO for buffer?";
70 return false;
72 EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
73 if (result == NULL) {
74 LOG(ERROR) << "Could not decode private key file: "
75 << filepath.value();
76 return false;
78 pkey->reset(result);
79 return true;
82 class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
83 public:
84 SSLClientSocketOpenSSLClientAuthTest()
85 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
86 cert_verifier_(new MockCertVerifier),
87 transport_security_state_(new TransportSecurityState) {
88 cert_verifier_->set_default_result(OK);
89 context_.cert_verifier = cert_verifier_.get();
90 context_.transport_security_state = transport_security_state_.get();
91 key_store_ = OpenSSLClientKeyStore::GetInstance();
94 ~SSLClientSocketOpenSSLClientAuthTest() override { key_store_->Flush(); }
96 protected:
97 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
98 scoped_ptr<StreamSocket> transport_socket,
99 const HostPortPair& host_and_port,
100 const SSLConfig& ssl_config) {
101 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
102 connection->SetSocket(transport_socket.Pass());
103 return socket_factory_->CreateSSLClientSocket(connection.Pass(),
104 host_and_port,
105 ssl_config,
106 context_);
109 // Connect to a HTTPS test server.
110 bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
111 test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
112 ssl_options,
113 base::FilePath()));
114 if (!test_server_->Start()) {
115 LOG(ERROR) << "Could not start SpawnedTestServer";
116 return false;
119 if (!test_server_->GetAddressList(&addr_)) {
120 LOG(ERROR) << "Could not get SpawnedTestServer address list";
121 return false;
124 transport_.reset(new TCPClientSocket(
125 addr_, &log_, NetLog::Source()));
126 int rv = callback_.GetResult(
127 transport_->Connect(callback_.callback()));
128 if (rv != OK) {
129 LOG(ERROR) << "Could not connect to SpawnedTestServer";
130 return false;
132 return true;
135 // Record a certificate's private key to ensure it can be used
136 // by the OpenSSL-based SSLClientSocket implementation.
137 // |ssl_config| provides a client certificate.
138 // |private_key| must be an EVP_PKEY for the corresponding private key.
139 // Returns true on success, false on failure.
140 bool RecordPrivateKey(SSLConfig& ssl_config,
141 EVP_PKEY* private_key) {
142 return key_store_->RecordClientCertPrivateKey(
143 ssl_config.client_cert.get(), private_key);
146 // Create an SSLClientSocket object and use it to connect to a test
147 // server, then wait for connection results. This must be called after
148 // a succesful ConnectToTestServer() call.
149 // |ssl_config| the SSL configuration to use.
150 // |result| will retrieve the ::Connect() result value.
151 // Returns true on succes, false otherwise. Success means that the socket
152 // could be created and its Connect() was called, not that the connection
153 // itself was a success.
154 bool CreateAndConnectSSLClientSocket(const SSLConfig& ssl_config,
155 int* result) {
156 sock_ = CreateSSLClientSocket(transport_.Pass(),
157 test_server_->host_port_pair(),
158 ssl_config);
160 if (sock_->IsConnected()) {
161 LOG(ERROR) << "SSL Socket prematurely connected";
162 return false;
165 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
166 return true;
170 // Check that the client certificate was sent.
171 // Returns true on success.
172 bool CheckSSLClientSocketSentCert() {
173 SSLInfo ssl_info;
174 sock_->GetSSLInfo(&ssl_info);
175 return ssl_info.client_cert_sent;
178 ClientSocketFactory* socket_factory_;
179 scoped_ptr<MockCertVerifier> cert_verifier_;
180 scoped_ptr<TransportSecurityState> transport_security_state_;
181 SSLClientSocketContext context_;
182 OpenSSLClientKeyStore* key_store_;
183 scoped_ptr<SpawnedTestServer> test_server_;
184 AddressList addr_;
185 TestCompletionCallback callback_;
186 NetLog log_;
187 scoped_ptr<StreamSocket> transport_;
188 scoped_ptr<SSLClientSocket> sock_;
191 // Connect to a server requesting client authentication, do not send
192 // any client certificates. It should refuse the connection.
193 TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
194 SpawnedTestServer::SSLOptions ssl_options;
195 ssl_options.request_client_certificate = true;
197 ASSERT_TRUE(ConnectToTestServer(ssl_options));
199 base::FilePath certs_dir = GetTestCertsDirectory();
201 int rv;
202 ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv));
204 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
205 EXPECT_FALSE(sock_->IsConnected());
208 // Connect to a server requesting client authentication, and send it
209 // an empty certificate. It should refuse the connection.
210 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
211 SpawnedTestServer::SSLOptions ssl_options;
212 ssl_options.request_client_certificate = true;
213 ssl_options.client_authorities.push_back(
214 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
216 ASSERT_TRUE(ConnectToTestServer(ssl_options));
218 base::FilePath certs_dir = GetTestCertsDirectory();
219 SSLConfig ssl_config;
220 ssl_config.send_client_cert = true;
221 ssl_config.client_cert = NULL;
223 int rv;
224 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
226 EXPECT_EQ(OK, rv);
227 EXPECT_TRUE(sock_->IsConnected());
230 // Connect to a server requesting client authentication. Send it a
231 // matching certificate. It should allow the connection.
232 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
233 SpawnedTestServer::SSLOptions ssl_options;
234 ssl_options.request_client_certificate = true;
235 ssl_options.client_authorities.push_back(
236 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
238 ASSERT_TRUE(ConnectToTestServer(ssl_options));
240 base::FilePath certs_dir = GetTestCertsDirectory();
241 SSLConfig ssl_config;
242 ssl_config.send_client_cert = true;
243 ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
245 // This is required to ensure that signing works with the client
246 // certificate's private key.
247 crypto::ScopedEVP_PKEY client_private_key;
248 ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
249 &client_private_key));
250 EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
252 int rv;
253 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
255 EXPECT_EQ(OK, rv);
256 EXPECT_TRUE(sock_->IsConnected());
258 EXPECT_TRUE(CheckSSLClientSocketSentCert());
260 sock_->Disconnect();
261 EXPECT_FALSE(sock_->IsConnected());
263 #endif // defined(USE_OPENSSL_CERTS)
265 } // namespace
266 } // namespace net