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>
18 #include <folly/SocketAddress.h>
19 #include <folly/io/Cursor.h>
20 #include <folly/io/async/AsyncSSLSocket.h>
21 #include <folly/io/async/EventBase.h>
22 #include <folly/portability/GMock.h>
23 #include <folly/portability/GTest.h>
24 #include <folly/portability/OpenSSL.h>
25 #include <folly/portability/Sockets.h>
26 #include <folly/portability/Unistd.h>
28 #include <folly/io/async/test/BlockingSocket.h>
32 #include <sys/types.h>
41 #include <sys/utsname.h>
51 using namespace testing;
54 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
55 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
56 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
58 constexpr size_t SSLClient::kMaxReadBufferSz;
59 constexpr size_t SSLClient::kMaxReadsPerEvent;
61 void getfds(int fds[2]) {
62 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
63 FAIL() << "failed to create socketpair: " << strerror(errno);
65 for (int idx = 0; idx < 2; ++idx) {
66 int flags = fcntl(fds[idx], F_GETFL, 0);
68 FAIL() << "failed to get flags for socket " << idx << ": "
71 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
72 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
79 std::shared_ptr<folly::SSLContext> clientCtx,
80 std::shared_ptr<folly::SSLContext> serverCtx) {
81 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
83 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
84 serverCtx->loadCertificate(kTestCert);
85 serverCtx->loadPrivateKey(kTestKey);
90 AsyncSSLSocket::UniquePtr* clientSock,
91 AsyncSSLSocket::UniquePtr* serverSock) {
92 auto clientCtx = std::make_shared<folly::SSLContext>();
93 auto serverCtx = std::make_shared<folly::SSLContext>();
96 getctx(clientCtx, serverCtx);
97 clientSock->reset(new AsyncSSLSocket(
98 clientCtx, eventBase, fds[0], false));
99 serverSock->reset(new AsyncSSLSocket(
100 serverCtx, eventBase, fds[1], true));
102 // (*clientSock)->setSendTimeout(100);
103 // (*serverSock)->setSendTimeout(100);
106 // client protocol filters
107 bool clientProtoFilterPickPony(unsigned char** client,
108 unsigned int* client_len, const unsigned char*, unsigned int ) {
109 //the protocol string in length prefixed byte string. the
110 //length byte is not included in the length
111 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
117 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
118 const unsigned char*, unsigned int) {
122 std::string getFileAsBuf(const char* fileName) {
124 folly::readFile(fileName, buffer);
128 std::string getCommonName(X509* cert) {
129 X509_NAME* subject = X509_get_subject_name(cert);
131 cn.resize(ub_common_name);
132 X509_NAME_get_text_by_NID(
133 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
138 * Test connecting to, writing to, reading from, and closing the
139 * connection to the SSL server.
141 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
142 // Start listening on a local port
143 WriteCallbackBase writeCallback;
144 ReadCallback readCallback(&writeCallback);
145 HandshakeCallback handshakeCallback(&readCallback);
146 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
147 TestSSLServer server(&acceptCallback);
149 // Set up SSL context.
150 std::shared_ptr<SSLContext> sslContext(new SSLContext());
151 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
152 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
153 //sslContext->authenticate(true, false);
156 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
158 socket->open(std::chrono::milliseconds(10000));
162 memset(buf, 'a', sizeof(buf));
163 socket->write(buf, sizeof(buf));
166 uint8_t readbuf[128];
167 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
168 EXPECT_EQ(bytesRead, 128);
169 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
174 cerr << "ConnectWriteReadClose test completed" << endl;
175 EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000);
179 * Test reading after server close.
181 TEST(AsyncSSLSocketTest, ReadAfterClose) {
182 // Start listening on a local port
183 WriteCallbackBase writeCallback;
184 ReadEOFCallback readCallback(&writeCallback);
185 HandshakeCallback handshakeCallback(&readCallback);
186 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
187 auto server = std::make_unique<TestSSLServer>(&acceptCallback);
189 // Set up SSL context.
190 auto sslContext = std::make_shared<SSLContext>();
191 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
194 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
197 // This should trigger an EOF on the client.
198 auto evb = handshakeCallback.getSocket()->getEventBase();
199 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
200 std::array<uint8_t, 128> readbuf;
201 auto bytesRead = socket->read(readbuf.data(), readbuf.size());
202 EXPECT_EQ(0, bytesRead);
206 * Test bad renegotiation
208 #if !defined(OPENSSL_IS_BORINGSSL)
209 TEST(AsyncSSLSocketTest, Renegotiate) {
211 auto clientCtx = std::make_shared<SSLContext>();
212 auto dfServerCtx = std::make_shared<SSLContext>();
213 std::array<int, 2> fds;
215 getctx(clientCtx, dfServerCtx);
217 AsyncSSLSocket::UniquePtr clientSock(
218 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
219 AsyncSSLSocket::UniquePtr serverSock(
220 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
221 SSLHandshakeClient client(std::move(clientSock), true, true);
222 RenegotiatingServer server(std::move(serverSock));
224 while (!client.handshakeSuccess_ && !client.handshakeError_) {
225 eventBase.loopOnce();
228 ASSERT_TRUE(client.handshakeSuccess_);
230 auto sslSock = std::move(client).moveSocket();
231 sslSock->detachEventBase();
232 // This is nasty, however we don't want to add support for
233 // renegotiation in AsyncSSLSocket.
234 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
236 auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
238 std::thread t([&]() { eventBase.loopForever(); });
240 // Trigger the renegotiation.
241 std::array<uint8_t, 128> buf;
242 memset(buf.data(), 'a', buf.size());
244 socket->write(buf.data(), buf.size());
245 } catch (AsyncSocketException& e) {
246 LOG(INFO) << "client got error " << e.what();
248 eventBase.terminateLoopSoon();
252 ASSERT_TRUE(server.renegotiationError_);
257 * Negative test for handshakeError().
259 TEST(AsyncSSLSocketTest, HandshakeError) {
260 // Start listening on a local port
261 WriteCallbackBase writeCallback;
262 WriteErrorCallback readCallback(&writeCallback);
263 HandshakeCallback handshakeCallback(&readCallback);
264 HandshakeErrorCallback acceptCallback(&handshakeCallback);
265 TestSSLServer server(&acceptCallback);
267 // Set up SSL context.
268 std::shared_ptr<SSLContext> sslContext(new SSLContext());
269 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
272 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
279 uint8_t readbuf[128];
280 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
281 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
282 } catch (AsyncSocketException&) {
289 cerr << "HandshakeError test completed" << endl;
293 * Negative test for readError().
295 TEST(AsyncSSLSocketTest, ReadError) {
296 // Start listening on a local port
297 WriteCallbackBase writeCallback;
298 ReadErrorCallback readCallback(&writeCallback);
299 HandshakeCallback handshakeCallback(&readCallback);
300 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
301 TestSSLServer server(&acceptCallback);
303 // Set up SSL context.
304 std::shared_ptr<SSLContext> sslContext(new SSLContext());
305 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
308 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
312 // write something to trigger ssl handshake
314 memset(buf, 'a', sizeof(buf));
315 socket->write(buf, sizeof(buf));
318 cerr << "ReadError test completed" << endl;
322 * Negative test for writeError().
324 TEST(AsyncSSLSocketTest, WriteError) {
325 // Start listening on a local port
326 WriteCallbackBase writeCallback;
327 WriteErrorCallback readCallback(&writeCallback);
328 HandshakeCallback handshakeCallback(&readCallback);
329 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
330 TestSSLServer server(&acceptCallback);
332 // Set up SSL context.
333 std::shared_ptr<SSLContext> sslContext(new SSLContext());
334 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
337 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
341 // write something to trigger ssl handshake
343 memset(buf, 'a', sizeof(buf));
344 socket->write(buf, sizeof(buf));
347 cerr << "WriteError test completed" << endl;
351 * Test a socket with TCP_NODELAY unset.
353 TEST(AsyncSSLSocketTest, SocketWithDelay) {
354 // Start listening on a local port
355 WriteCallbackBase writeCallback;
356 ReadCallback readCallback(&writeCallback);
357 HandshakeCallback handshakeCallback(&readCallback);
358 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
359 TestSSLServer server(&acceptCallback);
361 // Set up SSL context.
362 std::shared_ptr<SSLContext> sslContext(new SSLContext());
363 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
366 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
372 memset(buf, 'a', sizeof(buf));
373 socket->write(buf, sizeof(buf));
376 uint8_t readbuf[128];
377 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
378 EXPECT_EQ(bytesRead, 128);
379 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
384 cerr << "SocketWithDelay test completed" << endl;
387 using NextProtocolTypePair =
388 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
390 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
391 // For matching protos
393 void SetUp() override { getctx(clientCtx, serverCtx); }
395 void connect(bool unset = false) {
399 // unsetting NPN for any of [client, server] is enough to make NPN not
401 clientCtx->unsetNextProtocols();
404 AsyncSSLSocket::UniquePtr clientSock(
405 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
406 AsyncSSLSocket::UniquePtr serverSock(
407 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
408 client = std::make_unique<NpnClient>(std::move(clientSock));
409 server = std::make_unique<NpnServer>(std::move(serverSock));
414 void expectProtocol(const std::string& proto) {
415 expectHandshakeSuccess();
416 EXPECT_NE(client->nextProtoLength, 0);
417 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
419 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
421 string selected((const char*)client->nextProto, client->nextProtoLength);
422 EXPECT_EQ(proto, selected);
425 void expectNoProtocol() {
426 expectHandshakeSuccess();
427 EXPECT_EQ(client->nextProtoLength, 0);
428 EXPECT_EQ(server->nextProtoLength, 0);
429 EXPECT_EQ(client->nextProto, nullptr);
430 EXPECT_EQ(server->nextProto, nullptr);
433 void expectProtocolType() {
434 expectHandshakeSuccess();
435 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
436 GetParam().second == SSLContext::NextProtocolType::ANY) {
437 EXPECT_EQ(client->protocolType, server->protocolType);
438 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
439 GetParam().second == SSLContext::NextProtocolType::ANY) {
440 // Well not much we can say
442 expectProtocolType(GetParam());
446 void expectProtocolType(NextProtocolTypePair expected) {
447 expectHandshakeSuccess();
448 EXPECT_EQ(client->protocolType, expected.first);
449 EXPECT_EQ(server->protocolType, expected.second);
452 void expectHandshakeSuccess() {
453 EXPECT_FALSE(client->except.hasValue())
454 << "client handshake error: " << client->except->what();
455 EXPECT_FALSE(server->except.hasValue())
456 << "server handshake error: " << server->except->what();
459 void expectHandshakeError() {
460 EXPECT_TRUE(client->except.hasValue())
461 << "Expected client handshake error!";
462 EXPECT_TRUE(server->except.hasValue())
463 << "Expected server handshake error!";
467 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
468 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
470 std::unique_ptr<NpnClient> client;
471 std::unique_ptr<NpnServer> server;
474 class NextProtocolTLSExtTest : public NextProtocolTest {
475 // For extended TLS protos
478 class NextProtocolNPNOnlyTest : public NextProtocolTest {
479 // For mismatching protos
482 class NextProtocolMismatchTest : public NextProtocolTest {
483 // For mismatching protos
486 TEST_P(NextProtocolTest, NpnTestOverlap) {
487 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
488 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
493 expectProtocol("baz");
494 expectProtocolType();
497 TEST_P(NextProtocolTest, NpnTestUnset) {
498 // Identical to above test, except that we want unset NPN before
500 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
501 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
504 connect(true /* unset */);
506 // if alpn negotiation fails, type will appear as npn
508 EXPECT_EQ(client->protocolType, server->protocolType);
511 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
512 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
513 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
520 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
523 // Note: the behavior changed in the ANY/ANY case in OpenSSL 1.0.2h, this test
524 // will fail on 1.0.2 before that.
525 TEST_P(NextProtocolTest, NpnTestNoOverlap) {
526 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
527 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
531 if (GetParam().first == SSLContext::NextProtocolType::ALPN ||
532 GetParam().second == SSLContext::NextProtocolType::ALPN) {
533 // This is arguably incorrect behavior since RFC7301 states an ALPN protocol
534 // mismatch should result in a fatal alert, but this is the current behavior
535 // on all OpenSSL versions/variants, and we want to know if it changes.
538 #if FOLLY_OPENSSL_IS_110 || defined(OPENSSL_IS_BORINGSSL)
540 GetParam().first == SSLContext::NextProtocolType::ANY &&
541 GetParam().second == SSLContext::NextProtocolType::ANY) {
542 # if FOLLY_OPENSSL_IS_110
543 // OpenSSL 1.1.0 sends a fatal alert on mismatch, which is probavbly the
544 // correct behavior per RFC7301
545 expectHandshakeError();
547 // BoringSSL also doesn't fatal on mismatch but behaves slightly differently
548 // from OpenSSL 1.0.2h+ - it doesn't select a protocol if both ends support
555 expectProtocol("blub");
557 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
561 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
562 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
563 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
564 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
569 expectProtocol("ponies");
570 expectProtocolType();
573 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
574 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
575 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
576 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
581 expectProtocol("blub");
582 expectProtocolType();
585 TEST_P(NextProtocolTest, RandomizedNpnTest) {
586 // Probability that this test will fail is 2^-64, which could be considered
588 const int kTries = 64;
590 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
592 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
595 std::set<string> selectedProtocols;
596 for (int i = 0; i < kTries; ++i) {
599 EXPECT_NE(client->nextProtoLength, 0);
600 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
602 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
604 string selected((const char*)client->nextProto, client->nextProtoLength);
605 selectedProtocols.insert(selected);
606 expectProtocolType();
608 EXPECT_EQ(selectedProtocols.size(), 2);
611 INSTANTIATE_TEST_CASE_P(
615 NextProtocolTypePair(
616 SSLContext::NextProtocolType::NPN,
617 SSLContext::NextProtocolType::NPN),
618 NextProtocolTypePair(
619 SSLContext::NextProtocolType::NPN,
620 SSLContext::NextProtocolType::ANY),
621 NextProtocolTypePair(
622 SSLContext::NextProtocolType::ANY,
623 SSLContext::NextProtocolType::ANY)));
625 #if FOLLY_OPENSSL_HAS_ALPN
626 INSTANTIATE_TEST_CASE_P(
628 NextProtocolTLSExtTest,
630 NextProtocolTypePair(
631 SSLContext::NextProtocolType::ALPN,
632 SSLContext::NextProtocolType::ALPN),
633 NextProtocolTypePair(
634 SSLContext::NextProtocolType::ALPN,
635 SSLContext::NextProtocolType::ANY),
636 NextProtocolTypePair(
637 SSLContext::NextProtocolType::ANY,
638 SSLContext::NextProtocolType::ALPN)));
641 INSTANTIATE_TEST_CASE_P(
643 NextProtocolNPNOnlyTest,
644 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
645 SSLContext::NextProtocolType::NPN)));
647 #if FOLLY_OPENSSL_HAS_ALPN
648 INSTANTIATE_TEST_CASE_P(
650 NextProtocolMismatchTest,
651 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
652 SSLContext::NextProtocolType::ALPN),
653 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
654 SSLContext::NextProtocolType::NPN)));
657 #ifndef OPENSSL_NO_TLSEXT
659 * 1. Client sends TLSEXT_HOSTNAME in client hello.
660 * 2. Server found a match SSL_CTX and use this SSL_CTX to
661 * continue the SSL handshake.
662 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
664 TEST(AsyncSSLSocketTest, SNITestMatch) {
666 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
667 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
668 // Use the same SSLContext to continue the handshake after
669 // tlsext_hostname match.
670 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
671 const std::string serverName("xyz.newdev.facebook.com");
674 getctx(clientCtx, dfServerCtx);
676 AsyncSSLSocket::UniquePtr clientSock(
677 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
678 AsyncSSLSocket::UniquePtr serverSock(
679 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
680 SNIClient client(std::move(clientSock));
681 SNIServer server(std::move(serverSock),
688 EXPECT_TRUE(client.serverNameMatch);
689 EXPECT_TRUE(server.serverNameMatch);
693 * 1. Client sends TLSEXT_HOSTNAME in client hello.
694 * 2. Server cannot find a matching SSL_CTX and continue to use
695 * the current SSL_CTX to do the handshake.
696 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
698 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
700 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
701 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
702 // Use the same SSLContext to continue the handshake after
703 // tlsext_hostname match.
704 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
705 const std::string clientRequestingServerName("foo.com");
706 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
710 getctx(clientCtx, dfServerCtx);
712 AsyncSSLSocket::UniquePtr clientSock(
713 new AsyncSSLSocket(clientCtx,
716 clientRequestingServerName));
717 AsyncSSLSocket::UniquePtr serverSock(
718 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
719 SNIClient client(std::move(clientSock));
720 SNIServer server(std::move(serverSock),
723 serverExpectedServerName);
727 EXPECT_TRUE(!client.serverNameMatch);
728 EXPECT_TRUE(!server.serverNameMatch);
731 * 1. Client sends TLSEXT_HOSTNAME in client hello.
732 * 2. We then change the serverName.
733 * 3. We expect that we get 'false' as the result for serNameMatch.
736 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
738 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
739 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
740 // Use the same SSLContext to continue the handshake after
741 // tlsext_hostname match.
742 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
743 const std::string serverName("xyz.newdev.facebook.com");
746 getctx(clientCtx, dfServerCtx);
748 AsyncSSLSocket::UniquePtr clientSock(
749 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
750 //Change the server name
751 std::string newName("new.com");
752 clientSock->setServerName(newName);
753 AsyncSSLSocket::UniquePtr serverSock(
754 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
755 SNIClient client(std::move(clientSock));
756 SNIServer server(std::move(serverSock),
763 EXPECT_TRUE(!client.serverNameMatch);
767 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
768 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
770 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
772 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
773 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
774 // Use the same SSLContext to continue the handshake after
775 // tlsext_hostname match.
776 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
777 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
781 getctx(clientCtx, dfServerCtx);
783 AsyncSSLSocket::UniquePtr clientSock(
784 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
785 AsyncSSLSocket::UniquePtr serverSock(
786 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
787 SNIClient client(std::move(clientSock));
788 SNIServer server(std::move(serverSock),
791 serverExpectedServerName);
795 EXPECT_TRUE(!client.serverNameMatch);
796 EXPECT_TRUE(!server.serverNameMatch);
801 * Test SSL client socket
803 TEST(AsyncSSLSocketTest, SSLClientTest) {
804 // Start listening on a local port
805 WriteCallbackBase writeCallback;
806 ReadCallback readCallback(&writeCallback);
807 HandshakeCallback handshakeCallback(&readCallback);
808 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
809 TestSSLServer server(&acceptCallback);
813 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
816 EventBaseAborter eba(&eventBase, 3000);
819 EXPECT_EQ(client->getMiss(), 1);
820 EXPECT_EQ(client->getHit(), 0);
822 cerr << "SSLClientTest test completed" << endl;
827 * Test SSL client socket session re-use
829 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
830 // Start listening on a local port
831 WriteCallbackBase writeCallback;
832 ReadCallback readCallback(&writeCallback);
833 HandshakeCallback handshakeCallback(&readCallback);
834 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
835 TestSSLServer server(&acceptCallback);
840 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
843 EventBaseAborter eba(&eventBase, 3000);
846 EXPECT_EQ(client->getMiss(), 1);
847 EXPECT_EQ(client->getHit(), 9);
849 cerr << "SSLClientTestReuse test completed" << endl;
853 * Test SSL client socket timeout
855 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
856 // Start listening on a local port
857 EmptyReadCallback readCallback;
858 HandshakeCallback handshakeCallback(&readCallback,
859 HandshakeCallback::EXPECT_ERROR);
860 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
861 TestSSLServer server(&acceptCallback);
866 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
867 client->connect(true /* write before connect completes */);
868 EventBaseAborter eba(&eventBase, 3000);
872 // This is checking that the connectError callback precedes any queued
873 // writeError callbacks. This matches AsyncSocket's behavior
874 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
875 EXPECT_EQ(client->getErrors(), 1);
876 EXPECT_EQ(client->getMiss(), 0);
877 EXPECT_EQ(client->getHit(), 0);
879 cerr << "SSLClientTimeoutTest test completed" << endl;
882 // The next 3 tests need an FB-only extension, and will fail without it
883 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
885 * Test SSL server async cache
887 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
888 // Start listening on a local port
889 WriteCallbackBase writeCallback;
890 ReadCallback readCallback(&writeCallback);
891 HandshakeCallback handshakeCallback(&readCallback);
892 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
893 TestSSLAsyncCacheServer server(&acceptCallback);
898 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
901 EventBaseAborter eba(&eventBase, 3000);
904 EXPECT_EQ(server.getAsyncCallbacks(), 18);
905 EXPECT_EQ(server.getAsyncLookups(), 9);
906 EXPECT_EQ(client->getMiss(), 10);
907 EXPECT_EQ(client->getHit(), 0);
909 cerr << "SSLServerAsyncCacheTest test completed" << endl;
913 * Test SSL server accept timeout with cache path
915 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
916 // Start listening on a local port
917 WriteCallbackBase writeCallback;
918 ReadCallback readCallback(&writeCallback);
919 HandshakeCallback handshakeCallback(&readCallback);
920 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
921 TestSSLAsyncCacheServer server(&acceptCallback);
925 // only do a TCP connect
926 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
927 sock->connect(nullptr, server.getAddress());
929 EmptyReadCallback clientReadCallback;
930 clientReadCallback.tcpSocket_ = sock;
931 sock->setReadCB(&clientReadCallback);
933 EventBaseAborter eba(&eventBase, 3000);
936 EXPECT_EQ(readCallback.state, STATE_WAITING);
938 cerr << "SSLServerTimeoutTest test completed" << endl;
942 * Test SSL server accept timeout with cache path
944 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
945 // Start listening on a local port
946 WriteCallbackBase writeCallback;
947 ReadCallback readCallback(&writeCallback);
948 HandshakeCallback handshakeCallback(&readCallback);
949 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
950 TestSSLAsyncCacheServer server(&acceptCallback);
954 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
957 EventBaseAborter eba(&eventBase, 3000);
960 EXPECT_EQ(server.getAsyncCallbacks(), 1);
961 EXPECT_EQ(server.getAsyncLookups(), 1);
962 EXPECT_EQ(client->getErrors(), 1);
963 EXPECT_EQ(client->getMiss(), 1);
964 EXPECT_EQ(client->getHit(), 0);
966 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
970 * Test SSL server accept timeout with cache path
972 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
973 // Start listening on a local port
974 WriteCallbackBase writeCallback;
975 ReadCallback readCallback(&writeCallback);
976 HandshakeCallback handshakeCallback(&readCallback,
977 HandshakeCallback::EXPECT_ERROR);
978 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
979 TestSSLAsyncCacheServer server(&acceptCallback, 500);
984 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
987 EventBaseAborter eba(&eventBase, 3000);
990 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
991 handshakeCallback.closeSocket();});
992 // give time for the cache lookup to come back and find it closed
993 handshakeCallback.waitForHandshake();
995 EXPECT_EQ(server.getAsyncCallbacks(), 1);
996 EXPECT_EQ(server.getAsyncLookups(), 1);
997 EXPECT_EQ(client->getErrors(), 1);
998 EXPECT_EQ(client->getMiss(), 1);
999 EXPECT_EQ(client->getHit(), 0);
1001 cerr << "SSLServerCacheCloseTest test completed" << endl;
1003 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP
1006 * Verify Client Ciphers obtained using SSL MSG Callback.
1008 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
1009 EventBase eventBase;
1010 auto clientCtx = std::make_shared<SSLContext>();
1011 auto serverCtx = std::make_shared<SSLContext>();
1012 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1013 serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
1014 serverCtx->loadPrivateKey(kTestKey);
1015 serverCtx->loadCertificate(kTestCert);
1016 serverCtx->loadTrustedCertificates(kTestCA);
1017 serverCtx->loadClientCAList(kTestCA);
1019 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1020 clientCtx->ciphers("AES256-SHA:AES128-SHA");
1021 clientCtx->loadPrivateKey(kTestKey);
1022 clientCtx->loadCertificate(kTestCert);
1023 clientCtx->loadTrustedCertificates(kTestCA);
1028 AsyncSSLSocket::UniquePtr clientSock(
1029 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1030 AsyncSSLSocket::UniquePtr serverSock(
1031 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1033 SSLHandshakeClient client(std::move(clientSock), true, true);
1034 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
1038 #if defined(OPENSSL_IS_BORINGSSL)
1039 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
1041 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
1043 EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
1044 EXPECT_TRUE(client.handshakeVerify_);
1045 EXPECT_TRUE(client.handshakeSuccess_);
1046 EXPECT_TRUE(!client.handshakeError_);
1047 EXPECT_TRUE(server.handshakeVerify_);
1048 EXPECT_TRUE(server.handshakeSuccess_);
1049 EXPECT_TRUE(!server.handshakeError_);
1052 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1053 EventBase eventBase;
1054 auto ctx = std::make_shared<SSLContext>();
1060 uint8_t majorVersion = 18;
1061 uint8_t minorVersion = 25;
1063 // Create callback buf
1064 auto buf = IOBuf::create(bufLen);
1065 buf->append(bufLen);
1066 folly::io::RWPrivateCursor cursor(buf.get());
1067 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1068 cursor.write<uint16_t>(0);
1069 cursor.write<uint8_t>(38);
1070 cursor.write<uint8_t>(majorVersion);
1071 cursor.write<uint8_t>(minorVersion);
1073 cursor.write<uint32_t>(0);
1075 SSL* ssl = ctx->createSSL();
1076 SCOPE_EXIT { SSL_free(ssl); };
1077 AsyncSSLSocket::UniquePtr sock(
1078 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1079 sock->enableClientHelloParsing();
1081 // Test client hello parsing in one packet
1082 AsyncSSLSocket::clientHelloParsingCallback(
1083 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1086 auto parsedClientHello = sock->getClientHelloInfo();
1087 EXPECT_TRUE(parsedClientHello != nullptr);
1088 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1089 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1092 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1093 EventBase eventBase;
1094 auto ctx = std::make_shared<SSLContext>();
1100 uint8_t majorVersion = 18;
1101 uint8_t minorVersion = 25;
1103 // Create callback buf
1104 auto buf = IOBuf::create(bufLen);
1105 buf->append(bufLen);
1106 folly::io::RWPrivateCursor cursor(buf.get());
1107 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1108 cursor.write<uint16_t>(0);
1109 cursor.write<uint8_t>(38);
1110 cursor.write<uint8_t>(majorVersion);
1111 cursor.write<uint8_t>(minorVersion);
1113 cursor.write<uint32_t>(0);
1115 SSL* ssl = ctx->createSSL();
1116 SCOPE_EXIT { SSL_free(ssl); };
1117 AsyncSSLSocket::UniquePtr sock(
1118 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1119 sock->enableClientHelloParsing();
1121 // Test parsing with two packets with first packet size < 3
1122 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1123 AsyncSSLSocket::clientHelloParsingCallback(
1124 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1127 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1128 AsyncSSLSocket::clientHelloParsingCallback(
1129 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1133 auto parsedClientHello = sock->getClientHelloInfo();
1134 EXPECT_TRUE(parsedClientHello != nullptr);
1135 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1136 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1139 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1140 EventBase eventBase;
1141 auto ctx = std::make_shared<SSLContext>();
1147 uint8_t majorVersion = 18;
1148 uint8_t minorVersion = 25;
1150 // Create callback buf
1151 auto buf = IOBuf::create(bufLen);
1152 buf->append(bufLen);
1153 folly::io::RWPrivateCursor cursor(buf.get());
1154 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1155 cursor.write<uint16_t>(0);
1156 cursor.write<uint8_t>(38);
1157 cursor.write<uint8_t>(majorVersion);
1158 cursor.write<uint8_t>(minorVersion);
1160 cursor.write<uint32_t>(0);
1162 SSL* ssl = ctx->createSSL();
1163 SCOPE_EXIT { SSL_free(ssl); };
1164 AsyncSSLSocket::UniquePtr sock(
1165 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1166 sock->enableClientHelloParsing();
1168 // Test parsing with multiple small packets
1169 for (uint64_t i = 0; i < buf->length(); i += 3) {
1170 auto bufCopy = folly::IOBuf::copyBuffer(
1171 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1172 AsyncSSLSocket::clientHelloParsingCallback(
1173 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1178 auto parsedClientHello = sock->getClientHelloInfo();
1179 EXPECT_TRUE(parsedClientHello != nullptr);
1180 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1181 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1185 * Verify sucessful behavior of SSL certificate validation.
1187 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1188 EventBase eventBase;
1189 auto clientCtx = std::make_shared<SSLContext>();
1190 auto dfServerCtx = std::make_shared<SSLContext>();
1194 getctx(clientCtx, dfServerCtx);
1196 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1197 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1199 AsyncSSLSocket::UniquePtr clientSock(
1200 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1201 AsyncSSLSocket::UniquePtr serverSock(
1202 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1204 SSLHandshakeClient client(std::move(clientSock), true, true);
1205 clientCtx->loadTrustedCertificates(kTestCA);
1207 SSLHandshakeServer server(std::move(serverSock), true, true);
1211 EXPECT_TRUE(client.handshakeVerify_);
1212 EXPECT_TRUE(client.handshakeSuccess_);
1213 EXPECT_TRUE(!client.handshakeError_);
1214 EXPECT_LE(0, client.handshakeTime.count());
1215 EXPECT_TRUE(!server.handshakeVerify_);
1216 EXPECT_TRUE(server.handshakeSuccess_);
1217 EXPECT_TRUE(!server.handshakeError_);
1218 EXPECT_LE(0, server.handshakeTime.count());
1222 * Verify that the client's verification callback is able to fail SSL
1223 * connection establishment.
1225 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1226 EventBase eventBase;
1227 auto clientCtx = std::make_shared<SSLContext>();
1228 auto dfServerCtx = std::make_shared<SSLContext>();
1232 getctx(clientCtx, dfServerCtx);
1234 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1235 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1237 AsyncSSLSocket::UniquePtr clientSock(
1238 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1239 AsyncSSLSocket::UniquePtr serverSock(
1240 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1242 SSLHandshakeClient client(std::move(clientSock), true, false);
1243 clientCtx->loadTrustedCertificates(kTestCA);
1245 SSLHandshakeServer server(std::move(serverSock), true, true);
1249 EXPECT_TRUE(client.handshakeVerify_);
1250 EXPECT_TRUE(!client.handshakeSuccess_);
1251 EXPECT_TRUE(client.handshakeError_);
1252 EXPECT_LE(0, client.handshakeTime.count());
1253 EXPECT_TRUE(!server.handshakeVerify_);
1254 EXPECT_TRUE(!server.handshakeSuccess_);
1255 EXPECT_TRUE(server.handshakeError_);
1256 EXPECT_LE(0, server.handshakeTime.count());
1260 * Verify that the options in SSLContext can be overridden in
1261 * sslConnect/Accept.i.e specifying that no validation should be performed
1262 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1263 * the validation callback.
1265 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1266 EventBase eventBase;
1267 auto clientCtx = std::make_shared<SSLContext>();
1268 auto dfServerCtx = std::make_shared<SSLContext>();
1272 getctx(clientCtx, dfServerCtx);
1274 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1275 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1277 AsyncSSLSocket::UniquePtr clientSock(
1278 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1279 AsyncSSLSocket::UniquePtr serverSock(
1280 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1282 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1283 clientCtx->loadTrustedCertificates(kTestCA);
1285 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1289 EXPECT_TRUE(!client.handshakeVerify_);
1290 EXPECT_TRUE(client.handshakeSuccess_);
1291 EXPECT_TRUE(!client.handshakeError_);
1292 EXPECT_LE(0, client.handshakeTime.count());
1293 EXPECT_TRUE(!server.handshakeVerify_);
1294 EXPECT_TRUE(server.handshakeSuccess_);
1295 EXPECT_TRUE(!server.handshakeError_);
1296 EXPECT_LE(0, server.handshakeTime.count());
1300 * Verify that the options in SSLContext can be overridden in
1301 * sslConnect/Accept. Enable verification even if context says otherwise.
1302 * Test requireClientCert with client cert
1304 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1305 EventBase eventBase;
1306 auto clientCtx = std::make_shared<SSLContext>();
1307 auto serverCtx = std::make_shared<SSLContext>();
1308 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1309 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1310 serverCtx->loadPrivateKey(kTestKey);
1311 serverCtx->loadCertificate(kTestCert);
1312 serverCtx->loadTrustedCertificates(kTestCA);
1313 serverCtx->loadClientCAList(kTestCA);
1315 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1316 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1317 clientCtx->loadPrivateKey(kTestKey);
1318 clientCtx->loadCertificate(kTestCert);
1319 clientCtx->loadTrustedCertificates(kTestCA);
1324 AsyncSSLSocket::UniquePtr clientSock(
1325 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1326 AsyncSSLSocket::UniquePtr serverSock(
1327 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1329 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1330 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1334 EXPECT_TRUE(client.handshakeVerify_);
1335 EXPECT_TRUE(client.handshakeSuccess_);
1336 EXPECT_FALSE(client.handshakeError_);
1337 EXPECT_LE(0, client.handshakeTime.count());
1338 EXPECT_TRUE(server.handshakeVerify_);
1339 EXPECT_TRUE(server.handshakeSuccess_);
1340 EXPECT_FALSE(server.handshakeError_);
1341 EXPECT_LE(0, server.handshakeTime.count());
1345 * Verify that the client's verification callback is able to override
1346 * the preverification failure and allow a successful connection.
1348 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1349 EventBase eventBase;
1350 auto clientCtx = std::make_shared<SSLContext>();
1351 auto dfServerCtx = std::make_shared<SSLContext>();
1355 getctx(clientCtx, dfServerCtx);
1357 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1358 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1360 AsyncSSLSocket::UniquePtr clientSock(
1361 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1362 AsyncSSLSocket::UniquePtr serverSock(
1363 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1365 SSLHandshakeClient client(std::move(clientSock), false, true);
1366 SSLHandshakeServer server(std::move(serverSock), true, true);
1370 EXPECT_TRUE(client.handshakeVerify_);
1371 EXPECT_TRUE(client.handshakeSuccess_);
1372 EXPECT_TRUE(!client.handshakeError_);
1373 EXPECT_LE(0, client.handshakeTime.count());
1374 EXPECT_TRUE(!server.handshakeVerify_);
1375 EXPECT_TRUE(server.handshakeSuccess_);
1376 EXPECT_TRUE(!server.handshakeError_);
1377 EXPECT_LE(0, server.handshakeTime.count());
1381 * Verify that specifying that no validation should be performed allows an
1382 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1385 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1386 EventBase eventBase;
1387 auto clientCtx = std::make_shared<SSLContext>();
1388 auto dfServerCtx = std::make_shared<SSLContext>();
1392 getctx(clientCtx, dfServerCtx);
1394 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1395 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1397 AsyncSSLSocket::UniquePtr clientSock(
1398 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1399 AsyncSSLSocket::UniquePtr serverSock(
1400 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1402 SSLHandshakeClient client(std::move(clientSock), false, false);
1403 SSLHandshakeServer server(std::move(serverSock), false, false);
1407 EXPECT_TRUE(!client.handshakeVerify_);
1408 EXPECT_TRUE(client.handshakeSuccess_);
1409 EXPECT_TRUE(!client.handshakeError_);
1410 EXPECT_LE(0, client.handshakeTime.count());
1411 EXPECT_TRUE(!server.handshakeVerify_);
1412 EXPECT_TRUE(server.handshakeSuccess_);
1413 EXPECT_TRUE(!server.handshakeError_);
1414 EXPECT_LE(0, server.handshakeTime.count());
1418 * Test requireClientCert with client cert
1420 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1421 EventBase eventBase;
1422 auto clientCtx = std::make_shared<SSLContext>();
1423 auto serverCtx = std::make_shared<SSLContext>();
1424 serverCtx->setVerificationOption(
1425 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1426 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1427 serverCtx->loadPrivateKey(kTestKey);
1428 serverCtx->loadCertificate(kTestCert);
1429 serverCtx->loadTrustedCertificates(kTestCA);
1430 serverCtx->loadClientCAList(kTestCA);
1432 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1433 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1434 clientCtx->loadPrivateKey(kTestKey);
1435 clientCtx->loadCertificate(kTestCert);
1436 clientCtx->loadTrustedCertificates(kTestCA);
1441 AsyncSSLSocket::UniquePtr clientSock(
1442 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1443 AsyncSSLSocket::UniquePtr serverSock(
1444 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1446 SSLHandshakeClient client(std::move(clientSock), true, true);
1447 SSLHandshakeServer server(std::move(serverSock), true, true);
1451 EXPECT_TRUE(client.handshakeVerify_);
1452 EXPECT_TRUE(client.handshakeSuccess_);
1453 EXPECT_FALSE(client.handshakeError_);
1454 EXPECT_LE(0, client.handshakeTime.count());
1455 EXPECT_TRUE(server.handshakeVerify_);
1456 EXPECT_TRUE(server.handshakeSuccess_);
1457 EXPECT_FALSE(server.handshakeError_);
1458 EXPECT_LE(0, server.handshakeTime.count());
1463 * Test requireClientCert with no client cert
1465 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1466 EventBase eventBase;
1467 auto clientCtx = std::make_shared<SSLContext>();
1468 auto serverCtx = std::make_shared<SSLContext>();
1469 serverCtx->setVerificationOption(
1470 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1471 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1472 serverCtx->loadPrivateKey(kTestKey);
1473 serverCtx->loadCertificate(kTestCert);
1474 serverCtx->loadTrustedCertificates(kTestCA);
1475 serverCtx->loadClientCAList(kTestCA);
1476 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1477 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1482 AsyncSSLSocket::UniquePtr clientSock(
1483 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1484 AsyncSSLSocket::UniquePtr serverSock(
1485 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1487 SSLHandshakeClient client(std::move(clientSock), false, false);
1488 SSLHandshakeServer server(std::move(serverSock), false, false);
1492 EXPECT_FALSE(server.handshakeVerify_);
1493 EXPECT_FALSE(server.handshakeSuccess_);
1494 EXPECT_TRUE(server.handshakeError_);
1495 EXPECT_LE(0, client.handshakeTime.count());
1496 EXPECT_LE(0, server.handshakeTime.count());
1499 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1500 auto cert = getFileAsBuf(kTestCert);
1501 auto key = getFileAsBuf(kTestKey);
1503 ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1504 BIO_write(certBio.get(), cert.data(), cert.size());
1505 ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1506 BIO_write(keyBio.get(), key.data(), key.size());
1508 // Create SSL structs from buffers to get properties
1509 ssl::X509UniquePtr certStruct(
1510 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1511 ssl::EvpPkeyUniquePtr keyStruct(
1512 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1516 auto origCommonName = getCommonName(certStruct.get());
1517 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1518 certStruct = nullptr;
1519 keyStruct = nullptr;
1521 auto ctx = std::make_shared<SSLContext>();
1522 ctx->loadPrivateKeyFromBufferPEM(key);
1523 ctx->loadCertificateFromBufferPEM(cert);
1524 ctx->loadTrustedCertificates(kTestCA);
1526 ssl::SSLUniquePtr ssl(ctx->createSSL());
1528 auto newCert = SSL_get_certificate(ssl.get());
1529 auto newKey = SSL_get_privatekey(ssl.get());
1531 // Get properties from SSL struct
1532 auto newCommonName = getCommonName(newCert);
1533 auto newKeySize = EVP_PKEY_bits(newKey);
1535 // Check that the key and cert have the expected properties
1536 EXPECT_EQ(origCommonName, newCommonName);
1537 EXPECT_EQ(origKeySize, newKeySize);
1540 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1543 // Set up SSL context.
1544 auto sslContext = std::make_shared<SSLContext>();
1545 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1547 // create SSL socket
1548 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1550 EXPECT_EQ(1500, socket->getMinWriteSize());
1552 socket->setMinWriteSize(0);
1553 EXPECT_EQ(0, socket->getMinWriteSize());
1554 socket->setMinWriteSize(50000);
1555 EXPECT_EQ(50000, socket->getMinWriteSize());
1558 class ReadCallbackTerminator : public ReadCallback {
1560 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1564 // Do not write data back, terminate the loop.
1565 void readDataAvailable(size_t len) noexcept override {
1566 std::cerr << "readDataAvailable, len " << len << std::endl;
1568 currentBuffer.length = len;
1570 buffers.push_back(currentBuffer);
1571 currentBuffer.reset();
1572 state = STATE_SUCCEEDED;
1574 socket_->setReadCB(nullptr);
1575 base_->terminateLoopSoon();
1583 * Test a full unencrypted codepath
1585 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1588 auto clientCtx = std::make_shared<folly::SSLContext>();
1589 auto serverCtx = std::make_shared<folly::SSLContext>();
1592 getctx(clientCtx, serverCtx);
1593 auto client = AsyncSSLSocket::newSocket(
1594 clientCtx, &base, fds[0], false, true);
1595 auto server = AsyncSSLSocket::newSocket(
1596 serverCtx, &base, fds[1], true, true);
1598 ReadCallbackTerminator readCallback(&base, nullptr);
1599 server->setReadCB(&readCallback);
1600 readCallback.setSocket(server);
1603 memset(buf, 'a', sizeof(buf));
1604 client->write(nullptr, buf, sizeof(buf));
1606 // Check that bytes are unencrypted
1608 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1611 EventBaseAborter eba(&base, 3000);
1614 EXPECT_EQ(1, readCallback.buffers.size());
1615 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1617 server->setReadCB(&readCallback);
1620 server->sslAccept(nullptr);
1621 client->sslConn(nullptr);
1623 // Do NOT wait for handshake, writing should be queued and happen after
1625 client->write(nullptr, buf, sizeof(buf));
1627 // Check that bytes are *not* unencrypted
1629 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1635 EXPECT_EQ(2, readCallback.buffers.size());
1636 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1639 TEST(AsyncSSLSocketTest, ConnectUnencryptedTest) {
1640 auto clientCtx = std::make_shared<folly::SSLContext>();
1641 auto serverCtx = std::make_shared<folly::SSLContext>();
1642 getctx(clientCtx, serverCtx);
1644 WriteCallbackBase writeCallback;
1645 ReadCallback readCallback(&writeCallback);
1646 HandshakeCallback handshakeCallback(&readCallback);
1647 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1648 TestSSLServer server(&acceptCallback);
1651 std::shared_ptr<AsyncSSLSocket> socket =
1652 AsyncSSLSocket::newSocket(clientCtx, &evb, true);
1653 socket->connect(nullptr, server.getAddress(), 0);
1657 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState());
1658 socket->sslConn(nullptr);
1660 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState());
1663 std::array<uint8_t, 128> buf;
1664 memset(buf.data(), 'a', buf.size());
1665 socket->write(nullptr, buf.data(), buf.size());
1670 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1671 // Start listening on a local port
1672 WriteCallbackBase writeCallback;
1673 WriteErrorCallback readCallback(&writeCallback);
1674 HandshakeCallback handshakeCallback(&readCallback,
1675 HandshakeCallback::EXPECT_ERROR);
1676 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1677 TestSSLServer server(&acceptCallback);
1679 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1681 uint8_t buf[3] = {0x16, 0x03, 0x01};
1682 socket->write(buf, sizeof(buf));
1683 socket->closeWithReset();
1685 handshakeCallback.waitForHandshake();
1687 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1688 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1691 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1692 // Start listening on a local port
1693 WriteCallbackBase writeCallback;
1694 WriteErrorCallback readCallback(&writeCallback);
1695 HandshakeCallback handshakeCallback(&readCallback,
1696 HandshakeCallback::EXPECT_ERROR);
1697 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1698 TestSSLServer server(&acceptCallback);
1700 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1702 uint8_t buf[3] = {0x16, 0x03, 0x01};
1703 socket->write(buf, sizeof(buf));
1706 handshakeCallback.waitForHandshake();
1707 #if FOLLY_OPENSSL_IS_110
1709 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1712 handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
1716 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1717 // Start listening on a local port
1718 WriteCallbackBase writeCallback;
1719 WriteErrorCallback readCallback(&writeCallback);
1720 HandshakeCallback handshakeCallback(&readCallback,
1721 HandshakeCallback::EXPECT_ERROR);
1722 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1723 TestSSLServer server(&acceptCallback);
1725 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1727 uint8_t buf[256] = {0x16, 0x03};
1728 memset(buf + 2, 'a', sizeof(buf) - 2);
1729 socket->write(buf, sizeof(buf));
1732 handshakeCallback.waitForHandshake();
1733 EXPECT_NE(handshakeCallback.errorString_.find("SSL routines"),
1735 #if defined(OPENSSL_IS_BORINGSSL)
1737 handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
1739 #elif FOLLY_OPENSSL_IS_110
1740 EXPECT_NE(handshakeCallback.errorString_.find("packet length too long"),
1743 EXPECT_NE(handshakeCallback.errorString_.find("unknown protocol"),
1748 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
1749 using folly::ssl::OpenSSLUtils;
1751 OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384");
1752 // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this
1753 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), "");
1754 // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected
1755 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), "");
1760 class MockAsyncTFOSSLSocket : public AsyncSSLSocket {
1762 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
1764 explicit MockAsyncTFOSSLSocket(
1765 std::shared_ptr<folly::SSLContext> sslCtx,
1767 : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {}
1769 MOCK_METHOD3(tfoSendMsg, ssize_t(int fd, struct msghdr* msg, int msg_flags));
1773 * Test connecting to, writing to, reading from, and closing the
1774 * connection to the SSL server with TFO.
1776 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
1777 // Start listening on a local port
1778 WriteCallbackBase writeCallback;
1779 ReadCallback readCallback(&writeCallback);
1780 HandshakeCallback handshakeCallback(&readCallback);
1781 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1782 TestSSLServer server(&acceptCallback, true);
1784 // Set up SSL context.
1785 auto sslContext = std::make_shared<SSLContext>();
1789 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1790 socket->enableTFO();
1794 std::array<uint8_t, 128> buf;
1795 memset(buf.data(), 'a', buf.size());
1796 socket->write(buf.data(), buf.size());
1799 std::array<uint8_t, 128> readbuf;
1800 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1801 EXPECT_EQ(bytesRead, 128);
1802 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1809 * Test connecting to, writing to, reading from, and closing the
1810 * connection to the SSL server with TFO.
1812 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
1813 // Start listening on a local port
1814 WriteCallbackBase writeCallback;
1815 ReadCallback readCallback(&writeCallback);
1816 HandshakeCallback handshakeCallback(&readCallback);
1817 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1818 TestSSLServer server(&acceptCallback, false);
1820 // Set up SSL context.
1821 auto sslContext = std::make_shared<SSLContext>();
1825 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1826 socket->enableTFO();
1830 std::array<uint8_t, 128> buf;
1831 memset(buf.data(), 'a', buf.size());
1832 socket->write(buf.data(), buf.size());
1835 std::array<uint8_t, 128> readbuf;
1836 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1837 EXPECT_EQ(bytesRead, 128);
1838 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1844 class ConnCallback : public AsyncSocket::ConnectCallback {
1846 void connectSuccess() noexcept override {
1847 state = State::SUCCESS;
1850 void connectErr(const AsyncSocketException& ex) noexcept override {
1851 state = State::ERROR;
1855 enum class State { WAITING, SUCCESS, ERROR };
1857 State state{State::WAITING};
1861 template <class Cardinality>
1862 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
1864 const SocketAddress& address,
1865 Cardinality cardinality) {
1866 // Set up SSL context.
1867 auto sslContext = std::make_shared<SSLContext>();
1870 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
1871 new MockAsyncTFOSSLSocket(sslContext, evb));
1872 socket->enableTFO();
1874 EXPECT_CALL(*socket, tfoSendMsg(_, _, _))
1876 .WillOnce(Invoke([&](int fd, struct msghdr*, int) {
1877 sockaddr_storage addr;
1878 auto len = address.getAddress(&addr);
1879 return connect(fd, (const struct sockaddr*)&addr, len);
1884 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
1885 // Start listening on a local port
1886 WriteCallbackBase writeCallback;
1887 ReadCallback readCallback(&writeCallback);
1888 HandshakeCallback handshakeCallback(&readCallback);
1889 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1890 TestSSLServer server(&acceptCallback, true);
1894 auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1);
1896 socket->connect(&ccb, server.getAddress(), 30);
1899 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
1901 evb.runInEventBaseThread([&] { socket->detachEventBase(); });
1904 BlockingSocket sock(std::move(socket));
1906 std::array<uint8_t, 128> buf;
1907 memset(buf.data(), 'a', buf.size());
1908 sock.write(buf.data(), buf.size());
1911 std::array<uint8_t, 128> readbuf;
1912 uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size());
1913 EXPECT_EQ(bytesRead, 128);
1914 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1920 #if !defined(OPENSSL_IS_BORINGSSL)
1921 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
1922 // Start listening on a local port
1923 ConnectTimeoutCallback acceptCallback;
1924 TestSSLServer server(&acceptCallback, true);
1926 // Set up SSL context.
1927 auto sslContext = std::make_shared<SSLContext>();
1931 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1932 socket->enableTFO();
1934 socket->open(std::chrono::milliseconds(20)), AsyncSocketException);
1938 #if !defined(OPENSSL_IS_BORINGSSL)
1939 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
1940 // Start listening on a local port
1941 ConnectTimeoutCallback acceptCallback;
1942 TestSSLServer server(&acceptCallback, true);
1946 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1948 // Set a short timeout
1949 socket->connect(&ccb, server.getAddress(), 1);
1952 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1956 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
1957 // Start listening on a local port
1958 EmptyReadCallback readCallback;
1959 HandshakeCallback handshakeCallback(
1960 &readCallback, HandshakeCallback::EXPECT_ERROR);
1961 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
1962 TestSSLServer server(&acceptCallback, true);
1966 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1968 socket->connect(&ccb, server.getAddress(), 100);
1971 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1972 EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out"));
1975 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
1976 // Start listening on a local port
1979 // Hopefully nothing is listening on this address
1980 SocketAddress addr("127.0.0.1", 65535);
1981 auto socket = setupSocketWithFallback(&evb, addr, AtMost(1));
1983 socket->connect(&ccb, addr, 100);
1986 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1987 EXPECT_THAT(ccb.error, testing::HasSubstr("refused"));
1990 TEST(AsyncSSLSocketTest, TestPreReceivedData) {
1991 EventBase clientEventBase;
1992 EventBase serverEventBase;
1993 auto clientCtx = std::make_shared<SSLContext>();
1994 auto dfServerCtx = std::make_shared<SSLContext>();
1995 std::array<int, 2> fds;
1997 getctx(clientCtx, dfServerCtx);
1999 AsyncSSLSocket::UniquePtr clientSockPtr(
2000 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
2001 AsyncSSLSocket::UniquePtr serverSockPtr(
2002 new AsyncSSLSocket(dfServerCtx, &serverEventBase, fds[1], true));
2003 auto clientSock = clientSockPtr.get();
2004 auto serverSock = serverSockPtr.get();
2005 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
2007 // Steal some data from the server.
2008 clientEventBase.loopOnce();
2009 std::array<uint8_t, 10> buf;
2010 recv(fds[1], buf.data(), buf.size(), 0);
2012 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
2013 SSLHandshakeServer server(std::move(serverSockPtr), true, true);
2014 while (!client.handshakeSuccess_ && !client.handshakeError_) {
2015 serverEventBase.loopOnce();
2016 clientEventBase.loopOnce();
2019 EXPECT_TRUE(client.handshakeSuccess_);
2020 EXPECT_TRUE(server.handshakeSuccess_);
2022 serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2025 TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) {
2026 EventBase clientEventBase;
2027 EventBase serverEventBase;
2028 auto clientCtx = std::make_shared<SSLContext>();
2029 auto dfServerCtx = std::make_shared<SSLContext>();
2030 std::array<int, 2> fds;
2032 getctx(clientCtx, dfServerCtx);
2034 AsyncSSLSocket::UniquePtr clientSockPtr(
2035 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
2036 AsyncSocket::UniquePtr serverSockPtr(
2037 new AsyncSocket(&serverEventBase, fds[1]));
2038 auto clientSock = clientSockPtr.get();
2039 auto serverSock = serverSockPtr.get();
2040 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
2042 // Steal some data from the server.
2043 clientEventBase.loopOnce();
2044 std::array<uint8_t, 10> buf;
2045 recv(fds[1], buf.data(), buf.size(), 0);
2046 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
2047 AsyncSSLSocket::UniquePtr serverSSLSockPtr(
2048 new AsyncSSLSocket(dfServerCtx, std::move(serverSockPtr), true));
2049 auto serverSSLSock = serverSSLSockPtr.get();
2050 SSLHandshakeServer server(std::move(serverSSLSockPtr), true, true);
2051 while (!client.handshakeSuccess_ && !client.handshakeError_) {
2052 serverEventBase.loopOnce();
2053 clientEventBase.loopOnce();
2056 EXPECT_TRUE(client.handshakeSuccess_);
2057 EXPECT_TRUE(server.handshakeSuccess_);
2059 serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2063 * Test overriding the flags passed to "sendmsg()" system call,
2064 * and verifying that write requests fail properly.
2066 TEST(AsyncSSLSocketTest, SendMsgParamsCallback) {
2067 // Start listening on a local port
2068 SendMsgFlagsCallback msgCallback;
2069 ExpectWriteErrorCallback writeCallback(&msgCallback);
2070 ReadCallback readCallback(&writeCallback);
2071 HandshakeCallback handshakeCallback(&readCallback);
2072 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2073 TestSSLServer server(&acceptCallback);
2075 // Set up SSL context.
2076 auto sslContext = std::make_shared<SSLContext>();
2077 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2080 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
2084 // Setting flags to "-1" to trigger "Invalid argument" error
2085 // on attempt to use this flags in sendmsg() system call.
2086 msgCallback.resetFlags(-1);
2089 std::vector<uint8_t> buf(128, 'a');
2090 ASSERT_EQ(socket->write(buf.data(), buf.size()), buf.size());
2095 cerr << "SendMsgParamsCallback test completed" << endl;
2100 * Test connecting to, writing to, reading from, and closing the
2101 * connection to the SSL server.
2103 TEST(AsyncSSLSocketTest, SendMsgDataCallback) {
2104 // This test requires Linux kernel v4.6 or later
2105 struct utsname s_uname;
2106 memset(&s_uname, 0, sizeof(s_uname));
2107 ASSERT_EQ(uname(&s_uname), 0);
2109 folly::StringPiece extra;
2110 if (folly::split<false>(
2111 '.', std::string(s_uname.release) + ".", major, minor, extra)) {
2112 if (major < 4 || (major == 4 && minor < 6)) {
2113 LOG(INFO) << "Kernel version: 4.6 and newer required for this test ("
2114 << "kernel ver. " << s_uname.release << " detected).";
2119 // Start listening on a local port
2120 SendMsgDataCallback msgCallback;
2121 WriteCheckTimestampCallback writeCallback(&msgCallback);
2122 ReadCallback readCallback(&writeCallback);
2123 HandshakeCallback handshakeCallback(&readCallback);
2124 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2125 TestSSLServer server(&acceptCallback);
2127 // Set up SSL context.
2128 auto sslContext = std::make_shared<SSLContext>();
2129 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2132 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
2136 // Adding MSG_EOR flag to the message flags - it'll trigger
2137 // timestamp generation for the last byte of the message.
2138 msgCallback.resetFlags(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_EOR);
2140 // Init ancillary data buffer to trigger timestamp notification
2142 uint8_t ctrl_data[CMSG_LEN(sizeof(uint32_t))];
2143 struct cmsghdr cmsg;
2145 u.cmsg.cmsg_level = SOL_SOCKET;
2146 u.cmsg.cmsg_type = SO_TIMESTAMPING;
2147 u.cmsg.cmsg_len = CMSG_LEN(sizeof(uint32_t));
2149 SOF_TIMESTAMPING_TX_SCHED |
2150 SOF_TIMESTAMPING_TX_SOFTWARE |
2151 SOF_TIMESTAMPING_TX_ACK;
2152 memcpy(CMSG_DATA(&u.cmsg), &flags, sizeof(uint32_t));
2153 std::vector<char> ctrl(CMSG_LEN(sizeof(uint32_t)));
2154 memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(sizeof(uint32_t)));
2155 msgCallback.resetData(std::move(ctrl));
2158 std::vector<uint8_t> buf(128, 'a');
2159 socket->write(buf.data(), buf.size());
2162 std::vector<uint8_t> readbuf(buf.size());
2163 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
2164 EXPECT_EQ(bytesRead, buf.size());
2165 EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin()));
2167 writeCallback.checkForTimestampNotifications();
2172 cerr << "SendMsgDataCallback test completed" << endl;
2174 #endif // MSG_ERRQUEUE
2181 ///////////////////////////////////////////////////////////////////////////
2182 // init_unit_test_suite
2183 ///////////////////////////////////////////////////////////////////////////
2185 struct Initializer {
2187 signal(SIGPIPE, SIG_IGN);
2190 Initializer initializer;