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>
20 #include <folly/SocketAddress.h>
21 #include <folly/io/async/AsyncSSLSocket.h>
22 #include <folly/io/async/EventBase.h>
23 #include <folly/portability/GMock.h>
24 #include <folly/portability/GTest.h>
25 #include <folly/portability/OpenSSL.h>
26 #include <folly/portability/Sockets.h>
27 #include <folly/portability/Unistd.h>
29 #include <folly/io/async/test/BlockingSocket.h>
32 #include <folly/io/Cursor.h>
33 #include <openssl/bio.h>
34 #include <sys/types.h>
48 using namespace testing;
51 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
52 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
53 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
55 constexpr size_t SSLClient::kMaxReadBufferSz;
56 constexpr size_t SSLClient::kMaxReadsPerEvent;
58 void getfds(int fds[2]) {
59 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
60 FAIL() << "failed to create socketpair: " << strerror(errno);
62 for (int idx = 0; idx < 2; ++idx) {
63 int flags = fcntl(fds[idx], F_GETFL, 0);
65 FAIL() << "failed to get flags for socket " << idx << ": "
68 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
69 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
76 std::shared_ptr<folly::SSLContext> clientCtx,
77 std::shared_ptr<folly::SSLContext> serverCtx) {
78 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
80 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
81 serverCtx->loadCertificate(kTestCert);
82 serverCtx->loadPrivateKey(kTestKey);
87 AsyncSSLSocket::UniquePtr* clientSock,
88 AsyncSSLSocket::UniquePtr* serverSock) {
89 auto clientCtx = std::make_shared<folly::SSLContext>();
90 auto serverCtx = std::make_shared<folly::SSLContext>();
93 getctx(clientCtx, serverCtx);
94 clientSock->reset(new AsyncSSLSocket(
95 clientCtx, eventBase, fds[0], false));
96 serverSock->reset(new AsyncSSLSocket(
97 serverCtx, eventBase, fds[1], true));
99 // (*clientSock)->setSendTimeout(100);
100 // (*serverSock)->setSendTimeout(100);
103 // client protocol filters
104 bool clientProtoFilterPickPony(unsigned char** client,
105 unsigned int* client_len, const unsigned char*, unsigned int ) {
106 //the protocol string in length prefixed byte string. the
107 //length byte is not included in the length
108 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
114 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
115 const unsigned char*, unsigned int) {
119 std::string getFileAsBuf(const char* fileName) {
121 folly::readFile(fileName, buffer);
125 std::string getCommonName(X509* cert) {
126 X509_NAME* subject = X509_get_subject_name(cert);
128 cn.resize(ub_common_name);
129 X509_NAME_get_text_by_NID(
130 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
135 * Test connecting to, writing to, reading from, and closing the
136 * connection to the SSL server.
138 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
139 // Start listening on a local port
140 WriteCallbackBase writeCallback;
141 ReadCallback readCallback(&writeCallback);
142 HandshakeCallback handshakeCallback(&readCallback);
143 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
144 TestSSLServer server(&acceptCallback);
146 // Set up SSL context.
147 std::shared_ptr<SSLContext> sslContext(new SSLContext());
148 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
149 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
150 //sslContext->authenticate(true, false);
153 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
159 memset(buf, 'a', sizeof(buf));
160 socket->write(buf, sizeof(buf));
163 uint8_t readbuf[128];
164 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
165 EXPECT_EQ(bytesRead, 128);
166 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
171 cerr << "ConnectWriteReadClose test completed" << endl;
175 * Test reading after server close.
177 TEST(AsyncSSLSocketTest, ReadAfterClose) {
178 // Start listening on a local port
179 WriteCallbackBase writeCallback;
180 ReadEOFCallback readCallback(&writeCallback);
181 HandshakeCallback handshakeCallback(&readCallback);
182 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
183 auto server = folly::make_unique<TestSSLServer>(&acceptCallback);
185 // Set up SSL context.
186 auto sslContext = std::make_shared<SSLContext>();
187 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
190 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
193 // This should trigger an EOF on the client.
194 auto evb = handshakeCallback.getSocket()->getEventBase();
195 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
196 std::array<uint8_t, 128> readbuf;
197 auto bytesRead = socket->read(readbuf.data(), readbuf.size());
198 EXPECT_EQ(0, bytesRead);
202 * Test bad renegotiation
204 #if !defined(OPENSSL_IS_BORINGSSL)
205 TEST(AsyncSSLSocketTest, Renegotiate) {
207 auto clientCtx = std::make_shared<SSLContext>();
208 auto dfServerCtx = std::make_shared<SSLContext>();
209 std::array<int, 2> fds;
211 getctx(clientCtx, dfServerCtx);
213 AsyncSSLSocket::UniquePtr clientSock(
214 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
215 AsyncSSLSocket::UniquePtr serverSock(
216 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
217 SSLHandshakeClient client(std::move(clientSock), true, true);
218 RenegotiatingServer server(std::move(serverSock));
220 while (!client.handshakeSuccess_ && !client.handshakeError_) {
221 eventBase.loopOnce();
224 ASSERT_TRUE(client.handshakeSuccess_);
226 auto sslSock = std::move(client).moveSocket();
227 sslSock->detachEventBase();
228 // This is nasty, however we don't want to add support for
229 // renegotiation in AsyncSSLSocket.
230 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
232 auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
234 std::thread t([&]() { eventBase.loopForever(); });
236 // Trigger the renegotiation.
237 std::array<uint8_t, 128> buf;
238 memset(buf.data(), 'a', buf.size());
240 socket->write(buf.data(), buf.size());
241 } catch (AsyncSocketException& e) {
242 LOG(INFO) << "client got error " << e.what();
244 eventBase.terminateLoopSoon();
248 ASSERT_TRUE(server.renegotiationError_);
253 * Negative test for handshakeError().
255 TEST(AsyncSSLSocketTest, HandshakeError) {
256 // Start listening on a local port
257 WriteCallbackBase writeCallback;
258 WriteErrorCallback readCallback(&writeCallback);
259 HandshakeCallback handshakeCallback(&readCallback);
260 HandshakeErrorCallback acceptCallback(&handshakeCallback);
261 TestSSLServer server(&acceptCallback);
263 // Set up SSL context.
264 std::shared_ptr<SSLContext> sslContext(new SSLContext());
265 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
268 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
275 uint8_t readbuf[128];
276 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
277 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
278 } catch (AsyncSocketException&) {
285 cerr << "HandshakeError test completed" << endl;
289 * Negative test for readError().
291 TEST(AsyncSSLSocketTest, ReadError) {
292 // Start listening on a local port
293 WriteCallbackBase writeCallback;
294 ReadErrorCallback readCallback(&writeCallback);
295 HandshakeCallback handshakeCallback(&readCallback);
296 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
297 TestSSLServer server(&acceptCallback);
299 // Set up SSL context.
300 std::shared_ptr<SSLContext> sslContext(new SSLContext());
301 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
304 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
308 // write something to trigger ssl handshake
310 memset(buf, 'a', sizeof(buf));
311 socket->write(buf, sizeof(buf));
314 cerr << "ReadError test completed" << endl;
318 * Negative test for writeError().
320 TEST(AsyncSSLSocketTest, WriteError) {
321 // Start listening on a local port
322 WriteCallbackBase writeCallback;
323 WriteErrorCallback readCallback(&writeCallback);
324 HandshakeCallback handshakeCallback(&readCallback);
325 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
326 TestSSLServer server(&acceptCallback);
328 // Set up SSL context.
329 std::shared_ptr<SSLContext> sslContext(new SSLContext());
330 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
333 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
337 // write something to trigger ssl handshake
339 memset(buf, 'a', sizeof(buf));
340 socket->write(buf, sizeof(buf));
343 cerr << "WriteError test completed" << endl;
347 * Test a socket with TCP_NODELAY unset.
349 TEST(AsyncSSLSocketTest, SocketWithDelay) {
350 // Start listening on a local port
351 WriteCallbackBase writeCallback;
352 ReadCallback readCallback(&writeCallback);
353 HandshakeCallback handshakeCallback(&readCallback);
354 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
355 TestSSLServer server(&acceptCallback);
357 // Set up SSL context.
358 std::shared_ptr<SSLContext> sslContext(new SSLContext());
359 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
362 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
368 memset(buf, 'a', sizeof(buf));
369 socket->write(buf, sizeof(buf));
372 uint8_t readbuf[128];
373 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
374 EXPECT_EQ(bytesRead, 128);
375 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
380 cerr << "SocketWithDelay test completed" << endl;
383 using NextProtocolTypePair =
384 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
386 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
387 // For matching protos
389 void SetUp() override { getctx(clientCtx, serverCtx); }
391 void connect(bool unset = false) {
395 // unsetting NPN for any of [client, server] is enough to make NPN not
397 clientCtx->unsetNextProtocols();
400 AsyncSSLSocket::UniquePtr clientSock(
401 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
402 AsyncSSLSocket::UniquePtr serverSock(
403 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
404 client = folly::make_unique<NpnClient>(std::move(clientSock));
405 server = folly::make_unique<NpnServer>(std::move(serverSock));
410 void expectProtocol(const std::string& proto) {
411 EXPECT_NE(client->nextProtoLength, 0);
412 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
414 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
416 string selected((const char*)client->nextProto, client->nextProtoLength);
417 EXPECT_EQ(proto, selected);
420 void expectNoProtocol() {
421 EXPECT_EQ(client->nextProtoLength, 0);
422 EXPECT_EQ(server->nextProtoLength, 0);
423 EXPECT_EQ(client->nextProto, nullptr);
424 EXPECT_EQ(server->nextProto, nullptr);
427 void expectProtocolType() {
428 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
429 GetParam().second == SSLContext::NextProtocolType::ANY) {
430 EXPECT_EQ(client->protocolType, server->protocolType);
431 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
432 GetParam().second == SSLContext::NextProtocolType::ANY) {
433 // Well not much we can say
435 expectProtocolType(GetParam());
439 void expectProtocolType(NextProtocolTypePair expected) {
440 EXPECT_EQ(client->protocolType, expected.first);
441 EXPECT_EQ(server->protocolType, expected.second);
445 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
446 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
448 std::unique_ptr<NpnClient> client;
449 std::unique_ptr<NpnServer> server;
452 class NextProtocolTLSExtTest : public NextProtocolTest {
453 // For extended TLS protos
456 class NextProtocolNPNOnlyTest : public NextProtocolTest {
457 // For mismatching protos
460 class NextProtocolMismatchTest : public NextProtocolTest {
461 // For mismatching protos
464 TEST_P(NextProtocolTest, NpnTestOverlap) {
465 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
466 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
471 expectProtocol("baz");
472 expectProtocolType();
475 TEST_P(NextProtocolTest, NpnTestUnset) {
476 // Identical to above test, except that we want unset NPN before
478 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
479 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
482 connect(true /* unset */);
484 // if alpn negotiation fails, type will appear as npn
486 EXPECT_EQ(client->protocolType, server->protocolType);
489 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
490 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
491 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
498 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
501 // Note: the behavior changed in the ANY/ANY case in OpenSSL 1.0.2h, this test
502 // will fail on 1.0.2 before that.
503 TEST_P(NextProtocolTest, NpnTestNoOverlap) {
504 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
505 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
510 if (GetParam().first == SSLContext::NextProtocolType::ALPN ||
511 GetParam().second == SSLContext::NextProtocolType::ALPN) {
512 // This is arguably incorrect behavior since RFC7301 states an ALPN protocol
513 // mismatch should result in a fatal alert, but this is OpenSSL's current
514 // behavior and we want to know if it changes.
517 #if defined(OPENSSL_IS_BORINGSSL)
518 // BoringSSL also doesn't fatal on mismatch but behaves slightly differently
519 // from OpenSSL 1.0.2h+ - it doesn't select a protocol if both ends support
522 GetParam().first == SSLContext::NextProtocolType::ANY &&
523 GetParam().second == SSLContext::NextProtocolType::ANY) {
528 expectProtocol("blub");
530 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
534 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
535 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
536 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
537 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
542 expectProtocol("ponies");
543 expectProtocolType();
546 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
547 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
548 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
549 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
554 expectProtocol("blub");
555 expectProtocolType();
558 TEST_P(NextProtocolTest, RandomizedNpnTest) {
559 // Probability that this test will fail is 2^-64, which could be considered
561 const int kTries = 64;
563 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
565 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
568 std::set<string> selectedProtocols;
569 for (int i = 0; i < kTries; ++i) {
572 EXPECT_NE(client->nextProtoLength, 0);
573 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
575 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
577 string selected((const char*)client->nextProto, client->nextProtoLength);
578 selectedProtocols.insert(selected);
579 expectProtocolType();
581 EXPECT_EQ(selectedProtocols.size(), 2);
584 INSTANTIATE_TEST_CASE_P(
588 NextProtocolTypePair(
589 SSLContext::NextProtocolType::NPN,
590 SSLContext::NextProtocolType::NPN),
591 NextProtocolTypePair(
592 SSLContext::NextProtocolType::NPN,
593 SSLContext::NextProtocolType::ANY),
594 NextProtocolTypePair(
595 SSLContext::NextProtocolType::ANY,
596 SSLContext::NextProtocolType::ANY)));
598 #if FOLLY_OPENSSL_HAS_ALPN
599 INSTANTIATE_TEST_CASE_P(
601 NextProtocolTLSExtTest,
603 NextProtocolTypePair(
604 SSLContext::NextProtocolType::ALPN,
605 SSLContext::NextProtocolType::ALPN),
606 NextProtocolTypePair(
607 SSLContext::NextProtocolType::ALPN,
608 SSLContext::NextProtocolType::ANY),
609 NextProtocolTypePair(
610 SSLContext::NextProtocolType::ANY,
611 SSLContext::NextProtocolType::ALPN)));
614 INSTANTIATE_TEST_CASE_P(
616 NextProtocolNPNOnlyTest,
617 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
618 SSLContext::NextProtocolType::NPN)));
620 #if FOLLY_OPENSSL_HAS_ALPN
621 INSTANTIATE_TEST_CASE_P(
623 NextProtocolMismatchTest,
624 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
625 SSLContext::NextProtocolType::ALPN),
626 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
627 SSLContext::NextProtocolType::NPN)));
630 #ifndef OPENSSL_NO_TLSEXT
632 * 1. Client sends TLSEXT_HOSTNAME in client hello.
633 * 2. Server found a match SSL_CTX and use this SSL_CTX to
634 * continue the SSL handshake.
635 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
637 TEST(AsyncSSLSocketTest, SNITestMatch) {
639 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
640 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
641 // Use the same SSLContext to continue the handshake after
642 // tlsext_hostname match.
643 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
644 const std::string serverName("xyz.newdev.facebook.com");
647 getctx(clientCtx, dfServerCtx);
649 AsyncSSLSocket::UniquePtr clientSock(
650 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
651 AsyncSSLSocket::UniquePtr serverSock(
652 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
653 SNIClient client(std::move(clientSock));
654 SNIServer server(std::move(serverSock),
661 EXPECT_TRUE(client.serverNameMatch);
662 EXPECT_TRUE(server.serverNameMatch);
666 * 1. Client sends TLSEXT_HOSTNAME in client hello.
667 * 2. Server cannot find a matching SSL_CTX and continue to use
668 * the current SSL_CTX to do the handshake.
669 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
671 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
673 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
674 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
675 // Use the same SSLContext to continue the handshake after
676 // tlsext_hostname match.
677 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
678 const std::string clientRequestingServerName("foo.com");
679 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
683 getctx(clientCtx, dfServerCtx);
685 AsyncSSLSocket::UniquePtr clientSock(
686 new AsyncSSLSocket(clientCtx,
689 clientRequestingServerName));
690 AsyncSSLSocket::UniquePtr serverSock(
691 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
692 SNIClient client(std::move(clientSock));
693 SNIServer server(std::move(serverSock),
696 serverExpectedServerName);
700 EXPECT_TRUE(!client.serverNameMatch);
701 EXPECT_TRUE(!server.serverNameMatch);
704 * 1. Client sends TLSEXT_HOSTNAME in client hello.
705 * 2. We then change the serverName.
706 * 3. We expect that we get 'false' as the result for serNameMatch.
709 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
711 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
712 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
713 // Use the same SSLContext to continue the handshake after
714 // tlsext_hostname match.
715 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
716 const std::string serverName("xyz.newdev.facebook.com");
719 getctx(clientCtx, dfServerCtx);
721 AsyncSSLSocket::UniquePtr clientSock(
722 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
723 //Change the server name
724 std::string newName("new.com");
725 clientSock->setServerName(newName);
726 AsyncSSLSocket::UniquePtr serverSock(
727 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
728 SNIClient client(std::move(clientSock));
729 SNIServer server(std::move(serverSock),
736 EXPECT_TRUE(!client.serverNameMatch);
740 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
741 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
743 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
745 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
746 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
747 // Use the same SSLContext to continue the handshake after
748 // tlsext_hostname match.
749 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
750 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
754 getctx(clientCtx, dfServerCtx);
756 AsyncSSLSocket::UniquePtr clientSock(
757 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
758 AsyncSSLSocket::UniquePtr serverSock(
759 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
760 SNIClient client(std::move(clientSock));
761 SNIServer server(std::move(serverSock),
764 serverExpectedServerName);
768 EXPECT_TRUE(!client.serverNameMatch);
769 EXPECT_TRUE(!server.serverNameMatch);
774 * Test SSL client socket
776 TEST(AsyncSSLSocketTest, SSLClientTest) {
777 // Start listening on a local port
778 WriteCallbackBase writeCallback;
779 ReadCallback readCallback(&writeCallback);
780 HandshakeCallback handshakeCallback(&readCallback);
781 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
782 TestSSLServer server(&acceptCallback);
786 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
789 EventBaseAborter eba(&eventBase, 3000);
792 EXPECT_EQ(client->getMiss(), 1);
793 EXPECT_EQ(client->getHit(), 0);
795 cerr << "SSLClientTest test completed" << endl;
800 * Test SSL client socket session re-use
802 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
803 // Start listening on a local port
804 WriteCallbackBase writeCallback;
805 ReadCallback readCallback(&writeCallback);
806 HandshakeCallback handshakeCallback(&readCallback);
807 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
808 TestSSLServer server(&acceptCallback);
813 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
816 EventBaseAborter eba(&eventBase, 3000);
819 EXPECT_EQ(client->getMiss(), 1);
820 EXPECT_EQ(client->getHit(), 9);
822 cerr << "SSLClientTestReuse test completed" << endl;
826 * Test SSL client socket timeout
828 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
829 // Start listening on a local port
830 EmptyReadCallback readCallback;
831 HandshakeCallback handshakeCallback(&readCallback,
832 HandshakeCallback::EXPECT_ERROR);
833 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
834 TestSSLServer server(&acceptCallback);
839 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
840 client->connect(true /* write before connect completes */);
841 EventBaseAborter eba(&eventBase, 3000);
845 // This is checking that the connectError callback precedes any queued
846 // writeError callbacks. This matches AsyncSocket's behavior
847 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
848 EXPECT_EQ(client->getErrors(), 1);
849 EXPECT_EQ(client->getMiss(), 0);
850 EXPECT_EQ(client->getHit(), 0);
852 cerr << "SSLClientTimeoutTest test completed" << endl;
855 // The next 3 tests need an FB-only extension, and will fail without it
856 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
858 * Test SSL server async cache
860 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
861 // Start listening on a local port
862 WriteCallbackBase writeCallback;
863 ReadCallback readCallback(&writeCallback);
864 HandshakeCallback handshakeCallback(&readCallback);
865 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
866 TestSSLAsyncCacheServer server(&acceptCallback);
871 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
874 EventBaseAborter eba(&eventBase, 3000);
877 EXPECT_EQ(server.getAsyncCallbacks(), 18);
878 EXPECT_EQ(server.getAsyncLookups(), 9);
879 EXPECT_EQ(client->getMiss(), 10);
880 EXPECT_EQ(client->getHit(), 0);
882 cerr << "SSLServerAsyncCacheTest test completed" << endl;
886 * Test SSL server accept timeout with cache path
888 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
889 // Start listening on a local port
890 WriteCallbackBase writeCallback;
891 ReadCallback readCallback(&writeCallback);
892 HandshakeCallback handshakeCallback(&readCallback);
893 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
894 TestSSLAsyncCacheServer server(&acceptCallback);
898 // only do a TCP connect
899 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
900 sock->connect(nullptr, server.getAddress());
902 EmptyReadCallback clientReadCallback;
903 clientReadCallback.tcpSocket_ = sock;
904 sock->setReadCB(&clientReadCallback);
906 EventBaseAborter eba(&eventBase, 3000);
909 EXPECT_EQ(readCallback.state, STATE_WAITING);
911 cerr << "SSLServerTimeoutTest test completed" << endl;
915 * Test SSL server accept timeout with cache path
917 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
918 // Start listening on a local port
919 WriteCallbackBase writeCallback;
920 ReadCallback readCallback(&writeCallback);
921 HandshakeCallback handshakeCallback(&readCallback);
922 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
923 TestSSLAsyncCacheServer server(&acceptCallback);
927 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
930 EventBaseAborter eba(&eventBase, 3000);
933 EXPECT_EQ(server.getAsyncCallbacks(), 1);
934 EXPECT_EQ(server.getAsyncLookups(), 1);
935 EXPECT_EQ(client->getErrors(), 1);
936 EXPECT_EQ(client->getMiss(), 1);
937 EXPECT_EQ(client->getHit(), 0);
939 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
943 * Test SSL server accept timeout with cache path
945 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
946 // Start listening on a local port
947 WriteCallbackBase writeCallback;
948 ReadCallback readCallback(&writeCallback);
949 HandshakeCallback handshakeCallback(&readCallback,
950 HandshakeCallback::EXPECT_ERROR);
951 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
952 TestSSLAsyncCacheServer server(&acceptCallback, 500);
957 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
960 EventBaseAborter eba(&eventBase, 3000);
963 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
964 handshakeCallback.closeSocket();});
965 // give time for the cache lookup to come back and find it closed
966 handshakeCallback.waitForHandshake();
968 EXPECT_EQ(server.getAsyncCallbacks(), 1);
969 EXPECT_EQ(server.getAsyncLookups(), 1);
970 EXPECT_EQ(client->getErrors(), 1);
971 EXPECT_EQ(client->getMiss(), 1);
972 EXPECT_EQ(client->getHit(), 0);
974 cerr << "SSLServerCacheCloseTest test completed" << endl;
976 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP
979 * Verify Client Ciphers obtained using SSL MSG Callback.
981 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
983 auto clientCtx = std::make_shared<SSLContext>();
984 auto serverCtx = std::make_shared<SSLContext>();
985 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
986 serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
987 serverCtx->loadPrivateKey(kTestKey);
988 serverCtx->loadCertificate(kTestCert);
989 serverCtx->loadTrustedCertificates(kTestCA);
990 serverCtx->loadClientCAList(kTestCA);
992 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
993 clientCtx->ciphers("AES256-SHA:AES128-SHA");
994 clientCtx->loadPrivateKey(kTestKey);
995 clientCtx->loadCertificate(kTestCert);
996 clientCtx->loadTrustedCertificates(kTestCA);
1001 AsyncSSLSocket::UniquePtr clientSock(
1002 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1003 AsyncSSLSocket::UniquePtr serverSock(
1004 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1006 SSLHandshakeClient client(std::move(clientSock), true, true);
1007 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
1011 #if defined(OPENSSL_IS_BORINGSSL)
1012 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
1014 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
1016 EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
1017 EXPECT_TRUE(client.handshakeVerify_);
1018 EXPECT_TRUE(client.handshakeSuccess_);
1019 EXPECT_TRUE(!client.handshakeError_);
1020 EXPECT_TRUE(server.handshakeVerify_);
1021 EXPECT_TRUE(server.handshakeSuccess_);
1022 EXPECT_TRUE(!server.handshakeError_);
1025 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1026 EventBase eventBase;
1027 auto ctx = std::make_shared<SSLContext>();
1033 uint8_t majorVersion = 18;
1034 uint8_t minorVersion = 25;
1036 // Create callback buf
1037 auto buf = IOBuf::create(bufLen);
1038 buf->append(bufLen);
1039 folly::io::RWPrivateCursor cursor(buf.get());
1040 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1041 cursor.write<uint16_t>(0);
1042 cursor.write<uint8_t>(38);
1043 cursor.write<uint8_t>(majorVersion);
1044 cursor.write<uint8_t>(minorVersion);
1046 cursor.write<uint32_t>(0);
1048 SSL* ssl = ctx->createSSL();
1049 SCOPE_EXIT { SSL_free(ssl); };
1050 AsyncSSLSocket::UniquePtr sock(
1051 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1052 sock->enableClientHelloParsing();
1054 // Test client hello parsing in one packet
1055 AsyncSSLSocket::clientHelloParsingCallback(
1056 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1059 auto parsedClientHello = sock->getClientHelloInfo();
1060 EXPECT_TRUE(parsedClientHello != nullptr);
1061 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1062 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1065 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1066 EventBase eventBase;
1067 auto ctx = std::make_shared<SSLContext>();
1073 uint8_t majorVersion = 18;
1074 uint8_t minorVersion = 25;
1076 // Create callback buf
1077 auto buf = IOBuf::create(bufLen);
1078 buf->append(bufLen);
1079 folly::io::RWPrivateCursor cursor(buf.get());
1080 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1081 cursor.write<uint16_t>(0);
1082 cursor.write<uint8_t>(38);
1083 cursor.write<uint8_t>(majorVersion);
1084 cursor.write<uint8_t>(minorVersion);
1086 cursor.write<uint32_t>(0);
1088 SSL* ssl = ctx->createSSL();
1089 SCOPE_EXIT { SSL_free(ssl); };
1090 AsyncSSLSocket::UniquePtr sock(
1091 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1092 sock->enableClientHelloParsing();
1094 // Test parsing with two packets with first packet size < 3
1095 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1096 AsyncSSLSocket::clientHelloParsingCallback(
1097 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1100 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1101 AsyncSSLSocket::clientHelloParsingCallback(
1102 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1106 auto parsedClientHello = sock->getClientHelloInfo();
1107 EXPECT_TRUE(parsedClientHello != nullptr);
1108 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1109 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1112 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1113 EventBase eventBase;
1114 auto ctx = std::make_shared<SSLContext>();
1120 uint8_t majorVersion = 18;
1121 uint8_t minorVersion = 25;
1123 // Create callback buf
1124 auto buf = IOBuf::create(bufLen);
1125 buf->append(bufLen);
1126 folly::io::RWPrivateCursor cursor(buf.get());
1127 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1128 cursor.write<uint16_t>(0);
1129 cursor.write<uint8_t>(38);
1130 cursor.write<uint8_t>(majorVersion);
1131 cursor.write<uint8_t>(minorVersion);
1133 cursor.write<uint32_t>(0);
1135 SSL* ssl = ctx->createSSL();
1136 SCOPE_EXIT { SSL_free(ssl); };
1137 AsyncSSLSocket::UniquePtr sock(
1138 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1139 sock->enableClientHelloParsing();
1141 // Test parsing with multiple small packets
1142 for (uint64_t i = 0; i < buf->length(); i += 3) {
1143 auto bufCopy = folly::IOBuf::copyBuffer(
1144 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1145 AsyncSSLSocket::clientHelloParsingCallback(
1146 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1151 auto parsedClientHello = sock->getClientHelloInfo();
1152 EXPECT_TRUE(parsedClientHello != nullptr);
1153 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1154 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1158 * Verify sucessful behavior of SSL certificate validation.
1160 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1161 EventBase eventBase;
1162 auto clientCtx = std::make_shared<SSLContext>();
1163 auto dfServerCtx = std::make_shared<SSLContext>();
1167 getctx(clientCtx, dfServerCtx);
1169 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1170 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1172 AsyncSSLSocket::UniquePtr clientSock(
1173 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1174 AsyncSSLSocket::UniquePtr serverSock(
1175 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1177 SSLHandshakeClient client(std::move(clientSock), true, true);
1178 clientCtx->loadTrustedCertificates(kTestCA);
1180 SSLHandshakeServer server(std::move(serverSock), true, true);
1184 EXPECT_TRUE(client.handshakeVerify_);
1185 EXPECT_TRUE(client.handshakeSuccess_);
1186 EXPECT_TRUE(!client.handshakeError_);
1187 EXPECT_LE(0, client.handshakeTime.count());
1188 EXPECT_TRUE(!server.handshakeVerify_);
1189 EXPECT_TRUE(server.handshakeSuccess_);
1190 EXPECT_TRUE(!server.handshakeError_);
1191 EXPECT_LE(0, server.handshakeTime.count());
1195 * Verify that the client's verification callback is able to fail SSL
1196 * connection establishment.
1198 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1199 EventBase eventBase;
1200 auto clientCtx = std::make_shared<SSLContext>();
1201 auto dfServerCtx = std::make_shared<SSLContext>();
1205 getctx(clientCtx, dfServerCtx);
1207 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1208 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1210 AsyncSSLSocket::UniquePtr clientSock(
1211 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1212 AsyncSSLSocket::UniquePtr serverSock(
1213 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1215 SSLHandshakeClient client(std::move(clientSock), true, false);
1216 clientCtx->loadTrustedCertificates(kTestCA);
1218 SSLHandshakeServer server(std::move(serverSock), true, true);
1222 EXPECT_TRUE(client.handshakeVerify_);
1223 EXPECT_TRUE(!client.handshakeSuccess_);
1224 EXPECT_TRUE(client.handshakeError_);
1225 EXPECT_LE(0, client.handshakeTime.count());
1226 EXPECT_TRUE(!server.handshakeVerify_);
1227 EXPECT_TRUE(!server.handshakeSuccess_);
1228 EXPECT_TRUE(server.handshakeError_);
1229 EXPECT_LE(0, server.handshakeTime.count());
1233 * Verify that the options in SSLContext can be overridden in
1234 * sslConnect/Accept.i.e specifying that no validation should be performed
1235 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1236 * the validation callback.
1238 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1239 EventBase eventBase;
1240 auto clientCtx = std::make_shared<SSLContext>();
1241 auto dfServerCtx = std::make_shared<SSLContext>();
1245 getctx(clientCtx, dfServerCtx);
1247 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1248 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1250 AsyncSSLSocket::UniquePtr clientSock(
1251 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1252 AsyncSSLSocket::UniquePtr serverSock(
1253 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1255 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1256 clientCtx->loadTrustedCertificates(kTestCA);
1258 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1262 EXPECT_TRUE(!client.handshakeVerify_);
1263 EXPECT_TRUE(client.handshakeSuccess_);
1264 EXPECT_TRUE(!client.handshakeError_);
1265 EXPECT_LE(0, client.handshakeTime.count());
1266 EXPECT_TRUE(!server.handshakeVerify_);
1267 EXPECT_TRUE(server.handshakeSuccess_);
1268 EXPECT_TRUE(!server.handshakeError_);
1269 EXPECT_LE(0, server.handshakeTime.count());
1273 * Verify that the options in SSLContext can be overridden in
1274 * sslConnect/Accept. Enable verification even if context says otherwise.
1275 * Test requireClientCert with client cert
1277 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1278 EventBase eventBase;
1279 auto clientCtx = std::make_shared<SSLContext>();
1280 auto serverCtx = std::make_shared<SSLContext>();
1281 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1282 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1283 serverCtx->loadPrivateKey(kTestKey);
1284 serverCtx->loadCertificate(kTestCert);
1285 serverCtx->loadTrustedCertificates(kTestCA);
1286 serverCtx->loadClientCAList(kTestCA);
1288 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1289 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1290 clientCtx->loadPrivateKey(kTestKey);
1291 clientCtx->loadCertificate(kTestCert);
1292 clientCtx->loadTrustedCertificates(kTestCA);
1297 AsyncSSLSocket::UniquePtr clientSock(
1298 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1299 AsyncSSLSocket::UniquePtr serverSock(
1300 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1302 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1303 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1307 EXPECT_TRUE(client.handshakeVerify_);
1308 EXPECT_TRUE(client.handshakeSuccess_);
1309 EXPECT_FALSE(client.handshakeError_);
1310 EXPECT_LE(0, client.handshakeTime.count());
1311 EXPECT_TRUE(server.handshakeVerify_);
1312 EXPECT_TRUE(server.handshakeSuccess_);
1313 EXPECT_FALSE(server.handshakeError_);
1314 EXPECT_LE(0, server.handshakeTime.count());
1318 * Verify that the client's verification callback is able to override
1319 * the preverification failure and allow a successful connection.
1321 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1322 EventBase eventBase;
1323 auto clientCtx = std::make_shared<SSLContext>();
1324 auto dfServerCtx = std::make_shared<SSLContext>();
1328 getctx(clientCtx, dfServerCtx);
1330 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1331 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1333 AsyncSSLSocket::UniquePtr clientSock(
1334 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1335 AsyncSSLSocket::UniquePtr serverSock(
1336 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1338 SSLHandshakeClient client(std::move(clientSock), false, true);
1339 SSLHandshakeServer server(std::move(serverSock), true, true);
1343 EXPECT_TRUE(client.handshakeVerify_);
1344 EXPECT_TRUE(client.handshakeSuccess_);
1345 EXPECT_TRUE(!client.handshakeError_);
1346 EXPECT_LE(0, client.handshakeTime.count());
1347 EXPECT_TRUE(!server.handshakeVerify_);
1348 EXPECT_TRUE(server.handshakeSuccess_);
1349 EXPECT_TRUE(!server.handshakeError_);
1350 EXPECT_LE(0, server.handshakeTime.count());
1354 * Verify that specifying that no validation should be performed allows an
1355 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1358 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1359 EventBase eventBase;
1360 auto clientCtx = std::make_shared<SSLContext>();
1361 auto dfServerCtx = std::make_shared<SSLContext>();
1365 getctx(clientCtx, dfServerCtx);
1367 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1368 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1370 AsyncSSLSocket::UniquePtr clientSock(
1371 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1372 AsyncSSLSocket::UniquePtr serverSock(
1373 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1375 SSLHandshakeClient client(std::move(clientSock), false, false);
1376 SSLHandshakeServer server(std::move(serverSock), false, false);
1380 EXPECT_TRUE(!client.handshakeVerify_);
1381 EXPECT_TRUE(client.handshakeSuccess_);
1382 EXPECT_TRUE(!client.handshakeError_);
1383 EXPECT_LE(0, client.handshakeTime.count());
1384 EXPECT_TRUE(!server.handshakeVerify_);
1385 EXPECT_TRUE(server.handshakeSuccess_);
1386 EXPECT_TRUE(!server.handshakeError_);
1387 EXPECT_LE(0, server.handshakeTime.count());
1391 * Test requireClientCert with client cert
1393 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1394 EventBase eventBase;
1395 auto clientCtx = std::make_shared<SSLContext>();
1396 auto serverCtx = std::make_shared<SSLContext>();
1397 serverCtx->setVerificationOption(
1398 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1399 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1400 serverCtx->loadPrivateKey(kTestKey);
1401 serverCtx->loadCertificate(kTestCert);
1402 serverCtx->loadTrustedCertificates(kTestCA);
1403 serverCtx->loadClientCAList(kTestCA);
1405 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1406 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1407 clientCtx->loadPrivateKey(kTestKey);
1408 clientCtx->loadCertificate(kTestCert);
1409 clientCtx->loadTrustedCertificates(kTestCA);
1414 AsyncSSLSocket::UniquePtr clientSock(
1415 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1416 AsyncSSLSocket::UniquePtr serverSock(
1417 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1419 SSLHandshakeClient client(std::move(clientSock), true, true);
1420 SSLHandshakeServer server(std::move(serverSock), true, true);
1424 EXPECT_TRUE(client.handshakeVerify_);
1425 EXPECT_TRUE(client.handshakeSuccess_);
1426 EXPECT_FALSE(client.handshakeError_);
1427 EXPECT_LE(0, client.handshakeTime.count());
1428 EXPECT_TRUE(server.handshakeVerify_);
1429 EXPECT_TRUE(server.handshakeSuccess_);
1430 EXPECT_FALSE(server.handshakeError_);
1431 EXPECT_LE(0, server.handshakeTime.count());
1436 * Test requireClientCert with no client cert
1438 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1439 EventBase eventBase;
1440 auto clientCtx = std::make_shared<SSLContext>();
1441 auto serverCtx = std::make_shared<SSLContext>();
1442 serverCtx->setVerificationOption(
1443 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1444 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1445 serverCtx->loadPrivateKey(kTestKey);
1446 serverCtx->loadCertificate(kTestCert);
1447 serverCtx->loadTrustedCertificates(kTestCA);
1448 serverCtx->loadClientCAList(kTestCA);
1449 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1450 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1455 AsyncSSLSocket::UniquePtr clientSock(
1456 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1457 AsyncSSLSocket::UniquePtr serverSock(
1458 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1460 SSLHandshakeClient client(std::move(clientSock), false, false);
1461 SSLHandshakeServer server(std::move(serverSock), false, false);
1465 EXPECT_FALSE(server.handshakeVerify_);
1466 EXPECT_FALSE(server.handshakeSuccess_);
1467 EXPECT_TRUE(server.handshakeError_);
1468 EXPECT_LE(0, client.handshakeTime.count());
1469 EXPECT_LE(0, server.handshakeTime.count());
1472 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1473 auto cert = getFileAsBuf(kTestCert);
1474 auto key = getFileAsBuf(kTestKey);
1476 ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1477 BIO_write(certBio.get(), cert.data(), cert.size());
1478 ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1479 BIO_write(keyBio.get(), key.data(), key.size());
1481 // Create SSL structs from buffers to get properties
1482 ssl::X509UniquePtr certStruct(
1483 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1484 ssl::EvpPkeyUniquePtr keyStruct(
1485 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1489 auto origCommonName = getCommonName(certStruct.get());
1490 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1491 certStruct = nullptr;
1492 keyStruct = nullptr;
1494 auto ctx = std::make_shared<SSLContext>();
1495 ctx->loadPrivateKeyFromBufferPEM(key);
1496 ctx->loadCertificateFromBufferPEM(cert);
1497 ctx->loadTrustedCertificates(kTestCA);
1499 ssl::SSLUniquePtr ssl(ctx->createSSL());
1501 auto newCert = SSL_get_certificate(ssl.get());
1502 auto newKey = SSL_get_privatekey(ssl.get());
1504 // Get properties from SSL struct
1505 auto newCommonName = getCommonName(newCert);
1506 auto newKeySize = EVP_PKEY_bits(newKey);
1508 // Check that the key and cert have the expected properties
1509 EXPECT_EQ(origCommonName, newCommonName);
1510 EXPECT_EQ(origKeySize, newKeySize);
1513 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1516 // Set up SSL context.
1517 auto sslContext = std::make_shared<SSLContext>();
1518 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1520 // create SSL socket
1521 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1523 EXPECT_EQ(1500, socket->getMinWriteSize());
1525 socket->setMinWriteSize(0);
1526 EXPECT_EQ(0, socket->getMinWriteSize());
1527 socket->setMinWriteSize(50000);
1528 EXPECT_EQ(50000, socket->getMinWriteSize());
1531 class ReadCallbackTerminator : public ReadCallback {
1533 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1537 // Do not write data back, terminate the loop.
1538 void readDataAvailable(size_t len) noexcept override {
1539 std::cerr << "readDataAvailable, len " << len << std::endl;
1541 currentBuffer.length = len;
1543 buffers.push_back(currentBuffer);
1544 currentBuffer.reset();
1545 state = STATE_SUCCEEDED;
1547 socket_->setReadCB(nullptr);
1548 base_->terminateLoopSoon();
1556 * Test a full unencrypted codepath
1558 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1561 auto clientCtx = std::make_shared<folly::SSLContext>();
1562 auto serverCtx = std::make_shared<folly::SSLContext>();
1565 getctx(clientCtx, serverCtx);
1566 auto client = AsyncSSLSocket::newSocket(
1567 clientCtx, &base, fds[0], false, true);
1568 auto server = AsyncSSLSocket::newSocket(
1569 serverCtx, &base, fds[1], true, true);
1571 ReadCallbackTerminator readCallback(&base, nullptr);
1572 server->setReadCB(&readCallback);
1573 readCallback.setSocket(server);
1576 memset(buf, 'a', sizeof(buf));
1577 client->write(nullptr, buf, sizeof(buf));
1579 // Check that bytes are unencrypted
1581 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1584 EventBaseAborter eba(&base, 3000);
1587 EXPECT_EQ(1, readCallback.buffers.size());
1588 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1590 server->setReadCB(&readCallback);
1593 server->sslAccept(nullptr);
1594 client->sslConn(nullptr);
1596 // Do NOT wait for handshake, writing should be queued and happen after
1598 client->write(nullptr, buf, sizeof(buf));
1600 // Check that bytes are *not* unencrypted
1602 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1608 EXPECT_EQ(2, readCallback.buffers.size());
1609 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1612 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1613 // Start listening on a local port
1614 WriteCallbackBase writeCallback;
1615 WriteErrorCallback readCallback(&writeCallback);
1616 HandshakeCallback handshakeCallback(&readCallback,
1617 HandshakeCallback::EXPECT_ERROR);
1618 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1619 TestSSLServer server(&acceptCallback);
1621 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1623 uint8_t buf[3] = {0x16, 0x03, 0x01};
1624 socket->write(buf, sizeof(buf));
1625 socket->closeWithReset();
1627 handshakeCallback.waitForHandshake();
1629 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1630 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1633 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1634 // Start listening on a local port
1635 WriteCallbackBase writeCallback;
1636 WriteErrorCallback readCallback(&writeCallback);
1637 HandshakeCallback handshakeCallback(&readCallback,
1638 HandshakeCallback::EXPECT_ERROR);
1639 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1640 TestSSLServer server(&acceptCallback);
1642 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1644 uint8_t buf[3] = {0x16, 0x03, 0x01};
1645 socket->write(buf, sizeof(buf));
1648 handshakeCallback.waitForHandshake();
1650 handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
1651 EXPECT_NE(handshakeCallback.errorString_.find("EOF"), std::string::npos);
1654 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1655 // Start listening on a local port
1656 WriteCallbackBase writeCallback;
1657 WriteErrorCallback readCallback(&writeCallback);
1658 HandshakeCallback handshakeCallback(&readCallback,
1659 HandshakeCallback::EXPECT_ERROR);
1660 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1661 TestSSLServer server(&acceptCallback);
1663 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1665 uint8_t buf[256] = {0x16, 0x03};
1666 memset(buf + 2, 'a', sizeof(buf) - 2);
1667 socket->write(buf, sizeof(buf));
1670 handshakeCallback.waitForHandshake();
1671 EXPECT_NE(handshakeCallback.errorString_.find("SSL routines"),
1673 #if defined(OPENSSL_IS_BORINGSSL)
1675 handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
1678 EXPECT_NE(handshakeCallback.errorString_.find("unknown protocol"),
1683 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
1684 using folly::ssl::OpenSSLUtils;
1686 OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384");
1687 // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this
1688 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), "");
1689 // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected
1690 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), "");
1695 class MockAsyncTFOSSLSocket : public AsyncSSLSocket {
1697 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
1699 explicit MockAsyncTFOSSLSocket(
1700 std::shared_ptr<folly::SSLContext> sslCtx,
1702 : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {}
1704 MOCK_METHOD3(tfoSendMsg, ssize_t(int fd, struct msghdr* msg, int msg_flags));
1708 * Test connecting to, writing to, reading from, and closing the
1709 * connection to the SSL server with TFO.
1711 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
1712 // Start listening on a local port
1713 WriteCallbackBase writeCallback;
1714 ReadCallback readCallback(&writeCallback);
1715 HandshakeCallback handshakeCallback(&readCallback);
1716 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1717 TestSSLServer server(&acceptCallback, true);
1719 // Set up SSL context.
1720 auto sslContext = std::make_shared<SSLContext>();
1724 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1725 socket->enableTFO();
1729 std::array<uint8_t, 128> buf;
1730 memset(buf.data(), 'a', buf.size());
1731 socket->write(buf.data(), buf.size());
1734 std::array<uint8_t, 128> readbuf;
1735 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1736 EXPECT_EQ(bytesRead, 128);
1737 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1744 * Test connecting to, writing to, reading from, and closing the
1745 * connection to the SSL server with TFO.
1747 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
1748 // Start listening on a local port
1749 WriteCallbackBase writeCallback;
1750 ReadCallback readCallback(&writeCallback);
1751 HandshakeCallback handshakeCallback(&readCallback);
1752 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1753 TestSSLServer server(&acceptCallback, false);
1755 // Set up SSL context.
1756 auto sslContext = std::make_shared<SSLContext>();
1760 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1761 socket->enableTFO();
1765 std::array<uint8_t, 128> buf;
1766 memset(buf.data(), 'a', buf.size());
1767 socket->write(buf.data(), buf.size());
1770 std::array<uint8_t, 128> readbuf;
1771 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1772 EXPECT_EQ(bytesRead, 128);
1773 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1779 class ConnCallback : public AsyncSocket::ConnectCallback {
1781 virtual void connectSuccess() noexcept override {
1782 state = State::SUCCESS;
1785 virtual void connectErr(const AsyncSocketException& ex) noexcept override {
1786 state = State::ERROR;
1790 enum class State { WAITING, SUCCESS, ERROR };
1792 State state{State::WAITING};
1796 template <class Cardinality>
1797 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
1799 const SocketAddress& address,
1800 Cardinality cardinality) {
1801 // Set up SSL context.
1802 auto sslContext = std::make_shared<SSLContext>();
1805 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
1806 new MockAsyncTFOSSLSocket(sslContext, evb));
1807 socket->enableTFO();
1809 EXPECT_CALL(*socket, tfoSendMsg(_, _, _))
1811 .WillOnce(Invoke([&](int fd, struct msghdr*, int) {
1812 sockaddr_storage addr;
1813 auto len = address.getAddress(&addr);
1814 return connect(fd, (const struct sockaddr*)&addr, len);
1819 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
1820 // Start listening on a local port
1821 WriteCallbackBase writeCallback;
1822 ReadCallback readCallback(&writeCallback);
1823 HandshakeCallback handshakeCallback(&readCallback);
1824 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1825 TestSSLServer server(&acceptCallback, true);
1829 auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1);
1831 socket->connect(&ccb, server.getAddress(), 30);
1834 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
1836 evb.runInEventBaseThread([&] { socket->detachEventBase(); });
1839 BlockingSocket sock(std::move(socket));
1841 std::array<uint8_t, 128> buf;
1842 memset(buf.data(), 'a', buf.size());
1843 sock.write(buf.data(), buf.size());
1846 std::array<uint8_t, 128> readbuf;
1847 uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size());
1848 EXPECT_EQ(bytesRead, 128);
1849 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1855 #if !defined(OPENSSL_IS_BORINGSSL)
1856 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
1857 // Start listening on a local port
1858 ConnectTimeoutCallback acceptCallback;
1859 TestSSLServer server(&acceptCallback, true);
1861 // Set up SSL context.
1862 auto sslContext = std::make_shared<SSLContext>();
1866 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1867 socket->enableTFO();
1869 socket->open(std::chrono::milliseconds(20)), AsyncSocketException);
1873 #if !defined(OPENSSL_IS_BORINGSSL)
1874 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
1875 // Start listening on a local port
1876 ConnectTimeoutCallback acceptCallback;
1877 TestSSLServer server(&acceptCallback, true);
1881 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1883 // Set a short timeout
1884 socket->connect(&ccb, server.getAddress(), 1);
1887 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1891 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
1892 // Start listening on a local port
1893 EmptyReadCallback readCallback;
1894 HandshakeCallback handshakeCallback(
1895 &readCallback, HandshakeCallback::EXPECT_ERROR);
1896 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
1897 TestSSLServer server(&acceptCallback, true);
1901 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1903 socket->connect(&ccb, server.getAddress(), 100);
1906 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1907 EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out"));
1910 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
1911 // Start listening on a local port
1914 // Hopefully nothing is listening on this address
1915 SocketAddress addr("127.0.0.1", 65535);
1916 auto socket = setupSocketWithFallback(&evb, addr, AtMost(1));
1918 socket->connect(&ccb, addr, 100);
1921 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1922 EXPECT_THAT(ccb.error, testing::HasSubstr("refused"));
1925 TEST(AsyncSSLSocketTest, TestPreReceivedData) {
1926 EventBase clientEventBase;
1927 EventBase serverEventBase;
1928 auto clientCtx = std::make_shared<SSLContext>();
1929 auto dfServerCtx = std::make_shared<SSLContext>();
1930 std::array<int, 2> fds;
1932 getctx(clientCtx, dfServerCtx);
1934 AsyncSSLSocket::UniquePtr clientSockPtr(
1935 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
1936 AsyncSSLSocket::UniquePtr serverSockPtr(
1937 new AsyncSSLSocket(dfServerCtx, &serverEventBase, fds[1], true));
1938 auto clientSock = clientSockPtr.get();
1939 auto serverSock = serverSockPtr.get();
1940 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
1942 // Steal some data from the server.
1943 clientEventBase.loopOnce();
1944 std::array<uint8_t, 10> buf;
1945 recv(fds[1], buf.data(), buf.size(), 0);
1947 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
1948 SSLHandshakeServer server(std::move(serverSockPtr), true, true);
1949 while (!client.handshakeSuccess_ && !client.handshakeError_) {
1950 serverEventBase.loopOnce();
1951 clientEventBase.loopOnce();
1954 EXPECT_TRUE(client.handshakeSuccess_);
1955 EXPECT_TRUE(server.handshakeSuccess_);
1957 serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
1965 ///////////////////////////////////////////////////////////////////////////
1966 // init_unit_test_suite
1967 ///////////////////////////////////////////////////////////////////////////
1969 struct Initializer {
1971 signal(SIGPIPE, SIG_IGN);
1974 Initializer initializer;