2 * Copyright 2016 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>;
63 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase* acb)
64 : ctx_(new folly::SSLContext),
66 socket_(folly::AsyncServerSocket::newSocket(&evb_)) {
67 // Set up the SSL context
68 ctx_->loadCertificate(testCert);
69 ctx_->loadPrivateKey(testKey);
70 ctx_->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
75 //set up the listening socket
77 socket_->getAddress(&address_);
79 socket_->addAcceptCallback(acb_, &evb_);
80 socket_->startAccepting();
82 int ret = pthread_create(&thread_, nullptr, Main, this);
86 std::cerr << "Accepting connections on " << address_ << std::endl;
89 void getfds(int fds[2]) {
90 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
91 FAIL() << "failed to create socketpair: " << strerror(errno);
93 for (int idx = 0; idx < 2; ++idx) {
94 int flags = fcntl(fds[idx], F_GETFL, 0);
96 FAIL() << "failed to get flags for socket " << idx << ": "
99 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
100 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
107 std::shared_ptr<folly::SSLContext> clientCtx,
108 std::shared_ptr<folly::SSLContext> serverCtx) {
109 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
111 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
112 serverCtx->loadCertificate(
114 serverCtx->loadPrivateKey(
119 EventBase* eventBase,
120 AsyncSSLSocket::UniquePtr* clientSock,
121 AsyncSSLSocket::UniquePtr* serverSock) {
122 auto clientCtx = std::make_shared<folly::SSLContext>();
123 auto serverCtx = std::make_shared<folly::SSLContext>();
126 getctx(clientCtx, serverCtx);
127 clientSock->reset(new AsyncSSLSocket(
128 clientCtx, eventBase, fds[0], false));
129 serverSock->reset(new AsyncSSLSocket(
130 serverCtx, eventBase, fds[1], true));
132 // (*clientSock)->setSendTimeout(100);
133 // (*serverSock)->setSendTimeout(100);
136 // client protocol filters
137 bool clientProtoFilterPickPony(unsigned char** client,
138 unsigned int* client_len, const unsigned char*, unsigned int ) {
139 //the protocol string in length prefixed byte string. the
140 //length byte is not included in the length
141 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
147 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
148 const unsigned char*, unsigned int) {
152 std::string getFileAsBuf(const char* fileName) {
154 folly::readFile(fileName, buffer);
158 std::string getCommonName(X509* cert) {
159 X509_NAME* subject = X509_get_subject_name(cert);
161 cn.resize(ub_common_name);
162 X509_NAME_get_text_by_NID(
163 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
168 * Test connecting to, writing to, reading from, and closing the
169 * connection to the SSL server.
171 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
172 // Start listening on a local port
173 WriteCallbackBase writeCallback;
174 ReadCallback readCallback(&writeCallback);
175 HandshakeCallback handshakeCallback(&readCallback);
176 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
177 TestSSLServer server(&acceptCallback);
179 // Set up SSL context.
180 std::shared_ptr<SSLContext> sslContext(new SSLContext());
181 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
182 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
183 //sslContext->authenticate(true, false);
186 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
192 memset(buf, 'a', sizeof(buf));
193 socket->write(buf, sizeof(buf));
196 uint8_t readbuf[128];
197 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
198 EXPECT_EQ(bytesRead, 128);
199 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
204 cerr << "ConnectWriteReadClose test completed" << endl;
208 * Negative test for handshakeError().
210 TEST(AsyncSSLSocketTest, HandshakeError) {
211 // Start listening on a local port
212 WriteCallbackBase writeCallback;
213 ReadCallback readCallback(&writeCallback);
214 HandshakeCallback handshakeCallback(&readCallback);
215 HandshakeErrorCallback acceptCallback(&handshakeCallback);
216 TestSSLServer server(&acceptCallback);
218 // Set up SSL context.
219 std::shared_ptr<SSLContext> sslContext(new SSLContext());
220 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
223 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
230 uint8_t readbuf[128];
231 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
232 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
233 } catch (AsyncSocketException &e) {
240 cerr << "HandshakeError test completed" << endl;
244 * Negative test for readError().
246 TEST(AsyncSSLSocketTest, ReadError) {
247 // Start listening on a local port
248 WriteCallbackBase writeCallback;
249 ReadErrorCallback readCallback(&writeCallback);
250 HandshakeCallback handshakeCallback(&readCallback);
251 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
252 TestSSLServer server(&acceptCallback);
254 // Set up SSL context.
255 std::shared_ptr<SSLContext> sslContext(new SSLContext());
256 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
259 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
263 // write something to trigger ssl handshake
265 memset(buf, 'a', sizeof(buf));
266 socket->write(buf, sizeof(buf));
269 cerr << "ReadError test completed" << endl;
273 * Negative test for writeError().
275 TEST(AsyncSSLSocketTest, WriteError) {
276 // Start listening on a local port
277 WriteCallbackBase writeCallback;
278 WriteErrorCallback readCallback(&writeCallback);
279 HandshakeCallback handshakeCallback(&readCallback);
280 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
281 TestSSLServer server(&acceptCallback);
283 // Set up SSL context.
284 std::shared_ptr<SSLContext> sslContext(new SSLContext());
285 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
288 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
292 // write something to trigger ssl handshake
294 memset(buf, 'a', sizeof(buf));
295 socket->write(buf, sizeof(buf));
298 cerr << "WriteError test completed" << endl;
302 * Test a socket with TCP_NODELAY unset.
304 TEST(AsyncSSLSocketTest, SocketWithDelay) {
305 // Start listening on a local port
306 WriteCallbackBase writeCallback;
307 ReadCallback readCallback(&writeCallback);
308 HandshakeCallback handshakeCallback(&readCallback);
309 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
310 TestSSLServer server(&acceptCallback);
312 // Set up SSL context.
313 std::shared_ptr<SSLContext> sslContext(new SSLContext());
314 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
317 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
323 memset(buf, 'a', sizeof(buf));
324 socket->write(buf, sizeof(buf));
327 uint8_t readbuf[128];
328 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
329 EXPECT_EQ(bytesRead, 128);
330 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
335 cerr << "SocketWithDelay test completed" << endl;
338 using NextProtocolTypePair =
339 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
341 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
342 // For matching protos
344 void SetUp() override { getctx(clientCtx, serverCtx); }
346 void connect(bool unset = false) {
350 // unsetting NPN for any of [client, server] is enough to make NPN not
352 clientCtx->unsetNextProtocols();
355 AsyncSSLSocket::UniquePtr clientSock(
356 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
357 AsyncSSLSocket::UniquePtr serverSock(
358 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
359 client = folly::make_unique<NpnClient>(std::move(clientSock));
360 server = folly::make_unique<NpnServer>(std::move(serverSock));
365 void expectProtocol(const std::string& proto) {
366 EXPECT_NE(client->nextProtoLength, 0);
367 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
369 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
371 string selected((const char*)client->nextProto, client->nextProtoLength);
372 EXPECT_EQ(proto, selected);
375 void expectNoProtocol() {
376 EXPECT_EQ(client->nextProtoLength, 0);
377 EXPECT_EQ(server->nextProtoLength, 0);
378 EXPECT_EQ(client->nextProto, nullptr);
379 EXPECT_EQ(server->nextProto, nullptr);
382 void expectProtocolType() {
383 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
384 GetParam().second == SSLContext::NextProtocolType::ANY) {
385 EXPECT_EQ(client->protocolType, server->protocolType);
386 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
387 GetParam().second == SSLContext::NextProtocolType::ANY) {
388 // Well not much we can say
390 expectProtocolType(GetParam());
394 void expectProtocolType(NextProtocolTypePair expected) {
395 EXPECT_EQ(client->protocolType, expected.first);
396 EXPECT_EQ(server->protocolType, expected.second);
400 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
401 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
403 std::unique_ptr<NpnClient> client;
404 std::unique_ptr<NpnServer> server;
407 class NextProtocolNPNOnlyTest : public NextProtocolTest {
408 // For mismatching protos
411 class NextProtocolMismatchTest : public NextProtocolTest {
412 // For mismatching protos
415 TEST_P(NextProtocolTest, NpnTestOverlap) {
416 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
417 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
422 expectProtocol("baz");
423 expectProtocolType();
426 TEST_P(NextProtocolTest, NpnTestUnset) {
427 // Identical to above test, except that we want unset NPN before
429 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
430 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
433 connect(true /* unset */);
435 // if alpn negotiation fails, type will appear as npn
437 EXPECT_EQ(client->protocolType, server->protocolType);
440 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
441 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
442 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
449 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
452 TEST_P(NextProtocolNPNOnlyTest, NpnTestNoOverlap) {
453 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
454 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
459 expectProtocol("blub");
460 expectProtocolType();
463 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
464 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
465 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
466 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
471 expectProtocol("ponies");
472 expectProtocolType();
475 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
476 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
477 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
478 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
483 expectProtocol("blub");
484 expectProtocolType();
487 TEST_P(NextProtocolTest, RandomizedNpnTest) {
488 // Probability that this test will fail is 2^-64, which could be considered
490 const int kTries = 64;
492 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
494 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
497 std::set<string> selectedProtocols;
498 for (int i = 0; i < kTries; ++i) {
501 EXPECT_NE(client->nextProtoLength, 0);
502 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
504 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
506 string selected((const char*)client->nextProto, client->nextProtoLength);
507 selectedProtocols.insert(selected);
508 expectProtocolType();
510 EXPECT_EQ(selectedProtocols.size(), 2);
513 INSTANTIATE_TEST_CASE_P(
516 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
517 SSLContext::NextProtocolType::NPN),
518 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
519 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
520 SSLContext::NextProtocolType::ALPN),
522 NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
523 SSLContext::NextProtocolType::ANY),
524 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
525 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
526 SSLContext::NextProtocolType::ANY),
528 NextProtocolTypePair(SSLContext::NextProtocolType::ANY,
529 SSLContext::NextProtocolType::ANY)));
531 INSTANTIATE_TEST_CASE_P(
533 NextProtocolNPNOnlyTest,
534 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
535 SSLContext::NextProtocolType::NPN)));
537 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
538 INSTANTIATE_TEST_CASE_P(
540 NextProtocolMismatchTest,
541 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
542 SSLContext::NextProtocolType::ALPN),
543 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
544 SSLContext::NextProtocolType::NPN)));
547 #ifndef OPENSSL_NO_TLSEXT
549 * 1. Client sends TLSEXT_HOSTNAME in client hello.
550 * 2. Server found a match SSL_CTX and use this SSL_CTX to
551 * continue the SSL handshake.
552 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
554 TEST(AsyncSSLSocketTest, SNITestMatch) {
556 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
557 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
558 // Use the same SSLContext to continue the handshake after
559 // tlsext_hostname match.
560 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
561 const std::string serverName("xyz.newdev.facebook.com");
564 getctx(clientCtx, dfServerCtx);
566 AsyncSSLSocket::UniquePtr clientSock(
567 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
568 AsyncSSLSocket::UniquePtr serverSock(
569 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
570 SNIClient client(std::move(clientSock));
571 SNIServer server(std::move(serverSock),
578 EXPECT_TRUE(client.serverNameMatch);
579 EXPECT_TRUE(server.serverNameMatch);
583 * 1. Client sends TLSEXT_HOSTNAME in client hello.
584 * 2. Server cannot find a matching SSL_CTX and continue to use
585 * the current SSL_CTX to do the handshake.
586 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
588 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
590 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
591 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
592 // Use the same SSLContext to continue the handshake after
593 // tlsext_hostname match.
594 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
595 const std::string clientRequestingServerName("foo.com");
596 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
600 getctx(clientCtx, dfServerCtx);
602 AsyncSSLSocket::UniquePtr clientSock(
603 new AsyncSSLSocket(clientCtx,
606 clientRequestingServerName));
607 AsyncSSLSocket::UniquePtr serverSock(
608 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
609 SNIClient client(std::move(clientSock));
610 SNIServer server(std::move(serverSock),
613 serverExpectedServerName);
617 EXPECT_TRUE(!client.serverNameMatch);
618 EXPECT_TRUE(!server.serverNameMatch);
621 * 1. Client sends TLSEXT_HOSTNAME in client hello.
622 * 2. We then change the serverName.
623 * 3. We expect that we get 'false' as the result for serNameMatch.
626 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
628 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
629 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
630 // Use the same SSLContext to continue the handshake after
631 // tlsext_hostname match.
632 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
633 const std::string serverName("xyz.newdev.facebook.com");
636 getctx(clientCtx, dfServerCtx);
638 AsyncSSLSocket::UniquePtr clientSock(
639 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
640 //Change the server name
641 std::string newName("new.com");
642 clientSock->setServerName(newName);
643 AsyncSSLSocket::UniquePtr serverSock(
644 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
645 SNIClient client(std::move(clientSock));
646 SNIServer server(std::move(serverSock),
653 EXPECT_TRUE(!client.serverNameMatch);
657 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
658 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
660 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
662 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
663 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
664 // Use the same SSLContext to continue the handshake after
665 // tlsext_hostname match.
666 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
667 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
671 getctx(clientCtx, dfServerCtx);
673 AsyncSSLSocket::UniquePtr clientSock(
674 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
675 AsyncSSLSocket::UniquePtr serverSock(
676 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
677 SNIClient client(std::move(clientSock));
678 SNIServer server(std::move(serverSock),
681 serverExpectedServerName);
685 EXPECT_TRUE(!client.serverNameMatch);
686 EXPECT_TRUE(!server.serverNameMatch);
691 * Test SSL client socket
693 TEST(AsyncSSLSocketTest, SSLClientTest) {
694 // Start listening on a local port
695 WriteCallbackBase writeCallback;
696 ReadCallback readCallback(&writeCallback);
697 HandshakeCallback handshakeCallback(&readCallback);
698 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
699 TestSSLServer server(&acceptCallback);
703 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
706 EventBaseAborter eba(&eventBase, 3000);
709 EXPECT_EQ(client->getMiss(), 1);
710 EXPECT_EQ(client->getHit(), 0);
712 cerr << "SSLClientTest test completed" << endl;
717 * Test SSL client socket session re-use
719 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
720 // Start listening on a local port
721 WriteCallbackBase writeCallback;
722 ReadCallback readCallback(&writeCallback);
723 HandshakeCallback handshakeCallback(&readCallback);
724 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
725 TestSSLServer server(&acceptCallback);
730 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
733 EventBaseAborter eba(&eventBase, 3000);
736 EXPECT_EQ(client->getMiss(), 1);
737 EXPECT_EQ(client->getHit(), 9);
739 cerr << "SSLClientTestReuse test completed" << endl;
743 * Test SSL client socket timeout
745 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
746 // Start listening on a local port
747 EmptyReadCallback readCallback;
748 HandshakeCallback handshakeCallback(&readCallback,
749 HandshakeCallback::EXPECT_ERROR);
750 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
751 TestSSLServer server(&acceptCallback);
756 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
757 client->connect(true /* write before connect completes */);
758 EventBaseAborter eba(&eventBase, 3000);
762 // This is checking that the connectError callback precedes any queued
763 // writeError callbacks. This matches AsyncSocket's behavior
764 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
765 EXPECT_EQ(client->getErrors(), 1);
766 EXPECT_EQ(client->getMiss(), 0);
767 EXPECT_EQ(client->getHit(), 0);
769 cerr << "SSLClientTimeoutTest test completed" << endl;
774 * Test SSL server async cache
776 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
777 // Start listening on a local port
778 WriteCallbackBase writeCallback;
779 ReadCallback readCallback(&writeCallback);
780 HandshakeCallback handshakeCallback(&readCallback);
781 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
782 TestSSLAsyncCacheServer server(&acceptCallback);
787 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
790 EventBaseAborter eba(&eventBase, 3000);
793 EXPECT_EQ(server.getAsyncCallbacks(), 18);
794 EXPECT_EQ(server.getAsyncLookups(), 9);
795 EXPECT_EQ(client->getMiss(), 10);
796 EXPECT_EQ(client->getHit(), 0);
798 cerr << "SSLServerAsyncCacheTest test completed" << endl;
803 * Test SSL server accept timeout with cache path
805 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
806 // Start listening on a local port
807 WriteCallbackBase writeCallback;
808 ReadCallback readCallback(&writeCallback);
809 EmptyReadCallback clientReadCallback;
810 HandshakeCallback handshakeCallback(&readCallback);
811 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
812 TestSSLAsyncCacheServer server(&acceptCallback);
816 // only do a TCP connect
817 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
818 sock->connect(nullptr, server.getAddress());
819 clientReadCallback.tcpSocket_ = sock;
820 sock->setReadCB(&clientReadCallback);
822 EventBaseAborter eba(&eventBase, 3000);
825 EXPECT_EQ(readCallback.state, STATE_WAITING);
827 cerr << "SSLServerTimeoutTest test completed" << endl;
831 * Test SSL server accept timeout with cache path
833 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
834 // Start listening on a local port
835 WriteCallbackBase writeCallback;
836 ReadCallback readCallback(&writeCallback);
837 HandshakeCallback handshakeCallback(&readCallback);
838 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
839 TestSSLAsyncCacheServer server(&acceptCallback);
843 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
846 EventBaseAborter eba(&eventBase, 3000);
849 EXPECT_EQ(server.getAsyncCallbacks(), 1);
850 EXPECT_EQ(server.getAsyncLookups(), 1);
851 EXPECT_EQ(client->getErrors(), 1);
852 EXPECT_EQ(client->getMiss(), 1);
853 EXPECT_EQ(client->getHit(), 0);
855 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
859 * Test SSL server accept timeout with cache path
861 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
862 // Start listening on a local port
863 WriteCallbackBase writeCallback;
864 ReadCallback readCallback(&writeCallback);
865 HandshakeCallback handshakeCallback(&readCallback,
866 HandshakeCallback::EXPECT_ERROR);
867 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
868 TestSSLAsyncCacheServer server(&acceptCallback, 500);
873 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
876 EventBaseAborter eba(&eventBase, 3000);
879 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
880 handshakeCallback.closeSocket();});
881 // give time for the cache lookup to come back and find it closed
882 handshakeCallback.waitForHandshake();
884 EXPECT_EQ(server.getAsyncCallbacks(), 1);
885 EXPECT_EQ(server.getAsyncLookups(), 1);
886 EXPECT_EQ(client->getErrors(), 1);
887 EXPECT_EQ(client->getMiss(), 1);
888 EXPECT_EQ(client->getHit(), 0);
890 cerr << "SSLServerCacheCloseTest test completed" << endl;
894 * Verify Client Ciphers obtained using SSL MSG Callback.
896 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
898 auto clientCtx = std::make_shared<SSLContext>();
899 auto serverCtx = std::make_shared<SSLContext>();
900 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
901 serverCtx->ciphers("RSA:!SHA:!NULL:!SHA256@STRENGTH");
902 serverCtx->loadPrivateKey(testKey);
903 serverCtx->loadCertificate(testCert);
904 serverCtx->loadTrustedCertificates(testCA);
905 serverCtx->loadClientCAList(testCA);
907 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
908 clientCtx->ciphers("RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5");
909 clientCtx->loadPrivateKey(testKey);
910 clientCtx->loadCertificate(testCert);
911 clientCtx->loadTrustedCertificates(testCA);
916 AsyncSSLSocket::UniquePtr clientSock(
917 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
918 AsyncSSLSocket::UniquePtr serverSock(
919 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
921 SSLHandshakeClient client(std::move(clientSock), true, true);
922 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
926 EXPECT_EQ(server.clientCiphers_,
927 "RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5:00ff");
928 EXPECT_TRUE(client.handshakeVerify_);
929 EXPECT_TRUE(client.handshakeSuccess_);
930 EXPECT_TRUE(!client.handshakeError_);
931 EXPECT_TRUE(server.handshakeVerify_);
932 EXPECT_TRUE(server.handshakeSuccess_);
933 EXPECT_TRUE(!server.handshakeError_);
936 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
938 auto ctx = std::make_shared<SSLContext>();
944 uint8_t majorVersion = 18;
945 uint8_t minorVersion = 25;
947 // Create callback buf
948 auto buf = IOBuf::create(bufLen);
950 folly::io::RWPrivateCursor cursor(buf.get());
951 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
952 cursor.write<uint16_t>(0);
953 cursor.write<uint8_t>(38);
954 cursor.write<uint8_t>(majorVersion);
955 cursor.write<uint8_t>(minorVersion);
957 cursor.write<uint32_t>(0);
959 SSL* ssl = ctx->createSSL();
960 SCOPE_EXIT { SSL_free(ssl); };
961 AsyncSSLSocket::UniquePtr sock(
962 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
963 sock->enableClientHelloParsing();
965 // Test client hello parsing in one packet
966 AsyncSSLSocket::clientHelloParsingCallback(
967 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
970 auto parsedClientHello = sock->getClientHelloInfo();
971 EXPECT_TRUE(parsedClientHello != nullptr);
972 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
973 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
976 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
978 auto ctx = std::make_shared<SSLContext>();
984 uint8_t majorVersion = 18;
985 uint8_t minorVersion = 25;
987 // Create callback buf
988 auto buf = IOBuf::create(bufLen);
990 folly::io::RWPrivateCursor cursor(buf.get());
991 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
992 cursor.write<uint16_t>(0);
993 cursor.write<uint8_t>(38);
994 cursor.write<uint8_t>(majorVersion);
995 cursor.write<uint8_t>(minorVersion);
997 cursor.write<uint32_t>(0);
999 SSL* ssl = ctx->createSSL();
1000 SCOPE_EXIT { SSL_free(ssl); };
1001 AsyncSSLSocket::UniquePtr sock(
1002 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1003 sock->enableClientHelloParsing();
1005 // Test parsing with two packets with first packet size < 3
1006 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1007 AsyncSSLSocket::clientHelloParsingCallback(
1008 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1011 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1012 AsyncSSLSocket::clientHelloParsingCallback(
1013 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1017 auto parsedClientHello = sock->getClientHelloInfo();
1018 EXPECT_TRUE(parsedClientHello != nullptr);
1019 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1020 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1023 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1024 EventBase eventBase;
1025 auto ctx = std::make_shared<SSLContext>();
1031 uint8_t majorVersion = 18;
1032 uint8_t minorVersion = 25;
1034 // Create callback buf
1035 auto buf = IOBuf::create(bufLen);
1036 buf->append(bufLen);
1037 folly::io::RWPrivateCursor cursor(buf.get());
1038 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1039 cursor.write<uint16_t>(0);
1040 cursor.write<uint8_t>(38);
1041 cursor.write<uint8_t>(majorVersion);
1042 cursor.write<uint8_t>(minorVersion);
1044 cursor.write<uint32_t>(0);
1046 SSL* ssl = ctx->createSSL();
1047 SCOPE_EXIT { SSL_free(ssl); };
1048 AsyncSSLSocket::UniquePtr sock(
1049 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1050 sock->enableClientHelloParsing();
1052 // Test parsing with multiple small packets
1053 for (uint64_t i = 0; i < buf->length(); i += 3) {
1054 auto bufCopy = folly::IOBuf::copyBuffer(
1055 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1056 AsyncSSLSocket::clientHelloParsingCallback(
1057 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1062 auto parsedClientHello = sock->getClientHelloInfo();
1063 EXPECT_TRUE(parsedClientHello != nullptr);
1064 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1065 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1069 * Verify sucessful behavior of SSL certificate validation.
1071 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1072 EventBase eventBase;
1073 auto clientCtx = std::make_shared<SSLContext>();
1074 auto dfServerCtx = std::make_shared<SSLContext>();
1078 getctx(clientCtx, dfServerCtx);
1080 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1081 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1083 AsyncSSLSocket::UniquePtr clientSock(
1084 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1085 AsyncSSLSocket::UniquePtr serverSock(
1086 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1088 SSLHandshakeClient client(std::move(clientSock), true, true);
1089 clientCtx->loadTrustedCertificates(testCA);
1091 SSLHandshakeServer server(std::move(serverSock), true, true);
1095 EXPECT_TRUE(client.handshakeVerify_);
1096 EXPECT_TRUE(client.handshakeSuccess_);
1097 EXPECT_TRUE(!client.handshakeError_);
1098 EXPECT_LE(0, client.handshakeTime.count());
1099 EXPECT_TRUE(!server.handshakeVerify_);
1100 EXPECT_TRUE(server.handshakeSuccess_);
1101 EXPECT_TRUE(!server.handshakeError_);
1102 EXPECT_LE(0, server.handshakeTime.count());
1106 * Verify that the client's verification callback is able to fail SSL
1107 * connection establishment.
1109 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1110 EventBase eventBase;
1111 auto clientCtx = std::make_shared<SSLContext>();
1112 auto dfServerCtx = std::make_shared<SSLContext>();
1116 getctx(clientCtx, dfServerCtx);
1118 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1119 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1121 AsyncSSLSocket::UniquePtr clientSock(
1122 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1123 AsyncSSLSocket::UniquePtr serverSock(
1124 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1126 SSLHandshakeClient client(std::move(clientSock), true, false);
1127 clientCtx->loadTrustedCertificates(testCA);
1129 SSLHandshakeServer server(std::move(serverSock), true, true);
1133 EXPECT_TRUE(client.handshakeVerify_);
1134 EXPECT_TRUE(!client.handshakeSuccess_);
1135 EXPECT_TRUE(client.handshakeError_);
1136 EXPECT_LE(0, client.handshakeTime.count());
1137 EXPECT_TRUE(!server.handshakeVerify_);
1138 EXPECT_TRUE(!server.handshakeSuccess_);
1139 EXPECT_TRUE(server.handshakeError_);
1140 EXPECT_LE(0, server.handshakeTime.count());
1144 * Verify that the options in SSLContext can be overridden in
1145 * sslConnect/Accept.i.e specifying that no validation should be performed
1146 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1147 * the validation callback.
1149 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1150 EventBase eventBase;
1151 auto clientCtx = std::make_shared<SSLContext>();
1152 auto dfServerCtx = std::make_shared<SSLContext>();
1156 getctx(clientCtx, dfServerCtx);
1158 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1159 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1161 AsyncSSLSocket::UniquePtr clientSock(
1162 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1163 AsyncSSLSocket::UniquePtr serverSock(
1164 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1166 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1167 clientCtx->loadTrustedCertificates(testCA);
1169 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1173 EXPECT_TRUE(!client.handshakeVerify_);
1174 EXPECT_TRUE(client.handshakeSuccess_);
1175 EXPECT_TRUE(!client.handshakeError_);
1176 EXPECT_LE(0, client.handshakeTime.count());
1177 EXPECT_TRUE(!server.handshakeVerify_);
1178 EXPECT_TRUE(server.handshakeSuccess_);
1179 EXPECT_TRUE(!server.handshakeError_);
1180 EXPECT_LE(0, server.handshakeTime.count());
1184 * Verify that the options in SSLContext can be overridden in
1185 * sslConnect/Accept. Enable verification even if context says otherwise.
1186 * Test requireClientCert with client cert
1188 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1189 EventBase eventBase;
1190 auto clientCtx = std::make_shared<SSLContext>();
1191 auto serverCtx = std::make_shared<SSLContext>();
1192 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1193 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1194 serverCtx->loadPrivateKey(testKey);
1195 serverCtx->loadCertificate(testCert);
1196 serverCtx->loadTrustedCertificates(testCA);
1197 serverCtx->loadClientCAList(testCA);
1199 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1200 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1201 clientCtx->loadPrivateKey(testKey);
1202 clientCtx->loadCertificate(testCert);
1203 clientCtx->loadTrustedCertificates(testCA);
1208 AsyncSSLSocket::UniquePtr clientSock(
1209 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1210 AsyncSSLSocket::UniquePtr serverSock(
1211 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1213 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1214 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1218 EXPECT_TRUE(client.handshakeVerify_);
1219 EXPECT_TRUE(client.handshakeSuccess_);
1220 EXPECT_FALSE(client.handshakeError_);
1221 EXPECT_LE(0, client.handshakeTime.count());
1222 EXPECT_TRUE(server.handshakeVerify_);
1223 EXPECT_TRUE(server.handshakeSuccess_);
1224 EXPECT_FALSE(server.handshakeError_);
1225 EXPECT_LE(0, server.handshakeTime.count());
1229 * Verify that the client's verification callback is able to override
1230 * the preverification failure and allow a successful connection.
1232 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1233 EventBase eventBase;
1234 auto clientCtx = std::make_shared<SSLContext>();
1235 auto dfServerCtx = std::make_shared<SSLContext>();
1239 getctx(clientCtx, dfServerCtx);
1241 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1242 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1244 AsyncSSLSocket::UniquePtr clientSock(
1245 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1246 AsyncSSLSocket::UniquePtr serverSock(
1247 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1249 SSLHandshakeClient client(std::move(clientSock), false, true);
1250 SSLHandshakeServer server(std::move(serverSock), true, true);
1254 EXPECT_TRUE(client.handshakeVerify_);
1255 EXPECT_TRUE(client.handshakeSuccess_);
1256 EXPECT_TRUE(!client.handshakeError_);
1257 EXPECT_LE(0, client.handshakeTime.count());
1258 EXPECT_TRUE(!server.handshakeVerify_);
1259 EXPECT_TRUE(server.handshakeSuccess_);
1260 EXPECT_TRUE(!server.handshakeError_);
1261 EXPECT_LE(0, server.handshakeTime.count());
1265 * Verify that specifying that no validation should be performed allows an
1266 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1269 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1270 EventBase eventBase;
1271 auto clientCtx = std::make_shared<SSLContext>();
1272 auto dfServerCtx = std::make_shared<SSLContext>();
1276 getctx(clientCtx, dfServerCtx);
1278 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1279 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1281 AsyncSSLSocket::UniquePtr clientSock(
1282 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1283 AsyncSSLSocket::UniquePtr serverSock(
1284 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1286 SSLHandshakeClient client(std::move(clientSock), false, false);
1287 SSLHandshakeServer server(std::move(serverSock), false, false);
1291 EXPECT_TRUE(!client.handshakeVerify_);
1292 EXPECT_TRUE(client.handshakeSuccess_);
1293 EXPECT_TRUE(!client.handshakeError_);
1294 EXPECT_LE(0, client.handshakeTime.count());
1295 EXPECT_TRUE(!server.handshakeVerify_);
1296 EXPECT_TRUE(server.handshakeSuccess_);
1297 EXPECT_TRUE(!server.handshakeError_);
1298 EXPECT_LE(0, server.handshakeTime.count());
1302 * Test requireClientCert with client cert
1304 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1305 EventBase eventBase;
1306 auto clientCtx = std::make_shared<SSLContext>();
1307 auto serverCtx = std::make_shared<SSLContext>();
1308 serverCtx->setVerificationOption(
1309 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1310 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1311 serverCtx->loadPrivateKey(testKey);
1312 serverCtx->loadCertificate(testCert);
1313 serverCtx->loadTrustedCertificates(testCA);
1314 serverCtx->loadClientCAList(testCA);
1316 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1317 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1318 clientCtx->loadPrivateKey(testKey);
1319 clientCtx->loadCertificate(testCert);
1320 clientCtx->loadTrustedCertificates(testCA);
1325 AsyncSSLSocket::UniquePtr clientSock(
1326 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1327 AsyncSSLSocket::UniquePtr serverSock(
1328 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1330 SSLHandshakeClient client(std::move(clientSock), true, true);
1331 SSLHandshakeServer server(std::move(serverSock), true, true);
1335 EXPECT_TRUE(client.handshakeVerify_);
1336 EXPECT_TRUE(client.handshakeSuccess_);
1337 EXPECT_FALSE(client.handshakeError_);
1338 EXPECT_LE(0, client.handshakeTime.count());
1339 EXPECT_TRUE(server.handshakeVerify_);
1340 EXPECT_TRUE(server.handshakeSuccess_);
1341 EXPECT_FALSE(server.handshakeError_);
1342 EXPECT_LE(0, server.handshakeTime.count());
1347 * Test requireClientCert with no client cert
1349 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1350 EventBase eventBase;
1351 auto clientCtx = std::make_shared<SSLContext>();
1352 auto serverCtx = std::make_shared<SSLContext>();
1353 serverCtx->setVerificationOption(
1354 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1355 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1356 serverCtx->loadPrivateKey(testKey);
1357 serverCtx->loadCertificate(testCert);
1358 serverCtx->loadTrustedCertificates(testCA);
1359 serverCtx->loadClientCAList(testCA);
1360 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1361 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1366 AsyncSSLSocket::UniquePtr clientSock(
1367 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1368 AsyncSSLSocket::UniquePtr serverSock(
1369 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1371 SSLHandshakeClient client(std::move(clientSock), false, false);
1372 SSLHandshakeServer server(std::move(serverSock), false, false);
1376 EXPECT_FALSE(server.handshakeVerify_);
1377 EXPECT_FALSE(server.handshakeSuccess_);
1378 EXPECT_TRUE(server.handshakeError_);
1379 EXPECT_LE(0, client.handshakeTime.count());
1380 EXPECT_LE(0, server.handshakeTime.count());
1383 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1384 auto cert = getFileAsBuf(testCert);
1385 auto key = getFileAsBuf(testKey);
1387 std::unique_ptr<BIO, BIO_deleter> certBio(BIO_new(BIO_s_mem()));
1388 BIO_write(certBio.get(), cert.data(), cert.size());
1389 std::unique_ptr<BIO, BIO_deleter> keyBio(BIO_new(BIO_s_mem()));
1390 BIO_write(keyBio.get(), key.data(), key.size());
1392 // Create SSL structs from buffers to get properties
1393 X509_UniquePtr certStruct(
1394 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1395 EVP_PKEY_UniquePtr keyStruct(
1396 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1400 auto origCommonName = getCommonName(certStruct.get());
1401 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1402 certStruct = nullptr;
1403 keyStruct = nullptr;
1405 auto ctx = std::make_shared<SSLContext>();
1406 ctx->loadPrivateKeyFromBufferPEM(key);
1407 ctx->loadCertificateFromBufferPEM(cert);
1408 ctx->loadTrustedCertificates(testCA);
1410 SSL_UniquePtr ssl(ctx->createSSL());
1412 auto newCert = SSL_get_certificate(ssl.get());
1413 auto newKey = SSL_get_privatekey(ssl.get());
1415 // Get properties from SSL struct
1416 auto newCommonName = getCommonName(newCert);
1417 auto newKeySize = EVP_PKEY_bits(newKey);
1419 // Check that the key and cert have the expected properties
1420 EXPECT_EQ(origCommonName, newCommonName);
1421 EXPECT_EQ(origKeySize, newKeySize);
1424 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1427 // Set up SSL context.
1428 auto sslContext = std::make_shared<SSLContext>();
1429 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1431 // create SSL socket
1432 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1434 EXPECT_EQ(1500, socket->getMinWriteSize());
1436 socket->setMinWriteSize(0);
1437 EXPECT_EQ(0, socket->getMinWriteSize());
1438 socket->setMinWriteSize(50000);
1439 EXPECT_EQ(50000, socket->getMinWriteSize());
1442 class ReadCallbackTerminator : public ReadCallback {
1444 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1448 // Do not write data back, terminate the loop.
1449 void readDataAvailable(size_t len) noexcept override {
1450 std::cerr << "readDataAvailable, len " << len << std::endl;
1452 currentBuffer.length = len;
1454 buffers.push_back(currentBuffer);
1455 currentBuffer.reset();
1456 state = STATE_SUCCEEDED;
1458 socket_->setReadCB(nullptr);
1459 base_->terminateLoopSoon();
1467 * Test a full unencrypted codepath
1469 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1472 auto clientCtx = std::make_shared<folly::SSLContext>();
1473 auto serverCtx = std::make_shared<folly::SSLContext>();
1476 getctx(clientCtx, serverCtx);
1477 auto client = AsyncSSLSocket::newSocket(
1478 clientCtx, &base, fds[0], false, true);
1479 auto server = AsyncSSLSocket::newSocket(
1480 serverCtx, &base, fds[1], true, true);
1482 ReadCallbackTerminator readCallback(&base, nullptr);
1483 server->setReadCB(&readCallback);
1484 readCallback.setSocket(server);
1487 memset(buf, 'a', sizeof(buf));
1488 client->write(nullptr, buf, sizeof(buf));
1490 // Check that bytes are unencrypted
1492 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1495 EventBaseAborter eba(&base, 3000);
1498 EXPECT_EQ(1, readCallback.buffers.size());
1499 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1501 server->setReadCB(&readCallback);
1504 server->sslAccept(nullptr);
1505 client->sslConn(nullptr);
1507 // Do NOT wait for handshake, writing should be queued and happen after
1509 client->write(nullptr, buf, sizeof(buf));
1511 // Check that bytes are *not* unencrypted
1513 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1519 EXPECT_EQ(2, readCallback.buffers.size());
1520 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1523 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1524 // Start listening on a local port
1525 WriteCallbackBase writeCallback;
1526 WriteErrorCallback readCallback(&writeCallback);
1527 HandshakeCallback handshakeCallback(&readCallback,
1528 HandshakeCallback::EXPECT_ERROR);
1529 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1530 TestSSLServer server(&acceptCallback);
1532 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1534 uint8_t buf[3] = {0x16, 0x03, 0x01};
1535 socket->write(buf, sizeof(buf));
1536 socket->closeWithReset();
1538 handshakeCallback.waitForHandshake();
1539 EXPECT_NE(handshakeCallback.errorString_.find("SSL_ERROR_SYSCALL"),
1541 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1544 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1545 // Start listening on a local port
1546 WriteCallbackBase writeCallback;
1547 WriteErrorCallback readCallback(&writeCallback);
1548 HandshakeCallback handshakeCallback(&readCallback,
1549 HandshakeCallback::EXPECT_ERROR);
1550 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1551 TestSSLServer server(&acceptCallback);
1553 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1555 uint8_t buf[3] = {0x16, 0x03, 0x01};
1556 socket->write(buf, sizeof(buf));
1559 handshakeCallback.waitForHandshake();
1560 EXPECT_NE(handshakeCallback.errorString_.find("SSL_ERROR_SYSCALL"),
1562 EXPECT_NE(handshakeCallback.errorString_.find("EOF"), std::string::npos);
1565 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1566 // Start listening on a local port
1567 WriteCallbackBase writeCallback;
1568 WriteErrorCallback readCallback(&writeCallback);
1569 HandshakeCallback handshakeCallback(&readCallback,
1570 HandshakeCallback::EXPECT_ERROR);
1571 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1572 TestSSLServer server(&acceptCallback);
1574 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1576 uint8_t buf[256] = {0x16, 0x03};
1577 memset(buf + 2, 'a', sizeof(buf) - 2);
1578 socket->write(buf, sizeof(buf));
1581 handshakeCallback.waitForHandshake();
1582 EXPECT_NE(handshakeCallback.errorString_.find("SSL routines"),
1584 EXPECT_NE(handshakeCallback.errorString_.find("unknown protocol"),
1590 ///////////////////////////////////////////////////////////////////////////
1591 // init_unit_test_suite
1592 ///////////////////////////////////////////////////////////////////////////
1594 struct Initializer {
1596 signal(SIGPIPE, SIG_IGN);
1599 Initializer initializer;