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