ssl_client_socket_openssl_unittest.cc revision 3551c9c881056c480085172ff9840cab31610854
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.
4
5#include "net/socket/ssl_client_socket.h"
6
7#include <errno.h>
8#include <string.h>
9
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>
15
16#include "base/file_util.h"
17#include "base/files/file_path.h"
18#include "base/memory/ref_counted.h"
19#include "base/memory/scoped_handle.h"
20#include "base/values.h"
21#include "crypto/openssl_util.h"
22#include "net/base/address_list.h"
23#include "net/base/io_buffer.h"
24#include "net/base/net_errors.h"
25#include "net/base/net_log.h"
26#include "net/base/net_log_unittest.h"
27#include "net/base/test_completion_callback.h"
28#include "net/base/test_data_directory.h"
29#include "net/cert/mock_cert_verifier.h"
30#include "net/cert/test_root_certs.h"
31#include "net/dns/host_resolver.h"
32#include "net/http/transport_security_state.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"
44
45namespace net {
46
47namespace {
48
49typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY;
50
51// BIO_free is a macro, it can't be used as a template parameter.
52void BIO_free_func(BIO* bio) {
53    BIO_free(bio);
54}
55
56typedef crypto::ScopedOpenSSL<BIO, BIO_free_func> ScopedBIO;
57typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
58typedef crypto::ScopedOpenSSL<BIGNUM, BN_free> ScopedBIGNUM;
59
60const SSLConfig kDefaultSSLConfig;
61
62// Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
63// |filepath| is the private key file path.
64// |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
65// Returns true on success, false on failure.
66bool LoadPrivateKeyOpenSSL(
67    const base::FilePath& filepath,
68    OpenSSLClientKeyStore::ScopedEVP_PKEY* pkey) {
69  std::string data;
70  if (!file_util::ReadFileToString(filepath, &data)) {
71    LOG(ERROR) << "Could not read private key file: "
72               << filepath.value() << ": " << strerror(errno);
73    return false;
74  }
75  ScopedBIO bio(
76      BIO_new_mem_buf(
77          const_cast<char*>(reinterpret_cast<const char*>(data.data())),
78          static_cast<int>(data.size())));
79  if (!bio.get()) {
80    LOG(ERROR) << "Could not allocate BIO for buffer?";
81    return false;
82  }
83  EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
84  if (result == NULL) {
85    LOG(ERROR) << "Could not decode private key file: "
86               << filepath.value();
87    return false;
88  }
89  pkey->reset(result);
90  return true;
91}
92
93class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
94 public:
95  SSLClientSocketOpenSSLClientAuthTest()
96      : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
97        cert_verifier_(new net::MockCertVerifier),
98        transport_security_state_(new net::TransportSecurityState) {
99    cert_verifier_->set_default_result(net::OK);
100    context_.cert_verifier = cert_verifier_.get();
101    context_.transport_security_state = transport_security_state_.get();
102    key_store_ = net::OpenSSLClientKeyStore::GetInstance();
103  }
104
105  virtual ~SSLClientSocketOpenSSLClientAuthTest() {
106    key_store_->Flush();
107  }
108
109 protected:
110  scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
111      scoped_ptr<StreamSocket> transport_socket,
112      const HostPortPair& host_and_port,
113      const SSLConfig& ssl_config) {
114    scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
115    connection->SetSocket(transport_socket.Pass());
116    return socket_factory_->CreateSSLClientSocket(connection.Pass(),
117                                                  host_and_port,
118                                                  ssl_config,
119                                                  context_);
120  }
121
122  // Connect to a HTTPS test server.
123  bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
124    test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
125                                             ssl_options,
126                                             base::FilePath()));
127    if (!test_server_->Start()) {
128      LOG(ERROR) << "Could not start SpawnedTestServer";
129      return false;
130    }
131
132    if (!test_server_->GetAddressList(&addr_)) {
133      LOG(ERROR) << "Could not get SpawnedTestServer address list";
134      return false;
135    }
136
137    transport_.reset(new TCPClientSocket(
138        addr_, &log_, NetLog::Source()));
139    int rv = callback_.GetResult(
140        transport_->Connect(callback_.callback()));
141    if (rv != OK) {
142      LOG(ERROR) << "Could not connect to SpawnedTestServer";
143      return false;
144    }
145    return true;
146  }
147
148  // Record a certificate's private key to ensure it can be used
149  // by the OpenSSL-based SSLClientSocket implementation.
150  // |ssl_config| provides a client certificate.
151  // |private_key| must be an EVP_PKEY for the corresponding private key.
152  // Returns true on success, false on failure.
153  bool RecordPrivateKey(SSLConfig& ssl_config,
154                        EVP_PKEY* private_key) {
155    return key_store_->RecordClientCertPrivateKey(
156        ssl_config.client_cert.get(), private_key);
157  }
158
159  // Create an SSLClientSocket object and use it to connect to a test
160  // server, then wait for connection results. This must be called after
161  // a succesful ConnectToTestServer() call.
162  // |ssl_config| the SSL configuration to use.
163  // |result| will retrieve the ::Connect() result value.
164  // Returns true on succes, false otherwise. Success means that the socket
165  // could be created and its Connect() was called, not that the connection
166  // itself was a success.
167  bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config,
168                                       int* result) {
169    sock_ = CreateSSLClientSocket(transport_.Pass(),
170                                  test_server_->host_port_pair(),
171                                  ssl_config);
172
173    if (sock_->IsConnected()) {
174      LOG(ERROR) << "SSL Socket prematurely connected";
175      return false;
176    }
177
178    *result = callback_.GetResult(sock_->Connect(callback_.callback()));
179    return true;
180  }
181
182
183  // Check that the client certificate was sent.
184  // Returns true on success.
185  bool CheckSSLClientSocketSentCert() {
186    SSLInfo ssl_info;
187    sock_->GetSSLInfo(&ssl_info);
188    return ssl_info.client_cert_sent;
189  }
190
191  ClientSocketFactory* socket_factory_;
192  scoped_ptr<MockCertVerifier> cert_verifier_;
193  scoped_ptr<TransportSecurityState> transport_security_state_;
194  SSLClientSocketContext context_;
195  OpenSSLClientKeyStore* key_store_;
196  scoped_ptr<SpawnedTestServer> test_server_;
197  AddressList addr_;
198  TestCompletionCallback callback_;
199  CapturingNetLog log_;
200  scoped_ptr<StreamSocket> transport_;
201  scoped_ptr<SSLClientSocket> sock_;
202};
203
204// Connect to a server requesting client authentication, do not send
205// any client certificates. It should refuse the connection.
206TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
207  SpawnedTestServer::SSLOptions ssl_options;
208  ssl_options.request_client_certificate = true;
209
210  ASSERT_TRUE(ConnectToTestServer(ssl_options));
211
212  base::FilePath certs_dir = GetTestCertsDirectory();
213  SSLConfig ssl_config = kDefaultSSLConfig;
214
215  int rv;
216  ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
217
218  EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
219  EXPECT_FALSE(sock_->IsConnected());
220}
221
222// Connect to a server requesting client authentication, and send it
223// an empty certificate. It should refuse the connection.
224TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
225  SpawnedTestServer::SSLOptions ssl_options;
226  ssl_options.request_client_certificate = true;
227  ssl_options.client_authorities.push_back(
228      GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
229
230  ASSERT_TRUE(ConnectToTestServer(ssl_options));
231
232  base::FilePath certs_dir = GetTestCertsDirectory();
233  SSLConfig ssl_config = kDefaultSSLConfig;
234  ssl_config.send_client_cert = true;
235  ssl_config.client_cert = NULL;
236
237  int rv;
238  ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
239
240  EXPECT_EQ(OK, rv);
241  EXPECT_TRUE(sock_->IsConnected());
242}
243
244// Connect to a server requesting client authentication. Send it a
245// matching certificate. It should allow the connection.
246TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
247  SpawnedTestServer::SSLOptions ssl_options;
248  ssl_options.request_client_certificate = true;
249  ssl_options.client_authorities.push_back(
250      GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
251
252  ASSERT_TRUE(ConnectToTestServer(ssl_options));
253
254  base::FilePath certs_dir = GetTestCertsDirectory();
255  SSLConfig ssl_config = kDefaultSSLConfig;
256  ssl_config.send_client_cert = true;
257  ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
258
259  // This is required to ensure that signing works with the client
260  // certificate's private key.
261  OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key;
262  ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
263                                    &client_private_key));
264  EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
265
266  int rv;
267  ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
268
269  EXPECT_EQ(OK, rv);
270  EXPECT_TRUE(sock_->IsConnected());
271
272  EXPECT_TRUE(CheckSSLClientSocketSentCert());
273
274  sock_->Disconnect();
275  EXPECT_FALSE(sock_->IsConnected());
276}
277
278}  // namespace
279}  // namespace net
280