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 // These client auth tests are currently dependent on OpenSSL's struct X509.
53 #if defined(USE_OPENSSL_CERTS)
54 typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY
;
56 // BIO_free is a macro, it can't be used as a template parameter.
57 void BIO_free_func(BIO
* bio
) {
61 typedef crypto::ScopedOpenSSL
<BIO
, BIO_free_func
> ScopedBIO
;
62 typedef crypto::ScopedOpenSSL
<RSA
, RSA_free
> ScopedRSA
;
63 typedef crypto::ScopedOpenSSL
<BIGNUM
, BN_free
> ScopedBIGNUM
;
65 const SSLConfig kDefaultSSLConfig
;
67 // A ServerBoundCertStore that always returns an error when asked for a
69 class FailingServerBoundCertStore
: public ServerBoundCertStore
{
70 virtual int GetServerBoundCert(const std::string
& server_identifier
,
71 base::Time
* expiration_time
,
72 std::string
* private_key_result
,
73 std::string
* cert_result
,
74 const GetCertCallback
& callback
) OVERRIDE
{
75 return ERR_UNEXPECTED
;
77 virtual void SetServerBoundCert(const std::string
& server_identifier
,
78 base::Time creation_time
,
79 base::Time expiration_time
,
80 const std::string
& private_key
,
81 const std::string
& cert
) OVERRIDE
{}
82 virtual void DeleteServerBoundCert(const std::string
& server_identifier
,
83 const base::Closure
& completion_callback
)
85 virtual void DeleteAllCreatedBetween(base::Time delete_begin
,
86 base::Time delete_end
,
87 const base::Closure
& completion_callback
)
89 virtual void DeleteAll(const base::Closure
& completion_callback
) OVERRIDE
{}
90 virtual void GetAllServerBoundCerts(const GetCertListCallback
& callback
)
92 virtual int GetCertCount() OVERRIDE
{ return 0; }
93 virtual void SetForceKeepSessionState() OVERRIDE
{}
96 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
97 // |filepath| is the private key file path.
98 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
99 // Returns true on success, false on failure.
100 bool LoadPrivateKeyOpenSSL(
101 const base::FilePath
& filepath
,
102 OpenSSLClientKeyStore::ScopedEVP_PKEY
* pkey
) {
104 if (!base::ReadFileToString(filepath
, &data
)) {
105 LOG(ERROR
) << "Could not read private key file: "
106 << filepath
.value() << ": " << strerror(errno
);
111 const_cast<char*>(reinterpret_cast<const char*>(data
.data())),
112 static_cast<int>(data
.size())));
114 LOG(ERROR
) << "Could not allocate BIO for buffer?";
117 EVP_PKEY
* result
= PEM_read_bio_PrivateKey(bio
.get(), NULL
, NULL
, NULL
);
118 if (result
== NULL
) {
119 LOG(ERROR
) << "Could not decode private key file: "
127 class SSLClientSocketOpenSSLClientAuthTest
: public PlatformTest
{
129 SSLClientSocketOpenSSLClientAuthTest()
130 : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
131 cert_verifier_(new net::MockCertVerifier
),
132 transport_security_state_(new net::TransportSecurityState
) {
133 cert_verifier_
->set_default_result(net::OK
);
134 context_
.cert_verifier
= cert_verifier_
.get();
135 context_
.transport_security_state
= transport_security_state_
.get();
136 key_store_
= net::OpenSSLClientKeyStore::GetInstance();
139 virtual ~SSLClientSocketOpenSSLClientAuthTest() {
144 void EnabledChannelID() {
146 new ServerBoundCertService(new DefaultServerBoundCertStore(NULL
),
147 base::MessageLoopProxy::current()));
148 context_
.server_bound_cert_service
= cert_service_
.get();
151 void EnabledFailingChannelID() {
153 new ServerBoundCertService(new FailingServerBoundCertStore(),
154 base::MessageLoopProxy::current()));
155 context_
.server_bound_cert_service
= cert_service_
.get();
158 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
159 scoped_ptr
<StreamSocket
> transport_socket
,
160 const HostPortPair
& host_and_port
,
161 const SSLConfig
& ssl_config
) {
162 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
163 connection
->SetSocket(transport_socket
.Pass());
164 return socket_factory_
->CreateSSLClientSocket(connection
.Pass(),
170 // Connect to a HTTPS test server.
171 bool ConnectToTestServer(SpawnedTestServer::SSLOptions
& ssl_options
) {
172 test_server_
.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS
,
175 if (!test_server_
->Start()) {
176 LOG(ERROR
) << "Could not start SpawnedTestServer";
180 if (!test_server_
->GetAddressList(&addr_
)) {
181 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
185 transport_
.reset(new TCPClientSocket(
186 addr_
, &log_
, NetLog::Source()));
187 int rv
= callback_
.GetResult(
188 transport_
->Connect(callback_
.callback()));
190 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
196 // Record a certificate's private key to ensure it can be used
197 // by the OpenSSL-based SSLClientSocket implementation.
198 // |ssl_config| provides a client certificate.
199 // |private_key| must be an EVP_PKEY for the corresponding private key.
200 // Returns true on success, false on failure.
201 bool RecordPrivateKey(SSLConfig
& ssl_config
,
202 EVP_PKEY
* private_key
) {
203 return key_store_
->RecordClientCertPrivateKey(
204 ssl_config
.client_cert
.get(), private_key
);
207 // Create an SSLClientSocket object and use it to connect to a test
208 // server, then wait for connection results. This must be called after
209 // a succesful ConnectToTestServer() call.
210 // |ssl_config| the SSL configuration to use.
211 // |result| will retrieve the ::Connect() result value.
212 // Returns true on succes, false otherwise. Success means that the socket
213 // could be created and its Connect() was called, not that the connection
214 // itself was a success.
215 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
,
217 sock_
= CreateSSLClientSocket(transport_
.Pass(),
218 test_server_
->host_port_pair(),
221 if (sock_
->IsConnected()) {
222 LOG(ERROR
) << "SSL Socket prematurely connected";
226 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
231 // Check that the client certificate was sent.
232 // Returns true on success.
233 bool CheckSSLClientSocketSentCert() {
235 sock_
->GetSSLInfo(&ssl_info
);
236 return ssl_info
.client_cert_sent
;
239 scoped_ptr
<ServerBoundCertService
> cert_service_
;
240 ClientSocketFactory
* socket_factory_
;
241 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
242 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
243 SSLClientSocketContext context_
;
244 OpenSSLClientKeyStore
* key_store_
;
245 scoped_ptr
<SpawnedTestServer
> test_server_
;
247 TestCompletionCallback callback_
;
248 CapturingNetLog log_
;
249 scoped_ptr
<StreamSocket
> transport_
;
250 scoped_ptr
<SSLClientSocket
> sock_
;
253 // Connect to a server requesting client authentication, do not send
254 // any client certificates. It should refuse the connection.
255 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, NoCert
) {
256 SpawnedTestServer::SSLOptions ssl_options
;
257 ssl_options
.request_client_certificate
= true;
259 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
261 base::FilePath certs_dir
= GetTestCertsDirectory();
262 SSLConfig ssl_config
= kDefaultSSLConfig
;
265 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
267 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
268 EXPECT_FALSE(sock_
->IsConnected());
271 // Connect to a server requesting client authentication, and send it
272 // an empty certificate. It should refuse the connection.
273 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendEmptyCert
) {
274 SpawnedTestServer::SSLOptions ssl_options
;
275 ssl_options
.request_client_certificate
= true;
276 ssl_options
.client_authorities
.push_back(
277 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
279 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
281 base::FilePath certs_dir
= GetTestCertsDirectory();
282 SSLConfig ssl_config
= kDefaultSSLConfig
;
283 ssl_config
.send_client_cert
= true;
284 ssl_config
.client_cert
= NULL
;
287 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
290 EXPECT_TRUE(sock_
->IsConnected());
293 // Connect to a server requesting client authentication. Send it a
294 // matching certificate. It should allow the connection.
295 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendGoodCert
) {
296 SpawnedTestServer::SSLOptions ssl_options
;
297 ssl_options
.request_client_certificate
= true;
298 ssl_options
.client_authorities
.push_back(
299 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
301 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
303 base::FilePath certs_dir
= GetTestCertsDirectory();
304 SSLConfig ssl_config
= kDefaultSSLConfig
;
305 ssl_config
.send_client_cert
= true;
306 ssl_config
.client_cert
= ImportCertFromFile(certs_dir
, "client_1.pem");
308 // This is required to ensure that signing works with the client
309 // certificate's private key.
310 OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key
;
311 ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir
.AppendASCII("client_1.key"),
312 &client_private_key
));
313 EXPECT_TRUE(RecordPrivateKey(ssl_config
, client_private_key
.get()));
316 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
319 EXPECT_TRUE(sock_
->IsConnected());
321 EXPECT_TRUE(CheckSSLClientSocketSentCert());
324 EXPECT_FALSE(sock_
->IsConnected());
327 // Connect to a server using channel id. It should allow the connection.
328 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendChannelID
) {
329 SpawnedTestServer::SSLOptions ssl_options
;
331 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
334 SSLConfig ssl_config
= kDefaultSSLConfig
;
335 ssl_config
.channel_id_enabled
= true;
338 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
341 EXPECT_TRUE(sock_
->IsConnected());
342 EXPECT_TRUE(sock_
->WasChannelIDSent());
345 EXPECT_FALSE(sock_
->IsConnected());
348 // Connect to a server using channel id but without sending a key. It should
350 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, FailingChannelID
) {
351 SpawnedTestServer::SSLOptions ssl_options
;
353 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
355 EnabledFailingChannelID();
356 SSLConfig ssl_config
= kDefaultSSLConfig
;
357 ssl_config
.channel_id_enabled
= true;
360 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
362 EXPECT_EQ(ERR_UNEXPECTED
, rv
);
363 EXPECT_FALSE(sock_
->IsConnected());
365 #endif // defined(USE_OPENSSL_CERTS)