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