36 #include <sys/types.h> 48 #if FOLLY_OPENSSL_IS_110 49 #include <openssl/async.h> 52 #ifdef FOLLY_HAVE_MSG_ERRQUEUE 53 #include <sys/utsname.h> 69 typedef int (*setsockopt_ptr)(int, int, int,
const void*, socklen_t);
70 setsockopt_ptr real_setsockopt_ =
nullptr;
76 real_setsockopt_ = (setsockopt_ptr)dlsym(RTLD_NEXT,
"setsockopt");
79 ttlsDisabledSet.clear();
86 GlobalStatic globalStatic;
98 if (optname == SO_NO_TRANSPARENT_TLS) {
99 globalStatic.ttlsDisabledSet.insert(sockfd);
102 return real_setsockopt_(sockfd, level, optname, optval, optlen);
107 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
108 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
109 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
111 constexpr
size_t SSLClient::kMaxReadBufferSz;
112 constexpr
size_t SSLClient::kMaxReadsPerEvent;
115 if (
socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
116 FAIL() <<
"failed to create socketpair: " <<
errnoStr(errno);
118 for (
int idx = 0; idx < 2; ++idx) {
119 int flags = fcntl(fds[idx], F_GETFL, 0);
121 FAIL() <<
"failed to get flags for socket " << idx <<
": " 124 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
125 FAIL() <<
"failed to put socket " << idx
126 <<
" in non-blocking mode: " <<
errnoStr(errno);
132 std::shared_ptr<folly::SSLContext> clientCtx,
133 std::shared_ptr<folly::SSLContext> serverCtx) {
134 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
136 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
138 serverCtx->loadPrivateKey(
kTestKey);
145 auto clientCtx = std::make_shared<folly::SSLContext>();
146 auto serverCtx = std::make_shared<folly::SSLContext>();
149 getctx(clientCtx, serverCtx);
150 clientSock->reset(
new AsyncSSLSocket(clientCtx, eventBase, fds[0],
false));
151 serverSock->reset(
new AsyncSSLSocket(serverCtx, eventBase, fds[1],
true));
159 unsigned char** client,
160 unsigned int* client_len,
161 const unsigned char*,
165 static unsigned char p[7] = {6,
'p',
'o',
'n',
'i',
'e',
's'};
174 const unsigned char*,
189 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
198 std::shared_ptr<SSLContext> sslContext(
new SSLContext());
199 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
205 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
206 socket->open(std::chrono::milliseconds(10000));
210 memset(buf,
'a',
sizeof(buf));
211 socket->write(buf,
sizeof(buf));
217 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
222 cerr <<
"ConnectWriteReadClose test completed" << endl;
223 EXPECT_EQ(
socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000);
229 TEST(AsyncSSLSocketTest, ReadAfterClose) {
235 auto server = std::make_unique<TestSSLServer>(&acceptCallback);
238 auto sslContext = std::make_shared<SSLContext>();
239 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
242 std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
246 auto evb = handshakeCallback.
getSocket()->getEventBase();
247 evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.
closeSocket(); });
248 std::array<uint8_t, 128> readbuf;
249 auto bytesRead =
socket->read(readbuf.data(), readbuf.size());
256 #if !defined(OPENSSL_IS_BORINGSSL) 257 TEST(AsyncSSLSocketTest, Renegotiate) {
259 auto clientCtx = std::make_shared<SSLContext>();
260 auto dfServerCtx = std::make_shared<SSLContext>();
261 std::array<int, 2> fds;
263 getctx(clientCtx, dfServerCtx);
278 auto sslSock =
std::move(client).moveSocket();
279 sslSock->detachEventBase();
282 SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
289 std::array<uint8_t, 128> buf;
290 memset(buf.data(),
'a', buf.size());
292 socket->write(buf.data(), buf.size());
294 LOG(
INFO) <<
"client got error " << e.what();
307 TEST(AsyncSSLSocketTest, HandshakeError) {
316 std::shared_ptr<SSLContext> sslContext(
new SSLContext());
317 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
321 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
329 LOG(ERROR) <<
"readAll returned " << bytesRead <<
" instead of throwing";
337 cerr <<
"HandshakeError test completed" << endl;
343 TEST(AsyncSSLSocketTest, ReadError) {
352 std::shared_ptr<SSLContext> sslContext(
new SSLContext());
353 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
357 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
362 memset(buf,
'a',
sizeof(buf));
363 socket->write(buf,
sizeof(buf));
366 cerr <<
"ReadError test completed" << endl;
372 TEST(AsyncSSLSocketTest, WriteError) {
381 std::shared_ptr<SSLContext> sslContext(
new SSLContext());
382 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
386 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
391 memset(buf,
'a',
sizeof(buf));
392 socket->write(buf,
sizeof(buf));
395 cerr <<
"WriteError test completed" << endl;
401 TEST(AsyncSSLSocketTest, SocketWithDelay) {
410 std::shared_ptr<SSLContext> sslContext(
new SSLContext());
411 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
415 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
420 memset(buf,
'a',
sizeof(buf));
421 socket->write(buf,
sizeof(buf));
427 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
432 cerr <<
"SocketWithDelay test completed" << endl;
435 #if FOLLY_OPENSSL_HAS_ALPN 436 class NextProtocolTest :
public Test {
439 void SetUp()
override {
440 getctx(clientCtx, serverCtx);
443 void connect(
bool unset =
false) {
449 clientCtx->unsetNextProtocols();
456 client = std::make_unique<AlpnClient>(
std::move(clientSock));
457 server = std::make_unique<AlpnServer>(
std::move(serverSock));
463 expectHandshakeSuccess();
465 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
467 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
469 string selected((
const char*)client->nextProto, client->nextProtoLength);
473 void expectNoProtocol() {
474 expectHandshakeSuccess();
481 void expectHandshakeSuccess() {
483 <<
"client handshake error: " << client->except->what();
485 <<
"server handshake error: " << server->except->what();
488 void expectHandshakeError() {
490 <<
"Expected client handshake error!";
492 <<
"Expected server handshake error!";
496 std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()};
497 std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()};
499 std::unique_ptr<AlpnClient> client;
500 std::unique_ptr<AlpnServer> server;
503 TEST_F(NextProtocolTest, AlpnTestOverlap) {
504 clientCtx->setAdvertisedNextProtocols({
"blub",
"baz"});
505 serverCtx->setAdvertisedNextProtocols({
"foo",
"bar",
"baz"});
509 expectProtocol(
"baz");
512 TEST_F(NextProtocolTest, AlpnTestUnset) {
515 clientCtx->setAdvertisedNextProtocols({
"blub",
"baz"});
516 serverCtx->setAdvertisedNextProtocols({
"foo",
"bar",
"baz"});
523 TEST_F(NextProtocolTest, AlpnTestNoOverlap) {
524 clientCtx->setAdvertisedNextProtocols({
"blub"});
525 serverCtx->setAdvertisedNextProtocols({
"foo",
"bar",
"baz"});
531 TEST_F(NextProtocolTest, RandomizedAlpnTest) {
534 const int kTries = 64;
536 clientCtx->setAdvertisedNextProtocols({
"foo",
"bar",
"baz"});
537 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {
"foo"}}, {1, {
"bar"}}});
539 std::set<string> selectedProtocols;
540 for (
int i = 0;
i < kTries; ++
i) {
544 EXPECT_EQ(client->nextProtoLength, server->nextProtoLength);
546 memcmp(client->nextProto, server->nextProto, server->nextProtoLength),
548 string selected((
const char*)client->nextProto, client->nextProtoLength);
549 selectedProtocols.insert(selected);
550 expectHandshakeSuccess();
556 #ifndef OPENSSL_NO_TLSEXT 563 TEST(AsyncSSLSocketTest, SNITestMatch) {
565 std::shared_ptr<SSLContext> clientCtx(
new SSLContext);
566 std::shared_ptr<SSLContext> dfServerCtx(
new SSLContext);
569 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
570 const std::string serverName(
"xyz.newdev.facebook.com");
573 getctx(clientCtx, dfServerCtx);
581 std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
595 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
597 std::shared_ptr<SSLContext> clientCtx(
new SSLContext);
598 std::shared_ptr<SSLContext> dfServerCtx(
new SSLContext);
601 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
602 const std::string clientRequestingServerName(
"foo.com");
603 const std::string serverExpectedServerName(
"xyz.newdev.facebook.com");
607 getctx(clientCtx, dfServerCtx);
610 clientCtx, &eventBase, fds[0], clientRequestingServerName));
618 serverExpectedServerName);
631 TEST(AsyncSSLSocketTest, SNITestChangeServerName) {
633 std::shared_ptr<SSLContext> clientCtx(
new SSLContext);
634 std::shared_ptr<SSLContext> dfServerCtx(
new SSLContext);
637 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
638 const std::string serverName(
"xyz.newdev.facebook.com");
641 getctx(clientCtx, dfServerCtx);
647 clientSock->setServerName(newName);
652 std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
663 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
665 std::shared_ptr<SSLContext> clientCtx(
new SSLContext);
666 std::shared_ptr<SSLContext> dfServerCtx(
new SSLContext);
669 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
670 const std::string serverExpectedServerName(
"xyz.newdev.facebook.com");
674 getctx(clientCtx, dfServerCtx);
685 serverExpectedServerName);
697 TEST(AsyncSSLSocketTest, SSLClientTest) {
707 auto client = std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 1);
716 cerr <<
"SSLClientTest test completed" << endl;
722 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
733 std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 10);
742 cerr <<
"SSLClientTestReuse test completed" << endl;
748 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
752 &readCallback, HandshakeCallback::EXPECT_ERROR);
759 std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 1, 10);
760 client->connect(
true );
767 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
772 cerr <<
"SSLClientTimeoutTest test completed" << endl;
776 #ifdef SSL_ERROR_WANT_SESS_CACHE_LOOKUP 780 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
791 std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 10, 500);
802 cerr <<
"SSLServerAsyncCacheTest test completed" << endl;
808 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
819 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
824 sock->setReadCB(&clientReadCallback);
831 cerr <<
"SSLServerTimeoutTest test completed" << endl;
837 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
847 auto client = std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 2);
859 cerr <<
"SSLServerAsyncCacheTimeoutTest test completed" << endl;
865 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
870 &readCallback, HandshakeCallback::EXPECT_ERROR);
877 std::make_shared<SSLClient>(&eventBase, server.
getAddress(), 2, 100);
884 [&handshakeCallback] { handshakeCallback.
closeSocket(); });
894 cerr <<
"SSLServerCacheCloseTest test completed" << endl;
896 #endif // !SSL_ERROR_WANT_SESS_CACHE_LOOKUP 901 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
903 auto clientCtx = std::make_shared<SSLContext>();
904 auto serverCtx = std::make_shared<SSLContext>();
905 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
906 serverCtx->ciphers(
"ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
907 serverCtx->loadPrivateKey(
kTestKey);
909 serverCtx->loadTrustedCertificates(
kTestCA);
910 serverCtx->loadClientCAList(
kTestCA);
912 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
913 clientCtx->ciphers(
"AES256-SHA:AES128-SHA");
914 clientCtx->loadPrivateKey(
kTestKey);
916 clientCtx->loadTrustedCertificates(
kTestCA);
931 #if defined(OPENSSL_IS_BORINGSSL) 948 TEST(AsyncSSLSocketTest, GetClientCertificate) {
950 auto clientCtx = std::make_shared<SSLContext>();
951 auto serverCtx = std::make_shared<SSLContext>();
952 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
953 serverCtx->ciphers(
"ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
954 serverCtx->loadPrivateKey(
kTestKey);
959 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
960 clientCtx->ciphers(
"AES256-SHA:AES128-SHA");
963 clientCtx->loadTrustedCertificates(
kTestCA);
965 std::array<int, 2> fds;
983 auto cliSocket =
std::move(client).moveSocket();
984 auto srvSocket =
std::move(server).moveSocket();
988 CHECK(serverPeerCert);
991 const X509* clientSelfCert = cliSocket->getSelfCert();
992 CHECK(clientSelfCert);
995 EXPECT_EQ(0, X509_cmp(clientSelfCert, serverPeerCert.get()));
998 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
1000 auto ctx = std::make_shared<SSLContext>();
1010 auto buf = IOBuf::create(bufLen);
1011 buf->append(bufLen);
1016 cursor.write<
uint8_t>(majorVersion);
1017 cursor.write<
uint8_t>(minorVersion);
1021 SSL* ssl = ctx->createSSL();
1027 sock->enableClientHelloParsing();
1030 AsyncSSLSocket::clientHelloParsingCallback(
1031 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1034 auto parsedClientHello = sock->getClientHelloInfo();
1036 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1037 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1040 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
1042 auto ctx = std::make_shared<SSLContext>();
1052 auto buf = IOBuf::create(bufLen);
1053 buf->append(bufLen);
1058 cursor.write<
uint8_t>(majorVersion);
1059 cursor.write<
uint8_t>(minorVersion);
1063 SSL* ssl = ctx->createSSL();
1069 sock->enableClientHelloParsing();
1073 AsyncSSLSocket::clientHelloParsingCallback(
1083 AsyncSSLSocket::clientHelloParsingCallback(
1093 auto parsedClientHello = sock->getClientHelloInfo();
1095 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1096 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1099 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
1101 auto ctx = std::make_shared<SSLContext>();
1111 auto buf = IOBuf::create(bufLen);
1112 buf->append(bufLen);
1117 cursor.write<
uint8_t>(majorVersion);
1118 cursor.write<
uint8_t>(minorVersion);
1122 SSL* ssl = ctx->createSSL();
1128 sock->enableClientHelloParsing();
1131 for (std::size_t
i = 0;
i < buf->length();
i += 3) {
1133 buf->data() +
i,
std::min((std::size_t)3, buf->length() -
i));
1134 AsyncSSLSocket::clientHelloParsingCallback(
1145 auto parsedClientHello = sock->getClientHelloInfo();
1147 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1148 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1154 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
1156 auto clientCtx = std::make_shared<SSLContext>();
1157 auto dfServerCtx = std::make_shared<SSLContext>();
1161 getctx(clientCtx, dfServerCtx);
1163 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1164 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1172 clientCtx->loadTrustedCertificates(
kTestCA);
1192 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
1194 auto clientCtx = std::make_shared<SSLContext>();
1195 auto dfServerCtx = std::make_shared<SSLContext>();
1199 getctx(clientCtx, dfServerCtx);
1201 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1202 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1210 clientCtx->loadTrustedCertificates(
kTestCA);
1232 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
1234 auto clientCtx = std::make_shared<SSLContext>();
1235 auto dfServerCtx = std::make_shared<SSLContext>();
1239 getctx(clientCtx, dfServerCtx);
1241 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1242 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1250 clientCtx->loadTrustedCertificates(
kTestCA);
1271 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1273 auto clientCtx = std::make_shared<SSLContext>();
1274 auto serverCtx = std::make_shared<SSLContext>();
1275 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1276 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1277 serverCtx->loadPrivateKey(
kTestKey);
1279 serverCtx->loadTrustedCertificates(
kTestCA);
1280 serverCtx->loadClientCAList(
kTestCA);
1282 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1283 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1284 clientCtx->loadPrivateKey(
kTestKey);
1286 clientCtx->loadTrustedCertificates(
kTestCA);
1315 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1317 auto clientCtx = std::make_shared<SSLContext>();
1318 auto dfServerCtx = std::make_shared<SSLContext>();
1322 getctx(clientCtx, dfServerCtx);
1324 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1325 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1352 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1354 auto clientCtx = std::make_shared<SSLContext>();
1355 auto dfServerCtx = std::make_shared<SSLContext>();
1359 getctx(clientCtx, dfServerCtx);
1361 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1362 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1387 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1389 auto clientCtx = std::make_shared<SSLContext>();
1390 auto serverCtx = std::make_shared<SSLContext>();
1391 serverCtx->setVerificationOption(
1392 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1393 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1394 serverCtx->loadPrivateKey(
kTestKey);
1396 serverCtx->loadTrustedCertificates(
kTestCA);
1397 serverCtx->loadClientCAList(
kTestCA);
1399 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1400 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1401 clientCtx->loadPrivateKey(
kTestKey);
1403 clientCtx->loadTrustedCertificates(
kTestCA);
1428 auto clientSsl =
std::move(client).moveSocket();
1429 auto serverSsl =
std::move(server).moveSocket();
1431 auto clientPeer = clientSsl->getPeerCertificate();
1432 auto clientSelf = clientSsl->getSelfCertificate();
1433 auto serverPeer = serverSsl->getPeerCertificate();
1434 auto serverSelf = serverSsl->getSelfCertificate();
1441 EXPECT_EQ(clientPeer->getIdentity(), serverSelf->getIdentity());
1442 EXPECT_EQ(clientSelf->getIdentity(), serverPeer->getIdentity());
1448 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1450 auto clientCtx = std::make_shared<SSLContext>();
1451 auto serverCtx = std::make_shared<SSLContext>();
1452 serverCtx->setVerificationOption(
1453 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1454 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1455 serverCtx->loadPrivateKey(
kTestKey);
1457 serverCtx->loadTrustedCertificates(
kTestCA);
1458 serverCtx->loadClientCAList(
kTestCA);
1459 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1460 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1485 #if FOLLY_OPENSSL_IS_110 1487 static void makeNonBlockingPipe(
int pipefds[2]) {
1488 if (
pipe(pipefds) != 0) {
1489 throw std::runtime_error(
"Cannot create pipe");
1491 if (::fcntl(pipefds[0], F_SETFL, O_NONBLOCK) != 0) {
1492 throw std::runtime_error(
"Cannot set pipe to nonblocking");
1494 if (::fcntl(pipefds[1], F_SETFL, O_NONBLOCK) != 0) {
1495 throw std::runtime_error(
"Cannot set pipe to nonblocking");
1500 static int kRSAExIndex = -1;
1501 static int kRSAEvbExIndex = -1;
1502 static int kRSASocketExIndex = -1;
1503 static constexpr
StringPiece kEngineId =
"AsyncSSLSocketTest";
1505 static int customRsaPrivEnc(
1507 const unsigned char*
from,
1511 LOG(
INFO) <<
"rsa_priv_enc";
1513 reinterpret_cast<EventBase*
>(RSA_get_ex_data(rsa, kRSAEvbExIndex));
1516 RSA* actualRSA =
reinterpret_cast<RSA*
>(RSA_get_ex_data(rsa, kRSAExIndex));
1520 RSA_get_ex_data(rsa, kRSASocketExIndex));
1522 ASYNC_JOB* job = ASYNC_get_current_job();
1523 if (job ==
nullptr) {
1524 throw std::runtime_error(
"Expected call in job context");
1526 ASYNC_WAIT_CTX* waitctx = ASYNC_get_wait_ctx(job);
1527 OSSL_ASYNC_FD pipefds[2] = {0, 0};
1528 makeNonBlockingPipe(pipefds);
1529 if (!ASYNC_WAIT_CTX_set_wait_fd(
1530 waitctx, kEngineId.data(), pipefds[0],
nullptr,
nullptr)) {
1531 throw std::runtime_error(
"Cannot set wait fd");
1536 auto asyncPipeWriter =
1544 actualRSA = actualRSA,
1546 socket = socket]() {
1547 LOG(
INFO) <<
"Running job";
1549 LOG(
INFO) <<
"Got a socket passed in, closing it...";
1552 *retptr = RSA_meth_get_priv_enc(RSA_PKCS1_OpenSSL())(
1553 flen,
from,
to, actualRSA, padding);
1554 LOG(
INFO) <<
"Finished job, writing to pipe";
1555 uint8_t byte = *retptr > 0 ? 1 : 0;
1556 writer->write(
nullptr, &byte, 1);
1559 LOG(
INFO) <<
"About to pause job";
1562 LOG(
INFO) <<
"Resumed job with ret: " << ret;
1566 void rsaFree(
void*,
void*
ptr, CRYPTO_EX_DATA*,
int,
long,
void*) {
1567 LOG(
INFO) <<
"RSA_free is called with ptr " << std::hex <<
ptr;
1568 if (ptr ==
nullptr) {
1569 LOG(
INFO) <<
"Returning early from rsaFree because ptr is null";
1572 RSA* rsa = (RSA*)ptr;
1573 auto meth = RSA_get_method(rsa);
1574 if (meth != RSA_get_default_method()) {
1575 auto nonconst =
const_cast<RSA_METHOD*
>(meth);
1576 RSA_meth_free(nonconst);
1577 RSA_set_method(rsa, RSA_get_default_method());
1582 struct RSAPointers {
1583 RSA* actualrsa{
nullptr};
1584 RSA* dummyrsa{
nullptr};
1585 RSA_METHOD* meth{
nullptr};
1588 inline void RSAPointersFree(RSAPointers* p) {
1589 if (p->meth && p->dummyrsa && RSA_get_method(p->dummyrsa) == p->meth) {
1590 RSA_set_method(p->dummyrsa, RSA_get_default_method());
1594 LOG(
INFO) <<
"Freeing meth";
1595 RSA_meth_free(p->meth);
1599 LOG(
INFO) <<
"Freeing actualrsa";
1600 RSA_free(p->actualrsa);
1604 LOG(
INFO) <<
"Freeing dummyrsa";
1605 RSA_free(p->dummyrsa);
1611 using RSAPointersDeleter =
1614 std::unique_ptr<RSAPointers, RSAPointersDeleter>
1615 setupCustomRSA(
const char* certPath,
const char* keyPath,
EventBase* jobEvb) {
1620 BIO_new_mem_buf((
void*)certPEM.data(), certPEM.size()));
1622 BIO_new_mem_buf((
void*)keyPEM.data(), keyPEM.size()));
1625 PEM_read_bio_X509(certBio.get(),
nullptr,
nullptr,
nullptr));
1627 PEM_read_bio_PrivateKey(keyBio.get(),
nullptr,
nullptr,
nullptr));
1630 std::unique_ptr<RSAPointers, RSAPointersDeleter> ret(
new RSAPointers());
1632 RSA* actualrsa = EVP_PKEY_get1_RSA(evpPkey.get());
1633 LOG(
INFO) <<
"actualrsa ptr " << std::hex << (
void*)actualrsa;
1634 RSA* dummyrsa = EVP_PKEY_get1_RSA(publicEvpPkey.get());
1635 if (dummyrsa ==
nullptr) {
1636 throw std::runtime_error(
"Couldn't get RSA cert public factors");
1638 RSA_METHOD* meth = RSA_meth_dup(RSA_get_default_method());
1639 if (meth ==
nullptr || RSA_meth_set1_name(meth,
"Async RSA method") == 0 ||
1640 RSA_meth_set_priv_enc(meth, customRsaPrivEnc) == 0 ||
1641 RSA_meth_set_flags(meth, RSA_METHOD_FLAG_NO_CHECK) == 0) {
1642 throw std::runtime_error(
"Cannot create async RSA_METHOD");
1644 RSA_set_method(dummyrsa, meth);
1645 RSA_set_flags(dummyrsa, RSA_FLAG_EXT_PKEY);
1647 kRSAExIndex = RSA_get_ex_new_index(0,
nullptr,
nullptr,
nullptr,
nullptr);
1648 kRSAEvbExIndex = RSA_get_ex_new_index(0,
nullptr,
nullptr,
nullptr,
nullptr);
1650 RSA_get_ex_new_index(0,
nullptr,
nullptr,
nullptr,
nullptr);
1651 CHECK_NE(kRSAExIndex, -1);
1652 CHECK_NE(kRSAEvbExIndex, -1);
1653 CHECK_NE(kRSASocketExIndex, -1);
1654 RSA_set_ex_data(dummyrsa, kRSAExIndex, actualrsa);
1655 RSA_set_ex_data(dummyrsa, kRSAEvbExIndex, jobEvb);
1657 ret->actualrsa = actualrsa;
1658 ret->dummyrsa = dummyrsa;
1665 #ifndef FOLLY_SANITIZE_ADDRESS 1666 TEST(AsyncSSLSocketTest, OpenSSL110AsyncTest) {
1667 ASYNC_init_thread(1, 1);
1670 auto clientCtx = std::make_shared<SSLContext>();
1671 auto serverCtx = std::make_shared<SSLContext>();
1672 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1674 serverCtx->loadTrustedCertificates(
kTestCA);
1675 serverCtx->loadClientCAList(
kTestCA);
1679 CHECK(rsaPointers->dummyrsa);
1681 SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa);
1682 SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC);
1684 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1685 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1702 ASYNC_cleanup_thread();
1705 TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestFailure) {
1706 ASYNC_init_thread(1, 1);
1709 auto clientCtx = std::make_shared<SSLContext>();
1710 auto serverCtx = std::make_shared<SSLContext>();
1711 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1713 serverCtx->loadTrustedCertificates(
kTestCA);
1714 serverCtx->loadClientCAList(
kTestCA);
1718 CHECK(rsaPointers->dummyrsa);
1719 SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa);
1720 SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC);
1722 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1723 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1740 ASYNC_cleanup_thread();
1743 TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestClosedWithCallbackPending) {
1744 ASYNC_init_thread(1, 1);
1747 auto clientCtx = std::make_shared<SSLContext>();
1748 auto serverCtx = std::make_shared<SSLContext>();
1749 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1751 serverCtx->loadTrustedCertificates(
kTestCA);
1752 serverCtx->loadClientCAList(
kTestCA);
1756 CHECK(rsaPointers->dummyrsa);
1758 SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa);
1759 SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC);
1761 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1762 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1772 RSA_set_ex_data(rsaPointers->dummyrsa, kRSASocketExIndex, serverSock.get());
1781 ASYNC_cleanup_thread();
1783 #endif // FOLLY_SANITIZE_ADDRESS 1785 #endif // FOLLY_OPENSSL_IS_110 1787 TEST(AsyncSSLSocketTest, LoadCertFromMemory) {
1793 BIO_write(certBio.get(), cert.data(), cert.size());
1795 BIO_write(keyBio.get(), key.data(), key.size());
1799 PEM_read_bio_X509(certBio.get(),
nullptr,
nullptr,
nullptr));
1801 PEM_read_bio_PrivateKey(keyBio.get(),
nullptr,
nullptr,
nullptr));
1805 auto origCommonName = OpenSSLUtils::getCommonName(certStruct.get());
1806 auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1807 certStruct =
nullptr;
1808 keyStruct =
nullptr;
1810 auto ctx = std::make_shared<SSLContext>();
1811 ctx->loadPrivateKeyFromBufferPEM(key);
1812 ctx->loadCertificateFromBufferPEM(cert);
1813 ctx->loadTrustedCertificates(
kTestCA);
1817 auto newCert = SSL_get_certificate(ssl.get());
1818 auto newKey = SSL_get_privatekey(ssl.get());
1821 auto newCommonName = OpenSSLUtils::getCommonName(newCert);
1822 auto newKeySize = EVP_PKEY_bits(newKey);
1825 EXPECT_EQ(origCommonName, newCommonName);
1829 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1833 auto sslContext = std::make_shared<SSLContext>();
1834 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1839 EXPECT_EQ(1500, socket->getMinWriteSize());
1841 socket->setMinWriteSize(0);
1842 EXPECT_EQ(0, socket->getMinWriteSize());
1843 socket->setMinWriteSize(50000);
1844 EXPECT_EQ(50000, socket->getMinWriteSize());
1854 std::cerr <<
"readDataAvailable, len " << len << std::endl;
1856 currentBuffer.length = len;
1858 buffers.push_back(currentBuffer);
1859 currentBuffer.reset();
1863 base_->terminateLoopSoon();
1873 TEST(AsyncSSLSocketTest, UnencryptedTest) {
1876 auto clientCtx = std::make_shared<folly::SSLContext>();
1877 auto serverCtx = std::make_shared<folly::SSLContext>();
1880 getctx(clientCtx, serverCtx);
1882 AsyncSSLSocket::newSocket(clientCtx, &base, fds[0],
false,
true);
1883 auto server = AsyncSSLSocket::newSocket(serverCtx, &base, fds[1],
true,
true);
1886 server->setReadCB(&readCallback);
1890 memset(buf,
'a',
sizeof(buf));
1891 client->write(
nullptr, buf,
sizeof(buf));
1902 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1904 server->setReadCB(&readCallback);
1907 server->sslAccept(
nullptr);
1908 client->sslConn(
nullptr);
1912 client->write(
nullptr, buf,
sizeof(buf));
1922 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1925 TEST(AsyncSSLSocketTest, ConnectUnencryptedTest) {
1926 auto clientCtx = std::make_shared<folly::SSLContext>();
1927 auto serverCtx = std::make_shared<folly::SSLContext>();
1928 getctx(clientCtx, serverCtx);
1937 std::shared_ptr<AsyncSSLSocket>
socket =
1938 AsyncSSLSocket::newSocket(clientCtx, &evb,
true);
1939 socket->connect(
nullptr, server.
getAddress(), 0);
1943 EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState());
1944 socket->sslConn(
nullptr);
1946 EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState());
1949 std::array<uint8_t, 128> buf;
1950 memset(buf.data(),
'a', buf.size());
1951 socket->write(
nullptr, buf.data(), buf.size());
1959 TEST(AsyncSSLSocketTest, SSLAcceptRunnerBasic) {
1961 auto clientCtx = std::make_shared<SSLContext>();
1962 auto serverCtx = std::make_shared<SSLContext>();
1963 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1964 serverCtx->loadPrivateKey(
kTestKey);
1967 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1968 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1969 clientCtx->loadTrustedCertificates(
kTestCA);
1979 serverCtx->sslAcceptRunner(std::make_unique<SSLAcceptEvbRunner>(&eventBase));
1994 TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptError) {
1996 auto clientCtx = std::make_shared<SSLContext>();
1997 auto serverCtx = std::make_shared<SSLContext>();
1998 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1999 serverCtx->loadPrivateKey(
kTestKey);
2002 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2003 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2004 clientCtx->loadTrustedCertificates(
kTestCA);
2014 serverCtx->sslAcceptRunner(
2015 std::make_unique<SSLAcceptErrorRunner>(&eventBase));
2028 TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptClose) {
2030 auto clientCtx = std::make_shared<SSLContext>();
2031 auto serverCtx = std::make_shared<SSLContext>();
2032 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2033 serverCtx->loadPrivateKey(
kTestKey);
2036 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2037 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2038 clientCtx->loadTrustedCertificates(
kTestCA);
2048 serverCtx->sslAcceptRunner(
2049 std::make_unique<SSLAcceptCloseRunner>(&eventBase, serverSock.get()));
2062 TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptDestroy) {
2064 auto clientCtx = std::make_shared<SSLContext>();
2065 auto serverCtx = std::make_shared<SSLContext>();
2066 serverCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2067 serverCtx->loadPrivateKey(
kTestKey);
2070 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2071 clientCtx->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2072 clientCtx->loadTrustedCertificates(
kTestCA);
2085 serverCtx->sslAcceptRunner(
2086 std::make_unique<SSLAcceptDestroyRunner>(&eventBase, &server));
2096 TEST(AsyncSSLSocketTest, ConnResetErrorString) {
2101 &readCallback, HandshakeCallback::EXPECT_ERROR);
2105 auto socket = std::make_shared<BlockingSocket>(server.
getAddress(),
nullptr);
2107 uint8_t buf[3] = {0x16, 0x03, 0x01};
2108 socket->write(buf,
sizeof(buf));
2109 socket->closeWithReset();
2113 handshakeCallback.
errorString_.find(
"Network error"), std::string::npos);
2117 TEST(AsyncSSLSocketTest, ConnEOFErrorString) {
2122 &readCallback, HandshakeCallback::EXPECT_ERROR);
2126 auto socket = std::make_shared<BlockingSocket>(server.
getAddress(),
nullptr);
2128 uint8_t buf[3] = {0x16, 0x03, 0x01};
2129 socket->write(buf,
sizeof(buf));
2133 #if FOLLY_OPENSSL_IS_110 2135 handshakeCallback.
errorString_.find(
"Network error"), std::string::npos);
2138 handshakeCallback.
errorString_.find(
"Connection EOF"), std::string::npos);
2142 TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) {
2147 &readCallback, HandshakeCallback::EXPECT_ERROR);
2151 auto socket = std::make_shared<BlockingSocket>(server.
getAddress(),
nullptr);
2153 uint8_t buf[256] = {0x16, 0x03};
2154 memset(buf + 2,
'a',
sizeof(buf) - 2);
2155 socket->write(buf,
sizeof(buf));
2160 handshakeCallback.
errorString_.find(
"SSL routines"), std::string::npos);
2161 #if defined(OPENSSL_IS_BORINGSSL) 2163 handshakeCallback.
errorString_.find(
"ENCRYPTED_LENGTH_TOO_LONG"),
2165 #elif FOLLY_OPENSSL_IS_110 2167 handshakeCallback.
errorString_.find(
"packet length too long"),
2171 handshakeCallback.
errorString_.find(
"unknown protocol"),
2176 TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) {
2179 OpenSSLUtils::getCipherName(0xc02c),
"ECDHE-ECDSA-AES256-GCM-SHA384");
2181 EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015),
"");
2183 EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff),
"");
2186 #if defined __linux__ 2190 TEST(AsyncSSLSocketTest, TTLSDisabled) {
2192 globalStatic.reset();
2202 auto sslContext = std::make_shared<SSLContext>();
2206 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2209 EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getSocketFD()));
2212 std::array<uint8_t, 128> buf;
2213 memset(buf.data(),
'a', buf.size());
2214 socket->write(buf.data(), buf.size());
2225 using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>;
2227 explicit MockAsyncTFOSSLSocket(
2228 std::shared_ptr<folly::SSLContext> sslCtx,
2232 MOCK_METHOD3(tfoSendMsg, ssize_t(
int fd,
struct msghdr* msg,
int msg_flags));
2235 #if defined __linux__ 2239 TEST(AsyncSSLSocketTest, TTLSDisabledWithTFO) {
2241 globalStatic.reset();
2251 auto sslContext = std::make_shared<SSLContext>();
2255 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2256 socket->enableTFO();
2259 EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getSocketFD()));
2262 std::array<uint8_t, 128> buf;
2263 memset(buf.data(),
'a', buf.size());
2264 socket->write(buf.data(), buf.size());
2275 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) {
2284 auto sslContext = std::make_shared<SSLContext>();
2288 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2289 socket->enableTFO();
2293 std::array<uint8_t, 128> buf;
2294 memset(buf.data(),
'a', buf.size());
2295 socket->write(buf.data(), buf.size());
2298 std::array<uint8_t, 128> readbuf;
2299 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
2301 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
2311 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) {
2320 auto sslContext = std::make_shared<SSLContext>();
2324 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2325 socket->enableTFO();
2329 std::array<uint8_t, 128> buf;
2330 memset(buf.data(),
'a', buf.size());
2331 socket->write(buf.data(), buf.size());
2334 std::array<uint8_t, 128> readbuf;
2335 uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size());
2337 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
2345 void connectSuccess()
noexcept override {
2346 state = State::SUCCESS;
2350 state = State::ERROR;
2360 template <
class Cardinality>
2361 MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback(
2366 auto sslContext = std::make_shared<SSLContext>();
2369 auto socket = MockAsyncTFOSSLSocket::UniquePtr(
2370 new MockAsyncTFOSSLSocket(sslContext, evb));
2371 socket->enableTFO();
2375 .WillOnce(
Invoke([&](
int fd,
struct msghdr*,
int) {
2376 sockaddr_storage
addr;
2378 return connect(fd, (
const struct sockaddr*)&addr, len);
2383 TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) {
2398 EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state);
2405 std::array<uint8_t, 128> buf;
2406 memset(buf.data(),
'a', buf.size());
2407 sock.
write(buf.data(), buf.size());
2410 std::array<uint8_t, 128> readbuf;
2413 EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0);
2419 #if !defined(OPENSSL_IS_BORINGSSL) 2420 TEST(AsyncSSLSocketTest, ConnectTFOTimeout) {
2426 auto sslContext = std::make_shared<SSLContext>();
2430 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2431 socket->enableTFO();
2437 #if !defined(OPENSSL_IS_BORINGSSL) 2438 TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) {
2451 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
2455 TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) {
2459 &readCallback, HandshakeCallback::EXPECT_ERROR);
2470 EXPECT_EQ(ConnCallback::State::ERROR, ccb.state);
2474 TEST(AsyncSSLSocketTest, HandshakeTFORefused) {
2480 auto socket = setupSocketWithFallback(&evb, addr,
AtMost(1));
2482 socket->connect(&ccb, addr, 100);
2489 TEST(AsyncSSLSocketTest, TestPreReceivedData) {
2491 auto clientCtx = std::make_shared<SSLContext>();
2492 auto dfServerCtx = std::make_shared<SSLContext>();
2493 std::array<int, 2> fds;
2495 getctx(clientCtx, dfServerCtx);
2501 auto clientSock = clientSockPtr.get();
2502 auto serverSock = serverSockPtr.get();
2506 std::array<uint8_t, 10> buf;
2507 auto bytesReceived =
recv(fds[1], buf.data(), buf.size(), 0);
2510 serverSock->setPreReceivedData(
2511 IOBuf::wrapBuffer(
ByteRange(buf.data(), bytesReceived)));
2520 serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2523 TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) {
2525 auto clientCtx = std::make_shared<SSLContext>();
2526 auto dfServerCtx = std::make_shared<SSLContext>();
2527 std::array<int, 2> fds;
2529 getctx(clientCtx, dfServerCtx);
2534 auto clientSock = clientSockPtr.get();
2535 auto serverSock = serverSockPtr.get();
2539 std::array<uint8_t, 10> buf;
2540 auto bytesReceived =
recv(fds[1], buf.data(), buf.size(), 0);
2543 serverSock->setPreReceivedData(
2544 IOBuf::wrapBuffer(
ByteRange(buf.data(), bytesReceived)));
2547 auto serverSSLSock = serverSSLSockPtr.get();
2556 serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten());
2563 TEST(AsyncSSLSocketTest, SendMsgParamsCallback) {
2573 auto sslContext = std::make_shared<SSLContext>();
2574 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2578 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2586 std::vector<uint8_t> buf(128,
'a');
2592 cerr <<
"SendMsgParamsCallback test completed" << endl;
2595 #ifdef FOLLY_HAVE_MSG_ERRQUEUE 2602 struct utsname s_uname;
2603 memset(&s_uname, 0,
sizeof(s_uname));
2607 if (folly::split<false>(
2608 '.',
std::string(s_uname.release) +
".", major, minor, extra)) {
2609 if (major < 4 || (major == 4 && minor < 6)) {
2610 LOG(
INFO) <<
"Kernel version: 4.6 and newer required for this test (" 2611 <<
"kernel ver. " << s_uname.release <<
" detected).";
2618 WriteCheckTimestampCallback writeCallback(&msgCallback);
2625 auto sslContext = std::make_shared<SSLContext>();
2626 sslContext->ciphers(
"ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2630 std::make_shared<BlockingSocket>(server.
getAddress(), sslContext);
2635 msgCallback.
resetFlags(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_EOR);
2640 struct cmsghdr cmsg;
2642 u.cmsg.cmsg_level = SOL_SOCKET;
2643 u.cmsg.cmsg_type = SO_TIMESTAMPING;
2644 u.cmsg.cmsg_len = CMSG_LEN(
sizeof(
uint32_t));
2645 uint32_t flags = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE |
2646 SOF_TIMESTAMPING_TX_ACK;
2647 memcpy(CMSG_DATA(&u.cmsg), &flags,
sizeof(
uint32_t));
2648 std::vector<char> ctrl(CMSG_LEN(
sizeof(
uint32_t)));
2649 memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(
sizeof(
uint32_t)));
2653 std::vector<uint8_t> buf(128,
'a');
2654 socket->write(buf.data(), buf.size());
2657 std::vector<uint8_t> readbuf(buf.size());
2658 uint32_t bytesRead =
socket->readAll(readbuf.data(), readbuf.size());
2660 EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin()));
2662 writeCallback.checkForTimestampNotifications();
2667 cerr <<
"SendMsgDataCallback test completed" << endl;
2669 #endif // FOLLY_HAVE_MSG_ERRQUEUE 2680 struct Initializer {
2682 signal(SIGPIPE, SIG_IGN);
2685 Initializer initializer;
#define EXPECT_LE(val1, val2)
EventBase * getEventBase() const
std::vector< uint8_t > buffer(kBufferSize+16)
void resetData(std::vector< char > &&data)
std::string getFileAsBuf(const char *fileName)
bool readFile(int fd, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
bool clientProtoFilterPickNone(unsigned char **, unsigned int *, const unsigned char *, unsigned int)
uint32_t getAsyncCallbacks() const
int connect(NetworkSocket s, const sockaddr *name, socklen_t namelen)
#define EXPECT_THROW(statement, expected_exception)
#define ASSERT_EQ(val1, val2)
void readDataAvailable(size_t len) noexceptoverride
std::unique_ptr< X509, X509Deleter > X509UniquePtr
GTEST_API_ Cardinality AtMost(int n)
std::unique_ptr< BIO, BioDeleter > BioUniquePtr
int setsockopt(NetworkSocket s, int level, int optname, const void *optval, socklen_t optlen)
TEST_F(TestInfoTest, Names)
const std::string kTestKey
std::enable_if< std::is_arithmetic< T >::value >::type write(T value)
#define EXPECT_EQ(val1, val2)
const char * kClientTestKey
constexpr detail::Map< Move > move
EventBase & getEventBase()
std::vector< Buffer > buffers
void sslsocketpair(EventBase *eventBase, AsyncSSLSocket::UniquePtr *clientSock, AsyncSSLSocket::UniquePtr *serverSock)
std::unique_ptr< EVP_PKEY, EvpPkeyDeleter > EvpPkeyUniquePtr
—— Concurrent Priority Queue Implementation ——
requires E e noexcept(noexcept(s.error(std::move(e))))
const char * kClientTestCert
requires And< SemiMovable< VN >... > &&SemiMovable< E > auto error(E e)
#define MOCK_METHOD3(m,...)
std::unique_ptr< AsyncSSLSocket, Destructor > UniquePtr
State
See Core for details.
folly::Synchronized< EventBase * > base_
bool loopOnce(int flags=0)
PolymorphicMatcher< internal::HasSubstrMatcher< internal::string > > HasSubstr(const internal::string &substring)
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
std::enable_if< detail::is_chrono_conversion< Tgt, Src >::value, Tgt >::type to(const Src &value)
TEST(GTestEnvVarTest, Dummy)
AsyncServerSocket::UniquePtr socket_
Encoder::MutableCompressedList list
int32_t readAll(uint8_t *buf, size_t len)
uint32_t getAsyncLookups() const
bool runInEventBaseThread(void(*fn)(T *), T *arg)
bool clientProtoFilterPickPony(unsigned char **client, unsigned int *client_len, const unsigned char *, unsigned int)
NetworkSocket socket(int af, int type, int protocol)
socklen_t getAddress(sockaddr_storage *addr) const
PUSHMI_INLINE_VAR constexpr struct folly::pushmi::operators::from_fn from
fbstring errnoStr(int err)
void checkUnixError(ssize_t ret, Args &&...args)
std::string clientCiphers_
#define EXPECT_TRUE(condition)
std::chrono::nanoseconds handshakeTime
void resetFlags(int flags)
#define EXPECT_THAT(value, matcher)
std::shared_ptr< AsyncSSLSocket > getSocket()
Range< const unsigned char * > ByteRange
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
#define EXPECT_NE(val1, val2)
static UniquePtr newWriter(Args &&...args)
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
std::string chosenCipher_
#define EXPECT_FALSE(condition)
ssize_t recv(NetworkSocket s, void *buf, size_t len, int flags)
const char * kClientTestCA
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
std::shared_ptr< AsyncSocket > tcpSocket_
ReadCallbackTerminator(EventBase *base, WriteCallbackBase *wcb)
#define ASSERT_TRUE(condition)
ThreadPoolListHook * addr
std::unique_ptr< AsyncSocket, Destructor > UniquePtr
const SocketAddress & getAddress() const
void pipe(CPUExecutor cpu, IOExecutor io)
int32_t write(uint8_t const *buf, size_t len)
std::unique_ptr< SSL, SSLDeleter > SSLUniquePtr
void setSocket(const std::shared_ptr< AsyncSSLSocket > &socket)
int socketpair(int domain, int type, int protocol, NetworkSocket sv[2])