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/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/socket/client_socket_factory.h"
33 #include "net/socket/client_socket_handle.h"
34 #include "net/socket/socket_test_util.h"
35 #include "net/socket/tcp_client_socket.h"
36 #include "net/ssl/openssl_client_key_store.h"
37 #include "net/ssl/ssl_cert_request_info.h"
38 #include "net/ssl/ssl_config_service.h"
39 #include "net/test/cert_test_util.h"
40 #include "net/test/test_server.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42 #include "testing/platform_test.h"
48 typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY
;
50 // BIO_free is a macro, it can't be used as a template parameter.
51 void BIO_free_func(BIO
* bio
) {
55 typedef crypto::ScopedOpenSSL
<BIO
, BIO_free_func
> ScopedBIO
;
56 typedef crypto::ScopedOpenSSL
<RSA
, RSA_free
> ScopedRSA
;
57 typedef crypto::ScopedOpenSSL
<BIGNUM
, BN_free
> ScopedBIGNUM
;
59 const SSLConfig kDefaultSSLConfig
;
61 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
62 // |filepath| is the private key file path.
63 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
64 // Returns true on success, false on failure.
65 bool LoadPrivateKeyOpenSSL(
66 const base::FilePath
& filepath
,
67 OpenSSLClientKeyStore::ScopedEVP_PKEY
* pkey
) {
69 if (!file_util::ReadFileToString(filepath
, &data
)) {
70 LOG(ERROR
) << "Could not read private key file: "
71 << filepath
.value() << ": " << strerror(errno
);
76 const_cast<char*>(reinterpret_cast<const char*>(data
.data())),
77 static_cast<int>(data
.size())));
79 LOG(ERROR
) << "Could not allocate BIO for buffer?";
82 EVP_PKEY
* result
= PEM_read_bio_PrivateKey(bio
.get(), NULL
, NULL
, NULL
);
84 LOG(ERROR
) << "Could not decode private key file: "
92 class SSLClientSocketOpenSSLClientAuthTest
: public PlatformTest
{
94 SSLClientSocketOpenSSLClientAuthTest()
95 : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
96 cert_verifier_(new net::MockCertVerifier
) {
97 cert_verifier_
->set_default_result(net::OK
);
98 context_
.cert_verifier
= cert_verifier_
.get();
99 key_store_
= net::OpenSSLClientKeyStore::GetInstance();
102 virtual ~SSLClientSocketOpenSSLClientAuthTest() {
107 SSLClientSocket
* CreateSSLClientSocket(
108 StreamSocket
* transport_socket
,
109 const HostPortPair
& host_and_port
,
110 const SSLConfig
& ssl_config
) {
111 return socket_factory_
->CreateSSLClientSocket(transport_socket
,
117 // Connect to a HTTPS test server.
118 bool ConnectToTestServer(TestServer::SSLOptions
& ssl_options
) {
119 test_server_
.reset(new TestServer(TestServer::TYPE_HTTPS
,
122 if (!test_server_
->Start()) {
123 LOG(ERROR
) << "Could not start TestServer";
127 if (!test_server_
->GetAddressList(&addr_
)) {
128 LOG(ERROR
) << "Could not get TestServer address list";
132 transport_
.reset(new TCPClientSocket(
133 addr_
, &log_
, NetLog::Source()));
134 int rv
= callback_
.GetResult(
135 transport_
->Connect(callback_
.callback()));
137 LOG(ERROR
) << "Could not connect to TestServer";
143 // Record a certificate's private key to ensure it can be used
144 // by the OpenSSL-based SSLClientSocket implementation.
145 // |ssl_config| provides a client certificate.
146 // |private_key| must be an EVP_PKEY for the corresponding private key.
147 // Returns true on success, false on failure.
148 bool RecordPrivateKey(SSLConfig
& ssl_config
,
149 EVP_PKEY
* private_key
) {
150 return key_store_
->RecordClientCertPrivateKey(
151 ssl_config
.client_cert
.get(), private_key
);
154 // Create an SSLClientSocket object and use it to connect to a test
155 // server, then wait for connection results. This must be called after
156 // a succesful ConnectToTestServer() call.
157 // |ssl_config| the SSL configuration to use.
158 // |result| will retrieve the ::Connect() result value.
159 // Returns true on succes, false otherwise. Success means that the socket
160 // could be created and its Connect() was called, not that the connection
161 // itself was a success.
162 bool CreateAndConnectSSLClientSocket(SSLConfig
& ssl_config
,
164 sock_
.reset(CreateSSLClientSocket(transport_
.release(),
165 test_server_
->host_port_pair(),
168 if (sock_
->IsConnected()) {
169 LOG(ERROR
) << "SSL Socket prematurely connected";
173 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
178 // Check that the client certificate was sent.
179 // Returns true on success.
180 bool CheckSSLClientSocketSentCert() {
182 sock_
->GetSSLInfo(&ssl_info
);
183 return ssl_info
.client_cert_sent
;
186 ClientSocketFactory
* socket_factory_
;
187 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
188 SSLClientSocketContext context_
;
189 OpenSSLClientKeyStore
* key_store_
;
190 scoped_ptr
<TestServer
> test_server_
;
192 TestCompletionCallback callback_
;
193 CapturingNetLog log_
;
194 scoped_ptr
<StreamSocket
> transport_
;
195 scoped_ptr
<SSLClientSocket
> sock_
;
198 // Connect to a server requesting client authentication, do not send
199 // any client certificates. It should refuse the connection.
200 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, NoCert
) {
201 TestServer::SSLOptions ssl_options
;
202 ssl_options
.request_client_certificate
= true;
204 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
206 base::FilePath certs_dir
= GetTestCertsDirectory();
207 SSLConfig ssl_config
= kDefaultSSLConfig
;
210 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
212 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
213 EXPECT_FALSE(sock_
->IsConnected());
216 // Connect to a server requesting client authentication, and send it
217 // an empty certificate. It should refuse the connection.
218 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendEmptyCert
) {
219 TestServer::SSLOptions ssl_options
;
220 ssl_options
.request_client_certificate
= true;
221 ssl_options
.client_authorities
.push_back(
222 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
224 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
226 base::FilePath certs_dir
= GetTestCertsDirectory();
227 SSLConfig ssl_config
= kDefaultSSLConfig
;
228 ssl_config
.send_client_cert
= true;
229 ssl_config
.client_cert
= NULL
;
232 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
235 EXPECT_TRUE(sock_
->IsConnected());
238 // Connect to a server requesting client authentication. Send it a
239 // matching certificate. It should allow the connection.
240 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendGoodCert
) {
241 TestServer::SSLOptions ssl_options
;
242 ssl_options
.request_client_certificate
= true;
243 ssl_options
.client_authorities
.push_back(
244 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
246 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
248 base::FilePath certs_dir
= GetTestCertsDirectory();
249 SSLConfig ssl_config
= kDefaultSSLConfig
;
250 ssl_config
.send_client_cert
= true;
251 ssl_config
.client_cert
= ImportCertFromFile(certs_dir
, "client_1.pem");
253 // This is required to ensure that signing works with the client
254 // certificate's private key.
255 OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key
;
256 ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir
.AppendASCII("client_1.key"),
257 &client_private_key
));
258 EXPECT_TRUE(RecordPrivateKey(ssl_config
, client_private_key
.get()));
261 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
264 EXPECT_TRUE(sock_
->IsConnected());
266 EXPECT_TRUE(CheckSSLClientSocketSentCert());
269 EXPECT_FALSE(sock_
->IsConnected());