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>
35 #include <sys/utsname.h>
49 using namespace testing;
52 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
53 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
54 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
56 constexpr size_t SSLClient::kMaxReadBufferSz;
57 constexpr size_t SSLClient::kMaxReadsPerEvent;
59 void getfds(int fds[2]) {
60 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
61 FAIL() << "failed to create socketpair: " << strerror(errno);
63 for (int idx = 0; idx < 2; ++idx) {
64 int flags = fcntl(fds[idx], F_GETFL, 0);
66 FAIL() << "failed to get flags for socket " << idx << ": "
69 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
70 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
77 std::shared_ptr<folly::SSLContext> clientCtx,
78 std::shared_ptr<folly::SSLContext> serverCtx) {
79 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
81 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
82 serverCtx->loadCertificate(kTestCert);
83 serverCtx->loadPrivateKey(kTestKey);
88 AsyncSSLSocket::UniquePtr* clientSock,
89 AsyncSSLSocket::UniquePtr* serverSock) {
90 auto clientCtx = std::make_shared<folly::SSLContext>();
91 auto serverCtx = std::make_shared<folly::SSLContext>();
94 getctx(clientCtx, serverCtx);
95 clientSock->reset(new AsyncSSLSocket(
96 clientCtx, eventBase, fds[0], false));
97 serverSock->reset(new AsyncSSLSocket(
98 serverCtx, eventBase, fds[1], true));
100 // (*clientSock)->setSendTimeout(100);
101 // (*serverSock)->setSendTimeout(100);
104 // client protocol filters
105 bool clientProtoFilterPickPony(unsigned char** client,
106 unsigned int* client_len, const unsigned char*, unsigned int ) {
107 //the protocol string in length prefixed byte string. the
108 //length byte is not included in the length
109 static unsigned char p[7] = {6,'p','o','n','i','e','s'};
115 bool clientProtoFilterPickNone(unsigned char**, unsigned int*,
116 const unsigned char*, unsigned int) {
120 std::string getFileAsBuf(const char* fileName) {
122 folly::readFile(fileName, buffer);
126 std::string getCommonName(X509* cert) {
127 X509_NAME* subject = X509_get_subject_name(cert);
129 cn.resize(ub_common_name);
130 X509_NAME_get_text_by_NID(
131 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
136 * Test connecting to, writing to, reading from, and closing the
137 * connection to the SSL server.
139 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
140 // Start listening on a local port
141 WriteCallbackBase writeCallback;
142 ReadCallback readCallback(&writeCallback);
143 HandshakeCallback handshakeCallback(&readCallback);
144 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
145 TestSSLServer server(&acceptCallback);
147 // Set up SSL context.
148 std::shared_ptr<SSLContext> sslContext(new SSLContext());
149 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
150 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
151 //sslContext->authenticate(true, false);
154 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
156 socket->open(std::chrono::milliseconds(10000));
160 memset(buf, 'a', sizeof(buf));
161 socket->write(buf, sizeof(buf));
164 uint8_t readbuf[128];
165 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
166 EXPECT_EQ(bytesRead, 128);
167 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
172 cerr << "ConnectWriteReadClose test completed" << endl;
173 EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000);
177 * Test reading after server close.
179 TEST(AsyncSSLSocketTest, ReadAfterClose) {
180 // Start listening on a local port
181 WriteCallbackBase writeCallback;
182 ReadEOFCallback readCallback(&writeCallback);
183 HandshakeCallback handshakeCallback(&readCallback);
184 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
185 auto server = folly::make_unique<TestSSLServer>(&acceptCallback);
187 // Set up SSL context.
188 auto sslContext = std::make_shared<SSLContext>();
189 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
192 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
195 // This should trigger an EOF on the client.
196 auto evb = handshakeCallback.getSocket()->getEventBase();
197 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
198 std::array<uint8_t, 128> readbuf;
199 auto bytesRead = socket->read(readbuf.data(), readbuf.size());
200 EXPECT_EQ(0, bytesRead);
204 * Test bad renegotiation
206 #if !defined(OPENSSL_IS_BORINGSSL)
207 TEST(AsyncSSLSocketTest, Renegotiate) {
209 auto clientCtx = std::make_shared<SSLContext>();
210 auto dfServerCtx = std::make_shared<SSLContext>();
211 std::array<int, 2> fds;
213 getctx(clientCtx, dfServerCtx);
215 AsyncSSLSocket::UniquePtr clientSock(
216 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
217 AsyncSSLSocket::UniquePtr serverSock(
218 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
219 SSLHandshakeClient client(std::move(clientSock), true, true);
220 RenegotiatingServer server(std::move(serverSock));
222 while (!client.handshakeSuccess_ && !client.handshakeError_) {
223 eventBase.loopOnce();
226 ASSERT_TRUE(client.handshakeSuccess_);
228 auto sslSock = std::move(client).moveSocket();
229 sslSock->detachEventBase();
230 // This is nasty, however we don't want to add support for
231 // renegotiation in AsyncSSLSocket.
232 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
234 auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
236 std::thread t([&]() { eventBase.loopForever(); });
238 // Trigger the renegotiation.
239 std::array<uint8_t, 128> buf;
240 memset(buf.data(), 'a', buf.size());
242 socket->write(buf.data(), buf.size());
243 } catch (AsyncSocketException& e) {
244 LOG(INFO) << "client got error " << e.what();
246 eventBase.terminateLoopSoon();
250 ASSERT_TRUE(server.renegotiationError_);
255 * Negative test for handshakeError().
257 TEST(AsyncSSLSocketTest, HandshakeError) {
258 // Start listening on a local port
259 WriteCallbackBase writeCallback;
260 WriteErrorCallback readCallback(&writeCallback);
261 HandshakeCallback handshakeCallback(&readCallback);
262 HandshakeErrorCallback acceptCallback(&handshakeCallback);
263 TestSSLServer server(&acceptCallback);
265 // Set up SSL context.
266 std::shared_ptr<SSLContext> sslContext(new SSLContext());
267 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
270 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
277 uint8_t readbuf[128];
278 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
279 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
280 } catch (AsyncSocketException&) {
287 cerr << "HandshakeError test completed" << endl;
291 * Negative test for readError().
293 TEST(AsyncSSLSocketTest, ReadError) {
294 // Start listening on a local port
295 WriteCallbackBase writeCallback;
296 ReadErrorCallback readCallback(&writeCallback);
297 HandshakeCallback handshakeCallback(&readCallback);
298 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
299 TestSSLServer server(&acceptCallback);
301 // Set up SSL context.
302 std::shared_ptr<SSLContext> sslContext(new SSLContext());
303 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
306 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
310 // write something to trigger ssl handshake
312 memset(buf, 'a', sizeof(buf));
313 socket->write(buf, sizeof(buf));
316 cerr << "ReadError test completed" << endl;
320 * Negative test for writeError().
322 TEST(AsyncSSLSocketTest, WriteError) {
323 // Start listening on a local port
324 WriteCallbackBase writeCallback;
325 WriteErrorCallback readCallback(&writeCallback);
326 HandshakeCallback handshakeCallback(&readCallback);
327 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
328 TestSSLServer server(&acceptCallback);
330 // Set up SSL context.
331 std::shared_ptr<SSLContext> sslContext(new SSLContext());
332 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
335 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
339 // write something to trigger ssl handshake
341 memset(buf, 'a', sizeof(buf));
342 socket->write(buf, sizeof(buf));
345 cerr << "WriteError test completed" << endl;
349 * Test a socket with TCP_NODELAY unset.
351 TEST(AsyncSSLSocketTest, SocketWithDelay) {
352 // Start listening on a local port
353 WriteCallbackBase writeCallback;
354 ReadCallback readCallback(&writeCallback);
355 HandshakeCallback handshakeCallback(&readCallback);
356 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
357 TestSSLServer server(&acceptCallback);
359 // Set up SSL context.
360 std::shared_ptr<SSLContext> sslContext(new SSLContext());
361 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
364 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
370 memset(buf, 'a', sizeof(buf));
371 socket->write(buf, sizeof(buf));
374 uint8_t readbuf[128];
375 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
376 EXPECT_EQ(bytesRead, 128);
377 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
382 cerr << "SocketWithDelay test completed" << endl;
385 using NextProtocolTypePair =
386 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
388 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
389 // For matching protos
391 void SetUp() override { getctx(clientCtx, serverCtx); }
393 void connect(bool unset = false) {
397 // unsetting NPN for any of [client, server] is enough to make NPN not
399 clientCtx->unsetNextProtocols();
402 AsyncSSLSocket::UniquePtr clientSock(
403 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
404 AsyncSSLSocket::UniquePtr serverSock(
405 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
406 client = folly::make_unique<NpnClient>(std::move(clientSock));
407 server = folly::make_unique<NpnServer>(std::move(serverSock));
412 void expectProtocol(const std::string& proto) {
413 EXPECT_NE(client->nextProtoLength, 0);
414 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
416 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
418 string selected((const char*)client->nextProto, client->nextProtoLength);
419 EXPECT_EQ(proto, selected);
422 void expectNoProtocol() {
423 EXPECT_EQ(client->nextProtoLength, 0);
424 EXPECT_EQ(server->nextProtoLength, 0);
425 EXPECT_EQ(client->nextProto, nullptr);
426 EXPECT_EQ(server->nextProto, nullptr);
429 void expectProtocolType() {
430 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
431 GetParam().second == SSLContext::NextProtocolType::ANY) {
432 EXPECT_EQ(client->protocolType, server->protocolType);
433 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
434 GetParam().second == SSLContext::NextProtocolType::ANY) {
435 // Well not much we can say
437 expectProtocolType(GetParam());
441 void expectProtocolType(NextProtocolTypePair expected) {
442 EXPECT_EQ(client->protocolType, expected.first);
443 EXPECT_EQ(server->protocolType, expected.second);
447 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
448 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
450 std::unique_ptr<NpnClient> client;
451 std::unique_ptr<NpnServer> server;
454 class NextProtocolTLSExtTest : public NextProtocolTest {
455 // For extended TLS protos
458 class NextProtocolNPNOnlyTest : public NextProtocolTest {
459 // For mismatching protos
462 class NextProtocolMismatchTest : public NextProtocolTest {
463 // For mismatching protos
466 TEST_P(NextProtocolTest, NpnTestOverlap) {
467 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
468 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
473 expectProtocol("baz");
474 expectProtocolType();
477 TEST_P(NextProtocolTest, NpnTestUnset) {
478 // Identical to above test, except that we want unset NPN before
480 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
481 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
484 connect(true /* unset */);
486 // if alpn negotiation fails, type will appear as npn
488 EXPECT_EQ(client->protocolType, server->protocolType);
491 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
492 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
493 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
500 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
503 // Note: the behavior changed in the ANY/ANY case in OpenSSL 1.0.2h, this test
504 // will fail on 1.0.2 before that.
505 TEST_P(NextProtocolTest, NpnTestNoOverlap) {
506 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
507 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
512 if (GetParam().first == SSLContext::NextProtocolType::ALPN ||
513 GetParam().second == SSLContext::NextProtocolType::ALPN) {
514 // This is arguably incorrect behavior since RFC7301 states an ALPN protocol
515 // mismatch should result in a fatal alert, but this is OpenSSL's current
516 // behavior and we want to know if it changes.
519 #if defined(OPENSSL_IS_BORINGSSL)
520 // BoringSSL also doesn't fatal on mismatch but behaves slightly differently
521 // from OpenSSL 1.0.2h+ - it doesn't select a protocol if both ends support
524 GetParam().first == SSLContext::NextProtocolType::ANY &&
525 GetParam().second == SSLContext::NextProtocolType::ANY) {
530 expectProtocol("blub");
532 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
536 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
537 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
538 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
539 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
544 expectProtocol("ponies");
545 expectProtocolType();
548 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
549 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
550 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
551 serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
556 expectProtocol("blub");
557 expectProtocolType();
560 TEST_P(NextProtocolTest, RandomizedNpnTest) {
561 // Probability that this test will fail is 2^-64, which could be considered
563 const int kTries = 64;
565 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"},
567 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}},
570 std::set<string> selectedProtocols;
571 for (int i = 0; i < kTries; ++i) {
574 EXPECT_NE(client->nextProtoLength, 0);
575 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
577 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
579 string selected((const char*)client->nextProto, client->nextProtoLength);
580 selectedProtocols.insert(selected);
581 expectProtocolType();
583 EXPECT_EQ(selectedProtocols.size(), 2);
586 INSTANTIATE_TEST_CASE_P(
590 NextProtocolTypePair(
591 SSLContext::NextProtocolType::NPN,
592 SSLContext::NextProtocolType::NPN),
593 NextProtocolTypePair(
594 SSLContext::NextProtocolType::NPN,
595 SSLContext::NextProtocolType::ANY),
596 NextProtocolTypePair(
597 SSLContext::NextProtocolType::ANY,
598 SSLContext::NextProtocolType::ANY)));
600 #if FOLLY_OPENSSL_HAS_ALPN
601 INSTANTIATE_TEST_CASE_P(
603 NextProtocolTLSExtTest,
605 NextProtocolTypePair(
606 SSLContext::NextProtocolType::ALPN,
607 SSLContext::NextProtocolType::ALPN),
608 NextProtocolTypePair(
609 SSLContext::NextProtocolType::ALPN,
610 SSLContext::NextProtocolType::ANY),
611 NextProtocolTypePair(
612 SSLContext::NextProtocolType::ANY,
613 SSLContext::NextProtocolType::ALPN)));
616 INSTANTIATE_TEST_CASE_P(
618 NextProtocolNPNOnlyTest,
619 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
620 SSLContext::NextProtocolType::NPN)));
622 #if FOLLY_OPENSSL_HAS_ALPN
623 INSTANTIATE_TEST_CASE_P(
625 NextProtocolMismatchTest,
626 ::testing::Values(NextProtocolTypePair(SSLContext::NextProtocolType::NPN,
627 SSLContext::NextProtocolType::ALPN),
628 NextProtocolTypePair(SSLContext::NextProtocolType::ALPN,
629 SSLContext::NextProtocolType::NPN)));
632 #ifndef OPENSSL_NO_TLSEXT
634 * 1. Client sends TLSEXT_HOSTNAME in client hello.
635 * 2. Server found a match SSL_CTX and use this SSL_CTX to
636 * continue the SSL handshake.
637 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
639 TEST(AsyncSSLSocketTest, SNITestMatch) {
641 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
642 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
643 // Use the same SSLContext to continue the handshake after
644 // tlsext_hostname match.
645 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
646 const std::string serverName("xyz.newdev.facebook.com");
649 getctx(clientCtx, dfServerCtx);
651 AsyncSSLSocket::UniquePtr clientSock(
652 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
653 AsyncSSLSocket::UniquePtr serverSock(
654 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
655 SNIClient client(std::move(clientSock));
656 SNIServer server(std::move(serverSock),
663 EXPECT_TRUE(client.serverNameMatch);
664 EXPECT_TRUE(server.serverNameMatch);
668 * 1. Client sends TLSEXT_HOSTNAME in client hello.
669 * 2. Server cannot find a matching SSL_CTX and continue to use
670 * the current SSL_CTX to do the handshake.
671 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
673 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
675 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
676 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
677 // Use the same SSLContext to continue the handshake after
678 // tlsext_hostname match.
679 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
680 const std::string clientRequestingServerName("foo.com");
681 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
685 getctx(clientCtx, dfServerCtx);
687 AsyncSSLSocket::UniquePtr clientSock(
688 new AsyncSSLSocket(clientCtx,
691 clientRequestingServerName));
692 AsyncSSLSocket::UniquePtr serverSock(
693 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
694 SNIClient client(std::move(clientSock));
695 SNIServer server(std::move(serverSock),
698 serverExpectedServerName);
702 EXPECT_TRUE(!client.serverNameMatch);
703 EXPECT_TRUE(!server.serverNameMatch);
706 * 1. Client sends TLSEXT_HOSTNAME in client hello.
707 * 2. We then change the serverName.
708 * 3. We expect that we get 'false' as the result for serNameMatch.
711 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
713 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
714 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
715 // Use the same SSLContext to continue the handshake after
716 // tlsext_hostname match.
717 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
718 const std::string serverName("xyz.newdev.facebook.com");
721 getctx(clientCtx, dfServerCtx);
723 AsyncSSLSocket::UniquePtr clientSock(
724 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
725 //Change the server name
726 std::string newName("new.com");
727 clientSock->setServerName(newName);
728 AsyncSSLSocket::UniquePtr serverSock(
729 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
730 SNIClient client(std::move(clientSock));
731 SNIServer server(std::move(serverSock),
738 EXPECT_TRUE(!client.serverNameMatch);
742 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
743 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
745 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
747 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
748 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
749 // Use the same SSLContext to continue the handshake after
750 // tlsext_hostname match.
751 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
752 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
756 getctx(clientCtx, dfServerCtx);
758 AsyncSSLSocket::UniquePtr clientSock(
759 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
760 AsyncSSLSocket::UniquePtr serverSock(
761 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
762 SNIClient client(std::move(clientSock));
763 SNIServer server(std::move(serverSock),
766 serverExpectedServerName);
770 EXPECT_TRUE(!client.serverNameMatch);
771 EXPECT_TRUE(!server.serverNameMatch);
776 * Test SSL client socket
778 TEST(AsyncSSLSocketTest, SSLClientTest) {
779 // Start listening on a local port
780 WriteCallbackBase writeCallback;
781 ReadCallback readCallback(&writeCallback);
782 HandshakeCallback handshakeCallback(&readCallback);
783 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
784 TestSSLServer server(&acceptCallback);
788 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
791 EventBaseAborter eba(&eventBase, 3000);
794 EXPECT_EQ(client->getMiss(), 1);
795 EXPECT_EQ(client->getHit(), 0);
797 cerr << "SSLClientTest test completed" << endl;
802 * Test SSL client socket session re-use
804 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
805 // Start listening on a local port
806 WriteCallbackBase writeCallback;
807 ReadCallback readCallback(&writeCallback);
808 HandshakeCallback handshakeCallback(&readCallback);
809 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
810 TestSSLServer server(&acceptCallback);
815 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
818 EventBaseAborter eba(&eventBase, 3000);
821 EXPECT_EQ(client->getMiss(), 1);
822 EXPECT_EQ(client->getHit(), 9);
824 cerr << "SSLClientTestReuse test completed" << endl;
828 * Test SSL client socket timeout
830 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
831 // Start listening on a local port
832 EmptyReadCallback readCallback;
833 HandshakeCallback handshakeCallback(&readCallback,
834 HandshakeCallback::EXPECT_ERROR);
835 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
836 TestSSLServer server(&acceptCallback);
841 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
842 client->connect(true /* write before connect completes */);
843 EventBaseAborter eba(&eventBase, 3000);
847 // This is checking that the connectError callback precedes any queued
848 // writeError callbacks. This matches AsyncSocket's behavior
849 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
850 EXPECT_EQ(client->getErrors(), 1);
851 EXPECT_EQ(client->getMiss(), 0);
852 EXPECT_EQ(client->getHit(), 0);
854 cerr << "SSLClientTimeoutTest test completed" << endl;
857 // The next 3 tests need an FB-only extension, and will fail without it
858 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
860 * Test SSL server async cache
862 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
863 // Start listening on a local port
864 WriteCallbackBase writeCallback;
865 ReadCallback readCallback(&writeCallback);
866 HandshakeCallback handshakeCallback(&readCallback);
867 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
868 TestSSLAsyncCacheServer server(&acceptCallback);
873 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
876 EventBaseAborter eba(&eventBase, 3000);
879 EXPECT_EQ(server.getAsyncCallbacks(), 18);
880 EXPECT_EQ(server.getAsyncLookups(), 9);
881 EXPECT_EQ(client->getMiss(), 10);
882 EXPECT_EQ(client->getHit(), 0);
884 cerr << "SSLServerAsyncCacheTest test completed" << endl;
888 * Test SSL server accept timeout with cache path
890 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
891 // Start listening on a local port
892 WriteCallbackBase writeCallback;
893 ReadCallback readCallback(&writeCallback);
894 HandshakeCallback handshakeCallback(&readCallback);
895 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
896 TestSSLAsyncCacheServer server(&acceptCallback);
900 // only do a TCP connect
901 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
902 sock->connect(nullptr, server.getAddress());
904 EmptyReadCallback clientReadCallback;
905 clientReadCallback.tcpSocket_ = sock;
906 sock->setReadCB(&clientReadCallback);
908 EventBaseAborter eba(&eventBase, 3000);
911 EXPECT_EQ(readCallback.state, STATE_WAITING);
913 cerr << "SSLServerTimeoutTest test completed" << endl;
917 * Test SSL server accept timeout with cache path
919 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
920 // Start listening on a local port
921 WriteCallbackBase writeCallback;
922 ReadCallback readCallback(&writeCallback);
923 HandshakeCallback handshakeCallback(&readCallback);
924 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
925 TestSSLAsyncCacheServer server(&acceptCallback);
929 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
932 EventBaseAborter eba(&eventBase, 3000);
935 EXPECT_EQ(server.getAsyncCallbacks(), 1);
936 EXPECT_EQ(server.getAsyncLookups(), 1);
937 EXPECT_EQ(client->getErrors(), 1);
938 EXPECT_EQ(client->getMiss(), 1);
939 EXPECT_EQ(client->getHit(), 0);
941 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
945 * Test SSL server accept timeout with cache path
947 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
948 // Start listening on a local port
949 WriteCallbackBase writeCallback;
950 ReadCallback readCallback(&writeCallback);
951 HandshakeCallback handshakeCallback(&readCallback,
952 HandshakeCallback::EXPECT_ERROR);
953 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
954 TestSSLAsyncCacheServer server(&acceptCallback, 500);
959 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
962 EventBaseAborter eba(&eventBase, 3000);
965 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
966 handshakeCallback.closeSocket();});
967 // give time for the cache lookup to come back and find it closed
968 handshakeCallback.waitForHandshake();
970 EXPECT_EQ(server.getAsyncCallbacks(), 1);
971 EXPECT_EQ(server.getAsyncLookups(), 1);
972 EXPECT_EQ(client->getErrors(), 1);
973 EXPECT_EQ(client->getMiss(), 1);
974 EXPECT_EQ(client->getHit(), 0);
976 cerr << "SSLServerCacheCloseTest test completed" << endl;
978 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP
981 * Verify Client Ciphers obtained using SSL MSG Callback.
983 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
985 auto clientCtx = std::make_shared<SSLContext>();
986 auto serverCtx = std::make_shared<SSLContext>();
987 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
988 serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
989 serverCtx->loadPrivateKey(kTestKey);
990 serverCtx->loadCertificate(kTestCert);
991 serverCtx->loadTrustedCertificates(kTestCA);
992 serverCtx->loadClientCAList(kTestCA);
994 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
995 clientCtx->ciphers("AES256-SHA:AES128-SHA");
996 clientCtx->loadPrivateKey(kTestKey);
997 clientCtx->loadCertificate(kTestCert);
998 clientCtx->loadTrustedCertificates(kTestCA);
1003 AsyncSSLSocket::UniquePtr clientSock(
1004 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1005 AsyncSSLSocket::UniquePtr serverSock(
1006 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1008 SSLHandshakeClient client(std::move(clientSock), true, true);
1009 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
1013 #if defined(OPENSSL_IS_BORINGSSL)
1014 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
1016 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
1018 EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
1019 EXPECT_TRUE(client.handshakeVerify_);
1020 EXPECT_TRUE(client.handshakeSuccess_);
1021 EXPECT_TRUE(!client.handshakeError_);
1022 EXPECT_TRUE(server.handshakeVerify_);
1023 EXPECT_TRUE(server.handshakeSuccess_);
1024 EXPECT_TRUE(!server.handshakeError_);
1027 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1028 EventBase eventBase;
1029 auto ctx = std::make_shared<SSLContext>();
1035 uint8_t majorVersion = 18;
1036 uint8_t minorVersion = 25;
1038 // Create callback buf
1039 auto buf = IOBuf::create(bufLen);
1040 buf->append(bufLen);
1041 folly::io::RWPrivateCursor cursor(buf.get());
1042 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1043 cursor.write<uint16_t>(0);
1044 cursor.write<uint8_t>(38);
1045 cursor.write<uint8_t>(majorVersion);
1046 cursor.write<uint8_t>(minorVersion);
1048 cursor.write<uint32_t>(0);
1050 SSL* ssl = ctx->createSSL();
1051 SCOPE_EXIT { SSL_free(ssl); };
1052 AsyncSSLSocket::UniquePtr sock(
1053 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1054 sock->enableClientHelloParsing();
1056 // Test client hello parsing in one packet
1057 AsyncSSLSocket::clientHelloParsingCallback(
1058 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1061 auto parsedClientHello = sock->getClientHelloInfo();
1062 EXPECT_TRUE(parsedClientHello != nullptr);
1063 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1064 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1067 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1068 EventBase eventBase;
1069 auto ctx = std::make_shared<SSLContext>();
1075 uint8_t majorVersion = 18;
1076 uint8_t minorVersion = 25;
1078 // Create callback buf
1079 auto buf = IOBuf::create(bufLen);
1080 buf->append(bufLen);
1081 folly::io::RWPrivateCursor cursor(buf.get());
1082 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1083 cursor.write<uint16_t>(0);
1084 cursor.write<uint8_t>(38);
1085 cursor.write<uint8_t>(majorVersion);
1086 cursor.write<uint8_t>(minorVersion);
1088 cursor.write<uint32_t>(0);
1090 SSL* ssl = ctx->createSSL();
1091 SCOPE_EXIT { SSL_free(ssl); };
1092 AsyncSSLSocket::UniquePtr sock(
1093 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1094 sock->enableClientHelloParsing();
1096 // Test parsing with two packets with first packet size < 3
1097 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1098 AsyncSSLSocket::clientHelloParsingCallback(
1099 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1102 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1103 AsyncSSLSocket::clientHelloParsingCallback(
1104 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1108 auto parsedClientHello = sock->getClientHelloInfo();
1109 EXPECT_TRUE(parsedClientHello != nullptr);
1110 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1111 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1114 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1115 EventBase eventBase;
1116 auto ctx = std::make_shared<SSLContext>();
1122 uint8_t majorVersion = 18;
1123 uint8_t minorVersion = 25;
1125 // Create callback buf
1126 auto buf = IOBuf::create(bufLen);
1127 buf->append(bufLen);
1128 folly::io::RWPrivateCursor cursor(buf.get());
1129 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1130 cursor.write<uint16_t>(0);
1131 cursor.write<uint8_t>(38);
1132 cursor.write<uint8_t>(majorVersion);
1133 cursor.write<uint8_t>(minorVersion);
1135 cursor.write<uint32_t>(0);
1137 SSL* ssl = ctx->createSSL();
1138 SCOPE_EXIT { SSL_free(ssl); };
1139 AsyncSSLSocket::UniquePtr sock(
1140 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1141 sock->enableClientHelloParsing();
1143 // Test parsing with multiple small packets
1144 for (uint64_t i = 0; i < buf->length(); i += 3) {
1145 auto bufCopy = folly::IOBuf::copyBuffer(
1146 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1147 AsyncSSLSocket::clientHelloParsingCallback(
1148 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
1153 auto parsedClientHello = sock->getClientHelloInfo();
1154 EXPECT_TRUE(parsedClientHello != nullptr);
1155 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1156 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1160 * Verify sucessful behavior of SSL certificate validation.
1162 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1163 EventBase eventBase;
1164 auto clientCtx = std::make_shared<SSLContext>();
1165 auto dfServerCtx = std::make_shared<SSLContext>();
1169 getctx(clientCtx, dfServerCtx);
1171 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1172 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1174 AsyncSSLSocket::UniquePtr clientSock(
1175 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1176 AsyncSSLSocket::UniquePtr serverSock(
1177 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1179 SSLHandshakeClient client(std::move(clientSock), true, true);
1180 clientCtx->loadTrustedCertificates(kTestCA);
1182 SSLHandshakeServer server(std::move(serverSock), true, true);
1186 EXPECT_TRUE(client.handshakeVerify_);
1187 EXPECT_TRUE(client.handshakeSuccess_);
1188 EXPECT_TRUE(!client.handshakeError_);
1189 EXPECT_LE(0, client.handshakeTime.count());
1190 EXPECT_TRUE(!server.handshakeVerify_);
1191 EXPECT_TRUE(server.handshakeSuccess_);
1192 EXPECT_TRUE(!server.handshakeError_);
1193 EXPECT_LE(0, server.handshakeTime.count());
1197 * Verify that the client's verification callback is able to fail SSL
1198 * connection establishment.
1200 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1201 EventBase eventBase;
1202 auto clientCtx = std::make_shared<SSLContext>();
1203 auto dfServerCtx = std::make_shared<SSLContext>();
1207 getctx(clientCtx, dfServerCtx);
1209 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1210 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1212 AsyncSSLSocket::UniquePtr clientSock(
1213 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1214 AsyncSSLSocket::UniquePtr serverSock(
1215 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1217 SSLHandshakeClient client(std::move(clientSock), true, false);
1218 clientCtx->loadTrustedCertificates(kTestCA);
1220 SSLHandshakeServer server(std::move(serverSock), true, true);
1224 EXPECT_TRUE(client.handshakeVerify_);
1225 EXPECT_TRUE(!client.handshakeSuccess_);
1226 EXPECT_TRUE(client.handshakeError_);
1227 EXPECT_LE(0, client.handshakeTime.count());
1228 EXPECT_TRUE(!server.handshakeVerify_);
1229 EXPECT_TRUE(!server.handshakeSuccess_);
1230 EXPECT_TRUE(server.handshakeError_);
1231 EXPECT_LE(0, server.handshakeTime.count());
1235 * Verify that the options in SSLContext can be overridden in
1236 * sslConnect/Accept.i.e specifying that no validation should be performed
1237 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1238 * the validation callback.
1240 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1241 EventBase eventBase;
1242 auto clientCtx = std::make_shared<SSLContext>();
1243 auto dfServerCtx = std::make_shared<SSLContext>();
1247 getctx(clientCtx, dfServerCtx);
1249 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1250 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1252 AsyncSSLSocket::UniquePtr clientSock(
1253 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1254 AsyncSSLSocket::UniquePtr serverSock(
1255 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1257 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1258 clientCtx->loadTrustedCertificates(kTestCA);
1260 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1264 EXPECT_TRUE(!client.handshakeVerify_);
1265 EXPECT_TRUE(client.handshakeSuccess_);
1266 EXPECT_TRUE(!client.handshakeError_);
1267 EXPECT_LE(0, client.handshakeTime.count());
1268 EXPECT_TRUE(!server.handshakeVerify_);
1269 EXPECT_TRUE(server.handshakeSuccess_);
1270 EXPECT_TRUE(!server.handshakeError_);
1271 EXPECT_LE(0, server.handshakeTime.count());
1275 * Verify that the options in SSLContext can be overridden in
1276 * sslConnect/Accept. Enable verification even if context says otherwise.
1277 * Test requireClientCert with client cert
1279 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1280 EventBase eventBase;
1281 auto clientCtx = std::make_shared<SSLContext>();
1282 auto serverCtx = std::make_shared<SSLContext>();
1283 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1284 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1285 serverCtx->loadPrivateKey(kTestKey);
1286 serverCtx->loadCertificate(kTestCert);
1287 serverCtx->loadTrustedCertificates(kTestCA);
1288 serverCtx->loadClientCAList(kTestCA);
1290 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1291 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1292 clientCtx->loadPrivateKey(kTestKey);
1293 clientCtx->loadCertificate(kTestCert);
1294 clientCtx->loadTrustedCertificates(kTestCA);
1299 AsyncSSLSocket::UniquePtr clientSock(
1300 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1301 AsyncSSLSocket::UniquePtr serverSock(
1302 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1304 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1305 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1309 EXPECT_TRUE(client.handshakeVerify_);
1310 EXPECT_TRUE(client.handshakeSuccess_);
1311 EXPECT_FALSE(client.handshakeError_);
1312 EXPECT_LE(0, client.handshakeTime.count());
1313 EXPECT_TRUE(server.handshakeVerify_);
1314 EXPECT_TRUE(server.handshakeSuccess_);
1315 EXPECT_FALSE(server.handshakeError_);
1316 EXPECT_LE(0, server.handshakeTime.count());
1320 * Verify that the client's verification callback is able to override
1321 * the preverification failure and allow a successful connection.
1323 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1324 EventBase eventBase;
1325 auto clientCtx = std::make_shared<SSLContext>();
1326 auto dfServerCtx = std::make_shared<SSLContext>();
1330 getctx(clientCtx, dfServerCtx);
1332 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1333 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1335 AsyncSSLSocket::UniquePtr clientSock(
1336 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1337 AsyncSSLSocket::UniquePtr serverSock(
1338 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1340 SSLHandshakeClient client(std::move(clientSock), false, true);
1341 SSLHandshakeServer server(std::move(serverSock), true, true);
1345 EXPECT_TRUE(client.handshakeVerify_);
1346 EXPECT_TRUE(client.handshakeSuccess_);
1347 EXPECT_TRUE(!client.handshakeError_);
1348 EXPECT_LE(0, client.handshakeTime.count());
1349 EXPECT_TRUE(!server.handshakeVerify_);
1350 EXPECT_TRUE(server.handshakeSuccess_);
1351 EXPECT_TRUE(!server.handshakeError_);
1352 EXPECT_LE(0, server.handshakeTime.count());
1356 * Verify that specifying that no validation should be performed allows an
1357 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1360 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1361 EventBase eventBase;
1362 auto clientCtx = std::make_shared<SSLContext>();
1363 auto dfServerCtx = std::make_shared<SSLContext>();
1367 getctx(clientCtx, dfServerCtx);
1369 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1370 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1372 AsyncSSLSocket::UniquePtr clientSock(
1373 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1374 AsyncSSLSocket::UniquePtr serverSock(
1375 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1377 SSLHandshakeClient client(std::move(clientSock), false, false);
1378 SSLHandshakeServer server(std::move(serverSock), false, false);
1382 EXPECT_TRUE(!client.handshakeVerify_);
1383 EXPECT_TRUE(client.handshakeSuccess_);
1384 EXPECT_TRUE(!client.handshakeError_);
1385 EXPECT_LE(0, client.handshakeTime.count());
1386 EXPECT_TRUE(!server.handshakeVerify_);
1387 EXPECT_TRUE(server.handshakeSuccess_);
1388 EXPECT_TRUE(!server.handshakeError_);
1389 EXPECT_LE(0, server.handshakeTime.count());
1393 * Test requireClientCert with client cert
1395 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1396 EventBase eventBase;
1397 auto clientCtx = std::make_shared<SSLContext>();
1398 auto serverCtx = std::make_shared<SSLContext>();
1399 serverCtx->setVerificationOption(
1400 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1401 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1402 serverCtx->loadPrivateKey(kTestKey);
1403 serverCtx->loadCertificate(kTestCert);
1404 serverCtx->loadTrustedCertificates(kTestCA);
1405 serverCtx->loadClientCAList(kTestCA);
1407 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1408 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1409 clientCtx->loadPrivateKey(kTestKey);
1410 clientCtx->loadCertificate(kTestCert);
1411 clientCtx->loadTrustedCertificates(kTestCA);
1416 AsyncSSLSocket::UniquePtr clientSock(
1417 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1418 AsyncSSLSocket::UniquePtr serverSock(
1419 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1421 SSLHandshakeClient client(std::move(clientSock), true, true);
1422 SSLHandshakeServer server(std::move(serverSock), true, true);
1426 EXPECT_TRUE(client.handshakeVerify_);
1427 EXPECT_TRUE(client.handshakeSuccess_);
1428 EXPECT_FALSE(client.handshakeError_);
1429 EXPECT_LE(0, client.handshakeTime.count());
1430 EXPECT_TRUE(server.handshakeVerify_);
1431 EXPECT_TRUE(server.handshakeSuccess_);
1432 EXPECT_FALSE(server.handshakeError_);
1433 EXPECT_LE(0, server.handshakeTime.count());
1438 * Test requireClientCert with no client cert
1440 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1441 EventBase eventBase;
1442 auto clientCtx = std::make_shared<SSLContext>();
1443 auto serverCtx = std::make_shared<SSLContext>();
1444 serverCtx->setVerificationOption(
1445 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1446 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1447 serverCtx->loadPrivateKey(kTestKey);
1448 serverCtx->loadCertificate(kTestCert);
1449 serverCtx->loadTrustedCertificates(kTestCA);
1450 serverCtx->loadClientCAList(kTestCA);
1451 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1452 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1457 AsyncSSLSocket::UniquePtr clientSock(
1458 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1459 AsyncSSLSocket::UniquePtr serverSock(
1460 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1462 SSLHandshakeClient client(std::move(clientSock), false, false);
1463 SSLHandshakeServer server(std::move(serverSock), false, false);
1467 EXPECT_FALSE(server.handshakeVerify_);
1468 EXPECT_FALSE(server.handshakeSuccess_);
1469 EXPECT_TRUE(server.handshakeError_);
1470 EXPECT_LE(0, client.handshakeTime.count());
1471 EXPECT_LE(0, server.handshakeTime.count());
1474 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1475 auto cert = getFileAsBuf(kTestCert);
1476 auto key = getFileAsBuf(kTestKey);
1478 ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1479 BIO_write(certBio.get(), cert.data(), cert.size());
1480 ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1481 BIO_write(keyBio.get(), key.data(), key.size());
1483 // Create SSL structs from buffers to get properties
1484 ssl::X509UniquePtr certStruct(
1485 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1486 ssl::EvpPkeyUniquePtr keyStruct(
1487 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1491 auto origCommonName = getCommonName(certStruct.get());
1492 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1493 certStruct = nullptr;
1494 keyStruct = nullptr;
1496 auto ctx = std::make_shared<SSLContext>();
1497 ctx->loadPrivateKeyFromBufferPEM(key);
1498 ctx->loadCertificateFromBufferPEM(cert);
1499 ctx->loadTrustedCertificates(kTestCA);
1501 ssl::SSLUniquePtr ssl(ctx->createSSL());
1503 auto newCert = SSL_get_certificate(ssl.get());
1504 auto newKey = SSL_get_privatekey(ssl.get());
1506 // Get properties from SSL struct
1507 auto newCommonName = getCommonName(newCert);
1508 auto newKeySize = EVP_PKEY_bits(newKey);
1510 // Check that the key and cert have the expected properties
1511 EXPECT_EQ(origCommonName, newCommonName);
1512 EXPECT_EQ(origKeySize, newKeySize);
1515 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1518 // Set up SSL context.
1519 auto sslContext = std::make_shared<SSLContext>();
1520 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1522 // create SSL socket
1523 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1525 EXPECT_EQ(1500, socket->getMinWriteSize());
1527 socket->setMinWriteSize(0);
1528 EXPECT_EQ(0, socket->getMinWriteSize());
1529 socket->setMinWriteSize(50000);
1530 EXPECT_EQ(50000, socket->getMinWriteSize());
1533 class ReadCallbackTerminator : public ReadCallback {
1535 ReadCallbackTerminator(EventBase* base, WriteCallbackBase *wcb)
1539 // Do not write data back, terminate the loop.
1540 void readDataAvailable(size_t len) noexcept override {
1541 std::cerr << "readDataAvailable, len " << len << std::endl;
1543 currentBuffer.length = len;
1545 buffers.push_back(currentBuffer);
1546 currentBuffer.reset();
1547 state = STATE_SUCCEEDED;
1549 socket_->setReadCB(nullptr);
1550 base_->terminateLoopSoon();
1558 * Test a full unencrypted codepath
1560 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1563 auto clientCtx = std::make_shared<folly::SSLContext>();
1564 auto serverCtx = std::make_shared<folly::SSLContext>();
1567 getctx(clientCtx, serverCtx);
1568 auto client = AsyncSSLSocket::newSocket(
1569 clientCtx, &base, fds[0], false, true);
1570 auto server = AsyncSSLSocket::newSocket(
1571 serverCtx, &base, fds[1], true, true);
1573 ReadCallbackTerminator readCallback(&base, nullptr);
1574 server->setReadCB(&readCallback);
1575 readCallback.setSocket(server);
1578 memset(buf, 'a', sizeof(buf));
1579 client->write(nullptr, buf, sizeof(buf));
1581 // Check that bytes are unencrypted
1583 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1586 EventBaseAborter eba(&base, 3000);
1589 EXPECT_EQ(1, readCallback.buffers.size());
1590 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1592 server->setReadCB(&readCallback);
1595 server->sslAccept(nullptr);
1596 client->sslConn(nullptr);
1598 // Do NOT wait for handshake, writing should be queued and happen after
1600 client->write(nullptr, buf, sizeof(buf));
1602 // Check that bytes are *not* unencrypted
1604 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1610 EXPECT_EQ(2, readCallback.buffers.size());
1611 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1614 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1615 // Start listening on a local port
1616 WriteCallbackBase writeCallback;
1617 WriteErrorCallback readCallback(&writeCallback);
1618 HandshakeCallback handshakeCallback(&readCallback,
1619 HandshakeCallback::EXPECT_ERROR);
1620 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1621 TestSSLServer server(&acceptCallback);
1623 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1625 uint8_t buf[3] = {0x16, 0x03, 0x01};
1626 socket->write(buf, sizeof(buf));
1627 socket->closeWithReset();
1629 handshakeCallback.waitForHandshake();
1631 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1632 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1635 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1636 // Start listening on a local port
1637 WriteCallbackBase writeCallback;
1638 WriteErrorCallback readCallback(&writeCallback);
1639 HandshakeCallback handshakeCallback(&readCallback,
1640 HandshakeCallback::EXPECT_ERROR);
1641 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1642 TestSSLServer server(&acceptCallback);
1644 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1646 uint8_t buf[3] = {0x16, 0x03, 0x01};
1647 socket->write(buf, sizeof(buf));
1650 handshakeCallback.waitForHandshake();
1652 handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
1653 EXPECT_NE(handshakeCallback.errorString_.find("EOF"), std::string::npos);
1656 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1657 // Start listening on a local port
1658 WriteCallbackBase writeCallback;
1659 WriteErrorCallback readCallback(&writeCallback);
1660 HandshakeCallback handshakeCallback(&readCallback,
1661 HandshakeCallback::EXPECT_ERROR);
1662 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1663 TestSSLServer server(&acceptCallback);
1665 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1667 uint8_t buf[256] = {0x16, 0x03};
1668 memset(buf + 2, 'a', sizeof(buf) - 2);
1669 socket->write(buf, sizeof(buf));
1672 handshakeCallback.waitForHandshake();
1673 EXPECT_NE(handshakeCallback.errorString_.find("SSL routines"),
1675 #if defined(OPENSSL_IS_BORINGSSL)
1677 handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
1680 EXPECT_NE(handshakeCallback.errorString_.find("unknown protocol"),
1685 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
1686 using folly::ssl::OpenSSLUtils;
1688 OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384");
1689 // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this
1690 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), "");
1691 // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected
1692 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), "");
1697 class MockAsyncTFOSSLSocket : public AsyncSSLSocket {
1699 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
1701 explicit MockAsyncTFOSSLSocket(
1702 std::shared_ptr<folly::SSLContext> sslCtx,
1704 : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {}
1706 MOCK_METHOD3(tfoSendMsg, ssize_t(int fd, struct msghdr* msg, int msg_flags));
1710 * Test connecting to, writing to, reading from, and closing the
1711 * connection to the SSL server with TFO.
1713 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
1714 // Start listening on a local port
1715 WriteCallbackBase writeCallback;
1716 ReadCallback readCallback(&writeCallback);
1717 HandshakeCallback handshakeCallback(&readCallback);
1718 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1719 TestSSLServer server(&acceptCallback, true);
1721 // Set up SSL context.
1722 auto sslContext = std::make_shared<SSLContext>();
1726 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1727 socket->enableTFO();
1731 std::array<uint8_t, 128> buf;
1732 memset(buf.data(), 'a', buf.size());
1733 socket->write(buf.data(), buf.size());
1736 std::array<uint8_t, 128> readbuf;
1737 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1738 EXPECT_EQ(bytesRead, 128);
1739 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1746 * Test connecting to, writing to, reading from, and closing the
1747 * connection to the SSL server with TFO.
1749 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
1750 // Start listening on a local port
1751 WriteCallbackBase writeCallback;
1752 ReadCallback readCallback(&writeCallback);
1753 HandshakeCallback handshakeCallback(&readCallback);
1754 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1755 TestSSLServer server(&acceptCallback, false);
1757 // Set up SSL context.
1758 auto sslContext = std::make_shared<SSLContext>();
1762 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1763 socket->enableTFO();
1767 std::array<uint8_t, 128> buf;
1768 memset(buf.data(), 'a', buf.size());
1769 socket->write(buf.data(), buf.size());
1772 std::array<uint8_t, 128> readbuf;
1773 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1774 EXPECT_EQ(bytesRead, 128);
1775 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1781 class ConnCallback : public AsyncSocket::ConnectCallback {
1783 virtual void connectSuccess() noexcept override {
1784 state = State::SUCCESS;
1787 virtual void connectErr(const AsyncSocketException& ex) noexcept override {
1788 state = State::ERROR;
1792 enum class State { WAITING, SUCCESS, ERROR };
1794 State state{State::WAITING};
1798 template <class Cardinality>
1799 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
1801 const SocketAddress& address,
1802 Cardinality cardinality) {
1803 // Set up SSL context.
1804 auto sslContext = std::make_shared<SSLContext>();
1807 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
1808 new MockAsyncTFOSSLSocket(sslContext, evb));
1809 socket->enableTFO();
1811 EXPECT_CALL(*socket, tfoSendMsg(_, _, _))
1813 .WillOnce(Invoke([&](int fd, struct msghdr*, int) {
1814 sockaddr_storage addr;
1815 auto len = address.getAddress(&addr);
1816 return connect(fd, (const struct sockaddr*)&addr, len);
1821 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
1822 // Start listening on a local port
1823 WriteCallbackBase writeCallback;
1824 ReadCallback readCallback(&writeCallback);
1825 HandshakeCallback handshakeCallback(&readCallback);
1826 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1827 TestSSLServer server(&acceptCallback, true);
1831 auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1);
1833 socket->connect(&ccb, server.getAddress(), 30);
1836 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
1838 evb.runInEventBaseThread([&] { socket->detachEventBase(); });
1841 BlockingSocket sock(std::move(socket));
1843 std::array<uint8_t, 128> buf;
1844 memset(buf.data(), 'a', buf.size());
1845 sock.write(buf.data(), buf.size());
1848 std::array<uint8_t, 128> readbuf;
1849 uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size());
1850 EXPECT_EQ(bytesRead, 128);
1851 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1857 #if !defined(OPENSSL_IS_BORINGSSL)
1858 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
1859 // Start listening on a local port
1860 ConnectTimeoutCallback acceptCallback;
1861 TestSSLServer server(&acceptCallback, true);
1863 // Set up SSL context.
1864 auto sslContext = std::make_shared<SSLContext>();
1868 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1869 socket->enableTFO();
1871 socket->open(std::chrono::milliseconds(20)), AsyncSocketException);
1875 #if !defined(OPENSSL_IS_BORINGSSL)
1876 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
1877 // Start listening on a local port
1878 ConnectTimeoutCallback acceptCallback;
1879 TestSSLServer server(&acceptCallback, true);
1883 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1885 // Set a short timeout
1886 socket->connect(&ccb, server.getAddress(), 1);
1889 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1893 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
1894 // Start listening on a local port
1895 EmptyReadCallback readCallback;
1896 HandshakeCallback handshakeCallback(
1897 &readCallback, HandshakeCallback::EXPECT_ERROR);
1898 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
1899 TestSSLServer server(&acceptCallback, true);
1903 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1905 socket->connect(&ccb, server.getAddress(), 100);
1908 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1909 EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out"));
1912 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
1913 // Start listening on a local port
1916 // Hopefully nothing is listening on this address
1917 SocketAddress addr("127.0.0.1", 65535);
1918 auto socket = setupSocketWithFallback(&evb, addr, AtMost(1));
1920 socket->connect(&ccb, addr, 100);
1923 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1924 EXPECT_THAT(ccb.error, testing::HasSubstr("refused"));
1927 TEST(AsyncSSLSocketTest, TestPreReceivedData) {
1928 EventBase clientEventBase;
1929 EventBase serverEventBase;
1930 auto clientCtx = std::make_shared<SSLContext>();
1931 auto dfServerCtx = std::make_shared<SSLContext>();
1932 std::array<int, 2> fds;
1934 getctx(clientCtx, dfServerCtx);
1936 AsyncSSLSocket::UniquePtr clientSockPtr(
1937 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
1938 AsyncSSLSocket::UniquePtr serverSockPtr(
1939 new AsyncSSLSocket(dfServerCtx, &serverEventBase, fds[1], true));
1940 auto clientSock = clientSockPtr.get();
1941 auto serverSock = serverSockPtr.get();
1942 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
1944 // Steal some data from the server.
1945 clientEventBase.loopOnce();
1946 std::array<uint8_t, 10> buf;
1947 recv(fds[1], buf.data(), buf.size(), 0);
1949 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
1950 SSLHandshakeServer server(std::move(serverSockPtr), true, true);
1951 while (!client.handshakeSuccess_ && !client.handshakeError_) {
1952 serverEventBase.loopOnce();
1953 clientEventBase.loopOnce();
1956 EXPECT_TRUE(client.handshakeSuccess_);
1957 EXPECT_TRUE(server.handshakeSuccess_);
1959 serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
1962 TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) {
1963 EventBase clientEventBase;
1964 EventBase serverEventBase;
1965 auto clientCtx = std::make_shared<SSLContext>();
1966 auto dfServerCtx = std::make_shared<SSLContext>();
1967 std::array<int, 2> fds;
1969 getctx(clientCtx, dfServerCtx);
1971 AsyncSSLSocket::UniquePtr clientSockPtr(
1972 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
1973 AsyncSocket::UniquePtr serverSockPtr(
1974 new AsyncSocket(&serverEventBase, fds[1]));
1975 auto clientSock = clientSockPtr.get();
1976 auto serverSock = serverSockPtr.get();
1977 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
1979 // Steal some data from the server.
1980 clientEventBase.loopOnce();
1981 std::array<uint8_t, 10> buf;
1982 recv(fds[1], buf.data(), buf.size(), 0);
1983 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
1984 AsyncSSLSocket::UniquePtr serverSSLSockPtr(
1985 new AsyncSSLSocket(dfServerCtx, std::move(serverSockPtr), true));
1986 auto serverSSLSock = serverSSLSockPtr.get();
1987 SSLHandshakeServer server(std::move(serverSSLSockPtr), true, true);
1988 while (!client.handshakeSuccess_ && !client.handshakeError_) {
1989 serverEventBase.loopOnce();
1990 clientEventBase.loopOnce();
1993 EXPECT_TRUE(client.handshakeSuccess_);
1994 EXPECT_TRUE(server.handshakeSuccess_);
1996 serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2000 * Test overriding the flags passed to "sendmsg()" system call,
2001 * and verifying that write requests fail properly.
2003 TEST(AsyncSSLSocketTest, SendMsgParamsCallback) {
2004 // Start listening on a local port
2005 SendMsgFlagsCallback msgCallback;
2006 ExpectWriteErrorCallback writeCallback(&msgCallback);
2007 ReadCallback readCallback(&writeCallback);
2008 HandshakeCallback handshakeCallback(&readCallback);
2009 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2010 TestSSLServer server(&acceptCallback);
2012 // Set up SSL context.
2013 auto sslContext = std::make_shared<SSLContext>();
2014 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2017 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
2021 // Setting flags to "-1" to trigger "Invalid argument" error
2022 // on attempt to use this flags in sendmsg() system call.
2023 msgCallback.resetFlags(-1);
2026 std::vector<uint8_t> buf(128, 'a');
2027 ASSERT_EQ(socket->write(buf.data(), buf.size()), buf.size());
2032 cerr << "SendMsgParamsCallback test completed" << endl;
2037 * Test connecting to, writing to, reading from, and closing the
2038 * connection to the SSL server.
2040 TEST(AsyncSSLSocketTest, SendMsgDataCallback) {
2041 // This test requires Linux kernel v4.6 or later
2042 struct utsname s_uname;
2043 memset(&s_uname, 0, sizeof(s_uname));
2044 ASSERT_EQ(uname(&s_uname), 0);
2046 folly::StringPiece extra;
2047 if (folly::split<false>(
2048 '.', std::string(s_uname.release) + ".", major, minor, extra)) {
2049 if (major < 4 || (major == 4 && minor < 6)) {
2050 LOG(INFO) << "Kernel version: 4.6 and newer required for this test ("
2051 << "kernel ver. " << s_uname.release << " detected).";
2056 // Start listening on a local port
2057 SendMsgDataCallback msgCallback;
2058 WriteCheckTimestampCallback writeCallback(&msgCallback);
2059 ReadCallback readCallback(&writeCallback);
2060 HandshakeCallback handshakeCallback(&readCallback);
2061 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2062 TestSSLServer server(&acceptCallback);
2064 // Set up SSL context.
2065 auto sslContext = std::make_shared<SSLContext>();
2066 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2069 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
2073 // Adding MSG_EOR flag to the message flags - it'll trigger
2074 // timestamp generation for the last byte of the message.
2075 msgCallback.resetFlags(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_EOR);
2077 // Init ancillary data buffer to trigger timestamp notification
2079 uint8_t ctrl_data[CMSG_LEN(sizeof(uint32_t))];
2080 struct cmsghdr cmsg;
2082 u.cmsg.cmsg_level = SOL_SOCKET;
2083 u.cmsg.cmsg_type = SO_TIMESTAMPING;
2084 u.cmsg.cmsg_len = CMSG_LEN(sizeof(uint32_t));
2086 SOF_TIMESTAMPING_TX_SCHED |
2087 SOF_TIMESTAMPING_TX_SOFTWARE |
2088 SOF_TIMESTAMPING_TX_ACK;
2089 memcpy(CMSG_DATA(&u.cmsg), &flags, sizeof(uint32_t));
2090 std::vector<char> ctrl(CMSG_LEN(sizeof(uint32_t)));
2091 memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(sizeof(uint32_t)));
2092 msgCallback.resetData(std::move(ctrl));
2095 std::vector<uint8_t> buf(128, 'a');
2096 socket->write(buf.data(), buf.size());
2099 std::vector<uint8_t> readbuf(buf.size());
2100 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
2101 EXPECT_EQ(bytesRead, buf.size());
2102 EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin()));
2104 writeCallback.checkForTimestampNotifications();
2109 cerr << "SendMsgDataCallback test completed" << endl;
2111 #endif // MSG_ERRQUEUE
2118 ///////////////////////////////////////////////////////////////////////////
2119 // init_unit_test_suite
2120 ///////////////////////////////////////////////////////////////////////////
2122 struct Initializer {
2124 signal(SIGPIPE, SIG_IGN);
2127 Initializer initializer;