2 * Copyright 2015 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 #include <folly/io/async/test/AsyncSSLSocketTest.h>
21 #include <folly/io/async/AsyncSSLSocket.h>
22 #include <folly/io/async/EventBase.h>
23 #include <folly/SocketAddress.h>
25 #include <folly/io/async/test/BlockingSocket.h>
28 #include <gtest/gtest.h>
34 #include <openssl/bio.h>
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <netinet/tcp.h>
39 #include <folly/io/Cursor.h>
49 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
50 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
51 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
53 const char* testCert = "folly/io/async/test/certs/tests-cert.pem";
54 const char* testKey = "folly/io/async/test/certs/tests-key.pem";
55 const char* testCA = "folly/io/async/test/certs/ca-cert.pem";
57 constexpr size_t SSLClient::kMaxReadBufferSz;
58 constexpr size_t SSLClient::kMaxReadsPerEvent;
60 inline void BIO_free_fb(BIO* bio) { CHECK_EQ(1, BIO_free(bio)); }
61 using BIO_deleter = folly::static_function_deleter<BIO, &BIO_free_fb>;
62 using X509_deleter = folly::static_function_deleter<X509, &X509_free>;
63 using SSL_deleter = folly::static_function_deleter<SSL, &SSL_free>;
64 using EVP_PKEY_deleter =
65 folly::static_function_deleter<EVP_PKEY, &EVP_PKEY_free>;
67 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase* acb)
68 : ctx_(new folly::SSLContext),
70 socket_(folly::AsyncServerSocket::newSocket(&evb_)) {
71 // Set up the SSL context
72 ctx_->loadCertificate(testCert);
73 ctx_->loadPrivateKey(testKey);
74 ctx_->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
79 //set up the listening socket
81 socket_->getAddress(&address_);
83 socket_->addAcceptCallback(acb_, &evb_);
84 socket_->startAccepting();
86 int ret = pthread_create(&thread_, nullptr, Main, this);
90 std::cerr << "Accepting connections on " << address_ << std::endl;
93 void getfds(int fds[2]) {
94 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
95 FAIL() << "failed to create socketpair: " << strerror(errno);
97 for (int idx = 0; idx < 2; ++idx) {
98 int flags = fcntl(fds[idx], F_GETFL, 0);
100 FAIL() << "failed to get flags for socket " << idx << ": "
103 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
104 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
111 std::shared_ptr<folly::SSLContext> clientCtx,
112 std::shared_ptr<folly::SSLContext> serverCtx) {
113 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
115 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
116 serverCtx->loadCertificate(
118 serverCtx->loadPrivateKey(
123 EventBase* eventBase,
124 AsyncSSLSocket::UniquePtr* clientSock,
125 AsyncSSLSocket::UniquePtr* serverSock) {
126 auto clientCtx = std::make_shared<folly::SSLContext>();
127 auto serverCtx = std::make_shared<folly::SSLContext>();
130 getctx(clientCtx, serverCtx);
131 clientSock->reset(new AsyncSSLSocket(
132 clientCtx, eventBase, fds[0], false));
133 serverSock->reset(new AsyncSSLSocket(
134 serverCtx, eventBase, fds[1], true));
136 // (*clientSock)->setSendTimeout(100);
137 // (*serverSock)->setSendTimeout(100);
140 // client protocol filters
141 bool clientProtoFilterPickPony(unsigned char** client,
142 unsigned int* client_len, const unsigned char*, unsigned int ) {
143 //the protocol string in length prefixed byte string. the
144 //length byte is not included in the length
145 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
151 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
152 const unsigned char*, unsigned int) {
156 std::string getFileAsBuf(const char* fileName) {
158 folly::readFile(fileName, buffer);
162 std::string getCommonName(X509* cert) {
163 X509_NAME* subject = X509_get_subject_name(cert);
165 cn.resize(ub_common_name);
166 X509_NAME_get_text_by_NID(
167 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
172 * Test connecting to, writing to, reading from, and closing the
173 * connection to the SSL server.
175 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
176 // Start listening on a local port
177 WriteCallbackBase writeCallback;
178 ReadCallback readCallback(&writeCallback);
179 HandshakeCallback handshakeCallback(&readCallback);
180 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
181 TestSSLServer server(&acceptCallback);
183 // Set up SSL context.
184 std::shared_ptr<SSLContext> sslContext(new SSLContext());
185 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
186 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
187 //sslContext->authenticate(true, false);
190 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
196 memset(buf, 'a', sizeof(buf));
197 socket->write(buf, sizeof(buf));
200 uint8_t readbuf[128];
201 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
202 EXPECT_EQ(bytesRead, 128);
203 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
208 cerr << "ConnectWriteReadClose test completed" << endl;
212 * Negative test for handshakeError().
214 TEST(AsyncSSLSocketTest, HandshakeError) {
215 // Start listening on a local port
216 WriteCallbackBase writeCallback;
217 ReadCallback readCallback(&writeCallback);
218 HandshakeCallback handshakeCallback(&readCallback);
219 HandshakeErrorCallback acceptCallback(&handshakeCallback);
220 TestSSLServer server(&acceptCallback);
222 // Set up SSL context.
223 std::shared_ptr<SSLContext> sslContext(new SSLContext());
224 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
227 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
234 uint8_t readbuf[128];
235 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
236 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
237 } catch (AsyncSocketException &e) {
244 cerr << "HandshakeError test completed" << endl;
248 * Negative test for readError().
250 TEST(AsyncSSLSocketTest, ReadError) {
251 // Start listening on a local port
252 WriteCallbackBase writeCallback;
253 ReadErrorCallback readCallback(&writeCallback);
254 HandshakeCallback handshakeCallback(&readCallback);
255 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
256 TestSSLServer server(&acceptCallback);
258 // Set up SSL context.
259 std::shared_ptr<SSLContext> sslContext(new SSLContext());
260 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
263 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
267 // write something to trigger ssl handshake
269 memset(buf, 'a', sizeof(buf));
270 socket->write(buf, sizeof(buf));
273 cerr << "ReadError test completed" << endl;
277 * Negative test for writeError().
279 TEST(AsyncSSLSocketTest, WriteError) {
280 // Start listening on a local port
281 WriteCallbackBase writeCallback;
282 WriteErrorCallback readCallback(&writeCallback);
283 HandshakeCallback handshakeCallback(&readCallback);
284 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
285 TestSSLServer server(&acceptCallback);
287 // Set up SSL context.
288 std::shared_ptr<SSLContext> sslContext(new SSLContext());
289 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
292 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
296 // write something to trigger ssl handshake
298 memset(buf, 'a', sizeof(buf));
299 socket->write(buf, sizeof(buf));
302 cerr << "WriteError test completed" << endl;
306 * Test a socket with TCP_NODELAY unset.
308 TEST(AsyncSSLSocketTest, SocketWithDelay) {
309 // Start listening on a local port
310 WriteCallbackBase writeCallback;
311 ReadCallback readCallback(&writeCallback);
312 HandshakeCallback handshakeCallback(&readCallback);
313 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
314 TestSSLServer server(&acceptCallback);
316 // Set up SSL context.
317 std::shared_ptr<SSLContext> sslContext(new SSLContext());
318 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
321 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
327 memset(buf, 'a', sizeof(buf));
328 socket->write(buf, sizeof(buf));
331 uint8_t readbuf[128];
332 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
333 EXPECT_EQ(bytesRead, 128);
334 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
339 cerr << "SocketWithDelay test completed" << endl;
342 using NextProtocolTypePair =
343 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
345 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
346 // For matching protos
348 void SetUp() override { getctx(clientCtx, serverCtx); }
350 void connect(bool unset = false) {
354 // unsetting NPN for any of [client, server] is enough to make NPN not
356 clientCtx->unsetNextProtocols();
359 AsyncSSLSocket::UniquePtr clientSock(
360 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
361 AsyncSSLSocket::UniquePtr serverSock(
362 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
363 client = folly::make_unique<NpnClient>(std::move(clientSock));
364 server = folly::make_unique<NpnServer>(std::move(serverSock));
369 void expectProtocol(const std::string& proto) {
370 EXPECT_NE(client->nextProtoLength, 0);
371 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
373 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
375 string selected((const char*)client->nextProto, client->nextProtoLength);
376 EXPECT_EQ(proto, selected);
379 void expectNoProtocol() {
380 EXPECT_EQ(client->nextProtoLength, 0);
381 EXPECT_EQ(server->nextProtoLength, 0);
382 EXPECT_EQ(client->nextProto, nullptr);
383 EXPECT_EQ(server->nextProto, nullptr);
386 void expectProtocolType() {
387 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
388 GetParam().second == SSLContext::NextProtocolType::ANY) {
389 EXPECT_EQ(client->protocolType, server->protocolType);
390 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
391 GetParam().second == SSLContext::NextProtocolType::ANY) {
392 // Well not much we can say
394 expectProtocolType(GetParam());
398 void expectProtocolType(NextProtocolTypePair expected) {
399 EXPECT_EQ(client->protocolType, expected.first);
400 EXPECT_EQ(server->protocolType, expected.second);
404 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
405 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
407 std::unique_ptr<NpnClient> client;
408 std::unique_ptr<NpnServer> server;
411 class NextProtocolNPNOnlyTest : public NextProtocolTest {
412 // For mismatching protos
415 class NextProtocolMismatchTest : public NextProtocolTest {
416 // For mismatching protos
419 TEST_P(NextProtocolTest, NpnTestOverlap) {
420 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
421 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
426 expectProtocol("baz");
427 expectProtocolType();
430 TEST_P(NextProtocolTest, NpnTestUnset) {
431 // Identical to above test, except that we want unset NPN before
433 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
434 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
437 connect(true /* unset */);
439 // if alpn negotiation fails, type will appear as npn
441 EXPECT_EQ(client->protocolType, server->protocolType);
444 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
445 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
446 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
453 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
456 TEST_P(NextProtocolNPNOnlyTest, NpnTestNoOverlap) {
457 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
458 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
463 expectProtocol("blub");
464 expectProtocolType();
467 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
468 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
469 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
470 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
475 expectProtocol("ponies");
476 expectProtocolType();
479 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
480 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
481 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
482 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
487 expectProtocol("blub");
488 expectProtocolType();
491 TEST_P(NextProtocolTest, RandomizedNpnTest) {
492 // Probability that this test will fail is 2^-64, which could be considered
494 const int kTries = 64;
496 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
498 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
501 std::set<string> selectedProtocols;
502 for (int i = 0; i < kTries; ++i) {
505 EXPECT_NE(client->nextProtoLength, 0);
506 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
508 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
510 string selected((const char*)client->nextProto, client->nextProtoLength);
511 selectedProtocols.insert(selected);
512 expectProtocolType();
514 EXPECT_EQ(selectedProtocols.size(), 2);
517 INSTANTIATE_TEST_CASE_P(
520 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
521 SSLContext::NextProtocolType::NPN),
522 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
523 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
524 SSLContext::NextProtocolType::ALPN),
526 NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
527 SSLContext::NextProtocolType::ANY),
528 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
529 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
530 SSLContext::NextProtocolType::ANY),
532 NextProtocolTypePair(SSLContext::NextProtocolType::ANY,
533 SSLContext::NextProtocolType::ANY)));
535 INSTANTIATE_TEST_CASE_P(
537 NextProtocolNPNOnlyTest,
538 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
539 SSLContext::NextProtocolType::NPN)));
541 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
542 INSTANTIATE_TEST_CASE_P(
544 NextProtocolMismatchTest,
545 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
546 SSLContext::NextProtocolType::ALPN),
547 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
548 SSLContext::NextProtocolType::NPN)));
551 #ifndef OPENSSL_NO_TLSEXT
553 * 1. Client sends TLSEXT_HOSTNAME in client hello.
554 * 2. Server found a match SSL_CTX and use this SSL_CTX to
555 * continue the SSL handshake.
556 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
558 TEST(AsyncSSLSocketTest, SNITestMatch) {
560 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
561 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
562 // Use the same SSLContext to continue the handshake after
563 // tlsext_hostname match.
564 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
565 const std::string serverName("xyz.newdev.facebook.com");
568 getctx(clientCtx, dfServerCtx);
570 AsyncSSLSocket::UniquePtr clientSock(
571 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
572 AsyncSSLSocket::UniquePtr serverSock(
573 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
574 SNIClient client(std::move(clientSock));
575 SNIServer server(std::move(serverSock),
582 EXPECT_TRUE(client.serverNameMatch);
583 EXPECT_TRUE(server.serverNameMatch);
587 * 1. Client sends TLSEXT_HOSTNAME in client hello.
588 * 2. Server cannot find a matching SSL_CTX and continue to use
589 * the current SSL_CTX to do the handshake.
590 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
592 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
594 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
595 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
596 // Use the same SSLContext to continue the handshake after
597 // tlsext_hostname match.
598 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
599 const std::string clientRequestingServerName("foo.com");
600 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
604 getctx(clientCtx, dfServerCtx);
606 AsyncSSLSocket::UniquePtr clientSock(
607 new AsyncSSLSocket(clientCtx,
610 clientRequestingServerName));
611 AsyncSSLSocket::UniquePtr serverSock(
612 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
613 SNIClient client(std::move(clientSock));
614 SNIServer server(std::move(serverSock),
617 serverExpectedServerName);
621 EXPECT_TRUE(!client.serverNameMatch);
622 EXPECT_TRUE(!server.serverNameMatch);
625 * 1. Client sends TLSEXT_HOSTNAME in client hello.
626 * 2. We then change the serverName.
627 * 3. We expect that we get 'false' as the result for serNameMatch.
630 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
632 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
633 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
634 // Use the same SSLContext to continue the handshake after
635 // tlsext_hostname match.
636 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
637 const std::string serverName("xyz.newdev.facebook.com");
640 getctx(clientCtx, dfServerCtx);
642 AsyncSSLSocket::UniquePtr clientSock(
643 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
644 //Change the server name
645 std::string newName("new.com");
646 clientSock->setServerName(newName);
647 AsyncSSLSocket::UniquePtr serverSock(
648 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
649 SNIClient client(std::move(clientSock));
650 SNIServer server(std::move(serverSock),
657 EXPECT_TRUE(!client.serverNameMatch);
661 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
662 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
664 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
666 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
667 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
668 // Use the same SSLContext to continue the handshake after
669 // tlsext_hostname match.
670 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
671 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
675 getctx(clientCtx, dfServerCtx);
677 AsyncSSLSocket::UniquePtr clientSock(
678 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
679 AsyncSSLSocket::UniquePtr serverSock(
680 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
681 SNIClient client(std::move(clientSock));
682 SNIServer server(std::move(serverSock),
685 serverExpectedServerName);
689 EXPECT_TRUE(!client.serverNameMatch);
690 EXPECT_TRUE(!server.serverNameMatch);
695 * Test SSL client socket
697 TEST(AsyncSSLSocketTest, SSLClientTest) {
698 // Start listening on a local port
699 WriteCallbackBase writeCallback;
700 ReadCallback readCallback(&writeCallback);
701 HandshakeCallback handshakeCallback(&readCallback);
702 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
703 TestSSLServer server(&acceptCallback);
707 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
710 EventBaseAborter eba(&eventBase, 3000);
713 EXPECT_EQ(client->getMiss(), 1);
714 EXPECT_EQ(client->getHit(), 0);
716 cerr << "SSLClientTest test completed" << endl;
721 * Test SSL client socket session re-use
723 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
724 // Start listening on a local port
725 WriteCallbackBase writeCallback;
726 ReadCallback readCallback(&writeCallback);
727 HandshakeCallback handshakeCallback(&readCallback);
728 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
729 TestSSLServer server(&acceptCallback);
734 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
737 EventBaseAborter eba(&eventBase, 3000);
740 EXPECT_EQ(client->getMiss(), 1);
741 EXPECT_EQ(client->getHit(), 9);
743 cerr << "SSLClientTestReuse test completed" << endl;
747 * Test SSL client socket timeout
749 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
750 // Start listening on a local port
751 EmptyReadCallback readCallback;
752 HandshakeCallback handshakeCallback(&readCallback,
753 HandshakeCallback::EXPECT_ERROR);
754 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
755 TestSSLServer server(&acceptCallback);
760 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
761 client->connect(true /* write before connect completes */);
762 EventBaseAborter eba(&eventBase, 3000);
766 // This is checking that the connectError callback precedes any queued
767 // writeError callbacks. This matches AsyncSocket's behavior
768 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
769 EXPECT_EQ(client->getErrors(), 1);
770 EXPECT_EQ(client->getMiss(), 0);
771 EXPECT_EQ(client->getHit(), 0);
773 cerr << "SSLClientTimeoutTest test completed" << endl;
778 * Test SSL server async cache
780 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
781 // Start listening on a local port
782 WriteCallbackBase writeCallback;
783 ReadCallback readCallback(&writeCallback);
784 HandshakeCallback handshakeCallback(&readCallback);
785 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
786 TestSSLAsyncCacheServer server(&acceptCallback);
791 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
794 EventBaseAborter eba(&eventBase, 3000);
797 EXPECT_EQ(server.getAsyncCallbacks(), 18);
798 EXPECT_EQ(server.getAsyncLookups(), 9);
799 EXPECT_EQ(client->getMiss(), 10);
800 EXPECT_EQ(client->getHit(), 0);
802 cerr << "SSLServerAsyncCacheTest test completed" << endl;
807 * Test SSL server accept timeout with cache path
809 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
810 // Start listening on a local port
811 WriteCallbackBase writeCallback;
812 ReadCallback readCallback(&writeCallback);
813 EmptyReadCallback clientReadCallback;
814 HandshakeCallback handshakeCallback(&readCallback);
815 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
816 TestSSLAsyncCacheServer server(&acceptCallback);
820 // only do a TCP connect
821 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
822 sock->connect(nullptr, server.getAddress());
823 clientReadCallback.tcpSocket_ = sock;
824 sock->setReadCB(&clientReadCallback);
826 EventBaseAborter eba(&eventBase, 3000);
829 EXPECT_EQ(readCallback.state, STATE_WAITING);
831 cerr << "SSLServerTimeoutTest test completed" << endl;
835 * Test SSL server accept timeout with cache path
837 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
838 // Start listening on a local port
839 WriteCallbackBase writeCallback;
840 ReadCallback readCallback(&writeCallback);
841 HandshakeCallback handshakeCallback(&readCallback);
842 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
843 TestSSLAsyncCacheServer server(&acceptCallback);
847 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
850 EventBaseAborter eba(&eventBase, 3000);
853 EXPECT_EQ(server.getAsyncCallbacks(), 1);
854 EXPECT_EQ(server.getAsyncLookups(), 1);
855 EXPECT_EQ(client->getErrors(), 1);
856 EXPECT_EQ(client->getMiss(), 1);
857 EXPECT_EQ(client->getHit(), 0);
859 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
863 * Test SSL server accept timeout with cache path
865 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
866 // Start listening on a local port
867 WriteCallbackBase writeCallback;
868 ReadCallback readCallback(&writeCallback);
869 HandshakeCallback handshakeCallback(&readCallback,
870 HandshakeCallback::EXPECT_ERROR);
871 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
872 TestSSLAsyncCacheServer server(&acceptCallback, 500);
877 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
880 EventBaseAborter eba(&eventBase, 3000);
883 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
884 handshakeCallback.closeSocket();});
885 // give time for the cache lookup to come back and find it closed
888 EXPECT_EQ(server.getAsyncCallbacks(), 1);
889 EXPECT_EQ(server.getAsyncLookups(), 1);
890 EXPECT_EQ(client->getErrors(), 1);
891 EXPECT_EQ(client->getMiss(), 1);
892 EXPECT_EQ(client->getHit(), 0);
894 cerr << "SSLServerCacheCloseTest test completed" << endl;
898 * Verify Client Ciphers obtained using SSL MSG Callback.
900 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
902 auto clientCtx = std::make_shared<SSLContext>();
903 auto serverCtx = std::make_shared<SSLContext>();
904 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
905 serverCtx->ciphers("RSA:!SHA:!NULL:!SHA256@STRENGTH");
906 serverCtx->loadPrivateKey(testKey);
907 serverCtx->loadCertificate(testCert);
908 serverCtx->loadTrustedCertificates(testCA);
909 serverCtx->loadClientCAList(testCA);
911 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
912 clientCtx->ciphers("RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5");
913 clientCtx->loadPrivateKey(testKey);
914 clientCtx->loadCertificate(testCert);
915 clientCtx->loadTrustedCertificates(testCA);
920 AsyncSSLSocket::UniquePtr clientSock(
921 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
922 AsyncSSLSocket::UniquePtr serverSock(
923 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
925 SSLHandshakeClient client(std::move(clientSock), true, true);
926 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
930 EXPECT_EQ(server.clientCiphers_,
931 "RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5:00ff");
932 EXPECT_TRUE(client.handshakeVerify_);
933 EXPECT_TRUE(client.handshakeSuccess_);
934 EXPECT_TRUE(!client.handshakeError_);
935 EXPECT_TRUE(server.handshakeVerify_);
936 EXPECT_TRUE(server.handshakeSuccess_);
937 EXPECT_TRUE(!server.handshakeError_);
940 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
942 auto ctx = std::make_shared<SSLContext>();
948 uint8_t majorVersion = 18;
949 uint8_t minorVersion = 25;
951 // Create callback buf
952 auto buf = IOBuf::create(bufLen);
954 folly::io::RWPrivateCursor cursor(buf.get());
955 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
956 cursor.write<uint16_t>(0);
957 cursor.write<uint8_t>(38);
958 cursor.write<uint8_t>(majorVersion);
959 cursor.write<uint8_t>(minorVersion);
961 cursor.write<uint32_t>(0);
963 SSL* ssl = ctx->createSSL();
964 SCOPE_EXIT { SSL_free(ssl); };
965 AsyncSSLSocket::UniquePtr sock(
966 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
967 sock->enableClientHelloParsing();
969 // Test client hello parsing in one packet
970 AsyncSSLSocket::clientHelloParsingCallback(
971 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
974 auto parsedClientHello = sock->getClientHelloInfo();
975 EXPECT_TRUE(parsedClientHello != nullptr);
976 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
977 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
980 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
982 auto ctx = std::make_shared<SSLContext>();
988 uint8_t majorVersion = 18;
989 uint8_t minorVersion = 25;
991 // Create callback buf
992 auto buf = IOBuf::create(bufLen);
994 folly::io::RWPrivateCursor cursor(buf.get());
995 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
996 cursor.write<uint16_t>(0);
997 cursor.write<uint8_t>(38);
998 cursor.write<uint8_t>(majorVersion);
999 cursor.write<uint8_t>(minorVersion);
1001 cursor.write<uint32_t>(0);
1003 SSL* ssl = ctx->createSSL();
1004 SCOPE_EXIT { SSL_free(ssl); };
1005 AsyncSSLSocket::UniquePtr sock(
1006 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1007 sock->enableClientHelloParsing();
1009 // Test parsing with two packets with first packet size < 3
1010 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1011 AsyncSSLSocket::clientHelloParsingCallback(
1012 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1015 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1016 AsyncSSLSocket::clientHelloParsingCallback(
1017 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1021 auto parsedClientHello = sock->getClientHelloInfo();
1022 EXPECT_TRUE(parsedClientHello != nullptr);
1023 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1024 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1027 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1028 EventBase eventBase;
1029 auto ctx = std::make_shared<SSLContext>();
1035 uint8_t majorVersion = 18;
1036 uint8_t minorVersion = 25;
1038 // Create callback buf
1039 auto buf = IOBuf::create(bufLen);
1040 buf->append(bufLen);
1041 folly::io::RWPrivateCursor cursor(buf.get());
1042 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1043 cursor.write<uint16_t>(0);
1044 cursor.write<uint8_t>(38);
1045 cursor.write<uint8_t>(majorVersion);
1046 cursor.write<uint8_t>(minorVersion);
1048 cursor.write<uint32_t>(0);
1050 SSL* ssl = ctx->createSSL();
1051 SCOPE_EXIT { SSL_free(ssl); };
1052 AsyncSSLSocket::UniquePtr sock(
1053 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1054 sock->enableClientHelloParsing();
1056 // Test parsing with multiple small packets
1057 for (uint64_t i = 0; i < buf->length(); i += 3) {
1058 auto bufCopy = folly::IOBuf::copyBuffer(
1059 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1060 AsyncSSLSocket::clientHelloParsingCallback(
1061 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1066 auto parsedClientHello = sock->getClientHelloInfo();
1067 EXPECT_TRUE(parsedClientHello != nullptr);
1068 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1069 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1073 * Verify sucessful behavior of SSL certificate validation.
1075 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1076 EventBase eventBase;
1077 auto clientCtx = std::make_shared<SSLContext>();
1078 auto dfServerCtx = std::make_shared<SSLContext>();
1082 getctx(clientCtx, dfServerCtx);
1084 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1085 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1087 AsyncSSLSocket::UniquePtr clientSock(
1088 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1089 AsyncSSLSocket::UniquePtr serverSock(
1090 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1092 SSLHandshakeClient client(std::move(clientSock), true, true);
1093 clientCtx->loadTrustedCertificates(testCA);
1095 SSLHandshakeServer server(std::move(serverSock), true, true);
1099 EXPECT_TRUE(client.handshakeVerify_);
1100 EXPECT_TRUE(client.handshakeSuccess_);
1101 EXPECT_TRUE(!client.handshakeError_);
1102 EXPECT_LE(0, client.handshakeTime.count());
1103 EXPECT_TRUE(!server.handshakeVerify_);
1104 EXPECT_TRUE(server.handshakeSuccess_);
1105 EXPECT_TRUE(!server.handshakeError_);
1106 EXPECT_LE(0, server.handshakeTime.count());
1110 * Verify that the client's verification callback is able to fail SSL
1111 * connection establishment.
1113 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1114 EventBase eventBase;
1115 auto clientCtx = std::make_shared<SSLContext>();
1116 auto dfServerCtx = std::make_shared<SSLContext>();
1120 getctx(clientCtx, dfServerCtx);
1122 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1123 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1125 AsyncSSLSocket::UniquePtr clientSock(
1126 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1127 AsyncSSLSocket::UniquePtr serverSock(
1128 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1130 SSLHandshakeClient client(std::move(clientSock), true, false);
1131 clientCtx->loadTrustedCertificates(testCA);
1133 SSLHandshakeServer server(std::move(serverSock), true, true);
1137 EXPECT_TRUE(client.handshakeVerify_);
1138 EXPECT_TRUE(!client.handshakeSuccess_);
1139 EXPECT_TRUE(client.handshakeError_);
1140 EXPECT_LE(0, client.handshakeTime.count());
1141 EXPECT_TRUE(!server.handshakeVerify_);
1142 EXPECT_TRUE(!server.handshakeSuccess_);
1143 EXPECT_TRUE(server.handshakeError_);
1144 EXPECT_LE(0, server.handshakeTime.count());
1148 * Verify that the options in SSLContext can be overridden in
1149 * sslConnect/Accept.i.e specifying that no validation should be performed
1150 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1151 * the validation callback.
1153 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1154 EventBase eventBase;
1155 auto clientCtx = std::make_shared<SSLContext>();
1156 auto dfServerCtx = std::make_shared<SSLContext>();
1160 getctx(clientCtx, dfServerCtx);
1162 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1163 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1165 AsyncSSLSocket::UniquePtr clientSock(
1166 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1167 AsyncSSLSocket::UniquePtr serverSock(
1168 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1170 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1171 clientCtx->loadTrustedCertificates(testCA);
1173 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1177 EXPECT_TRUE(!client.handshakeVerify_);
1178 EXPECT_TRUE(client.handshakeSuccess_);
1179 EXPECT_TRUE(!client.handshakeError_);
1180 EXPECT_LE(0, client.handshakeTime.count());
1181 EXPECT_TRUE(!server.handshakeVerify_);
1182 EXPECT_TRUE(server.handshakeSuccess_);
1183 EXPECT_TRUE(!server.handshakeError_);
1184 EXPECT_LE(0, server.handshakeTime.count());
1188 * Verify that the options in SSLContext can be overridden in
1189 * sslConnect/Accept. Enable verification even if context says otherwise.
1190 * Test requireClientCert with client cert
1192 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1193 EventBase eventBase;
1194 auto clientCtx = std::make_shared<SSLContext>();
1195 auto serverCtx = std::make_shared<SSLContext>();
1196 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1197 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1198 serverCtx->loadPrivateKey(testKey);
1199 serverCtx->loadCertificate(testCert);
1200 serverCtx->loadTrustedCertificates(testCA);
1201 serverCtx->loadClientCAList(testCA);
1203 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1204 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1205 clientCtx->loadPrivateKey(testKey);
1206 clientCtx->loadCertificate(testCert);
1207 clientCtx->loadTrustedCertificates(testCA);
1212 AsyncSSLSocket::UniquePtr clientSock(
1213 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1214 AsyncSSLSocket::UniquePtr serverSock(
1215 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1217 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1218 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1222 EXPECT_TRUE(client.handshakeVerify_);
1223 EXPECT_TRUE(client.handshakeSuccess_);
1224 EXPECT_FALSE(client.handshakeError_);
1225 EXPECT_LE(0, client.handshakeTime.count());
1226 EXPECT_TRUE(server.handshakeVerify_);
1227 EXPECT_TRUE(server.handshakeSuccess_);
1228 EXPECT_FALSE(server.handshakeError_);
1229 EXPECT_LE(0, server.handshakeTime.count());
1233 * Verify that the client's verification callback is able to override
1234 * the preverification failure and allow a successful connection.
1236 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1237 EventBase eventBase;
1238 auto clientCtx = std::make_shared<SSLContext>();
1239 auto dfServerCtx = std::make_shared<SSLContext>();
1243 getctx(clientCtx, dfServerCtx);
1245 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1246 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1248 AsyncSSLSocket::UniquePtr clientSock(
1249 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1250 AsyncSSLSocket::UniquePtr serverSock(
1251 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1253 SSLHandshakeClient client(std::move(clientSock), false, true);
1254 SSLHandshakeServer server(std::move(serverSock), true, true);
1258 EXPECT_TRUE(client.handshakeVerify_);
1259 EXPECT_TRUE(client.handshakeSuccess_);
1260 EXPECT_TRUE(!client.handshakeError_);
1261 EXPECT_LE(0, client.handshakeTime.count());
1262 EXPECT_TRUE(!server.handshakeVerify_);
1263 EXPECT_TRUE(server.handshakeSuccess_);
1264 EXPECT_TRUE(!server.handshakeError_);
1265 EXPECT_LE(0, server.handshakeTime.count());
1269 * Verify that specifying that no validation should be performed allows an
1270 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1273 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1274 EventBase eventBase;
1275 auto clientCtx = std::make_shared<SSLContext>();
1276 auto dfServerCtx = std::make_shared<SSLContext>();
1280 getctx(clientCtx, dfServerCtx);
1282 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1283 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1285 AsyncSSLSocket::UniquePtr clientSock(
1286 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1287 AsyncSSLSocket::UniquePtr serverSock(
1288 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1290 SSLHandshakeClient client(std::move(clientSock), false, false);
1291 SSLHandshakeServer server(std::move(serverSock), false, false);
1295 EXPECT_TRUE(!client.handshakeVerify_);
1296 EXPECT_TRUE(client.handshakeSuccess_);
1297 EXPECT_TRUE(!client.handshakeError_);
1298 EXPECT_LE(0, client.handshakeTime.count());
1299 EXPECT_TRUE(!server.handshakeVerify_);
1300 EXPECT_TRUE(server.handshakeSuccess_);
1301 EXPECT_TRUE(!server.handshakeError_);
1302 EXPECT_LE(0, server.handshakeTime.count());
1306 * Test requireClientCert with client cert
1308 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1309 EventBase eventBase;
1310 auto clientCtx = std::make_shared<SSLContext>();
1311 auto serverCtx = std::make_shared<SSLContext>();
1312 serverCtx->setVerificationOption(
1313 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1314 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1315 serverCtx->loadPrivateKey(testKey);
1316 serverCtx->loadCertificate(testCert);
1317 serverCtx->loadTrustedCertificates(testCA);
1318 serverCtx->loadClientCAList(testCA);
1320 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1321 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1322 clientCtx->loadPrivateKey(testKey);
1323 clientCtx->loadCertificate(testCert);
1324 clientCtx->loadTrustedCertificates(testCA);
1329 AsyncSSLSocket::UniquePtr clientSock(
1330 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1331 AsyncSSLSocket::UniquePtr serverSock(
1332 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1334 SSLHandshakeClient client(std::move(clientSock), true, true);
1335 SSLHandshakeServer server(std::move(serverSock), true, true);
1339 EXPECT_TRUE(client.handshakeVerify_);
1340 EXPECT_TRUE(client.handshakeSuccess_);
1341 EXPECT_FALSE(client.handshakeError_);
1342 EXPECT_LE(0, client.handshakeTime.count());
1343 EXPECT_TRUE(server.handshakeVerify_);
1344 EXPECT_TRUE(server.handshakeSuccess_);
1345 EXPECT_FALSE(server.handshakeError_);
1346 EXPECT_LE(0, server.handshakeTime.count());
1351 * Test requireClientCert with no client cert
1353 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1354 EventBase eventBase;
1355 auto clientCtx = std::make_shared<SSLContext>();
1356 auto serverCtx = std::make_shared<SSLContext>();
1357 serverCtx->setVerificationOption(
1358 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1359 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1360 serverCtx->loadPrivateKey(testKey);
1361 serverCtx->loadCertificate(testCert);
1362 serverCtx->loadTrustedCertificates(testCA);
1363 serverCtx->loadClientCAList(testCA);
1364 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1365 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1370 AsyncSSLSocket::UniquePtr clientSock(
1371 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1372 AsyncSSLSocket::UniquePtr serverSock(
1373 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1375 SSLHandshakeClient client(std::move(clientSock), false, false);
1376 SSLHandshakeServer server(std::move(serverSock), false, false);
1380 EXPECT_FALSE(server.handshakeVerify_);
1381 EXPECT_FALSE(server.handshakeSuccess_);
1382 EXPECT_TRUE(server.handshakeError_);
1383 EXPECT_LE(0, client.handshakeTime.count());
1384 EXPECT_LE(0, server.handshakeTime.count());
1387 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1388 auto cert = getFileAsBuf(testCert);
1389 auto key = getFileAsBuf(testKey);
1391 std::unique_ptr<BIO, BIO_deleter> certBio(BIO_new(BIO_s_mem()));
1392 BIO_write(certBio.get(), cert.data(), cert.size());
1393 std::unique_ptr<BIO, BIO_deleter> keyBio(BIO_new(BIO_s_mem()));
1394 BIO_write(keyBio.get(), key.data(), key.size());
1396 // Create SSL structs from buffers to get properties
1397 std::unique_ptr<X509, X509_deleter> certStruct(
1398 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1399 std::unique_ptr<EVP_PKEY, EVP_PKEY_deleter> keyStruct(
1400 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1404 auto origCommonName = getCommonName(certStruct.get());
1405 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1406 certStruct = nullptr;
1407 keyStruct = nullptr;
1409 auto ctx = std::make_shared<SSLContext>();
1410 ctx->loadPrivateKeyFromBufferPEM(key);
1411 ctx->loadCertificateFromBufferPEM(cert);
1412 ctx->loadTrustedCertificates(testCA);
1414 std::unique_ptr<SSL, SSL_deleter> ssl(ctx->createSSL());
1416 auto newCert = SSL_get_certificate(ssl.get());
1417 auto newKey = SSL_get_privatekey(ssl.get());
1419 // Get properties from SSL struct
1420 auto newCommonName = getCommonName(newCert);
1421 auto newKeySize = EVP_PKEY_bits(newKey);
1423 // Check that the key and cert have the expected properties
1424 EXPECT_EQ(origCommonName, newCommonName);
1425 EXPECT_EQ(origKeySize, newKeySize);
1428 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1431 // Set up SSL context.
1432 auto sslContext = std::make_shared<SSLContext>();
1433 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1435 // create SSL socket
1436 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1438 EXPECT_EQ(1500, socket->getMinWriteSize());
1440 socket->setMinWriteSize(0);
1441 EXPECT_EQ(0, socket->getMinWriteSize());
1442 socket->setMinWriteSize(50000);
1443 EXPECT_EQ(50000, socket->getMinWriteSize());
1446 class ReadCallbackTerminator : public ReadCallback {
1448 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1452 // Do not write data back, terminate the loop.
1453 void readDataAvailable(size_t len) noexcept override {
1454 std::cerr << "readDataAvailable, len " << len << std::endl;
1456 currentBuffer.length = len;
1458 buffers.push_back(currentBuffer);
1459 currentBuffer.reset();
1460 state = STATE_SUCCEEDED;
1462 socket_->setReadCB(nullptr);
1463 base_->terminateLoopSoon();
1471 * Test a full unencrypted codepath
1473 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1476 auto clientCtx = std::make_shared<folly::SSLContext>();
1477 auto serverCtx = std::make_shared<folly::SSLContext>();
1480 getctx(clientCtx, serverCtx);
1481 auto client = AsyncSSLSocket::newSocket(
1482 clientCtx, &base, fds[0], false, true);
1483 auto server = AsyncSSLSocket::newSocket(
1484 serverCtx, &base, fds[1], true, true);
1486 ReadCallbackTerminator readCallback(&base, nullptr);
1487 server->setReadCB(&readCallback);
1488 readCallback.setSocket(server);
1491 memset(buf, 'a', sizeof(buf));
1492 client->write(nullptr, buf, sizeof(buf));
1494 // Check that bytes are unencrypted
1496 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1499 EventBaseAborter eba(&base, 3000);
1502 EXPECT_EQ(1, readCallback.buffers.size());
1503 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1505 server->setReadCB(&readCallback);
1508 server->sslAccept(nullptr);
1509 client->sslConn(nullptr);
1511 // Do NOT wait for handshake, writing should be queued and happen after
1513 client->write(nullptr, buf, sizeof(buf));
1515 // Check that bytes are *not* unencrypted
1517 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1523 EXPECT_EQ(2, readCallback.buffers.size());
1524 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1529 ///////////////////////////////////////////////////////////////////////////
1530 // init_unit_test_suite
1531 ///////////////////////////////////////////////////////////////////////////
1533 struct Initializer {
1535 signal(SIGPIPE, SIG_IGN);
1538 Initializer initializer;