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"
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/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/message_loop/message_loop_proxy.h"
21 #include "base/values.h"
22 #include "crypto/openssl_util.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/default_server_bound_cert_store.h"
39 #include "net/ssl/openssl_client_key_store.h"
40 #include "net/ssl/server_bound_cert_service.h"
41 #include "net/ssl/ssl_cert_request_info.h"
42 #include "net/ssl/ssl_config_service.h"
43 #include "net/test/cert_test_util.h"
44 #include "net/test/spawned_test_server/spawned_test_server.h"
45 #include "testing/gtest/include/gtest/gtest.h"
46 #include "testing/platform_test.h"
52 typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY;
54 // BIO_free is a macro, it can't be used as a template parameter.
55 void BIO_free_func(BIO* bio) {
59 typedef crypto::ScopedOpenSSL<BIO, BIO_free_func> ScopedBIO;
60 typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
61 typedef crypto::ScopedOpenSSL<BIGNUM, BN_free> ScopedBIGNUM;
63 const SSLConfig kDefaultSSLConfig;
65 // A ServerBoundCertStore that always returns an error when asked for a
67 class FailingServerBoundCertStore : public ServerBoundCertStore {
68 virtual int GetServerBoundCert(const std::string& server_identifier,
69 base::Time* expiration_time,
70 std::string* private_key_result,
71 std::string* cert_result,
72 const GetCertCallback& callback) OVERRIDE {
73 return ERR_UNEXPECTED;
75 virtual void SetServerBoundCert(const std::string& server_identifier,
76 base::Time creation_time,
77 base::Time expiration_time,
78 const std::string& private_key,
79 const std::string& cert) OVERRIDE {}
80 virtual void DeleteServerBoundCert(const std::string& server_identifier,
81 const base::Closure& completion_callback)
83 virtual void DeleteAllCreatedBetween(base::Time delete_begin,
84 base::Time delete_end,
85 const base::Closure& completion_callback)
87 virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
88 virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
90 virtual int GetCertCount() OVERRIDE { return 0; }
91 virtual void SetForceKeepSessionState() OVERRIDE {}
94 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
95 // |filepath| is the private key file path.
96 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
97 // Returns true on success, false on failure.
98 bool LoadPrivateKeyOpenSSL(
99 const base::FilePath& filepath,
100 OpenSSLClientKeyStore::ScopedEVP_PKEY* pkey) {
102 if (!base::ReadFileToString(filepath, &data)) {
103 LOG(ERROR) << "Could not read private key file: "
104 << filepath.value() << ": " << strerror(errno);
109 const_cast<char*>(reinterpret_cast<const char*>(data.data())),
110 static_cast<int>(data.size())));
112 LOG(ERROR) << "Could not allocate BIO for buffer?";
115 EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
116 if (result == NULL) {
117 LOG(ERROR) << "Could not decode private key file: "
125 class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
127 SSLClientSocketOpenSSLClientAuthTest()
128 : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
129 cert_verifier_(new net::MockCertVerifier),
130 transport_security_state_(new net::TransportSecurityState) {
131 cert_verifier_->set_default_result(net::OK);
132 context_.cert_verifier = cert_verifier_.get();
133 context_.transport_security_state = transport_security_state_.get();
134 key_store_ = net::OpenSSLClientKeyStore::GetInstance();
137 virtual ~SSLClientSocketOpenSSLClientAuthTest() {
142 void EnabledChannelID() {
144 new ServerBoundCertService(new DefaultServerBoundCertStore(NULL),
145 base::MessageLoopProxy::current()));
146 context_.server_bound_cert_service = cert_service_.get();
149 void EnabledFailingChannelID() {
151 new ServerBoundCertService(new FailingServerBoundCertStore(),
152 base::MessageLoopProxy::current()));
153 context_.server_bound_cert_service = cert_service_.get();
156 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
157 scoped_ptr<StreamSocket> transport_socket,
158 const HostPortPair& host_and_port,
159 const SSLConfig& ssl_config) {
160 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
161 connection->SetSocket(transport_socket.Pass());
162 return socket_factory_->CreateSSLClientSocket(connection.Pass(),
168 // Connect to a HTTPS test server.
169 bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
170 test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
173 if (!test_server_->Start()) {
174 LOG(ERROR) << "Could not start SpawnedTestServer";
178 if (!test_server_->GetAddressList(&addr_)) {
179 LOG(ERROR) << "Could not get SpawnedTestServer address list";
183 transport_.reset(new TCPClientSocket(
184 addr_, &log_, NetLog::Source()));
185 int rv = callback_.GetResult(
186 transport_->Connect(callback_.callback()));
188 LOG(ERROR) << "Could not connect to SpawnedTestServer";
194 // Record a certificate's private key to ensure it can be used
195 // by the OpenSSL-based SSLClientSocket implementation.
196 // |ssl_config| provides a client certificate.
197 // |private_key| must be an EVP_PKEY for the corresponding private key.
198 // Returns true on success, false on failure.
199 bool RecordPrivateKey(SSLConfig& ssl_config,
200 EVP_PKEY* private_key) {
201 return key_store_->RecordClientCertPrivateKey(
202 ssl_config.client_cert.get(), private_key);
205 // Create an SSLClientSocket object and use it to connect to a test
206 // server, then wait for connection results. This must be called after
207 // a succesful ConnectToTestServer() call.
208 // |ssl_config| the SSL configuration to use.
209 // |result| will retrieve the ::Connect() result value.
210 // Returns true on succes, false otherwise. Success means that the socket
211 // could be created and its Connect() was called, not that the connection
212 // itself was a success.
213 bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config,
215 sock_ = CreateSSLClientSocket(transport_.Pass(),
216 test_server_->host_port_pair(),
219 if (sock_->IsConnected()) {
220 LOG(ERROR) << "SSL Socket prematurely connected";
224 *result = callback_.GetResult(sock_->Connect(callback_.callback()));
229 // Check that the client certificate was sent.
230 // Returns true on success.
231 bool CheckSSLClientSocketSentCert() {
233 sock_->GetSSLInfo(&ssl_info);
234 return ssl_info.client_cert_sent;
237 scoped_ptr<ServerBoundCertService> cert_service_;
238 ClientSocketFactory* socket_factory_;
239 scoped_ptr<MockCertVerifier> cert_verifier_;
240 scoped_ptr<TransportSecurityState> transport_security_state_;
241 SSLClientSocketContext context_;
242 OpenSSLClientKeyStore* key_store_;
243 scoped_ptr<SpawnedTestServer> test_server_;
245 TestCompletionCallback callback_;
246 CapturingNetLog log_;
247 scoped_ptr<StreamSocket> transport_;
248 scoped_ptr<SSLClientSocket> sock_;
251 // Connect to a server requesting client authentication, do not send
252 // any client certificates. It should refuse the connection.
253 TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
254 SpawnedTestServer::SSLOptions ssl_options;
255 ssl_options.request_client_certificate = true;
257 ASSERT_TRUE(ConnectToTestServer(ssl_options));
259 base::FilePath certs_dir = GetTestCertsDirectory();
260 SSLConfig ssl_config = kDefaultSSLConfig;
263 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
265 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
266 EXPECT_FALSE(sock_->IsConnected());
269 // Connect to a server requesting client authentication, and send it
270 // an empty certificate. It should refuse the connection.
271 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
272 SpawnedTestServer::SSLOptions ssl_options;
273 ssl_options.request_client_certificate = true;
274 ssl_options.client_authorities.push_back(
275 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
277 ASSERT_TRUE(ConnectToTestServer(ssl_options));
279 base::FilePath certs_dir = GetTestCertsDirectory();
280 SSLConfig ssl_config = kDefaultSSLConfig;
281 ssl_config.send_client_cert = true;
282 ssl_config.client_cert = NULL;
285 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
288 EXPECT_TRUE(sock_->IsConnected());
291 // Connect to a server requesting client authentication. Send it a
292 // matching certificate. It should allow the connection.
293 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
294 SpawnedTestServer::SSLOptions ssl_options;
295 ssl_options.request_client_certificate = true;
296 ssl_options.client_authorities.push_back(
297 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
299 ASSERT_TRUE(ConnectToTestServer(ssl_options));
301 base::FilePath certs_dir = GetTestCertsDirectory();
302 SSLConfig ssl_config = kDefaultSSLConfig;
303 ssl_config.send_client_cert = true;
304 ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
306 // This is required to ensure that signing works with the client
307 // certificate's private key.
308 OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key;
309 ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
310 &client_private_key));
311 EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
314 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
317 EXPECT_TRUE(sock_->IsConnected());
319 EXPECT_TRUE(CheckSSLClientSocketSentCert());
322 EXPECT_FALSE(sock_->IsConnected());
325 // Connect to a server using channel id. It should allow the connection.
326 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendChannelID) {
327 SpawnedTestServer::SSLOptions ssl_options;
329 ASSERT_TRUE(ConnectToTestServer(ssl_options));
332 SSLConfig ssl_config = kDefaultSSLConfig;
333 ssl_config.channel_id_enabled = true;
336 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
339 EXPECT_TRUE(sock_->IsConnected());
340 EXPECT_TRUE(sock_->WasChannelIDSent());
343 EXPECT_FALSE(sock_->IsConnected());
346 // Connect to a server using channel id but without sending a key. It should
348 TEST_F(SSLClientSocketOpenSSLClientAuthTest, FailingChannelID) {
349 SpawnedTestServer::SSLOptions ssl_options;
351 ASSERT_TRUE(ConnectToTestServer(ssl_options));
353 EnabledFailingChannelID();
354 SSLConfig ssl_config = kDefaultSSLConfig;
355 ssl_config.channel_id_enabled = true;
358 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
360 EXPECT_EQ(ERR_UNEXPECTED, rv);
361 EXPECT_FALSE(sock_->IsConnected());