Home | History | Annotate | Download | only in socket
      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/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/http/transport_security_state.h"
     33 #include "net/socket/client_socket_factory.h"
     34 #include "net/socket/client_socket_handle.h"
     35 #include "net/socket/socket_test_util.h"
     36 #include "net/socket/tcp_client_socket.h"
     37 #include "net/ssl/openssl_client_key_store.h"
     38 #include "net/ssl/ssl_cert_request_info.h"
     39 #include "net/ssl/ssl_config_service.h"
     40 #include "net/test/cert_test_util.h"
     41 #include "net/test/spawned_test_server/spawned_test_server.h"
     42 #include "testing/gtest/include/gtest/gtest.h"
     43 #include "testing/platform_test.h"
     44 
     45 namespace net {
     46 
     47 namespace {
     48 
     49 typedef OpenSSLClientKeyStore::ScopedEVP_PKEY ScopedEVP_PKEY;
     50 
     51 // BIO_free is a macro, it can't be used as a template parameter.
     52 void BIO_free_func(BIO* bio) {
     53     BIO_free(bio);
     54 }
     55 
     56 typedef crypto::ScopedOpenSSL<BIO, BIO_free_func> ScopedBIO;
     57 typedef crypto::ScopedOpenSSL<RSA, RSA_free> ScopedRSA;
     58 typedef crypto::ScopedOpenSSL<BIGNUM, BN_free> ScopedBIGNUM;
     59 
     60 const SSLConfig kDefaultSSLConfig;
     61 
     62 // Loads a PEM-encoded private key file into a scoped EVP_PKEY object.
     63 // |filepath| is the private key file path.
     64 // |*pkey| is reset to the new EVP_PKEY on success, untouched otherwise.
     65 // Returns true on success, false on failure.
     66 bool LoadPrivateKeyOpenSSL(
     67     const base::FilePath& filepath,
     68     OpenSSLClientKeyStore::ScopedEVP_PKEY* pkey) {
     69   std::string data;
     70   if (!file_util::ReadFileToString(filepath, &data)) {
     71     LOG(ERROR) << "Could not read private key file: "
     72                << filepath.value() << ": " << strerror(errno);
     73     return false;
     74   }
     75   ScopedBIO bio(
     76       BIO_new_mem_buf(
     77           const_cast<char*>(reinterpret_cast<const char*>(data.data())),
     78           static_cast<int>(data.size())));
     79   if (!bio.get()) {
     80     LOG(ERROR) << "Could not allocate BIO for buffer?";
     81     return false;
     82   }
     83   EVP_PKEY* result = PEM_read_bio_PrivateKey(bio.get(), NULL, NULL, NULL);
     84   if (result == NULL) {
     85     LOG(ERROR) << "Could not decode private key file: "
     86                << filepath.value();
     87     return false;
     88   }
     89   pkey->reset(result);
     90   return true;
     91 }
     92 
     93 class SSLClientSocketOpenSSLClientAuthTest : public PlatformTest {
     94  public:
     95   SSLClientSocketOpenSSLClientAuthTest()
     96       : socket_factory_(net::ClientSocketFactory::GetDefaultFactory()),
     97         cert_verifier_(new net::MockCertVerifier),
     98         transport_security_state_(new net::TransportSecurityState) {
     99     cert_verifier_->set_default_result(net::OK);
    100     context_.cert_verifier = cert_verifier_.get();
    101     context_.transport_security_state = transport_security_state_.get();
    102     key_store_ = net::OpenSSLClientKeyStore::GetInstance();
    103   }
    104 
    105   virtual ~SSLClientSocketOpenSSLClientAuthTest() {
    106     key_store_->Flush();
    107   }
    108 
    109  protected:
    110   SSLClientSocket* CreateSSLClientSocket(
    111       StreamSocket* transport_socket,
    112       const HostPortPair& host_and_port,
    113       const SSLConfig& ssl_config) {
    114     return socket_factory_->CreateSSLClientSocket(transport_socket,
    115                                                   host_and_port,
    116                                                   ssl_config,
    117                                                   context_);
    118   }
    119 
    120   // Connect to a HTTPS test server.
    121   bool ConnectToTestServer(SpawnedTestServer::SSLOptions& ssl_options) {
    122     test_server_.reset(new SpawnedTestServer(SpawnedTestServer::TYPE_HTTPS,
    123                                              ssl_options,
    124                                              base::FilePath()));
    125     if (!test_server_->Start()) {
    126       LOG(ERROR) << "Could not start SpawnedTestServer";
    127       return false;
    128     }
    129 
    130     if (!test_server_->GetAddressList(&addr_)) {
    131       LOG(ERROR) << "Could not get SpawnedTestServer address list";
    132       return false;
    133     }
    134 
    135     transport_.reset(new TCPClientSocket(
    136         addr_, &log_, NetLog::Source()));
    137     int rv = callback_.GetResult(
    138         transport_->Connect(callback_.callback()));
    139     if (rv != OK) {
    140       LOG(ERROR) << "Could not connect to SpawnedTestServer";
    141       return false;
    142     }
    143     return true;
    144   }
    145 
    146   // Record a certificate's private key to ensure it can be used
    147   // by the OpenSSL-based SSLClientSocket implementation.
    148   // |ssl_config| provides a client certificate.
    149   // |private_key| must be an EVP_PKEY for the corresponding private key.
    150   // Returns true on success, false on failure.
    151   bool RecordPrivateKey(SSLConfig& ssl_config,
    152                         EVP_PKEY* private_key) {
    153     return key_store_->RecordClientCertPrivateKey(
    154         ssl_config.client_cert.get(), private_key);
    155   }
    156 
    157   // Create an SSLClientSocket object and use it to connect to a test
    158   // server, then wait for connection results. This must be called after
    159   // a succesful ConnectToTestServer() call.
    160   // |ssl_config| the SSL configuration to use.
    161   // |result| will retrieve the ::Connect() result value.
    162   // Returns true on succes, false otherwise. Success means that the socket
    163   // could be created and its Connect() was called, not that the connection
    164   // itself was a success.
    165   bool CreateAndConnectSSLClientSocket(SSLConfig& ssl_config,
    166                                        int* result) {
    167     sock_.reset(CreateSSLClientSocket(transport_.release(),
    168                                       test_server_->host_port_pair(),
    169                                       ssl_config));
    170 
    171     if (sock_->IsConnected()) {
    172       LOG(ERROR) << "SSL Socket prematurely connected";
    173       return false;
    174     }
    175 
    176     *result = callback_.GetResult(sock_->Connect(callback_.callback()));
    177     return true;
    178   }
    179 
    180 
    181   // Check that the client certificate was sent.
    182   // Returns true on success.
    183   bool CheckSSLClientSocketSentCert() {
    184     SSLInfo ssl_info;
    185     sock_->GetSSLInfo(&ssl_info);
    186     return ssl_info.client_cert_sent;
    187   }
    188 
    189   ClientSocketFactory* socket_factory_;
    190   scoped_ptr<MockCertVerifier> cert_verifier_;
    191   scoped_ptr<TransportSecurityState> transport_security_state_;
    192   SSLClientSocketContext context_;
    193   OpenSSLClientKeyStore* key_store_;
    194   scoped_ptr<SpawnedTestServer> test_server_;
    195   AddressList addr_;
    196   TestCompletionCallback callback_;
    197   CapturingNetLog log_;
    198   scoped_ptr<StreamSocket> transport_;
    199   scoped_ptr<SSLClientSocket> sock_;
    200 };
    201 
    202 // Connect to a server requesting client authentication, do not send
    203 // any client certificates. It should refuse the connection.
    204 TEST_F(SSLClientSocketOpenSSLClientAuthTest, NoCert) {
    205   SpawnedTestServer::SSLOptions ssl_options;
    206   ssl_options.request_client_certificate = true;
    207 
    208   ASSERT_TRUE(ConnectToTestServer(ssl_options));
    209 
    210   base::FilePath certs_dir = GetTestCertsDirectory();
    211   SSLConfig ssl_config = kDefaultSSLConfig;
    212 
    213   int rv;
    214   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
    215 
    216   EXPECT_EQ(ERR_SSL_CLIENT_AUTH_CERT_NEEDED, rv);
    217   EXPECT_FALSE(sock_->IsConnected());
    218 }
    219 
    220 // Connect to a server requesting client authentication, and send it
    221 // an empty certificate. It should refuse the connection.
    222 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendEmptyCert) {
    223   SpawnedTestServer::SSLOptions ssl_options;
    224   ssl_options.request_client_certificate = true;
    225   ssl_options.client_authorities.push_back(
    226       GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
    227 
    228   ASSERT_TRUE(ConnectToTestServer(ssl_options));
    229 
    230   base::FilePath certs_dir = GetTestCertsDirectory();
    231   SSLConfig ssl_config = kDefaultSSLConfig;
    232   ssl_config.send_client_cert = true;
    233   ssl_config.client_cert = NULL;
    234 
    235   int rv;
    236   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
    237 
    238   EXPECT_EQ(OK, rv);
    239   EXPECT_TRUE(sock_->IsConnected());
    240 }
    241 
    242 // Connect to a server requesting client authentication. Send it a
    243 // matching certificate. It should allow the connection.
    244 TEST_F(SSLClientSocketOpenSSLClientAuthTest, SendGoodCert) {
    245   SpawnedTestServer::SSLOptions ssl_options;
    246   ssl_options.request_client_certificate = true;
    247   ssl_options.client_authorities.push_back(
    248       GetTestClientCertsDirectory().AppendASCII("client_1_ca.pem"));
    249 
    250   ASSERT_TRUE(ConnectToTestServer(ssl_options));
    251 
    252   base::FilePath certs_dir = GetTestCertsDirectory();
    253   SSLConfig ssl_config = kDefaultSSLConfig;
    254   ssl_config.send_client_cert = true;
    255   ssl_config.client_cert = ImportCertFromFile(certs_dir, "client_1.pem");
    256 
    257   // This is required to ensure that signing works with the client
    258   // certificate's private key.
    259   OpenSSLClientKeyStore::ScopedEVP_PKEY client_private_key;
    260   ASSERT_TRUE(LoadPrivateKeyOpenSSL(certs_dir.AppendASCII("client_1.key"),
    261                                     &client_private_key));
    262   EXPECT_TRUE(RecordPrivateKey(ssl_config, client_private_key.get()));
    263 
    264   int rv;
    265   ASSERT_TRUE(CreateAndConnectSSLClientSocket(ssl_config, &rv));
    266 
    267   EXPECT_EQ(OK, rv);
    268   EXPECT_TRUE(sock_->IsConnected());
    269 
    270   EXPECT_TRUE(CheckSSLClientSocketSentCert());
    271 
    272   sock_->Disconnect();
    273   EXPECT_FALSE(sock_->IsConnected());
    274 }
    275 
    276 }  // namespace
    277 }  // namespace net
    278