Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / net / socket / ssl_client_socket_openssl_unittest.cc
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/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"
47
48 namespace net {
49
50 namespace {
51
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;
55
56 // BIO_free is a macro, it can't be used as a template parameter.
57 void BIO_free_func(BIO* bio) {
58     BIO_free(bio);
59 }
60
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;
64
65 const SSLConfig kDefaultSSLConfig;
66
67 // A ServerBoundCertStore that always returns an error when asked for a
68 // certificate.
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;
76   }
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)
84       OVERRIDE {}
85   virtual void DeleteAllCreatedBetween(base::Time delete_begin,
86                                        base::Time delete_end,
87                                        const base::Closure& completion_callback)
88       OVERRIDE {}
89   virtual void DeleteAll(const base::Closure& completion_callback) OVERRIDE {}
90   virtual void GetAllServerBoundCerts(const GetCertListCallback& callback)
91       OVERRIDE {}
92   virtual int GetCertCount() OVERRIDE { return 0; }
93   virtual void SetForceKeepSessionState() OVERRIDE {}
94 };
95
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) {
103   std::string data;
104   if (!base::ReadFileToString(filepath, &data)) {
105     LOG(ERROR) << "Could not read private key file: "
106                << filepath.value() << ": " << strerror(errno);
107     return false;
108   }
109   ScopedBIO bio(
110       BIO_new_mem_buf(
111           const_cast<char*>(reinterpret_cast<const char*>(data.data())),
112           static_cast<int>(data.size())));
113   if (!bio.get()) {
114     LOG(ERROR) << "Could not allocate BIO for buffer?";
115     return false;
116   }
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: "
120                << filepath.value();
121     return false;
122   }
123   pkey->reset(result);
124   return true;
125 }
126
127 class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
128  public:
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();
137   }
138
139   virtual ~SSLClientSocketOpenSSLClientAuthTest() {
140     key_store_->Flush();
141   }
142
143  protected:
144   void EnabledChannelID() {
145     cert_service_.reset(
146         new ServerBoundCertService(new DefaultServerBoundCertStore(NULL),
147                                    base::MessageLoopProxy::current()));
148     context_.server_bound_cert_service = cert_service_.get();
149   }
150
151   void EnabledFailingChannelID() {
152     cert_service_.reset(
153         new ServerBoundCertService(new FailingServerBoundCertStore(),
154                                    base::MessageLoopProxy::current()));
155     context_.server_bound_cert_service = cert_service_.get();
156   }
157
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(),
165                                                   host_and_port,
166                                                   ssl_config,
167                                                   context_);
168   }
169
170   // Connect to a HTTPS test server.
171   bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
172     test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
173                                              ssl_options,
174                                              base::FilePath()));
175     if (!test_server_->Start()) {
176       LOG(ERROR) << "Could not start SpawnedTestServer";
177       return false;
178     }
179
180     if (!test_server_->GetAddressList(&addr_)) {
181       LOG(ERROR) << "Could not get SpawnedTestServer address list";
182       return false;
183     }
184
185     transport_.reset(new TCPClientSocket(
186         addr_, &log_, NetLog::Source()));
187     int rv = callback_.GetResult(
188         transport_->Connect(callback_.callback()));
189     if (rv != OK) {
190       LOG(ERROR) << "Could not connect to SpawnedTestServer";
191       return false;
192     }
193     return true;
194   }
195
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);
205   }
206
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,
216                                        int* result) {
217     sock_ = CreateSSLClientSocket(transport_.Pass(),
218                                   test_server_->host_port_pair(),
219                                   ssl_config);
220
221     if (sock_->IsConnected()) {
222       LOG(ERROR) << "SSL Socket prematurely connected";
223       return false;
224     }
225
226     *result = callback_.GetResult(sock_->Connect(callback_.callback()));
227     return true;
228   }
229
230
231   // Check that the client certificate was sent.
232   // Returns true on success.
233   bool CheckSSLClientSocketSentCert() {
234     SSLInfo ssl_info;
235     sock_->GetSSLInfo(&ssl_info);
236     return ssl_info.client_cert_sent;
237   }
238
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_;
246   AddressList addr_;
247   TestCompletionCallback callback_;
248   CapturingNetLog log_;
249   scoped_ptr<StreamSocket> transport_;
250   scoped_ptr<SSLClientSocket> sock_;
251 };
252
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;
258
259   ASSERT_TRUE(ConnectToTestServer(ssl_options));
260
261   base::FilePath certs_dir = GetTestCertsDirectory();
262   SSLConfig ssl_config = kDefaultSSLConfig;
263
264   int rv;
265   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
266
267   EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
268   EXPECT_FALSE(sock_->IsConnected());
269 }
270
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"));
278
279   ASSERT_TRUE(ConnectToTestServer(ssl_options));
280
281   base::FilePath certs_dir = GetTestCertsDirectory();
282   SSLConfig ssl_config = kDefaultSSLConfig;
283   ssl_config.send_client_cert = true;
284   ssl_config.client_cert = NULL;
285
286   int rv;
287   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
288
289   EXPECT_EQ(OK, rv);
290   EXPECT_TRUE(sock_->IsConnected());
291 }
292
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"));
300
301   ASSERT_TRUE(ConnectToTestServer(ssl_options));
302
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");
307
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()));
314
315   int rv;
316   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
317
318   EXPECT_EQ(OK, rv);
319   EXPECT_TRUE(sock_->IsConnected());
320
321   EXPECT_TRUE(CheckSSLClientSocketSentCert());
322
323   sock_->Disconnect();
324   EXPECT_FALSE(sock_->IsConnected());
325 }
326
327 // Connect to a server using channel id. It should allow the connection.
328 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendChannelID) {
329   SpawnedTestServer::SSLOptions ssl_options;
330
331   ASSERT_TRUE(ConnectToTestServer(ssl_options));
332
333   EnabledChannelID();
334   SSLConfig ssl_config = kDefaultSSLConfig;
335   ssl_config.channel_id_enabled = true;
336
337   int rv;
338   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
339
340   EXPECT_EQ(OK, rv);
341   EXPECT_TRUE(sock_->IsConnected());
342   EXPECT_TRUE(sock_->WasChannelIDSent());
343
344   sock_->Disconnect();
345   EXPECT_FALSE(sock_->IsConnected());
346 }
347
348 // Connect to a server using channel id but without sending a key. It should
349 // fail.
350 TEST_F(SSLClientSocketOpenSSLClientAuthTest, FailingChannelID) {
351   SpawnedTestServer::SSLOptions ssl_options;
352
353   ASSERT_TRUE(ConnectToTestServer(ssl_options));
354
355   EnabledFailingChannelID();
356   SSLConfig ssl_config = kDefaultSSLConfig;
357   ssl_config.channel_id_enabled = true;
358
359   int rv;
360   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
361
362   EXPECT_EQ(ERR_UNEXPECTED, rv);
363   EXPECT_FALSE(sock_->IsConnected());
364 }
365 #endif  // defined(USE_OPENSSL_CERTS)
366
367 }  // namespace
368 }  // namespace net