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