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/files/file_path.h"
17 #include "base/files/file_util.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/values.h"
20 #include "crypto/openssl_util.h"
21 #include "crypto/scoped_openssl_types.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/test_completion_callback.h"
26 #include "net/base/test_data_directory.h"
27 #include "net/cert/mock_cert_verifier.h"
28 #include "net/cert/test_root_certs.h"
29 #include "net/dns/host_resolver.h"
30 #include "net/http/transport_security_state.h"
31 #include "net/log/net_log.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/spawned_test_server/spawned_test_server.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42 #include "testing/platform_test.h"
48 // These client auth tests are currently dependent on OpenSSL's struct X509.
49 #if defined(USE_OPENSSL_CERTS)
51 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
52 // |filepath| is the private key file path.
53 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
54 // Returns true on success, false on failure.
55 bool LoadPrivateKeyOpenSSL(
56 const base::FilePath
& filepath
,
57 crypto::ScopedEVP_PKEY
* pkey
) {
59 if (!base::ReadFileToString(filepath
, &data
)) {
60 LOG(ERROR
) << "Could not read private key file: "
61 << filepath
.value() << ": " << strerror(errno
);
64 crypto::ScopedBIO
bio(BIO_new_mem_buf(
65 const_cast<char*>(reinterpret_cast<const char*>(data
.data())),
66 static_cast<int>(data
.size())));
68 LOG(ERROR
) << "Could not allocate BIO for buffer?";
71 EVP_PKEY
* result
= PEM_read_bio_PrivateKey(bio
.get(), NULL
, NULL
, NULL
);
73 LOG(ERROR
) << "Could not decode private key file: "
81 class SSLClientSocketOpenSSLClientAuthTest
: public PlatformTest
{
83 SSLClientSocketOpenSSLClientAuthTest()
84 : socket_factory_(ClientSocketFactory::GetDefaultFactory()),
85 cert_verifier_(new MockCertVerifier
),
86 transport_security_state_(new TransportSecurityState
) {
87 cert_verifier_
->set_default_result(OK
);
88 context_
.cert_verifier
= cert_verifier_
.get();
89 context_
.transport_security_state
= transport_security_state_
.get();
90 key_store_
= OpenSSLClientKeyStore::GetInstance();
93 ~SSLClientSocketOpenSSLClientAuthTest() override
{ key_store_
->Flush(); }
96 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
97 scoped_ptr
<StreamSocket
> transport_socket
,
98 const HostPortPair
& host_and_port
,
99 const SSLConfig
& ssl_config
) {
100 scoped_ptr
<ClientSocketHandle
> connection(new ClientSocketHandle
);
101 connection
->SetSocket(transport_socket
.Pass());
102 return socket_factory_
->CreateSSLClientSocket(connection
.Pass(),
108 // Connect to a HTTPS test server.
109 bool ConnectToTestServer(SpawnedTestServer::SSLOptions
& ssl_options
) {
110 test_server_
.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS
,
113 if (!test_server_
->Start()) {
114 LOG(ERROR
) << "Could not start SpawnedTestServer";
118 if (!test_server_
->GetAddressList(&addr_
)) {
119 LOG(ERROR
) << "Could not get SpawnedTestServer address list";
123 transport_
.reset(new TCPClientSocket(
124 addr_
, &log_
, NetLog::Source()));
125 int rv
= callback_
.GetResult(
126 transport_
->Connect(callback_
.callback()));
128 LOG(ERROR
) << "Could not connect to SpawnedTestServer";
134 // Record a certificate's private key to ensure it can be used
135 // by the OpenSSL-based SSLClientSocket implementation.
136 // |ssl_config| provides a client certificate.
137 // |private_key| must be an EVP_PKEY for the corresponding private key.
138 // Returns true on success, false on failure.
139 bool RecordPrivateKey(SSLConfig
& ssl_config
,
140 EVP_PKEY
* private_key
) {
141 return key_store_
->RecordClientCertPrivateKey(
142 ssl_config
.client_cert
.get(), private_key
);
145 // Create an SSLClientSocket object and use it to connect to a test
146 // server, then wait for connection results. This must be called after
147 // a succesful ConnectToTestServer() call.
148 // |ssl_config| the SSL configuration to use.
149 // |result| will retrieve the ::Connect() result value.
150 // Returns true on succes, false otherwise. Success means that the socket
151 // could be created and its Connect() was called, not that the connection
152 // itself was a success.
153 bool CreateAndConnectSSLClientSocket(const SSLConfig
& ssl_config
,
155 sock_
= CreateSSLClientSocket(transport_
.Pass(),
156 test_server_
->host_port_pair(),
159 if (sock_
->IsConnected()) {
160 LOG(ERROR
) << "SSL Socket prematurely connected";
164 *result
= callback_
.GetResult(sock_
->Connect(callback_
.callback()));
169 // Check that the client certificate was sent.
170 // Returns true on success.
171 bool CheckSSLClientSocketSentCert() {
173 sock_
->GetSSLInfo(&ssl_info
);
174 return ssl_info
.client_cert_sent
;
177 ClientSocketFactory
* socket_factory_
;
178 scoped_ptr
<MockCertVerifier
> cert_verifier_
;
179 scoped_ptr
<TransportSecurityState
> transport_security_state_
;
180 SSLClientSocketContext context_
;
181 OpenSSLClientKeyStore
* key_store_
;
182 scoped_ptr
<SpawnedTestServer
> test_server_
;
184 TestCompletionCallback callback_
;
186 scoped_ptr
<StreamSocket
> transport_
;
187 scoped_ptr
<SSLClientSocket
> sock_
;
190 // Connect to a server requesting client authentication, do not send
191 // any client certificates. It should refuse the connection.
192 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, NoCert
) {
193 SpawnedTestServer::SSLOptions ssl_options
;
194 ssl_options
.request_client_certificate
= true;
196 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
198 base::FilePath certs_dir
= GetTestCertsDirectory();
201 ASSERT_TRUE(CreateAndConnectSSLClientSocket(SSLConfig(), &rv
));
203 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED
, rv
);
204 EXPECT_FALSE(sock_
->IsConnected());
207 // Connect to a server requesting client authentication, and send it
208 // an empty certificate. It should refuse the connection.
209 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendEmptyCert
) {
210 SpawnedTestServer::SSLOptions ssl_options
;
211 ssl_options
.request_client_certificate
= true;
212 ssl_options
.client_authorities
.push_back(
213 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
215 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
217 base::FilePath certs_dir
= GetTestCertsDirectory();
218 SSLConfig ssl_config
;
219 ssl_config
.send_client_cert
= true;
220 ssl_config
.client_cert
= NULL
;
223 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
226 EXPECT_TRUE(sock_
->IsConnected());
229 // Connect to a server requesting client authentication. Send it a
230 // matching certificate. It should allow the connection.
231 TEST_F(SSLClientSocketOpenSSLClientAuthTest
, SendGoodCert
) {
232 SpawnedTestServer::SSLOptions ssl_options
;
233 ssl_options
.request_client_certificate
= true;
234 ssl_options
.client_authorities
.push_back(
235 GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
237 ASSERT_TRUE(ConnectToTestServer(ssl_options
));
239 base::FilePath certs_dir
= GetTestCertsDirectory();
240 SSLConfig ssl_config
;
241 ssl_config
.send_client_cert
= true;
242 ssl_config
.client_cert
= ImportCertFromFile(certs_dir
, "client_1.pem");
244 // This is required to ensure that signing works with the client
245 // certificate's private key.
246 crypto::ScopedEVP_PKEY client_private_key
;
247 ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir
.AppendASCII("client_1.key"),
248 &client_private_key
));
249 EXPECT_TRUE(RecordPrivateKey(ssl_config
, client_private_key
.get()));
252 ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config
, &rv
));
255 EXPECT_TRUE(sock_
->IsConnected());
257 EXPECT_TRUE(CheckSSLClientSocketSentCert());
260 EXPECT_FALSE(sock_
->IsConnected());
262 #endif // defined(USE_OPENSSL_CERTS)