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
73 << " in non-blocking mode: " << strerror(errno);
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(clientCtx, eventBase, fds[0], false));
98 serverSock->reset(new AsyncSSLSocket(serverCtx, eventBase, fds[1], true));
100 // (*clientSock)->setSendTimeout(100);
101 // (*serverSock)->setSendTimeout(100);
104 // client protocol filters
105 bool clientProtoFilterPickPony(
106 unsigned char** client,
107 unsigned int* client_len,
108 const unsigned char*,
110 // the protocol string in length prefixed byte string. the
111 // length byte is not included in the length
112 static unsigned char p[7] = {6, 'p', 'o', 'n', 'i', 'e', 's'};
118 bool clientProtoFilterPickNone(
121 const unsigned char*,
126 std::string getFileAsBuf(const char* fileName) {
128 folly::readFile(fileName, buffer);
132 std::string getCommonName(X509* cert) {
133 X509_NAME* subject = X509_get_subject_name(cert);
135 cn.resize(ub_common_name);
136 X509_NAME_get_text_by_NID(
137 subject, NID_commonName, const_cast<char*>(cn.data()), ub_common_name);
142 * Test connecting to, writing to, reading from, and closing the
143 * connection to the SSL server.
145 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
146 // Start listening on a local port
147 WriteCallbackBase writeCallback;
148 ReadCallback readCallback(&writeCallback);
149 HandshakeCallback handshakeCallback(&readCallback);
150 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
151 TestSSLServer server(&acceptCallback);
153 // Set up SSL context.
154 std::shared_ptr<SSLContext> sslContext(new SSLContext());
155 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
156 // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
157 // sslContext->authenticate(true, false);
161 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
162 socket->open(std::chrono::milliseconds(10000));
166 memset(buf, 'a', sizeof(buf));
167 socket->write(buf, sizeof(buf));
170 uint8_t readbuf[128];
171 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
172 EXPECT_EQ(bytesRead, 128);
173 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
178 cerr << "ConnectWriteReadClose test completed" << endl;
179 EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000);
183 * Test reading after server close.
185 TEST(AsyncSSLSocketTest, ReadAfterClose) {
186 // Start listening on a local port
187 WriteCallbackBase writeCallback;
188 ReadEOFCallback readCallback(&writeCallback);
189 HandshakeCallback handshakeCallback(&readCallback);
190 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
191 auto server = std::make_unique<TestSSLServer>(&acceptCallback);
193 // Set up SSL context.
194 auto sslContext = std::make_shared<SSLContext>();
195 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
198 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
201 // This should trigger an EOF on the client.
202 auto evb = handshakeCallback.getSocket()->getEventBase();
203 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
204 std::array<uint8_t, 128> readbuf;
205 auto bytesRead = socket->read(readbuf.data(), readbuf.size());
206 EXPECT_EQ(0, bytesRead);
210 * Test bad renegotiation
212 #if !defined(OPENSSL_IS_BORINGSSL)
213 TEST(AsyncSSLSocketTest, Renegotiate) {
215 auto clientCtx = std::make_shared<SSLContext>();
216 auto dfServerCtx = std::make_shared<SSLContext>();
217 std::array<int, 2> fds;
219 getctx(clientCtx, dfServerCtx);
221 AsyncSSLSocket::UniquePtr clientSock(
222 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
223 AsyncSSLSocket::UniquePtr serverSock(
224 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
225 SSLHandshakeClient client(std::move(clientSock), true, true);
226 RenegotiatingServer server(std::move(serverSock));
228 while (!client.handshakeSuccess_ && !client.handshakeError_) {
229 eventBase.loopOnce();
232 ASSERT_TRUE(client.handshakeSuccess_);
234 auto sslSock = std::move(client).moveSocket();
235 sslSock->detachEventBase();
236 // This is nasty, however we don't want to add support for
237 // renegotiation in AsyncSSLSocket.
238 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
240 auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
242 std::thread t([&]() { eventBase.loopForever(); });
244 // Trigger the renegotiation.
245 std::array<uint8_t, 128> buf;
246 memset(buf.data(), 'a', buf.size());
248 socket->write(buf.data(), buf.size());
249 } catch (AsyncSocketException& e) {
250 LOG(INFO) << "client got error " << e.what();
252 eventBase.terminateLoopSoon();
256 ASSERT_TRUE(server.renegotiationError_);
261 * Negative test for handshakeError().
263 TEST(AsyncSSLSocketTest, HandshakeError) {
264 // Start listening on a local port
265 WriteCallbackBase writeCallback;
266 WriteErrorCallback readCallback(&writeCallback);
267 HandshakeCallback handshakeCallback(&readCallback);
268 HandshakeErrorCallback acceptCallback(&handshakeCallback);
269 TestSSLServer server(&acceptCallback);
271 // Set up SSL context.
272 std::shared_ptr<SSLContext> sslContext(new SSLContext());
273 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
277 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
283 uint8_t readbuf[128];
284 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
285 LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
286 } catch (AsyncSocketException&) {
293 cerr << "HandshakeError test completed" << endl;
297 * Negative test for readError().
299 TEST(AsyncSSLSocketTest, ReadError) {
300 // Start listening on a local port
301 WriteCallbackBase writeCallback;
302 ReadErrorCallback readCallback(&writeCallback);
303 HandshakeCallback handshakeCallback(&readCallback);
304 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
305 TestSSLServer server(&acceptCallback);
307 // Set up SSL context.
308 std::shared_ptr<SSLContext> sslContext(new SSLContext());
309 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
313 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
316 // write something to trigger ssl handshake
318 memset(buf, 'a', sizeof(buf));
319 socket->write(buf, sizeof(buf));
322 cerr << "ReadError test completed" << endl;
326 * Negative test for writeError().
328 TEST(AsyncSSLSocketTest, WriteError) {
329 // Start listening on a local port
330 WriteCallbackBase writeCallback;
331 WriteErrorCallback readCallback(&writeCallback);
332 HandshakeCallback handshakeCallback(&readCallback);
333 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
334 TestSSLServer server(&acceptCallback);
336 // Set up SSL context.
337 std::shared_ptr<SSLContext> sslContext(new SSLContext());
338 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
342 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
345 // write something to trigger ssl handshake
347 memset(buf, 'a', sizeof(buf));
348 socket->write(buf, sizeof(buf));
351 cerr << "WriteError test completed" << endl;
355 * Test a socket with TCP_NODELAY unset.
357 TEST(AsyncSSLSocketTest, SocketWithDelay) {
358 // Start listening on a local port
359 WriteCallbackBase writeCallback;
360 ReadCallback readCallback(&writeCallback);
361 HandshakeCallback handshakeCallback(&readCallback);
362 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
363 TestSSLServer server(&acceptCallback);
365 // Set up SSL context.
366 std::shared_ptr<SSLContext> sslContext(new SSLContext());
367 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
371 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
376 memset(buf, 'a', sizeof(buf));
377 socket->write(buf, sizeof(buf));
380 uint8_t readbuf[128];
381 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
382 EXPECT_EQ(bytesRead, 128);
383 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
388 cerr << "SocketWithDelay test completed" << endl;
391 using NextProtocolTypePair =
392 std::pair<SSLContext::NextProtocolType, SSLContext::NextProtocolType>;
394 class NextProtocolTest : public testing::TestWithParam<NextProtocolTypePair> {
395 // For matching protos
397 void SetUp() override {
398 getctx(clientCtx, serverCtx);
401 void connect(bool unset = false) {
405 // unsetting NPN for any of [client, server] is enough to make NPN not
407 clientCtx->unsetNextProtocols();
410 AsyncSSLSocket::UniquePtr clientSock(
411 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
412 AsyncSSLSocket::UniquePtr serverSock(
413 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
414 client = std::make_unique<NpnClient>(std::move(clientSock));
415 server = std::make_unique<NpnServer>(std::move(serverSock));
420 void expectProtocol(const std::string& proto) {
421 expectHandshakeSuccess();
422 EXPECT_NE(client->nextProtoLength, 0);
423 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
425 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
427 string selected((const char*)client->nextProto, client->nextProtoLength);
428 EXPECT_EQ(proto, selected);
431 void expectNoProtocol() {
432 expectHandshakeSuccess();
433 EXPECT_EQ(client->nextProtoLength, 0);
434 EXPECT_EQ(server->nextProtoLength, 0);
435 EXPECT_EQ(client->nextProto, nullptr);
436 EXPECT_EQ(server->nextProto, nullptr);
439 void expectProtocolType() {
440 expectHandshakeSuccess();
441 if (GetParam().first == SSLContext::NextProtocolType::ANY &&
442 GetParam().second == SSLContext::NextProtocolType::ANY) {
443 EXPECT_EQ(client->protocolType, server->protocolType);
444 } else if (GetParam().first == SSLContext::NextProtocolType::ANY ||
445 GetParam().second == SSLContext::NextProtocolType::ANY) {
446 // Well not much we can say
448 expectProtocolType(GetParam());
452 void expectProtocolType(NextProtocolTypePair expected) {
453 expectHandshakeSuccess();
454 EXPECT_EQ(client->protocolType, expected.first);
455 EXPECT_EQ(server->protocolType, expected.second);
458 void expectHandshakeSuccess() {
459 EXPECT_FALSE(client->except.hasValue())
460 << "client handshake error: " << client->except->what();
461 EXPECT_FALSE(server->except.hasValue())
462 << "server handshake error: " << server->except->what();
465 void expectHandshakeError() {
466 EXPECT_TRUE(client->except.hasValue())
467 << "Expected client handshake error!";
468 EXPECT_TRUE(server->except.hasValue())
469 << "Expected server handshake error!";
473 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
474 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
476 std::unique_ptr<NpnClient> client;
477 std::unique_ptr<NpnServer> server;
480 class NextProtocolTLSExtTest : public NextProtocolTest {
481 // For extended TLS protos
484 class NextProtocolNPNOnlyTest : public NextProtocolTest {
485 // For mismatching protos
488 class NextProtocolMismatchTest : public NextProtocolTest {
489 // For mismatching protos
492 TEST_P(NextProtocolTest, NpnTestOverlap) {
493 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
494 serverCtx->setAdvertisedNextProtocols(
495 {"foo", "bar", "baz"}, GetParam().second);
499 expectProtocol("baz");
500 expectProtocolType();
503 TEST_P(NextProtocolTest, NpnTestUnset) {
504 // Identical to above test, except that we want unset NPN before
506 clientCtx->setAdvertisedNextProtocols({"blub", "baz"}, GetParam().first);
507 serverCtx->setAdvertisedNextProtocols(
508 {"foo", "bar", "baz"}, GetParam().second);
510 connect(true /* unset */);
512 // if alpn negotiation fails, type will appear as npn
514 EXPECT_EQ(client->protocolType, server->protocolType);
517 TEST_P(NextProtocolMismatchTest, NpnAlpnTestNoOverlap) {
518 clientCtx->setAdvertisedNextProtocols({"foo"}, GetParam().first);
519 serverCtx->setAdvertisedNextProtocols(
520 {"foo", "bar", "baz"}, GetParam().second);
526 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
529 // Note: the behavior changed in the ANY/ANY case in OpenSSL 1.0.2h, this test
530 // will fail on 1.0.2 before that.
531 TEST_P(NextProtocolTest, NpnTestNoOverlap) {
532 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
533 serverCtx->setAdvertisedNextProtocols(
534 {"foo", "bar", "baz"}, GetParam().second);
537 if (GetParam().first == SSLContext::NextProtocolType::ALPN ||
538 GetParam().second == SSLContext::NextProtocolType::ALPN) {
539 // This is arguably incorrect behavior since RFC7301 states an ALPN protocol
540 // mismatch should result in a fatal alert, but this is the current behavior
541 // on all OpenSSL versions/variants, and we want to know if it changes.
544 #if FOLLY_OPENSSL_IS_110 || defined(OPENSSL_IS_BORINGSSL)
546 GetParam().first == SSLContext::NextProtocolType::ANY &&
547 GetParam().second == SSLContext::NextProtocolType::ANY) {
548 #if FOLLY_OPENSSL_IS_110
549 // OpenSSL 1.1.0 sends a fatal alert on mismatch, which is probavbly the
550 // correct behavior per RFC7301
551 expectHandshakeError();
553 // BoringSSL also doesn't fatal on mismatch but behaves slightly differently
554 // from OpenSSL 1.0.2h+ - it doesn't select a protocol if both ends support
561 expectProtocol("blub");
563 {SSLContext::NextProtocolType::NPN, SSLContext::NextProtocolType::NPN});
567 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterHit) {
568 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
569 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickPony);
570 serverCtx->setAdvertisedNextProtocols(
571 {"foo", "bar", "baz"}, GetParam().second);
575 expectProtocol("ponies");
576 expectProtocolType();
579 TEST_P(NextProtocolNPNOnlyTest, NpnTestClientProtoFilterMiss) {
580 clientCtx->setAdvertisedNextProtocols({"blub"}, GetParam().first);
581 clientCtx->setClientProtocolFilterCallback(clientProtoFilterPickNone);
582 serverCtx->setAdvertisedNextProtocols(
583 {"foo", "bar", "baz"}, GetParam().second);
587 expectProtocol("blub");
588 expectProtocolType();
591 TEST_P(NextProtocolTest, RandomizedNpnTest) {
592 // Probability that this test will fail is 2^-64, which could be considered
594 const int kTries = 64;
596 clientCtx->setAdvertisedNextProtocols(
597 {"foo", "bar", "baz"}, GetParam().first);
598 serverCtx->setRandomizedAdvertisedNextProtocols(
599 {{1, {"foo"}}, {1, {"bar"}}}, GetParam().second);
601 std::set<string> selectedProtocols;
602 for (int i = 0; i < kTries; ++i) {
605 EXPECT_NE(client->nextProtoLength, 0);
606 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
608 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
610 string selected((const char*)client->nextProto, client->nextProtoLength);
611 selectedProtocols.insert(selected);
612 expectProtocolType();
614 EXPECT_EQ(selectedProtocols.size(), 2);
617 INSTANTIATE_TEST_CASE_P(
621 NextProtocolTypePair(
622 SSLContext::NextProtocolType::NPN,
623 SSLContext::NextProtocolType::NPN),
624 NextProtocolTypePair(
625 SSLContext::NextProtocolType::NPN,
626 SSLContext::NextProtocolType::ANY),
627 NextProtocolTypePair(
628 SSLContext::NextProtocolType::ANY,
629 SSLContext::NextProtocolType::ANY)));
631 #if FOLLY_OPENSSL_HAS_ALPN
632 INSTANTIATE_TEST_CASE_P(
634 NextProtocolTLSExtTest,
636 NextProtocolTypePair(
637 SSLContext::NextProtocolType::ALPN,
638 SSLContext::NextProtocolType::ALPN),
639 NextProtocolTypePair(
640 SSLContext::NextProtocolType::ALPN,
641 SSLContext::NextProtocolType::ANY),
642 NextProtocolTypePair(
643 SSLContext::NextProtocolType::ANY,
644 SSLContext::NextProtocolType::ALPN)));
647 INSTANTIATE_TEST_CASE_P(
649 NextProtocolNPNOnlyTest,
650 ::testing::Values(NextProtocolTypePair(
651 SSLContext::NextProtocolType::NPN,
652 SSLContext::NextProtocolType::NPN)));
654 #if FOLLY_OPENSSL_HAS_ALPN
655 INSTANTIATE_TEST_CASE_P(
657 NextProtocolMismatchTest,
659 NextProtocolTypePair(
660 SSLContext::NextProtocolType::NPN,
661 SSLContext::NextProtocolType::ALPN),
662 NextProtocolTypePair(
663 SSLContext::NextProtocolType::ALPN,
664 SSLContext::NextProtocolType::NPN)));
667 #ifndef OPENSSL_NO_TLSEXT
669 * 1. Client sends TLSEXT_HOSTNAME in client hello.
670 * 2. Server found a match SSL_CTX and use this SSL_CTX to
671 * continue the SSL handshake.
672 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
674 TEST(AsyncSSLSocketTest, SNITestMatch) {
676 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
677 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
678 // Use the same SSLContext to continue the handshake after
679 // tlsext_hostname match.
680 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
681 const std::string serverName("xyz.newdev.facebook.com");
684 getctx(clientCtx, dfServerCtx);
686 AsyncSSLSocket::UniquePtr clientSock(
687 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
688 AsyncSSLSocket::UniquePtr serverSock(
689 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
690 SNIClient client(std::move(clientSock));
692 std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
696 EXPECT_TRUE(client.serverNameMatch);
697 EXPECT_TRUE(server.serverNameMatch);
701 * 1. Client sends TLSEXT_HOSTNAME in client hello.
702 * 2. Server cannot find a matching SSL_CTX and continue to use
703 * the current SSL_CTX to do the handshake.
704 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
706 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
708 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
709 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
710 // Use the same SSLContext to continue the handshake after
711 // tlsext_hostname match.
712 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
713 const std::string clientRequestingServerName("foo.com");
714 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
718 getctx(clientCtx, dfServerCtx);
720 AsyncSSLSocket::UniquePtr clientSock(new AsyncSSLSocket(
721 clientCtx, &eventBase, fds[0], clientRequestingServerName));
722 AsyncSSLSocket::UniquePtr serverSock(
723 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
724 SNIClient client(std::move(clientSock));
726 std::move(serverSock),
729 serverExpectedServerName);
733 EXPECT_TRUE(!client.serverNameMatch);
734 EXPECT_TRUE(!server.serverNameMatch);
737 * 1. Client sends TLSEXT_HOSTNAME in client hello.
738 * 2. We then change the serverName.
739 * 3. We expect that we get 'false' as the result for serNameMatch.
742 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
744 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
745 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
746 // Use the same SSLContext to continue the handshake after
747 // tlsext_hostname match.
748 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
749 const std::string serverName("xyz.newdev.facebook.com");
752 getctx(clientCtx, dfServerCtx);
754 AsyncSSLSocket::UniquePtr clientSock(
755 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
756 // Change the server name
757 std::string newName("new.com");
758 clientSock->setServerName(newName);
759 AsyncSSLSocket::UniquePtr serverSock(
760 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
761 SNIClient client(std::move(clientSock));
763 std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
767 EXPECT_TRUE(!client.serverNameMatch);
771 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
772 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
774 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
776 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
777 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
778 // Use the same SSLContext to continue the handshake after
779 // tlsext_hostname match.
780 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
781 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
785 getctx(clientCtx, dfServerCtx);
787 AsyncSSLSocket::UniquePtr clientSock(
788 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
789 AsyncSSLSocket::UniquePtr serverSock(
790 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
791 SNIClient client(std::move(clientSock));
793 std::move(serverSock),
796 serverExpectedServerName);
800 EXPECT_TRUE(!client.serverNameMatch);
801 EXPECT_TRUE(!server.serverNameMatch);
806 * Test SSL client socket
808 TEST(AsyncSSLSocketTest, SSLClientTest) {
809 // Start listening on a local port
810 WriteCallbackBase writeCallback;
811 ReadCallback readCallback(&writeCallback);
812 HandshakeCallback handshakeCallback(&readCallback);
813 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
814 TestSSLServer server(&acceptCallback);
818 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
821 EventBaseAborter eba(&eventBase, 3000);
824 EXPECT_EQ(client->getMiss(), 1);
825 EXPECT_EQ(client->getHit(), 0);
827 cerr << "SSLClientTest test completed" << endl;
831 * Test SSL client socket session re-use
833 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
834 // Start listening on a local port
835 WriteCallbackBase writeCallback;
836 ReadCallback readCallback(&writeCallback);
837 HandshakeCallback handshakeCallback(&readCallback);
838 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
839 TestSSLServer server(&acceptCallback);
844 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
847 EventBaseAborter eba(&eventBase, 3000);
850 EXPECT_EQ(client->getMiss(), 1);
851 EXPECT_EQ(client->getHit(), 9);
853 cerr << "SSLClientTestReuse test completed" << endl;
857 * Test SSL client socket timeout
859 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
860 // Start listening on a local port
861 EmptyReadCallback readCallback;
862 HandshakeCallback handshakeCallback(
863 &readCallback, HandshakeCallback::EXPECT_ERROR);
864 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
865 TestSSLServer server(&acceptCallback);
870 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
871 client->connect(true /* write before connect completes */);
872 EventBaseAborter eba(&eventBase, 3000);
876 // This is checking that the connectError callback precedes any queued
877 // writeError callbacks. This matches AsyncSocket's behavior
878 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
879 EXPECT_EQ(client->getErrors(), 1);
880 EXPECT_EQ(client->getMiss(), 0);
881 EXPECT_EQ(client->getHit(), 0);
883 cerr << "SSLClientTimeoutTest test completed" << endl;
886 // The next 3 tests need an FB-only extension, and will fail without it
887 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP
889 * Test SSL server async cache
891 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
892 // Start listening on a local port
893 WriteCallbackBase writeCallback;
894 ReadCallback readCallback(&writeCallback);
895 HandshakeCallback handshakeCallback(&readCallback);
896 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
897 TestSSLAsyncCacheServer server(&acceptCallback);
902 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10, 500);
905 EventBaseAborter eba(&eventBase, 3000);
908 EXPECT_EQ(server.getAsyncCallbacks(), 18);
909 EXPECT_EQ(server.getAsyncLookups(), 9);
910 EXPECT_EQ(client->getMiss(), 10);
911 EXPECT_EQ(client->getHit(), 0);
913 cerr << "SSLServerAsyncCacheTest test completed" << endl;
917 * Test SSL server accept timeout with cache path
919 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
920 // Start listening on a local port
921 WriteCallbackBase writeCallback;
922 ReadCallback readCallback(&writeCallback);
923 HandshakeCallback handshakeCallback(&readCallback);
924 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
925 TestSSLAsyncCacheServer server(&acceptCallback);
929 // only do a TCP connect
930 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
931 sock->connect(nullptr, server.getAddress());
933 EmptyReadCallback clientReadCallback;
934 clientReadCallback.tcpSocket_ = sock;
935 sock->setReadCB(&clientReadCallback);
937 EventBaseAborter eba(&eventBase, 3000);
940 EXPECT_EQ(readCallback.state, STATE_WAITING);
942 cerr << "SSLServerTimeoutTest test completed" << endl;
946 * Test SSL server accept timeout with cache path
948 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
949 // Start listening on a local port
950 WriteCallbackBase writeCallback;
951 ReadCallback readCallback(&writeCallback);
952 HandshakeCallback handshakeCallback(&readCallback);
953 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
954 TestSSLAsyncCacheServer server(&acceptCallback);
958 auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2);
961 EventBaseAborter eba(&eventBase, 3000);
964 EXPECT_EQ(server.getAsyncCallbacks(), 1);
965 EXPECT_EQ(server.getAsyncLookups(), 1);
966 EXPECT_EQ(client->getErrors(), 1);
967 EXPECT_EQ(client->getMiss(), 1);
968 EXPECT_EQ(client->getHit(), 0);
970 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
974 * Test SSL server accept timeout with cache path
976 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
977 // Start listening on a local port
978 WriteCallbackBase writeCallback;
979 ReadCallback readCallback(&writeCallback);
980 HandshakeCallback handshakeCallback(
981 &readCallback, HandshakeCallback::EXPECT_ERROR);
982 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
983 TestSSLAsyncCacheServer server(&acceptCallback, 500);
988 std::make_shared<SSLClient>(&eventBase, server.getAddress(), 2, 100);
991 EventBaseAborter eba(&eventBase, 3000);
994 server.getEventBase().runInEventBaseThread(
995 [&handshakeCallback] { handshakeCallback.closeSocket(); });
996 // give time for the cache lookup to come back and find it closed
997 handshakeCallback.waitForHandshake();
999 EXPECT_EQ(server.getAsyncCallbacks(), 1);
1000 EXPECT_EQ(server.getAsyncLookups(), 1);
1001 EXPECT_EQ(client->getErrors(), 1);
1002 EXPECT_EQ(client->getMiss(), 1);
1003 EXPECT_EQ(client->getHit(), 0);
1005 cerr << "SSLServerCacheCloseTest test completed" << endl;
1007 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP
1010 * Verify Client Ciphers obtained using SSL MSG Callback.
1012 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
1013 EventBase eventBase;
1014 auto clientCtx = std::make_shared<SSLContext>();
1015 auto serverCtx = std::make_shared<SSLContext>();
1016 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1017 serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
1018 serverCtx->loadPrivateKey(kTestKey);
1019 serverCtx->loadCertificate(kTestCert);
1020 serverCtx->loadTrustedCertificates(kTestCA);
1021 serverCtx->loadClientCAList(kTestCA);
1023 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1024 clientCtx->ciphers("AES256-SHA:AES128-SHA");
1025 clientCtx->loadPrivateKey(kTestKey);
1026 clientCtx->loadCertificate(kTestCert);
1027 clientCtx->loadTrustedCertificates(kTestCA);
1032 AsyncSSLSocket::UniquePtr clientSock(
1033 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1034 AsyncSSLSocket::UniquePtr serverSock(
1035 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1037 SSLHandshakeClient client(std::move(clientSock), true, true);
1038 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
1042 #if defined(OPENSSL_IS_BORINGSSL)
1043 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
1045 EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
1047 EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
1048 EXPECT_TRUE(client.handshakeVerify_);
1049 EXPECT_TRUE(client.handshakeSuccess_);
1050 EXPECT_TRUE(!client.handshakeError_);
1051 EXPECT_TRUE(server.handshakeVerify_);
1052 EXPECT_TRUE(server.handshakeSuccess_);
1053 EXPECT_TRUE(!server.handshakeError_);
1056 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1057 EventBase eventBase;
1058 auto ctx = std::make_shared<SSLContext>();
1064 uint8_t majorVersion = 18;
1065 uint8_t minorVersion = 25;
1067 // Create callback buf
1068 auto buf = IOBuf::create(bufLen);
1069 buf->append(bufLen);
1070 folly::io::RWPrivateCursor cursor(buf.get());
1071 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1072 cursor.write<uint16_t>(0);
1073 cursor.write<uint8_t>(38);
1074 cursor.write<uint8_t>(majorVersion);
1075 cursor.write<uint8_t>(minorVersion);
1077 cursor.write<uint32_t>(0);
1079 SSL* ssl = ctx->createSSL();
1083 AsyncSSLSocket::UniquePtr sock(
1084 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1085 sock->enableClientHelloParsing();
1087 // Test client hello parsing in one packet
1088 AsyncSSLSocket::clientHelloParsingCallback(
1089 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1092 auto parsedClientHello = sock->getClientHelloInfo();
1093 EXPECT_TRUE(parsedClientHello != nullptr);
1094 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1095 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1098 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1099 EventBase eventBase;
1100 auto ctx = std::make_shared<SSLContext>();
1106 uint8_t majorVersion = 18;
1107 uint8_t minorVersion = 25;
1109 // Create callback buf
1110 auto buf = IOBuf::create(bufLen);
1111 buf->append(bufLen);
1112 folly::io::RWPrivateCursor cursor(buf.get());
1113 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1114 cursor.write<uint16_t>(0);
1115 cursor.write<uint8_t>(38);
1116 cursor.write<uint8_t>(majorVersion);
1117 cursor.write<uint8_t>(minorVersion);
1119 cursor.write<uint32_t>(0);
1121 SSL* ssl = ctx->createSSL();
1125 AsyncSSLSocket::UniquePtr sock(
1126 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1127 sock->enableClientHelloParsing();
1129 // Test parsing with two packets with first packet size < 3
1130 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1131 AsyncSSLSocket::clientHelloParsingCallback(
1140 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1141 AsyncSSLSocket::clientHelloParsingCallback(
1151 auto parsedClientHello = sock->getClientHelloInfo();
1152 EXPECT_TRUE(parsedClientHello != nullptr);
1153 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1154 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1157 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1158 EventBase eventBase;
1159 auto ctx = std::make_shared<SSLContext>();
1165 uint8_t majorVersion = 18;
1166 uint8_t minorVersion = 25;
1168 // Create callback buf
1169 auto buf = IOBuf::create(bufLen);
1170 buf->append(bufLen);
1171 folly::io::RWPrivateCursor cursor(buf.get());
1172 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1173 cursor.write<uint16_t>(0);
1174 cursor.write<uint8_t>(38);
1175 cursor.write<uint8_t>(majorVersion);
1176 cursor.write<uint8_t>(minorVersion);
1178 cursor.write<uint32_t>(0);
1180 SSL* ssl = ctx->createSSL();
1184 AsyncSSLSocket::UniquePtr sock(
1185 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1186 sock->enableClientHelloParsing();
1188 // Test parsing with multiple small packets
1189 for (uint64_t i = 0; i < buf->length(); i += 3) {
1190 auto bufCopy = folly::IOBuf::copyBuffer(
1191 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
1192 AsyncSSLSocket::clientHelloParsingCallback(
1203 auto parsedClientHello = sock->getClientHelloInfo();
1204 EXPECT_TRUE(parsedClientHello != nullptr);
1205 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1206 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1210 * Verify sucessful behavior of SSL certificate validation.
1212 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1213 EventBase eventBase;
1214 auto clientCtx = std::make_shared<SSLContext>();
1215 auto dfServerCtx = std::make_shared<SSLContext>();
1219 getctx(clientCtx, dfServerCtx);
1221 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1222 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1224 AsyncSSLSocket::UniquePtr clientSock(
1225 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1226 AsyncSSLSocket::UniquePtr serverSock(
1227 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1229 SSLHandshakeClient client(std::move(clientSock), true, true);
1230 clientCtx->loadTrustedCertificates(kTestCA);
1232 SSLHandshakeServer server(std::move(serverSock), true, true);
1236 EXPECT_TRUE(client.handshakeVerify_);
1237 EXPECT_TRUE(client.handshakeSuccess_);
1238 EXPECT_TRUE(!client.handshakeError_);
1239 EXPECT_LE(0, client.handshakeTime.count());
1240 EXPECT_TRUE(!server.handshakeVerify_);
1241 EXPECT_TRUE(server.handshakeSuccess_);
1242 EXPECT_TRUE(!server.handshakeError_);
1243 EXPECT_LE(0, server.handshakeTime.count());
1247 * Verify that the client's verification callback is able to fail SSL
1248 * connection establishment.
1250 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1251 EventBase eventBase;
1252 auto clientCtx = std::make_shared<SSLContext>();
1253 auto dfServerCtx = std::make_shared<SSLContext>();
1257 getctx(clientCtx, dfServerCtx);
1259 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1260 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1262 AsyncSSLSocket::UniquePtr clientSock(
1263 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1264 AsyncSSLSocket::UniquePtr serverSock(
1265 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1267 SSLHandshakeClient client(std::move(clientSock), true, false);
1268 clientCtx->loadTrustedCertificates(kTestCA);
1270 SSLHandshakeServer server(std::move(serverSock), true, true);
1274 EXPECT_TRUE(client.handshakeVerify_);
1275 EXPECT_TRUE(!client.handshakeSuccess_);
1276 EXPECT_TRUE(client.handshakeError_);
1277 EXPECT_LE(0, client.handshakeTime.count());
1278 EXPECT_TRUE(!server.handshakeVerify_);
1279 EXPECT_TRUE(!server.handshakeSuccess_);
1280 EXPECT_TRUE(server.handshakeError_);
1281 EXPECT_LE(0, server.handshakeTime.count());
1285 * Verify that the options in SSLContext can be overridden in
1286 * sslConnect/Accept.i.e specifying that no validation should be performed
1287 * allows an otherwise-invalid certificate to be accepted and doesn't fire
1288 * the validation callback.
1290 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1291 EventBase eventBase;
1292 auto clientCtx = std::make_shared<SSLContext>();
1293 auto dfServerCtx = std::make_shared<SSLContext>();
1297 getctx(clientCtx, dfServerCtx);
1299 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1300 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1302 AsyncSSLSocket::UniquePtr clientSock(
1303 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1304 AsyncSSLSocket::UniquePtr serverSock(
1305 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1307 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1308 clientCtx->loadTrustedCertificates(kTestCA);
1310 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1314 EXPECT_TRUE(!client.handshakeVerify_);
1315 EXPECT_TRUE(client.handshakeSuccess_);
1316 EXPECT_TRUE(!client.handshakeError_);
1317 EXPECT_LE(0, client.handshakeTime.count());
1318 EXPECT_TRUE(!server.handshakeVerify_);
1319 EXPECT_TRUE(server.handshakeSuccess_);
1320 EXPECT_TRUE(!server.handshakeError_);
1321 EXPECT_LE(0, server.handshakeTime.count());
1325 * Verify that the options in SSLContext can be overridden in
1326 * sslConnect/Accept. Enable verification even if context says otherwise.
1327 * Test requireClientCert with client cert
1329 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1330 EventBase eventBase;
1331 auto clientCtx = std::make_shared<SSLContext>();
1332 auto serverCtx = std::make_shared<SSLContext>();
1333 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1334 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1335 serverCtx->loadPrivateKey(kTestKey);
1336 serverCtx->loadCertificate(kTestCert);
1337 serverCtx->loadTrustedCertificates(kTestCA);
1338 serverCtx->loadClientCAList(kTestCA);
1340 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1341 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1342 clientCtx->loadPrivateKey(kTestKey);
1343 clientCtx->loadCertificate(kTestCert);
1344 clientCtx->loadTrustedCertificates(kTestCA);
1349 AsyncSSLSocket::UniquePtr clientSock(
1350 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1351 AsyncSSLSocket::UniquePtr serverSock(
1352 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1354 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1355 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1359 EXPECT_TRUE(client.handshakeVerify_);
1360 EXPECT_TRUE(client.handshakeSuccess_);
1361 EXPECT_FALSE(client.handshakeError_);
1362 EXPECT_LE(0, client.handshakeTime.count());
1363 EXPECT_TRUE(server.handshakeVerify_);
1364 EXPECT_TRUE(server.handshakeSuccess_);
1365 EXPECT_FALSE(server.handshakeError_);
1366 EXPECT_LE(0, server.handshakeTime.count());
1370 * Verify that the client's verification callback is able to override
1371 * the preverification failure and allow a successful connection.
1373 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1374 EventBase eventBase;
1375 auto clientCtx = std::make_shared<SSLContext>();
1376 auto dfServerCtx = std::make_shared<SSLContext>();
1380 getctx(clientCtx, dfServerCtx);
1382 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1383 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1385 AsyncSSLSocket::UniquePtr clientSock(
1386 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1387 AsyncSSLSocket::UniquePtr serverSock(
1388 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1390 SSLHandshakeClient client(std::move(clientSock), false, true);
1391 SSLHandshakeServer server(std::move(serverSock), true, true);
1395 EXPECT_TRUE(client.handshakeVerify_);
1396 EXPECT_TRUE(client.handshakeSuccess_);
1397 EXPECT_TRUE(!client.handshakeError_);
1398 EXPECT_LE(0, client.handshakeTime.count());
1399 EXPECT_TRUE(!server.handshakeVerify_);
1400 EXPECT_TRUE(server.handshakeSuccess_);
1401 EXPECT_TRUE(!server.handshakeError_);
1402 EXPECT_LE(0, server.handshakeTime.count());
1406 * Verify that specifying that no validation should be performed allows an
1407 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1410 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1411 EventBase eventBase;
1412 auto clientCtx = std::make_shared<SSLContext>();
1413 auto dfServerCtx = std::make_shared<SSLContext>();
1417 getctx(clientCtx, dfServerCtx);
1419 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1420 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1422 AsyncSSLSocket::UniquePtr clientSock(
1423 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1424 AsyncSSLSocket::UniquePtr serverSock(
1425 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1427 SSLHandshakeClient client(std::move(clientSock), false, false);
1428 SSLHandshakeServer server(std::move(serverSock), false, false);
1432 EXPECT_TRUE(!client.handshakeVerify_);
1433 EXPECT_TRUE(client.handshakeSuccess_);
1434 EXPECT_TRUE(!client.handshakeError_);
1435 EXPECT_LE(0, client.handshakeTime.count());
1436 EXPECT_TRUE(!server.handshakeVerify_);
1437 EXPECT_TRUE(server.handshakeSuccess_);
1438 EXPECT_TRUE(!server.handshakeError_);
1439 EXPECT_LE(0, server.handshakeTime.count());
1443 * Test requireClientCert with client cert
1445 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1446 EventBase eventBase;
1447 auto clientCtx = std::make_shared<SSLContext>();
1448 auto serverCtx = std::make_shared<SSLContext>();
1449 serverCtx->setVerificationOption(
1450 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1451 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1452 serverCtx->loadPrivateKey(kTestKey);
1453 serverCtx->loadCertificate(kTestCert);
1454 serverCtx->loadTrustedCertificates(kTestCA);
1455 serverCtx->loadClientCAList(kTestCA);
1457 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1458 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1459 clientCtx->loadPrivateKey(kTestKey);
1460 clientCtx->loadCertificate(kTestCert);
1461 clientCtx->loadTrustedCertificates(kTestCA);
1466 AsyncSSLSocket::UniquePtr clientSock(
1467 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1468 AsyncSSLSocket::UniquePtr serverSock(
1469 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1471 SSLHandshakeClient client(std::move(clientSock), true, true);
1472 SSLHandshakeServer server(std::move(serverSock), true, true);
1476 EXPECT_TRUE(client.handshakeVerify_);
1477 EXPECT_TRUE(client.handshakeSuccess_);
1478 EXPECT_FALSE(client.handshakeError_);
1479 EXPECT_LE(0, client.handshakeTime.count());
1480 EXPECT_TRUE(server.handshakeVerify_);
1481 EXPECT_TRUE(server.handshakeSuccess_);
1482 EXPECT_FALSE(server.handshakeError_);
1483 EXPECT_LE(0, server.handshakeTime.count());
1487 * Test requireClientCert with no client cert
1489 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1490 EventBase eventBase;
1491 auto clientCtx = std::make_shared<SSLContext>();
1492 auto serverCtx = std::make_shared<SSLContext>();
1493 serverCtx->setVerificationOption(
1494 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1495 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1496 serverCtx->loadPrivateKey(kTestKey);
1497 serverCtx->loadCertificate(kTestCert);
1498 serverCtx->loadTrustedCertificates(kTestCA);
1499 serverCtx->loadClientCAList(kTestCA);
1500 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1501 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1506 AsyncSSLSocket::UniquePtr clientSock(
1507 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1508 AsyncSSLSocket::UniquePtr serverSock(
1509 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1511 SSLHandshakeClient client(std::move(clientSock), false, false);
1512 SSLHandshakeServer server(std::move(serverSock), false, false);
1516 EXPECT_FALSE(server.handshakeVerify_);
1517 EXPECT_FALSE(server.handshakeSuccess_);
1518 EXPECT_TRUE(server.handshakeError_);
1519 EXPECT_LE(0, client.handshakeTime.count());
1520 EXPECT_LE(0, server.handshakeTime.count());
1523 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1524 auto cert = getFileAsBuf(kTestCert);
1525 auto key = getFileAsBuf(kTestKey);
1527 ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1528 BIO_write(certBio.get(), cert.data(), cert.size());
1529 ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1530 BIO_write(keyBio.get(), key.data(), key.size());
1532 // Create SSL structs from buffers to get properties
1533 ssl::X509UniquePtr certStruct(
1534 PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1535 ssl::EvpPkeyUniquePtr keyStruct(
1536 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1540 auto origCommonName = getCommonName(certStruct.get());
1541 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1542 certStruct = nullptr;
1543 keyStruct = nullptr;
1545 auto ctx = std::make_shared<SSLContext>();
1546 ctx->loadPrivateKeyFromBufferPEM(key);
1547 ctx->loadCertificateFromBufferPEM(cert);
1548 ctx->loadTrustedCertificates(kTestCA);
1550 ssl::SSLUniquePtr ssl(ctx->createSSL());
1552 auto newCert = SSL_get_certificate(ssl.get());
1553 auto newKey = SSL_get_privatekey(ssl.get());
1555 // Get properties from SSL struct
1556 auto newCommonName = getCommonName(newCert);
1557 auto newKeySize = EVP_PKEY_bits(newKey);
1559 // Check that the key and cert have the expected properties
1560 EXPECT_EQ(origCommonName, newCommonName);
1561 EXPECT_EQ(origKeySize, newKeySize);
1564 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1567 // Set up SSL context.
1568 auto sslContext = std::make_shared<SSLContext>();
1569 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1571 // create SSL socket
1572 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1574 EXPECT_EQ(1500, socket->getMinWriteSize());
1576 socket->setMinWriteSize(0);
1577 EXPECT_EQ(0, socket->getMinWriteSize());
1578 socket->setMinWriteSize(50000);
1579 EXPECT_EQ(50000, socket->getMinWriteSize());
1582 class ReadCallbackTerminator : public ReadCallback {
1584 ReadCallbackTerminator(EventBase* base, WriteCallbackBase* wcb)
1585 : ReadCallback(wcb), base_(base) {}
1587 // Do not write data back, terminate the loop.
1588 void readDataAvailable(size_t len) noexcept override {
1589 std::cerr << "readDataAvailable, len " << len << std::endl;
1591 currentBuffer.length = len;
1593 buffers.push_back(currentBuffer);
1594 currentBuffer.reset();
1595 state = STATE_SUCCEEDED;
1597 socket_->setReadCB(nullptr);
1598 base_->terminateLoopSoon();
1606 * Test a full unencrypted codepath
1608 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1611 auto clientCtx = std::make_shared<folly::SSLContext>();
1612 auto serverCtx = std::make_shared<folly::SSLContext>();
1615 getctx(clientCtx, serverCtx);
1617 AsyncSSLSocket::newSocket(clientCtx, &base, fds[0], false, true);
1618 auto server = AsyncSSLSocket::newSocket(serverCtx, &base, fds[1], true, true);
1620 ReadCallbackTerminator readCallback(&base, nullptr);
1621 server->setReadCB(&readCallback);
1622 readCallback.setSocket(server);
1625 memset(buf, 'a', sizeof(buf));
1626 client->write(nullptr, buf, sizeof(buf));
1628 // Check that bytes are unencrypted
1630 EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1633 EventBaseAborter eba(&base, 3000);
1636 EXPECT_EQ(1, readCallback.buffers.size());
1637 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1639 server->setReadCB(&readCallback);
1642 server->sslAccept(nullptr);
1643 client->sslConn(nullptr);
1645 // Do NOT wait for handshake, writing should be queued and happen after
1647 client->write(nullptr, buf, sizeof(buf));
1649 // Check that bytes are *not* unencrypted
1651 EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1656 EXPECT_EQ(2, readCallback.buffers.size());
1657 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1660 TEST(AsyncSSLSocketTest, ConnectUnencryptedTest) {
1661 auto clientCtx = std::make_shared<folly::SSLContext>();
1662 auto serverCtx = std::make_shared<folly::SSLContext>();
1663 getctx(clientCtx, serverCtx);
1665 WriteCallbackBase writeCallback;
1666 ReadCallback readCallback(&writeCallback);
1667 HandshakeCallback handshakeCallback(&readCallback);
1668 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1669 TestSSLServer server(&acceptCallback);
1672 std::shared_ptr<AsyncSSLSocket> socket =
1673 AsyncSSLSocket::newSocket(clientCtx, &evb, true);
1674 socket->connect(nullptr, server.getAddress(), 0);
1678 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState());
1679 socket->sslConn(nullptr);
1681 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState());
1684 std::array<uint8_t, 128> buf;
1685 memset(buf.data(), 'a', buf.size());
1686 socket->write(nullptr, buf.data(), buf.size());
1691 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
1692 // Start listening on a local port
1693 WriteCallbackBase writeCallback;
1694 WriteErrorCallback readCallback(&writeCallback);
1695 HandshakeCallback handshakeCallback(
1696 &readCallback, 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));
1704 socket->closeWithReset();
1706 handshakeCallback.waitForHandshake();
1708 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1709 EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
1712 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
1713 // Start listening on a local port
1714 WriteCallbackBase writeCallback;
1715 WriteErrorCallback readCallback(&writeCallback);
1716 HandshakeCallback handshakeCallback(
1717 &readCallback, HandshakeCallback::EXPECT_ERROR);
1718 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1719 TestSSLServer server(&acceptCallback);
1721 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1723 uint8_t buf[3] = {0x16, 0x03, 0x01};
1724 socket->write(buf, sizeof(buf));
1727 handshakeCallback.waitForHandshake();
1728 #if FOLLY_OPENSSL_IS_110
1730 handshakeCallback.errorString_.find("Network error"), std::string::npos);
1733 handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
1737 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
1738 // Start listening on a local port
1739 WriteCallbackBase writeCallback;
1740 WriteErrorCallback readCallback(&writeCallback);
1741 HandshakeCallback handshakeCallback(
1742 &readCallback, HandshakeCallback::EXPECT_ERROR);
1743 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1744 TestSSLServer server(&acceptCallback);
1746 auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
1748 uint8_t buf[256] = {0x16, 0x03};
1749 memset(buf + 2, 'a', sizeof(buf) - 2);
1750 socket->write(buf, sizeof(buf));
1753 handshakeCallback.waitForHandshake();
1755 handshakeCallback.errorString_.find("SSL routines"), std::string::npos);
1756 #if defined(OPENSSL_IS_BORINGSSL)
1758 handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
1760 #elif FOLLY_OPENSSL_IS_110
1762 handshakeCallback.errorString_.find("packet length too long"),
1766 handshakeCallback.errorString_.find("unknown protocol"),
1771 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
1772 using folly::ssl::OpenSSLUtils;
1774 OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384");
1775 // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this
1776 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), "");
1777 // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected
1778 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), "");
1783 class MockAsyncTFOSSLSocket : public AsyncSSLSocket {
1785 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
1787 explicit MockAsyncTFOSSLSocket(
1788 std::shared_ptr<folly::SSLContext> sslCtx,
1790 : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {}
1792 MOCK_METHOD3(tfoSendMsg, ssize_t(int fd, struct msghdr* msg, int msg_flags));
1796 * Test connecting to, writing to, reading from, and closing the
1797 * connection to the SSL server with TFO.
1799 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
1800 // Start listening on a local port
1801 WriteCallbackBase writeCallback;
1802 ReadCallback readCallback(&writeCallback);
1803 HandshakeCallback handshakeCallback(&readCallback);
1804 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1805 TestSSLServer server(&acceptCallback, true);
1807 // Set up SSL context.
1808 auto sslContext = std::make_shared<SSLContext>();
1812 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1813 socket->enableTFO();
1817 std::array<uint8_t, 128> buf;
1818 memset(buf.data(), 'a', buf.size());
1819 socket->write(buf.data(), buf.size());
1822 std::array<uint8_t, 128> readbuf;
1823 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1824 EXPECT_EQ(bytesRead, 128);
1825 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1832 * Test connecting to, writing to, reading from, and closing the
1833 * connection to the SSL server with TFO.
1835 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
1836 // Start listening on a local port
1837 WriteCallbackBase writeCallback;
1838 ReadCallback readCallback(&writeCallback);
1839 HandshakeCallback handshakeCallback(&readCallback);
1840 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1841 TestSSLServer server(&acceptCallback, false);
1843 // Set up SSL context.
1844 auto sslContext = std::make_shared<SSLContext>();
1848 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1849 socket->enableTFO();
1853 std::array<uint8_t, 128> buf;
1854 memset(buf.data(), 'a', buf.size());
1855 socket->write(buf.data(), buf.size());
1858 std::array<uint8_t, 128> readbuf;
1859 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
1860 EXPECT_EQ(bytesRead, 128);
1861 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1867 class ConnCallback : public AsyncSocket::ConnectCallback {
1869 void connectSuccess() noexcept override {
1870 state = State::SUCCESS;
1873 void connectErr(const AsyncSocketException& ex) noexcept override {
1874 state = State::ERROR;
1878 enum class State { WAITING, SUCCESS, ERROR };
1880 State state{State::WAITING};
1884 template <class Cardinality>
1885 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
1887 const SocketAddress& address,
1888 Cardinality cardinality) {
1889 // Set up SSL context.
1890 auto sslContext = std::make_shared<SSLContext>();
1893 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
1894 new MockAsyncTFOSSLSocket(sslContext, evb));
1895 socket->enableTFO();
1897 EXPECT_CALL(*socket, tfoSendMsg(_, _, _))
1899 .WillOnce(Invoke([&](int fd, struct msghdr*, int) {
1900 sockaddr_storage addr;
1901 auto len = address.getAddress(&addr);
1902 return connect(fd, (const struct sockaddr*)&addr, len);
1907 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
1908 // Start listening on a local port
1909 WriteCallbackBase writeCallback;
1910 ReadCallback readCallback(&writeCallback);
1911 HandshakeCallback handshakeCallback(&readCallback);
1912 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1913 TestSSLServer server(&acceptCallback, true);
1917 auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1);
1919 socket->connect(&ccb, server.getAddress(), 30);
1922 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
1924 evb.runInEventBaseThread([&] { socket->detachEventBase(); });
1927 BlockingSocket sock(std::move(socket));
1929 std::array<uint8_t, 128> buf;
1930 memset(buf.data(), 'a', buf.size());
1931 sock.write(buf.data(), buf.size());
1934 std::array<uint8_t, 128> readbuf;
1935 uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size());
1936 EXPECT_EQ(bytesRead, 128);
1937 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
1943 #if !defined(OPENSSL_IS_BORINGSSL)
1944 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
1945 // Start listening on a local port
1946 ConnectTimeoutCallback acceptCallback;
1947 TestSSLServer server(&acceptCallback, true);
1949 // Set up SSL context.
1950 auto sslContext = std::make_shared<SSLContext>();
1954 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
1955 socket->enableTFO();
1957 socket->open(std::chrono::milliseconds(20)), AsyncSocketException);
1961 #if !defined(OPENSSL_IS_BORINGSSL)
1962 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
1963 // Start listening on a local port
1964 ConnectTimeoutCallback acceptCallback;
1965 TestSSLServer server(&acceptCallback, true);
1969 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1971 // Set a short timeout
1972 socket->connect(&ccb, server.getAddress(), 1);
1975 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1979 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
1980 // Start listening on a local port
1981 EmptyReadCallback readCallback;
1982 HandshakeCallback handshakeCallback(
1983 &readCallback, HandshakeCallback::EXPECT_ERROR);
1984 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
1985 TestSSLServer server(&acceptCallback, true);
1989 auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1));
1991 socket->connect(&ccb, server.getAddress(), 100);
1994 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
1995 EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out"));
1998 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
1999 // Start listening on a local port
2002 // Hopefully nothing is listening on this address
2003 SocketAddress addr("127.0.0.1", 65535);
2004 auto socket = setupSocketWithFallback(&evb, addr, AtMost(1));
2006 socket->connect(&ccb, addr, 100);
2009 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
2010 EXPECT_THAT(ccb.error, testing::HasSubstr("refused"));
2013 TEST(AsyncSSLSocketTest, TestPreReceivedData) {
2014 EventBase clientEventBase;
2015 EventBase serverEventBase;
2016 auto clientCtx = std::make_shared<SSLContext>();
2017 auto dfServerCtx = std::make_shared<SSLContext>();
2018 std::array<int, 2> fds;
2020 getctx(clientCtx, dfServerCtx);
2022 AsyncSSLSocket::UniquePtr clientSockPtr(
2023 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
2024 AsyncSSLSocket::UniquePtr serverSockPtr(
2025 new AsyncSSLSocket(dfServerCtx, &serverEventBase, fds[1], true));
2026 auto clientSock = clientSockPtr.get();
2027 auto serverSock = serverSockPtr.get();
2028 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
2030 // Steal some data from the server.
2031 clientEventBase.loopOnce();
2032 std::array<uint8_t, 10> buf;
2033 recv(fds[1], buf.data(), buf.size(), 0);
2035 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
2036 SSLHandshakeServer server(std::move(serverSockPtr), true, true);
2037 while (!client.handshakeSuccess_ && !client.handshakeError_) {
2038 serverEventBase.loopOnce();
2039 clientEventBase.loopOnce();
2042 EXPECT_TRUE(client.handshakeSuccess_);
2043 EXPECT_TRUE(server.handshakeSuccess_);
2045 serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2048 TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) {
2049 EventBase clientEventBase;
2050 EventBase serverEventBase;
2051 auto clientCtx = std::make_shared<SSLContext>();
2052 auto dfServerCtx = std::make_shared<SSLContext>();
2053 std::array<int, 2> fds;
2055 getctx(clientCtx, dfServerCtx);
2057 AsyncSSLSocket::UniquePtr clientSockPtr(
2058 new AsyncSSLSocket(clientCtx, &clientEventBase, fds[0], false));
2059 AsyncSocket::UniquePtr serverSockPtr(
2060 new AsyncSocket(&serverEventBase, fds[1]));
2061 auto clientSock = clientSockPtr.get();
2062 auto serverSock = serverSockPtr.get();
2063 SSLHandshakeClient client(std::move(clientSockPtr), true, true);
2065 // Steal some data from the server.
2066 clientEventBase.loopOnce();
2067 std::array<uint8_t, 10> buf;
2068 recv(fds[1], buf.data(), buf.size(), 0);
2069 serverSock->setPreReceivedData(IOBuf::wrapBuffer(range(buf)));
2070 AsyncSSLSocket::UniquePtr serverSSLSockPtr(
2071 new AsyncSSLSocket(dfServerCtx, std::move(serverSockPtr), true));
2072 auto serverSSLSock = serverSSLSockPtr.get();
2073 SSLHandshakeServer server(std::move(serverSSLSockPtr), true, true);
2074 while (!client.handshakeSuccess_ && !client.handshakeError_) {
2075 serverEventBase.loopOnce();
2076 clientEventBase.loopOnce();
2079 EXPECT_TRUE(client.handshakeSuccess_);
2080 EXPECT_TRUE(server.handshakeSuccess_);
2082 serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2086 * Test overriding the flags passed to "sendmsg()" system call,
2087 * and verifying that write requests fail properly.
2089 TEST(AsyncSSLSocketTest, SendMsgParamsCallback) {
2090 // Start listening on a local port
2091 SendMsgFlagsCallback msgCallback;
2092 ExpectWriteErrorCallback writeCallback(&msgCallback);
2093 ReadCallback readCallback(&writeCallback);
2094 HandshakeCallback handshakeCallback(&readCallback);
2095 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2096 TestSSLServer server(&acceptCallback);
2098 // Set up SSL context.
2099 auto sslContext = std::make_shared<SSLContext>();
2100 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2104 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
2107 // Setting flags to "-1" to trigger "Invalid argument" error
2108 // on attempt to use this flags in sendmsg() system call.
2109 msgCallback.resetFlags(-1);
2112 std::vector<uint8_t> buf(128, 'a');
2113 ASSERT_EQ(socket->write(buf.data(), buf.size()), buf.size());
2118 cerr << "SendMsgParamsCallback test completed" << endl;
2123 * Test connecting to, writing to, reading from, and closing the
2124 * connection to the SSL server.
2126 TEST(AsyncSSLSocketTest, SendMsgDataCallback) {
2127 // This test requires Linux kernel v4.6 or later
2128 struct utsname s_uname;
2129 memset(&s_uname, 0, sizeof(s_uname));
2130 ASSERT_EQ(uname(&s_uname), 0);
2132 folly::StringPiece extra;
2133 if (folly::split<false>(
2134 '.', std::string(s_uname.release) + ".", major, minor, extra)) {
2135 if (major < 4 || (major == 4 && minor < 6)) {
2136 LOG(INFO) << "Kernel version: 4.6 and newer required for this test ("
2137 << "kernel ver. " << s_uname.release << " detected).";
2142 // Start listening on a local port
2143 SendMsgDataCallback msgCallback;
2144 WriteCheckTimestampCallback writeCallback(&msgCallback);
2145 ReadCallback readCallback(&writeCallback);
2146 HandshakeCallback handshakeCallback(&readCallback);
2147 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2148 TestSSLServer server(&acceptCallback);
2150 // Set up SSL context.
2151 auto sslContext = std::make_shared<SSLContext>();
2152 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2156 std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
2159 // Adding MSG_EOR flag to the message flags - it'll trigger
2160 // timestamp generation for the last byte of the message.
2161 msgCallback.resetFlags(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_EOR);
2163 // Init ancillary data buffer to trigger timestamp notification
2165 uint8_t ctrl_data[CMSG_LEN(sizeof(uint32_t))];
2166 struct cmsghdr cmsg;
2168 u.cmsg.cmsg_level = SOL_SOCKET;
2169 u.cmsg.cmsg_type = SO_TIMESTAMPING;
2170 u.cmsg.cmsg_len = CMSG_LEN(sizeof(uint32_t));
2171 uint32_t flags = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE |
2172 SOF_TIMESTAMPING_TX_ACK;
2173 memcpy(CMSG_DATA(&u.cmsg), &flags, sizeof(uint32_t));
2174 std::vector<char> ctrl(CMSG_LEN(sizeof(uint32_t)));
2175 memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(sizeof(uint32_t)));
2176 msgCallback.resetData(std::move(ctrl));
2179 std::vector<uint8_t> buf(128, 'a');
2180 socket->write(buf.data(), buf.size());
2183 std::vector<uint8_t> readbuf(buf.size());
2184 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
2185 EXPECT_EQ(bytesRead, buf.size());
2186 EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin()));
2188 writeCallback.checkForTimestampNotifications();
2193 cerr << "SendMsgDataCallback test completed" << endl;
2195 #endif // MSG_ERRQUEUE
2202 ///////////////////////////////////////////////////////////////////////////
2203 // init_unit_test_suite
2204 ///////////////////////////////////////////////////////////////////////////
2206 struct Initializer {
2208 signal(SIGPIPE, SIG_IGN);
2211 Initializer initializer;