2 * Copyright 2017 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/SocketAddress.h>
22 #include <folly/io/async/AsyncSSLSocket.h>
23 #include <folly/io/async/EventBase.h>
24 #include <folly/portability/GMock.h>
25 #include <folly/portability/GTest.h>
26 #include <folly/portability/OpenSSL.h>
27 #include <folly/portability/Sockets.h>
28 #include <folly/portability/Unistd.h>
30 #include <folly/io/async/test/BlockingSocket.h>
33 #include <folly/io/Cursor.h>
34 #include <openssl/bio.h>
35 #include <sys/types.h>
49 using namespace testing;
52 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
53 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
54 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
56 const char* testCert = "folly/io/async/test/certs/tests-cert.pem";
57 const char* testKey = "folly/io/async/test/certs/tests-key.pem";
58 const char* testCA = "folly/io/async/test/certs/ca-cert.pem";
60 constexpr size_t SSLClient::kMaxReadBufferSz;
61 constexpr size_t SSLClient::kMaxReadsPerEvent;
63 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase* acb, bool enableTFO)
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");
77 LOG(INFO) << "server TFO enabled";
78 socket_->setTFOEnabled(true, 1000);
81 // set up the listening socket
83 socket_->getAddress(&address_);
85 socket_->addAcceptCallback(acb_, &evb_);
86 socket_->startAccepting();
88 int ret = pthread_create(&thread_, nullptr, Main, this);
92 std::cerr << "Accepting connections on " << address_ << std::endl;
95 void getfds(int fds[2]) {
96 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
97 FAIL() << "failed to create socketpair: " << strerror(errno);
99 for (int idx = 0; idx < 2; ++idx) {
100 int flags = fcntl(fds[idx], F_GETFL, 0);
102 FAIL() << "failed to get flags for socket " << idx << ": "
105 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
106 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
113 std::shared_ptr<folly::SSLContext> clientCtx,
114 std::shared_ptr<folly::SSLContext> serverCtx) {
115 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
117 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
118 serverCtx->loadCertificate(
120 serverCtx->loadPrivateKey(
125 EventBase* eventBase,
126 AsyncSSLSocket::UniquePtr* clientSock,
127 AsyncSSLSocket::UniquePtr* serverSock) {
128 auto clientCtx = std::make_shared<folly::SSLContext>();
129 auto serverCtx = std::make_shared<folly::SSLContext>();
132 getctx(clientCtx, serverCtx);
133 clientSock->reset(new AsyncSSLSocket(
134 clientCtx, eventBase, fds[0], false));
135 serverSock->reset(new AsyncSSLSocket(
136 serverCtx, eventBase, fds[1], true));
138 // (*clientSock)->setSendTimeout(100);
139 // (*serverSock)->setSendTimeout(100);
142 // client protocol filters
143 bool clientProtoFilterPickPony(unsigned char** client,
144 unsigned int* client_len, const unsigned char*, unsigned int ) {
145 //the protocol string in length prefixed byte string. the
146 //length byte is not included in the length
147 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
153 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
154 const unsigned char*, unsigned int) {
158 std::string getFileAsBuf(const char* fileName) {
160 folly::readFile(fileName, buffer);
164 std::string getCommonName(X509* cert) {
165 X509_NAME* subject = X509_get_subject_name(cert);
167 cn.resize(ub_common_name);
168 X509_NAME_get_text_by_NID(
169 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
174 * Test connecting to, writing to, reading from, and closing the
175 * connection to the SSL server.
177 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
178 // Start listening on a local port
179 WriteCallbackBase writeCallback;
180 ReadCallback readCallback(&writeCallback);
181 HandshakeCallback handshakeCallback(&readCallback);
182 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
183 TestSSLServer server(&acceptCallback);
185 // Set up SSL context.
186 std::shared_ptr<SSLContext> sslContext(new SSLContext());
187 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
188 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
189 //sslContext->authenticate(true, false);
192 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
198 memset(buf, 'a', sizeof(buf));
199 socket->write(buf, sizeof(buf));
202 uint8_t readbuf[128];
203 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
204 EXPECT_EQ(bytesRead, 128);
205 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
210 cerr << "ConnectWriteReadClose test completed" << endl;
214 * Test reading after server close.
216 TEST(AsyncSSLSocketTest, ReadAfterClose) {
217 // Start listening on a local port
218 WriteCallbackBase writeCallback;
219 ReadEOFCallback readCallback(&writeCallback);
220 HandshakeCallback handshakeCallback(&readCallback);
221 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
222 auto server = folly::make_unique<TestSSLServer>(&acceptCallback);
224 // Set up SSL context.
225 auto sslContext = std::make_shared<SSLContext>();
226 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
229 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
232 // This should trigger an EOF on the client.
233 auto evb = handshakeCallback.getSocket()->getEventBase();
234 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
235 std::array<uint8_t, 128> readbuf;
236 auto bytesRead = socket->read(readbuf.data(), readbuf.size());
237 EXPECT_EQ(0, bytesRead);
241 * Test bad renegotiation
243 #if !defined(OPENSSL_IS_BORINGSSL)
244 TEST(AsyncSSLSocketTest, Renegotiate) {
246 auto clientCtx = std::make_shared<SSLContext>();
247 auto dfServerCtx = std::make_shared<SSLContext>();
248 std::array<int, 2> fds;
250 getctx(clientCtx, dfServerCtx);
252 AsyncSSLSocket::UniquePtr clientSock(
253 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
254 AsyncSSLSocket::UniquePtr serverSock(
255 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
256 SSLHandshakeClient client(std::move(clientSock), true, true);
257 RenegotiatingServer server(std::move(serverSock));
259 while (!client.handshakeSuccess_ && !client.handshakeError_) {
260 eventBase.loopOnce();
263 ASSERT_TRUE(client.handshakeSuccess_);
265 auto sslSock = std::move(client).moveSocket();
266 sslSock->detachEventBase();
267 // This is nasty, however we don't want to add support for
268 // renegotiation in AsyncSSLSocket.
269 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
271 auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
273 std::thread t([&]() { eventBase.loopForever(); });
275 // Trigger the renegotiation.
276 std::array<uint8_t, 128> buf;
277 memset(buf.data(), 'a', buf.size());
279 socket->write(buf.data(), buf.size());
280 } catch (AsyncSocketException& e) {
281 LOG(INFO) << "client got error " << e.what();
283 eventBase.terminateLoopSoon();
287 ASSERT_TRUE(server.renegotiationError_);
292 * Negative test for handshakeError().
294 TEST(AsyncSSLSocketTest, HandshakeError) {
295 // Start listening on a local port
296 WriteCallbackBase writeCallback;
297 WriteErrorCallback readCallback(&writeCallback);
298 HandshakeCallback handshakeCallback(&readCallback);
299 HandshakeErrorCallback acceptCallback(&handshakeCallback);
300 TestSSLServer server(&acceptCallback);
302 // Set up SSL context.
303 std::shared_ptr<SSLContext> sslContext(new SSLContext());
304 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
307 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
314 uint8_t readbuf[128];
315 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
316 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
317 } catch (AsyncSocketException&) {
324 cerr << "HandshakeError test completed" << endl;
328 * Negative test for readError().
330 TEST(AsyncSSLSocketTest, ReadError) {
331 // Start listening on a local port
332 WriteCallbackBase writeCallback;
333 ReadErrorCallback readCallback(&writeCallback);
334 HandshakeCallback handshakeCallback(&readCallback);
335 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
336 TestSSLServer server(&acceptCallback);
338 // Set up SSL context.
339 std::shared_ptr<SSLContext> sslContext(new SSLContext());
340 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
343 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
347 // write something to trigger ssl handshake
349 memset(buf, 'a', sizeof(buf));
350 socket->write(buf, sizeof(buf));
353 cerr << "ReadError test completed" << endl;
357 * Negative test for writeError().
359 TEST(AsyncSSLSocketTest, WriteError) {
360 // Start listening on a local port
361 WriteCallbackBase writeCallback;
362 WriteErrorCallback readCallback(&writeCallback);
363 HandshakeCallback handshakeCallback(&readCallback);
364 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
365 TestSSLServer server(&acceptCallback);
367 // Set up SSL context.
368 std::shared_ptr<SSLContext> sslContext(new SSLContext());
369 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
372 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
376 // write something to trigger ssl handshake
378 memset(buf, 'a', sizeof(buf));
379 socket->write(buf, sizeof(buf));
382 cerr << "WriteError test completed" << endl;
386 * Test a socket with TCP_NODELAY unset.
388 TEST(AsyncSSLSocketTest, SocketWithDelay) {
389 // Start listening on a local port
390 WriteCallbackBase writeCallback;
391 ReadCallback readCallback(&writeCallback);
392 HandshakeCallback handshakeCallback(&readCallback);
393 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
394 TestSSLServer server(&acceptCallback);
396 // Set up SSL context.
397 std::shared_ptr<SSLContext> sslContext(new SSLContext());
398 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
401 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
407 memset(buf, 'a', sizeof(buf));
408 socket->write(buf, sizeof(buf));
411 uint8_t readbuf[128];
412 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
413 EXPECT_EQ(bytesRead, 128);
414 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
419 cerr << "SocketWithDelay test completed" << endl;
422 using NextProtocolTypePair =
423 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
425 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
426 // For matching protos
428 void SetUp() override { getctx(clientCtx, serverCtx); }
430 void connect(bool unset = false) {
434 // unsetting NPN for any of [client, server] is enough to make NPN not
436 clientCtx->unsetNextProtocols();
439 AsyncSSLSocket::UniquePtr clientSock(
440 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
441 AsyncSSLSocket::UniquePtr serverSock(
442 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
443 client = folly::make_unique<NpnClient>(std::move(clientSock));
444 server = folly::make_unique<NpnServer>(std::move(serverSock));
449 void expectProtocol(const std::string& proto) {
450 EXPECT_NE(client->nextProtoLength, 0);
451 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
453 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
455 string selected((const char*)client->nextProto, client->nextProtoLength);
456 EXPECT_EQ(proto, selected);
459 void expectNoProtocol() {
460 EXPECT_EQ(client->nextProtoLength, 0);
461 EXPECT_EQ(server->nextProtoLength, 0);
462 EXPECT_EQ(client->nextProto, nullptr);
463 EXPECT_EQ(server->nextProto, nullptr);
466 void expectProtocolType() {
467 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
468 GetParam().second == SSLContext::NextProtocolType::ANY) {
469 EXPECT_EQ(client->protocolType, server->protocolType);
470 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
471 GetParam().second == SSLContext::NextProtocolType::ANY) {
472 // Well not much we can say
474 expectProtocolType(GetParam());
478 void expectProtocolType(NextProtocolTypePair expected) {
479 EXPECT_EQ(client->protocolType, expected.first);
480 EXPECT_EQ(server->protocolType, expected.second);
484 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
485 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
487 std::unique_ptr<NpnClient> client;
488 std::unique_ptr<NpnServer> server;
491 class NextProtocolTLSExtTest : public NextProtocolTest {
492 // For extended TLS protos
495 class NextProtocolNPNOnlyTest : public NextProtocolTest {
496 // For mismatching protos
499 class NextProtocolMismatchTest : public NextProtocolTest {
500 // For mismatching protos
503 TEST_P(NextProtocolTest, NpnTestOverlap) {
504 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
505 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
510 expectProtocol("baz");
511 expectProtocolType();
514 TEST_P(NextProtocolTest, NpnTestUnset) {
515 // Identical to above test, except that we want unset NPN before
517 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
518 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
521 connect(true /* unset */);
523 // if alpn negotiation fails, type will appear as npn
525 EXPECT_EQ(client->protocolType, server->protocolType);
528 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
529 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
530 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
537 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
540 // Note: the behavior changed in the ANY/ANY case in OpenSSL 1.0.2h, this test
541 // will fail on 1.0.2 before that.
542 TEST_P(NextProtocolTest, NpnTestNoOverlap) {
543 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
544 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
549 if (GetParam().first == SSLContext::NextProtocolType::ALPN ||
550 GetParam().second == SSLContext::NextProtocolType::ALPN) {
551 // This is arguably incorrect behavior since RFC7301 states an ALPN protocol
552 // mismatch should result in a fatal alert, but this is OpenSSL's current
553 // behavior and we want to know if it changes.
556 #if defined(OPENSSL_IS_BORINGSSL)
557 // BoringSSL also doesn't fatal on mismatch but behaves slightly differently
558 // from OpenSSL 1.0.2h+ - it doesn't select a protocol if both ends support
561 GetParam().first == SSLContext::NextProtocolType::ANY &&
562 GetParam().second == SSLContext::NextProtocolType::ANY) {
567 expectProtocol("blub");
569 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
573 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
574 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
575 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
576 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
581 expectProtocol("ponies");
582 expectProtocolType();
585 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
586 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
587 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
588 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
593 expectProtocol("blub");
594 expectProtocolType();
597 TEST_P(NextProtocolTest, RandomizedNpnTest) {
598 // Probability that this test will fail is 2^-64, which could be considered
600 const int kTries = 64;
602 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
604 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
607 std::set<string> selectedProtocols;
608 for (int i = 0; i < kTries; ++i) {
611 EXPECT_NE(client->nextProtoLength, 0);
612 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
614 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
616 string selected((const char*)client->nextProto, client->nextProtoLength);
617 selectedProtocols.insert(selected);
618 expectProtocolType();
620 EXPECT_EQ(selectedProtocols.size(), 2);
623 INSTANTIATE_TEST_CASE_P(
627 NextProtocolTypePair(
628 SSLContext::NextProtocolType::NPN,
629 SSLContext::NextProtocolType::NPN),
630 NextProtocolTypePair(
631 SSLContext::NextProtocolType::NPN,
632 SSLContext::NextProtocolType::ANY),
633 NextProtocolTypePair(
634 SSLContext::NextProtocolType::ANY,
635 SSLContext::NextProtocolType::ANY)));
637 #if FOLLY_OPENSSL_HAS_ALPN
638 INSTANTIATE_TEST_CASE_P(
640 NextProtocolTLSExtTest,
642 NextProtocolTypePair(
643 SSLContext::NextProtocolType::ALPN,
644 SSLContext::NextProtocolType::ALPN),
645 NextProtocolTypePair(
646 SSLContext::NextProtocolType::ALPN,
647 SSLContext::NextProtocolType::ANY),
648 NextProtocolTypePair(
649 SSLContext::NextProtocolType::ANY,
650 SSLContext::NextProtocolType::ALPN)));
653 INSTANTIATE_TEST_CASE_P(
655 NextProtocolNPNOnlyTest,
656 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
657 SSLContext::NextProtocolType::NPN)));
659 #if FOLLY_OPENSSL_HAS_ALPN
660 INSTANTIATE_TEST_CASE_P(
662 NextProtocolMismatchTest,
663 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
664 SSLContext::NextProtocolType::ALPN),
665 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
666 SSLContext::NextProtocolType::NPN)));
669 #ifndef OPENSSL_NO_TLSEXT
671 * 1. Client sends TLSEXT_HOSTNAME in client hello.
672 * 2. Server found a match SSL_CTX and use this SSL_CTX to
673 * continue the SSL handshake.
674 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
676 TEST(AsyncSSLSocketTest, SNITestMatch) {
678 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
679 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
680 // Use the same SSLContext to continue the handshake after
681 // tlsext_hostname match.
682 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
683 const std::string serverName("xyz.newdev.facebook.com");
686 getctx(clientCtx, dfServerCtx);
688 AsyncSSLSocket::UniquePtr clientSock(
689 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
690 AsyncSSLSocket::UniquePtr serverSock(
691 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
692 SNIClient client(std::move(clientSock));
693 SNIServer server(std::move(serverSock),
700 EXPECT_TRUE(client.serverNameMatch);
701 EXPECT_TRUE(server.serverNameMatch);
705 * 1. Client sends TLSEXT_HOSTNAME in client hello.
706 * 2. Server cannot find a matching SSL_CTX and continue to use
707 * the current SSL_CTX to do the handshake.
708 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
710 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
712 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
713 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
714 // Use the same SSLContext to continue the handshake after
715 // tlsext_hostname match.
716 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
717 const std::string clientRequestingServerName("foo.com");
718 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
722 getctx(clientCtx, dfServerCtx);
724 AsyncSSLSocket::UniquePtr clientSock(
725 new AsyncSSLSocket(clientCtx,
728 clientRequestingServerName));
729 AsyncSSLSocket::UniquePtr serverSock(
730 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
731 SNIClient client(std::move(clientSock));
732 SNIServer server(std::move(serverSock),
735 serverExpectedServerName);
739 EXPECT_TRUE(!client.serverNameMatch);
740 EXPECT_TRUE(!server.serverNameMatch);
743 * 1. Client sends TLSEXT_HOSTNAME in client hello.
744 * 2. We then change the serverName.
745 * 3. We expect that we get 'false' as the result for serNameMatch.
748 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
750 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
751 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
752 // Use the same SSLContext to continue the handshake after
753 // tlsext_hostname match.
754 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
755 const std::string serverName("xyz.newdev.facebook.com");
758 getctx(clientCtx, dfServerCtx);
760 AsyncSSLSocket::UniquePtr clientSock(
761 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
762 //Change the server name
763 std::string newName("new.com");
764 clientSock->setServerName(newName);
765 AsyncSSLSocket::UniquePtr serverSock(
766 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
767 SNIClient client(std::move(clientSock));
768 SNIServer server(std::move(serverSock),
775 EXPECT_TRUE(!client.serverNameMatch);
779 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
780 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
782 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
784 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
785 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
786 // Use the same SSLContext to continue the handshake after
787 // tlsext_hostname match.
788 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
789 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
793 getctx(clientCtx, dfServerCtx);
795 AsyncSSLSocket::UniquePtr clientSock(
796 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
797 AsyncSSLSocket::UniquePtr serverSock(
798 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
799 SNIClient client(std::move(clientSock));
800 SNIServer server(std::move(serverSock),
803 serverExpectedServerName);
807 EXPECT_TRUE(!client.serverNameMatch);
808 EXPECT_TRUE(!server.serverNameMatch);
813 * Test SSL client socket
815 TEST(AsyncSSLSocketTest, SSLClientTest) {
816 // Start listening on a local port
817 WriteCallbackBase writeCallback;
818 ReadCallback readCallback(&writeCallback);
819 HandshakeCallback handshakeCallback(&readCallback);
820 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
821 TestSSLServer server(&acceptCallback);
825 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
828 EventBaseAborter eba(&eventBase, 3000);
831 EXPECT_EQ(client->getMiss(), 1);
832 EXPECT_EQ(client->getHit(), 0);
834 cerr << "SSLClientTest test completed" << endl;
839 * Test SSL client socket session re-use
841 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
842 // Start listening on a local port
843 WriteCallbackBase writeCallback;
844 ReadCallback readCallback(&writeCallback);
845 HandshakeCallback handshakeCallback(&readCallback);
846 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
847 TestSSLServer server(&acceptCallback);
852 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
855 EventBaseAborter eba(&eventBase, 3000);
858 EXPECT_EQ(client->getMiss(), 1);
859 EXPECT_EQ(client->getHit(), 9);
861 cerr << "SSLClientTestReuse test completed" << endl;
865 * Test SSL client socket timeout
867 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
868 // Start listening on a local port
869 EmptyReadCallback readCallback;
870 HandshakeCallback handshakeCallback(&readCallback,
871 HandshakeCallback::EXPECT_ERROR);
872 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
873 TestSSLServer server(&acceptCallback);
878 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
879 client->connect(true /* write before connect completes */);
880 EventBaseAborter eba(&eventBase, 3000);
884 // This is checking that the connectError callback precedes any queued
885 // writeError callbacks. This matches AsyncSocket's behavior
886 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
887 EXPECT_EQ(client->getErrors(), 1);
888 EXPECT_EQ(client->getMiss(), 0);
889 EXPECT_EQ(client->getHit(), 0);
891 cerr << "SSLClientTimeoutTest test completed" << endl;
894 // The next 3 tests need an FB-only extension, and will fail without it
895 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
897 * Test SSL server async cache
899 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
900 // Start listening on a local port
901 WriteCallbackBase writeCallback;
902 ReadCallback readCallback(&writeCallback);
903 HandshakeCallback handshakeCallback(&readCallback);
904 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
905 TestSSLAsyncCacheServer server(&acceptCallback);
910 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
913 EventBaseAborter eba(&eventBase, 3000);
916 EXPECT_EQ(server.getAsyncCallbacks(), 18);
917 EXPECT_EQ(server.getAsyncLookups(), 9);
918 EXPECT_EQ(client->getMiss(), 10);
919 EXPECT_EQ(client->getHit(), 0);
921 cerr << "SSLServerAsyncCacheTest test completed" << endl;
925 * Test SSL server accept timeout with cache path
927 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
928 // Start listening on a local port
929 WriteCallbackBase writeCallback;
930 ReadCallback readCallback(&writeCallback);
931 HandshakeCallback handshakeCallback(&readCallback);
932 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
933 TestSSLAsyncCacheServer server(&acceptCallback);
937 // only do a TCP connect
938 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
939 sock->connect(nullptr, server.getAddress());
941 EmptyReadCallback clientReadCallback;
942 clientReadCallback.tcpSocket_ = sock;
943 sock->setReadCB(&clientReadCallback);
945 EventBaseAborter eba(&eventBase, 3000);
948 EXPECT_EQ(readCallback.state, STATE_WAITING);
950 cerr << "SSLServerTimeoutTest test completed" << endl;
954 * Test SSL server accept timeout with cache path
956 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
957 // Start listening on a local port
958 WriteCallbackBase writeCallback;
959 ReadCallback readCallback(&writeCallback);
960 HandshakeCallback handshakeCallback(&readCallback);
961 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
962 TestSSLAsyncCacheServer server(&acceptCallback);
966 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
969 EventBaseAborter eba(&eventBase, 3000);
972 EXPECT_EQ(server.getAsyncCallbacks(), 1);
973 EXPECT_EQ(server.getAsyncLookups(), 1);
974 EXPECT_EQ(client->getErrors(), 1);
975 EXPECT_EQ(client->getMiss(), 1);
976 EXPECT_EQ(client->getHit(), 0);
978 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
982 * Test SSL server accept timeout with cache path
984 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
985 // Start listening on a local port
986 WriteCallbackBase writeCallback;
987 ReadCallback readCallback(&writeCallback);
988 HandshakeCallback handshakeCallback(&readCallback,
989 HandshakeCallback::EXPECT_ERROR);
990 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
991 TestSSLAsyncCacheServer server(&acceptCallback, 500);
996 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
999 EventBaseAborter eba(&eventBase, 3000);
1002 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
1003 handshakeCallback.closeSocket();});
1004 // give time for the cache lookup to come back and find it closed
1005 handshakeCallback.waitForHandshake();
1007 EXPECT_EQ(server.getAsyncCallbacks(), 1);
1008 EXPECT_EQ(server.getAsyncLookups(), 1);
1009 EXPECT_EQ(client->getErrors(), 1);
1010 EXPECT_EQ(client->getMiss(), 1);
1011 EXPECT_EQ(client->getHit(), 0);
1013 cerr << "SSLServerCacheCloseTest test completed" << endl;
1015 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP
1018 * Verify Client Ciphers obtained using SSL MSG Callback.
1020 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
1021 EventBase eventBase;
1022 auto clientCtx = std::make_shared<SSLContext>();
1023 auto serverCtx = std::make_shared<SSLContext>();
1024 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1025 serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
1026 serverCtx->loadPrivateKey(testKey);
1027 serverCtx->loadCertificate(testCert);
1028 serverCtx->loadTrustedCertificates(testCA);
1029 serverCtx->loadClientCAList(testCA);
1031 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1032 clientCtx->ciphers("AES256-SHA:AES128-SHA");
1033 clientCtx->loadPrivateKey(testKey);
1034 clientCtx->loadCertificate(testCert);
1035 clientCtx->loadTrustedCertificates(testCA);
1040 AsyncSSLSocket::UniquePtr clientSock(
1041 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1042 AsyncSSLSocket::UniquePtr serverSock(
1043 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1045 SSLHandshakeClient client(std::move(clientSock), true, true);
1046 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
1050 #if defined(OPENSSL_IS_BORINGSSL)
1051 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
1053 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
1055 EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
1056 EXPECT_TRUE(client.handshakeVerify_);
1057 EXPECT_TRUE(client.handshakeSuccess_);
1058 EXPECT_TRUE(!client.handshakeError_);
1059 EXPECT_TRUE(server.handshakeVerify_);
1060 EXPECT_TRUE(server.handshakeSuccess_);
1061 EXPECT_TRUE(!server.handshakeError_);
1064 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1065 EventBase eventBase;
1066 auto ctx = std::make_shared<SSLContext>();
1072 uint8_t majorVersion = 18;
1073 uint8_t minorVersion = 25;
1075 // Create callback buf
1076 auto buf = IOBuf::create(bufLen);
1077 buf->append(bufLen);
1078 folly::io::RWPrivateCursor cursor(buf.get());
1079 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1080 cursor.write<uint16_t>(0);
1081 cursor.write<uint8_t>(38);
1082 cursor.write<uint8_t>(majorVersion);
1083 cursor.write<uint8_t>(minorVersion);
1085 cursor.write<uint32_t>(0);
1087 SSL* ssl = ctx->createSSL();
1088 SCOPE_EXIT { SSL_free(ssl); };
1089 AsyncSSLSocket::UniquePtr sock(
1090 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1091 sock->enableClientHelloParsing();
1093 // Test client hello parsing in one packet
1094 AsyncSSLSocket::clientHelloParsingCallback(
1095 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1098 auto parsedClientHello = sock->getClientHelloInfo();
1099 EXPECT_TRUE(parsedClientHello != nullptr);
1100 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1101 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1104 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1105 EventBase eventBase;
1106 auto ctx = std::make_shared<SSLContext>();
1112 uint8_t majorVersion = 18;
1113 uint8_t minorVersion = 25;
1115 // Create callback buf
1116 auto buf = IOBuf::create(bufLen);
1117 buf->append(bufLen);
1118 folly::io::RWPrivateCursor cursor(buf.get());
1119 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1120 cursor.write<uint16_t>(0);
1121 cursor.write<uint8_t>(38);
1122 cursor.write<uint8_t>(majorVersion);
1123 cursor.write<uint8_t>(minorVersion);
1125 cursor.write<uint32_t>(0);
1127 SSL* ssl = ctx->createSSL();
1128 SCOPE_EXIT { SSL_free(ssl); };
1129 AsyncSSLSocket::UniquePtr sock(
1130 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1131 sock->enableClientHelloParsing();
1133 // Test parsing with two packets with first packet size < 3
1134 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1135 AsyncSSLSocket::clientHelloParsingCallback(
1136 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1139 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1140 AsyncSSLSocket::clientHelloParsingCallback(
1141 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1145 auto parsedClientHello = sock->getClientHelloInfo();
1146 EXPECT_TRUE(parsedClientHello != nullptr);
1147 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1148 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1151 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1152 EventBase eventBase;
1153 auto ctx = std::make_shared<SSLContext>();
1159 uint8_t majorVersion = 18;
1160 uint8_t minorVersion = 25;
1162 // Create callback buf
1163 auto buf = IOBuf::create(bufLen);
1164 buf->append(bufLen);
1165 folly::io::RWPrivateCursor cursor(buf.get());
1166 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1167 cursor.write<uint16_t>(0);
1168 cursor.write<uint8_t>(38);
1169 cursor.write<uint8_t>(majorVersion);
1170 cursor.write<uint8_t>(minorVersion);
1172 cursor.write<uint32_t>(0);
1174 SSL* ssl = ctx->createSSL();
1175 SCOPE_EXIT { SSL_free(ssl); };
1176 AsyncSSLSocket::UniquePtr sock(
1177 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1178 sock->enableClientHelloParsing();
1180 // Test parsing with multiple small packets
1181 for (uint64_t i = 0; i < buf->length(); i += 3) {
1182 auto bufCopy = folly::IOBuf::copyBuffer(
1183 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1184 AsyncSSLSocket::clientHelloParsingCallback(
1185 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1190 auto parsedClientHello = sock->getClientHelloInfo();
1191 EXPECT_TRUE(parsedClientHello != nullptr);
1192 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1193 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1197 * Verify sucessful behavior of SSL certificate validation.
1199 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1200 EventBase eventBase;
1201 auto clientCtx = std::make_shared<SSLContext>();
1202 auto dfServerCtx = std::make_shared<SSLContext>();
1206 getctx(clientCtx, dfServerCtx);
1208 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1209 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1211 AsyncSSLSocket::UniquePtr clientSock(
1212 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1213 AsyncSSLSocket::UniquePtr serverSock(
1214 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1216 SSLHandshakeClient client(std::move(clientSock), true, true);
1217 clientCtx->loadTrustedCertificates(testCA);
1219 SSLHandshakeServer server(std::move(serverSock), true, true);
1223 EXPECT_TRUE(client.handshakeVerify_);
1224 EXPECT_TRUE(client.handshakeSuccess_);
1225 EXPECT_TRUE(!client.handshakeError_);
1226 EXPECT_LE(0, client.handshakeTime.count());
1227 EXPECT_TRUE(!server.handshakeVerify_);
1228 EXPECT_TRUE(server.handshakeSuccess_);
1229 EXPECT_TRUE(!server.handshakeError_);
1230 EXPECT_LE(0, server.handshakeTime.count());
1234 * Verify that the client's verification callback is able to fail SSL
1235 * connection establishment.
1237 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1238 EventBase eventBase;
1239 auto clientCtx = std::make_shared<SSLContext>();
1240 auto dfServerCtx = std::make_shared<SSLContext>();
1244 getctx(clientCtx, dfServerCtx);
1246 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1247 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1249 AsyncSSLSocket::UniquePtr clientSock(
1250 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1251 AsyncSSLSocket::UniquePtr serverSock(
1252 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1254 SSLHandshakeClient client(std::move(clientSock), true, false);
1255 clientCtx->loadTrustedCertificates(testCA);
1257 SSLHandshakeServer server(std::move(serverSock), true, true);
1261 EXPECT_TRUE(client.handshakeVerify_);
1262 EXPECT_TRUE(!client.handshakeSuccess_);
1263 EXPECT_TRUE(client.handshakeError_);
1264 EXPECT_LE(0, client.handshakeTime.count());
1265 EXPECT_TRUE(!server.handshakeVerify_);
1266 EXPECT_TRUE(!server.handshakeSuccess_);
1267 EXPECT_TRUE(server.handshakeError_);
1268 EXPECT_LE(0, server.handshakeTime.count());
1272 * Verify that the options in SSLContext can be overridden in
1273 * sslConnect/Accept.i.e specifying that no validation should be performed
1274 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1275 * the validation callback.
1277 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1278 EventBase eventBase;
1279 auto clientCtx = std::make_shared<SSLContext>();
1280 auto dfServerCtx = std::make_shared<SSLContext>();
1284 getctx(clientCtx, dfServerCtx);
1286 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1287 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1289 AsyncSSLSocket::UniquePtr clientSock(
1290 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1291 AsyncSSLSocket::UniquePtr serverSock(
1292 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1294 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1295 clientCtx->loadTrustedCertificates(testCA);
1297 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1301 EXPECT_TRUE(!client.handshakeVerify_);
1302 EXPECT_TRUE(client.handshakeSuccess_);
1303 EXPECT_TRUE(!client.handshakeError_);
1304 EXPECT_LE(0, client.handshakeTime.count());
1305 EXPECT_TRUE(!server.handshakeVerify_);
1306 EXPECT_TRUE(server.handshakeSuccess_);
1307 EXPECT_TRUE(!server.handshakeError_);
1308 EXPECT_LE(0, server.handshakeTime.count());
1312 * Verify that the options in SSLContext can be overridden in
1313 * sslConnect/Accept. Enable verification even if context says otherwise.
1314 * Test requireClientCert with client cert
1316 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1317 EventBase eventBase;
1318 auto clientCtx = std::make_shared<SSLContext>();
1319 auto serverCtx = std::make_shared<SSLContext>();
1320 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1321 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1322 serverCtx->loadPrivateKey(testKey);
1323 serverCtx->loadCertificate(testCert);
1324 serverCtx->loadTrustedCertificates(testCA);
1325 serverCtx->loadClientCAList(testCA);
1327 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1328 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1329 clientCtx->loadPrivateKey(testKey);
1330 clientCtx->loadCertificate(testCert);
1331 clientCtx->loadTrustedCertificates(testCA);
1336 AsyncSSLSocket::UniquePtr clientSock(
1337 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1338 AsyncSSLSocket::UniquePtr serverSock(
1339 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1341 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1342 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1346 EXPECT_TRUE(client.handshakeVerify_);
1347 EXPECT_TRUE(client.handshakeSuccess_);
1348 EXPECT_FALSE(client.handshakeError_);
1349 EXPECT_LE(0, client.handshakeTime.count());
1350 EXPECT_TRUE(server.handshakeVerify_);
1351 EXPECT_TRUE(server.handshakeSuccess_);
1352 EXPECT_FALSE(server.handshakeError_);
1353 EXPECT_LE(0, server.handshakeTime.count());
1357 * Verify that the client's verification callback is able to override
1358 * the preverification failure and allow a successful connection.
1360 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1361 EventBase eventBase;
1362 auto clientCtx = std::make_shared<SSLContext>();
1363 auto dfServerCtx = std::make_shared<SSLContext>();
1367 getctx(clientCtx, dfServerCtx);
1369 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1370 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1372 AsyncSSLSocket::UniquePtr clientSock(
1373 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1374 AsyncSSLSocket::UniquePtr serverSock(
1375 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1377 SSLHandshakeClient client(std::move(clientSock), false, true);
1378 SSLHandshakeServer server(std::move(serverSock), true, true);
1382 EXPECT_TRUE(client.handshakeVerify_);
1383 EXPECT_TRUE(client.handshakeSuccess_);
1384 EXPECT_TRUE(!client.handshakeError_);
1385 EXPECT_LE(0, client.handshakeTime.count());
1386 EXPECT_TRUE(!server.handshakeVerify_);
1387 EXPECT_TRUE(server.handshakeSuccess_);
1388 EXPECT_TRUE(!server.handshakeError_);
1389 EXPECT_LE(0, server.handshakeTime.count());
1393 * Verify that specifying that no validation should be performed allows an
1394 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1397 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1398 EventBase eventBase;
1399 auto clientCtx = std::make_shared<SSLContext>();
1400 auto dfServerCtx = std::make_shared<SSLContext>();
1404 getctx(clientCtx, dfServerCtx);
1406 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1407 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1409 AsyncSSLSocket::UniquePtr clientSock(
1410 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1411 AsyncSSLSocket::UniquePtr serverSock(
1412 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1414 SSLHandshakeClient client(std::move(clientSock), false, false);
1415 SSLHandshakeServer server(std::move(serverSock), false, false);
1419 EXPECT_TRUE(!client.handshakeVerify_);
1420 EXPECT_TRUE(client.handshakeSuccess_);
1421 EXPECT_TRUE(!client.handshakeError_);
1422 EXPECT_LE(0, client.handshakeTime.count());
1423 EXPECT_TRUE(!server.handshakeVerify_);
1424 EXPECT_TRUE(server.handshakeSuccess_);
1425 EXPECT_TRUE(!server.handshakeError_);
1426 EXPECT_LE(0, server.handshakeTime.count());
1430 * Test requireClientCert with client cert
1432 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1433 EventBase eventBase;
1434 auto clientCtx = std::make_shared<SSLContext>();
1435 auto serverCtx = std::make_shared<SSLContext>();
1436 serverCtx->setVerificationOption(
1437 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1438 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1439 serverCtx->loadPrivateKey(testKey);
1440 serverCtx->loadCertificate(testCert);
1441 serverCtx->loadTrustedCertificates(testCA);
1442 serverCtx->loadClientCAList(testCA);
1444 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1445 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1446 clientCtx->loadPrivateKey(testKey);
1447 clientCtx->loadCertificate(testCert);
1448 clientCtx->loadTrustedCertificates(testCA);
1453 AsyncSSLSocket::UniquePtr clientSock(
1454 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1455 AsyncSSLSocket::UniquePtr serverSock(
1456 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1458 SSLHandshakeClient client(std::move(clientSock), true, true);
1459 SSLHandshakeServer server(std::move(serverSock), true, true);
1463 EXPECT_TRUE(client.handshakeVerify_);
1464 EXPECT_TRUE(client.handshakeSuccess_);
1465 EXPECT_FALSE(client.handshakeError_);
1466 EXPECT_LE(0, client.handshakeTime.count());
1467 EXPECT_TRUE(server.handshakeVerify_);
1468 EXPECT_TRUE(server.handshakeSuccess_);
1469 EXPECT_FALSE(server.handshakeError_);
1470 EXPECT_LE(0, server.handshakeTime.count());
1475 * Test requireClientCert with no client cert
1477 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1478 EventBase eventBase;
1479 auto clientCtx = std::make_shared<SSLContext>();
1480 auto serverCtx = std::make_shared<SSLContext>();
1481 serverCtx->setVerificationOption(
1482 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1483 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1484 serverCtx->loadPrivateKey(testKey);
1485 serverCtx->loadCertificate(testCert);
1486 serverCtx->loadTrustedCertificates(testCA);
1487 serverCtx->loadClientCAList(testCA);
1488 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1489 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1494 AsyncSSLSocket::UniquePtr clientSock(
1495 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1496 AsyncSSLSocket::UniquePtr serverSock(
1497 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1499 SSLHandshakeClient client(std::move(clientSock), false, false);
1500 SSLHandshakeServer server(std::move(serverSock), false, false);
1504 EXPECT_FALSE(server.handshakeVerify_);
1505 EXPECT_FALSE(server.handshakeSuccess_);
1506 EXPECT_TRUE(server.handshakeError_);
1507 EXPECT_LE(0, client.handshakeTime.count());
1508 EXPECT_LE(0, server.handshakeTime.count());
1511 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1512 auto cert = getFileAsBuf(testCert);
1513 auto key = getFileAsBuf(testKey);
1515 ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1516 BIO_write(certBio.get(), cert.data(), cert.size());
1517 ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1518 BIO_write(keyBio.get(), key.data(), key.size());
1520 // Create SSL structs from buffers to get properties
1521 ssl::X509UniquePtr certStruct(
1522 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1523 ssl::EvpPkeyUniquePtr keyStruct(
1524 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1528 auto origCommonName = getCommonName(certStruct.get());
1529 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1530 certStruct = nullptr;
1531 keyStruct = nullptr;
1533 auto ctx = std::make_shared<SSLContext>();
1534 ctx->loadPrivateKeyFromBufferPEM(key);
1535 ctx->loadCertificateFromBufferPEM(cert);
1536 ctx->loadTrustedCertificates(testCA);
1538 ssl::SSLUniquePtr ssl(ctx->createSSL());
1540 auto newCert = SSL_get_certificate(ssl.get());
1541 auto newKey = SSL_get_privatekey(ssl.get());
1543 // Get properties from SSL struct
1544 auto newCommonName = getCommonName(newCert);
1545 auto newKeySize = EVP_PKEY_bits(newKey);
1547 // Check that the key and cert have the expected properties
1548 EXPECT_EQ(origCommonName, newCommonName);
1549 EXPECT_EQ(origKeySize, newKeySize);
1552 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1555 // Set up SSL context.
1556 auto sslContext = std::make_shared<SSLContext>();
1557 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1559 // create SSL socket
1560 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1562 EXPECT_EQ(1500, socket->getMinWriteSize());
1564 socket->setMinWriteSize(0);
1565 EXPECT_EQ(0, socket->getMinWriteSize());
1566 socket->setMinWriteSize(50000);
1567 EXPECT_EQ(50000, socket->getMinWriteSize());
1570 class ReadCallbackTerminator : public ReadCallback {
1572 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1576 // Do not write data back, terminate the loop.
1577 void readDataAvailable(size_t len) noexcept override {
1578 std::cerr << "readDataAvailable, len " << len << std::endl;
1580 currentBuffer.length = len;
1582 buffers.push_back(currentBuffer);
1583 currentBuffer.reset();
1584 state = STATE_SUCCEEDED;
1586 socket_->setReadCB(nullptr);
1587 base_->terminateLoopSoon();
1595 * Test a full unencrypted codepath
1597 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1600 auto clientCtx = std::make_shared<folly::SSLContext>();
1601 auto serverCtx = std::make_shared<folly::SSLContext>();
1604 getctx(clientCtx, serverCtx);
1605 auto client = AsyncSSLSocket::newSocket(
1606 clientCtx, &base, fds[0], false, true);
1607 auto server = AsyncSSLSocket::newSocket(
1608 serverCtx, &base, fds[1], true, true);
1610 ReadCallbackTerminator readCallback(&base, nullptr);
1611 server->setReadCB(&readCallback);
1612 readCallback.setSocket(server);
1615 memset(buf, 'a', sizeof(buf));
1616 client->write(nullptr, buf, sizeof(buf));
1618 // Check that bytes are unencrypted
1620 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1623 EventBaseAborter eba(&base, 3000);
1626 EXPECT_EQ(1, readCallback.buffers.size());
1627 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1629 server->setReadCB(&readCallback);
1632 server->sslAccept(nullptr);
1633 client->sslConn(nullptr);
1635 // Do NOT wait for handshake, writing should be queued and happen after
1637 client->write(nullptr, buf, sizeof(buf));
1639 // Check that bytes are *not* unencrypted
1641 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1647 EXPECT_EQ(2, readCallback.buffers.size());
1648 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1651 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1652 // Start listening on a local port
1653 WriteCallbackBase writeCallback;
1654 WriteErrorCallback readCallback(&writeCallback);
1655 HandshakeCallback handshakeCallback(&readCallback,
1656 HandshakeCallback::EXPECT_ERROR);
1657 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1658 TestSSLServer server(&acceptCallback);
1660 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1662 uint8_t buf[3] = {0x16, 0x03, 0x01};
1663 socket->write(buf, sizeof(buf));
1664 socket->closeWithReset();
1666 handshakeCallback.waitForHandshake();
1668 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1669 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1672 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1673 // Start listening on a local port
1674 WriteCallbackBase writeCallback;
1675 WriteErrorCallback readCallback(&writeCallback);
1676 HandshakeCallback handshakeCallback(&readCallback,
1677 HandshakeCallback::EXPECT_ERROR);
1678 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1679 TestSSLServer server(&acceptCallback);
1681 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1683 uint8_t buf[3] = {0x16, 0x03, 0x01};
1684 socket->write(buf, sizeof(buf));
1687 handshakeCallback.waitForHandshake();
1689 handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
1690 EXPECT_NE(handshakeCallback.errorString_.find("EOF"), std::string::npos);
1693 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1694 // Start listening on a local port
1695 WriteCallbackBase writeCallback;
1696 WriteErrorCallback readCallback(&writeCallback);
1697 HandshakeCallback handshakeCallback(&readCallback,
1698 HandshakeCallback::EXPECT_ERROR);
1699 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1700 TestSSLServer server(&acceptCallback);
1702 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1704 uint8_t buf[256] = {0x16, 0x03};
1705 memset(buf + 2, 'a', sizeof(buf) - 2);
1706 socket->write(buf, sizeof(buf));
1709 handshakeCallback.waitForHandshake();
1710 EXPECT_NE(handshakeCallback.errorString_.find("SSL routines"),
1712 #if defined(OPENSSL_IS_BORINGSSL)
1714 handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
1717 EXPECT_NE(handshakeCallback.errorString_.find("unknown protocol"),
1722 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
1723 using folly::ssl::OpenSSLUtils;
1725 OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384");
1726 // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this
1727 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), "");
1728 // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected
1729 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), "");
1734 class MockAsyncTFOSSLSocket : public AsyncSSLSocket {
1736 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
1738 explicit MockAsyncTFOSSLSocket(
1739 std::shared_ptr<folly::SSLContext> sslCtx,
1741 : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {}
1743 MOCK_METHOD3(tfoSendMsg, ssize_t(int fd, struct msghdr* msg, int msg_flags));
1747 * Test connecting to, writing to, reading from, and closing the
1748 * connection to the SSL server with TFO.
1750 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
1751 // Start listening on a local port
1752 WriteCallbackBase writeCallback;
1753 ReadCallback readCallback(&writeCallback);
1754 HandshakeCallback handshakeCallback(&readCallback);
1755 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1756 TestSSLServer server(&acceptCallback, true);
1758 // Set up SSL context.
1759 auto sslContext = std::make_shared<SSLContext>();
1763 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1764 socket->enableTFO();
1768 std::array<uint8_t, 128> buf;
1769 memset(buf.data(), 'a', buf.size());
1770 socket->write(buf.data(), buf.size());
1773 std::array<uint8_t, 128> readbuf;
1774 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1775 EXPECT_EQ(bytesRead, 128);
1776 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1783 * Test connecting to, writing to, reading from, and closing the
1784 * connection to the SSL server with TFO.
1786 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
1787 // Start listening on a local port
1788 WriteCallbackBase writeCallback;
1789 ReadCallback readCallback(&writeCallback);
1790 HandshakeCallback handshakeCallback(&readCallback);
1791 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1792 TestSSLServer server(&acceptCallback, false);
1794 // Set up SSL context.
1795 auto sslContext = std::make_shared<SSLContext>();
1799 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1800 socket->enableTFO();
1804 std::array<uint8_t, 128> buf;
1805 memset(buf.data(), 'a', buf.size());
1806 socket->write(buf.data(), buf.size());
1809 std::array<uint8_t, 128> readbuf;
1810 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1811 EXPECT_EQ(bytesRead, 128);
1812 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1818 class ConnCallback : public AsyncSocket::ConnectCallback {
1820 virtual void connectSuccess() noexcept override {
1821 state = State::SUCCESS;
1824 virtual void connectErr(const AsyncSocketException& ex) noexcept override {
1825 state = State::ERROR;
1829 enum class State { WAITING, SUCCESS, ERROR };
1831 State state{State::WAITING};
1835 template <class Cardinality>
1836 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
1838 const SocketAddress& address,
1839 Cardinality cardinality) {
1840 // Set up SSL context.
1841 auto sslContext = std::make_shared<SSLContext>();
1844 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
1845 new MockAsyncTFOSSLSocket(sslContext, evb));
1846 socket->enableTFO();
1848 EXPECT_CALL(*socket, tfoSendMsg(_, _, _))
1850 .WillOnce(Invoke([&](int fd, struct msghdr*, int) {
1851 sockaddr_storage addr;
1852 auto len = address.getAddress(&addr);
1853 return connect(fd, (const struct sockaddr*)&addr, len);
1858 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
1859 // Start listening on a local port
1860 WriteCallbackBase writeCallback;
1861 ReadCallback readCallback(&writeCallback);
1862 HandshakeCallback handshakeCallback(&readCallback);
1863 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1864 TestSSLServer server(&acceptCallback, true);
1868 auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1);
1870 socket->connect(&ccb, server.getAddress(), 30);
1873 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
1875 evb.runInEventBaseThread([&] { socket->detachEventBase(); });
1878 BlockingSocket sock(std::move(socket));
1880 std::array<uint8_t, 128> buf;
1881 memset(buf.data(), 'a', buf.size());
1882 sock.write(buf.data(), buf.size());
1885 std::array<uint8_t, 128> readbuf;
1886 uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size());
1887 EXPECT_EQ(bytesRead, 128);
1888 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1894 #if !defined(OPENSSL_IS_BORINGSSL)
1895 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
1896 // Start listening on a local port
1897 ConnectTimeoutCallback acceptCallback;
1898 TestSSLServer server(&acceptCallback, true);
1900 // Set up SSL context.
1901 auto sslContext = std::make_shared<SSLContext>();
1905 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1906 socket->enableTFO();
1908 socket->open(std::chrono::milliseconds(20)), AsyncSocketException);
1912 #if !defined(OPENSSL_IS_BORINGSSL)
1913 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
1914 // Start listening on a local port
1915 ConnectTimeoutCallback acceptCallback;
1916 TestSSLServer server(&acceptCallback, true);
1920 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1922 // Set a short timeout
1923 socket->connect(&ccb, server.getAddress(), 1);
1926 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1930 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
1931 // Start listening on a local port
1932 EmptyReadCallback readCallback;
1933 HandshakeCallback handshakeCallback(
1934 &readCallback, HandshakeCallback::EXPECT_ERROR);
1935 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
1936 TestSSLServer server(&acceptCallback, true);
1940 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1942 socket->connect(&ccb, server.getAddress(), 100);
1945 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1946 EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out"));
1949 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
1950 // Start listening on a local port
1953 // Hopefully nothing is listening on this address
1954 SocketAddress addr("127.0.0.1", 65535);
1955 auto socket = setupSocketWithFallback(&evb, addr, AtMost(1));
1957 socket->connect(&ccb, addr, 100);
1960 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1961 EXPECT_THAT(ccb.error, testing::HasSubstr("refused"));
1969 ///////////////////////////////////////////////////////////////////////////
1970 // init_unit_test_suite
1971 ///////////////////////////////////////////////////////////////////////////
1973 struct Initializer {
1975 signal(SIGPIPE, SIG_IGN);
1978 Initializer initializer;