2 * Copyright 2015 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>
21 #include <folly/io/async/AsyncSSLSocket.h>
22 #include <folly/io/async/EventBase.h>
23 #include <folly/SocketAddress.h>
25 #include <folly/io/async/test/BlockingSocket.h>
27 #include <gtest/gtest.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/tcp.h>
37 #include <folly/io/Cursor.h>
47 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
48 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
49 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
51 const char* testCert = "folly/io/async/test/certs/tests-cert.pem";
52 const char* testKey = "folly/io/async/test/certs/tests-key.pem";
53 const char* testCA = "folly/io/async/test/certs/ca-cert.pem";
55 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase *acb) :
56 ctx_(new folly::SSLContext),
58 socket_(new folly::AsyncServerSocket(&evb_)) {
59 // Set up the SSL context
60 ctx_->loadCertificate(testCert);
61 ctx_->loadPrivateKey(testKey);
62 ctx_->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
67 //set up the listening socket
69 socket_->getAddress(&address_);
71 socket_->addAcceptCallback(acb_, &evb_);
72 socket_->startAccepting();
74 int ret = pthread_create(&thread_, nullptr, Main, this);
77 std::cerr << "Accepting connections on " << address_ << std::endl;
80 void getfds(int fds[2]) {
81 if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
82 FAIL() << "failed to create socketpair: " << strerror(errno);
84 for (int idx = 0; idx < 2; ++idx) {
85 int flags = fcntl(fds[idx], F_GETFL, 0);
87 FAIL() << "failed to get flags for socket " << idx << ": "
90 if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
91 FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
98 std::shared_ptr<folly::SSLContext> clientCtx,
99 std::shared_ptr<folly::SSLContext> serverCtx) {
100 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
102 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
103 serverCtx->loadCertificate(
105 serverCtx->loadPrivateKey(
110 EventBase* eventBase,
111 AsyncSSLSocket::UniquePtr* clientSock,
112 AsyncSSLSocket::UniquePtr* serverSock) {
113 auto clientCtx = std::make_shared<folly::SSLContext>();
114 auto serverCtx = std::make_shared<folly::SSLContext>();
117 getctx(clientCtx, serverCtx);
118 clientSock->reset(new AsyncSSLSocket(
119 clientCtx, eventBase, fds[0], false));
120 serverSock->reset(new AsyncSSLSocket(
121 serverCtx, eventBase, fds[1], true));
123 // (*clientSock)->setSendTimeout(100);
124 // (*serverSock)->setSendTimeout(100);
129 * Test connecting to, writing to, reading from, and closing the
130 * connection to the SSL server.
132 TEST(AsyncSSLSocketTest, ConnectWriteReadClose) {
133 // Start listening on a local port
134 WriteCallbackBase writeCallback;
135 ReadCallback readCallback(&writeCallback);
136 HandshakeCallback handshakeCallback(&readCallback);
137 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
138 TestSSLServer server(&acceptCallback);
140 // Set up SSL context.
141 std::shared_ptr<SSLContext> sslContext(new SSLContext());
142 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
143 //sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
144 //sslContext->authenticate(true, false);
147 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
153 memset(buf, 'a', sizeof(buf));
154 socket->write(buf, sizeof(buf));
157 uint8_t readbuf[128];
158 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
159 EXPECT_EQ(bytesRead, 128);
160 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
165 cerr << "ConnectWriteReadClose test completed" << endl;
169 * Negative test for handshakeError().
171 TEST(AsyncSSLSocketTest, HandshakeError) {
172 // Start listening on a local port
173 WriteCallbackBase writeCallback;
174 ReadCallback readCallback(&writeCallback);
175 HandshakeCallback handshakeCallback(&readCallback);
176 HandshakeErrorCallback acceptCallback(&handshakeCallback);
177 TestSSLServer server(&acceptCallback);
179 // Set up SSL context.
180 std::shared_ptr<SSLContext> sslContext(new SSLContext());
181 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
184 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
191 uint8_t readbuf[128];
192 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
193 } catch (AsyncSocketException &e) {
200 cerr << "HandshakeError test completed" << endl;
204 * Negative test for readError().
206 TEST(AsyncSSLSocketTest, ReadError) {
207 // Start listening on a local port
208 WriteCallbackBase writeCallback;
209 ReadErrorCallback readCallback(&writeCallback);
210 HandshakeCallback handshakeCallback(&readCallback);
211 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
212 TestSSLServer server(&acceptCallback);
214 // Set up SSL context.
215 std::shared_ptr<SSLContext> sslContext(new SSLContext());
216 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
219 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
223 // write something to trigger ssl handshake
225 memset(buf, 'a', sizeof(buf));
226 socket->write(buf, sizeof(buf));
229 cerr << "ReadError test completed" << endl;
233 * Negative test for writeError().
235 TEST(AsyncSSLSocketTest, WriteError) {
236 // Start listening on a local port
237 WriteCallbackBase writeCallback;
238 WriteErrorCallback readCallback(&writeCallback);
239 HandshakeCallback handshakeCallback(&readCallback);
240 SSLServerAcceptCallback acceptCallback(&handshakeCallback);
241 TestSSLServer server(&acceptCallback);
243 // Set up SSL context.
244 std::shared_ptr<SSLContext> sslContext(new SSLContext());
245 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
248 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
252 // write something to trigger ssl handshake
254 memset(buf, 'a', sizeof(buf));
255 socket->write(buf, sizeof(buf));
258 cerr << "WriteError test completed" << endl;
262 * Test a socket with TCP_NODELAY unset.
264 TEST(AsyncSSLSocketTest, SocketWithDelay) {
265 // Start listening on a local port
266 WriteCallbackBase writeCallback;
267 ReadCallback readCallback(&writeCallback);
268 HandshakeCallback handshakeCallback(&readCallback);
269 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
270 TestSSLServer server(&acceptCallback);
272 // Set up SSL context.
273 std::shared_ptr<SSLContext> sslContext(new SSLContext());
274 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
277 auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
283 memset(buf, 'a', sizeof(buf));
284 socket->write(buf, sizeof(buf));
287 uint8_t readbuf[128];
288 uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
289 EXPECT_EQ(bytesRead, 128);
290 EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
295 cerr << "SocketWithDelay test completed" << endl;
298 TEST(AsyncSSLSocketTest, NpnTestOverlap) {
300 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
301 std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
304 getctx(clientCtx, serverCtx);
306 clientCtx->setAdvertisedNextProtocols({"blub","baz"});
307 serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
309 AsyncSSLSocket::UniquePtr clientSock(
310 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
311 AsyncSSLSocket::UniquePtr serverSock(
312 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
313 NpnClient client(std::move(clientSock));
314 NpnServer server(std::move(serverSock));
318 EXPECT_TRUE(client.nextProtoLength != 0);
319 EXPECT_EQ(client.nextProtoLength, server.nextProtoLength);
320 EXPECT_EQ(memcmp(client.nextProto, server.nextProto,
321 server.nextProtoLength), 0);
322 string selected((const char*)client.nextProto, client.nextProtoLength);
323 EXPECT_EQ(selected.compare("baz"), 0);
326 TEST(AsyncSSLSocketTest, NpnTestUnset) {
327 // Identical to above test, except that we want unset NPN before
330 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
331 std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
334 getctx(clientCtx, serverCtx);
336 clientCtx->setAdvertisedNextProtocols({"blub","baz"});
337 serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
339 AsyncSSLSocket::UniquePtr clientSock(
340 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
341 AsyncSSLSocket::UniquePtr serverSock(
342 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
344 // unsetting NPN for any of [client, server] is enought to make NPN not
346 clientCtx->unsetNextProtocols();
348 NpnClient client(std::move(clientSock));
349 NpnServer server(std::move(serverSock));
353 EXPECT_TRUE(client.nextProtoLength == 0);
354 EXPECT_TRUE(server.nextProtoLength == 0);
355 EXPECT_TRUE(client.nextProto == nullptr);
356 EXPECT_TRUE(server.nextProto == nullptr);
359 TEST(AsyncSSLSocketTest, NpnTestNoOverlap) {
361 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
362 std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
365 getctx(clientCtx, serverCtx);
367 clientCtx->setAdvertisedNextProtocols({"blub"});
368 serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
370 AsyncSSLSocket::UniquePtr clientSock(
371 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
372 AsyncSSLSocket::UniquePtr serverSock(
373 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
374 NpnClient client(std::move(clientSock));
375 NpnServer server(std::move(serverSock));
379 EXPECT_TRUE(client.nextProtoLength != 0);
380 EXPECT_EQ(client.nextProtoLength, server.nextProtoLength);
381 EXPECT_EQ(memcmp(client.nextProto, server.nextProto,
382 server.nextProtoLength), 0);
383 string selected((const char*)client.nextProto, client.nextProtoLength);
384 EXPECT_EQ(selected.compare("blub"), 0);
387 TEST(AsyncSSLSocketTest, RandomizedNpnTest) {
388 // Probability that this test will fail is 2^-64, which could be considered
390 const int kTries = 64;
392 std::set<string> selectedProtocols;
393 for (int i = 0; i < kTries; ++i) {
395 std::shared_ptr<SSLContext> clientCtx = std::make_shared<SSLContext>();
396 std::shared_ptr<SSLContext> serverCtx = std::make_shared<SSLContext>();
399 getctx(clientCtx, serverCtx);
401 clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"});
402 serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}},
406 AsyncSSLSocket::UniquePtr clientSock(
407 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
408 AsyncSSLSocket::UniquePtr serverSock(
409 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
410 NpnClient client(std::move(clientSock));
411 NpnServer server(std::move(serverSock));
415 EXPECT_TRUE(client.nextProtoLength != 0);
416 EXPECT_EQ(client.nextProtoLength, server.nextProtoLength);
417 EXPECT_EQ(memcmp(client.nextProto, server.nextProto,
418 server.nextProtoLength), 0);
419 string selected((const char*)client.nextProto, client.nextProtoLength);
420 selectedProtocols.insert(selected);
422 EXPECT_EQ(selectedProtocols.size(), 2);
426 #ifndef OPENSSL_NO_TLSEXT
428 * 1. Client sends TLSEXT_HOSTNAME in client hello.
429 * 2. Server found a match SSL_CTX and use this SSL_CTX to
430 * continue the SSL handshake.
431 * 3. Server sends back TLSEXT_HOSTNAME in server hello.
433 TEST(AsyncSSLSocketTest, SNITestMatch) {
435 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
436 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
437 // Use the same SSLContext to continue the handshake after
438 // tlsext_hostname match.
439 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
440 const std::string serverName("xyz.newdev.facebook.com");
443 getctx(clientCtx, dfServerCtx);
445 AsyncSSLSocket::UniquePtr clientSock(
446 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
447 AsyncSSLSocket::UniquePtr serverSock(
448 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
449 SNIClient client(std::move(clientSock));
450 SNIServer server(std::move(serverSock),
457 EXPECT_TRUE(client.serverNameMatch);
458 EXPECT_TRUE(server.serverNameMatch);
462 * 1. Client sends TLSEXT_HOSTNAME in client hello.
463 * 2. Server cannot find a matching SSL_CTX and continue to use
464 * the current SSL_CTX to do the handshake.
465 * 3. Server does not send back TLSEXT_HOSTNAME in server hello.
467 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
469 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
470 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
471 // Use the same SSLContext to continue the handshake after
472 // tlsext_hostname match.
473 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
474 const std::string clientRequestingServerName("foo.com");
475 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
479 getctx(clientCtx, dfServerCtx);
481 AsyncSSLSocket::UniquePtr clientSock(
482 new AsyncSSLSocket(clientCtx,
485 clientRequestingServerName));
486 AsyncSSLSocket::UniquePtr serverSock(
487 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
488 SNIClient client(std::move(clientSock));
489 SNIServer server(std::move(serverSock),
492 serverExpectedServerName);
496 EXPECT_TRUE(!client.serverNameMatch);
497 EXPECT_TRUE(!server.serverNameMatch);
501 * 1. Client does not send TLSEXT_HOSTNAME in client hello.
502 * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
504 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
506 std::shared_ptr<SSLContext> clientCtx(new SSLContext);
507 std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
508 // Use the same SSLContext to continue the handshake after
509 // tlsext_hostname match.
510 std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
511 const std::string serverExpectedServerName("xyz.newdev.facebook.com");
515 getctx(clientCtx, dfServerCtx);
517 AsyncSSLSocket::UniquePtr clientSock(
518 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
519 AsyncSSLSocket::UniquePtr serverSock(
520 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
521 SNIClient client(std::move(clientSock));
522 SNIServer server(std::move(serverSock),
525 serverExpectedServerName);
529 EXPECT_TRUE(!client.serverNameMatch);
530 EXPECT_TRUE(!server.serverNameMatch);
535 * Test SSL client socket
537 TEST(AsyncSSLSocketTest, SSLClientTest) {
538 // Start listening on a local port
539 WriteCallbackBase writeCallback;
540 ReadCallback readCallback(&writeCallback);
541 HandshakeCallback handshakeCallback(&readCallback);
542 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
543 TestSSLServer server(&acceptCallback);
547 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
551 EventBaseAborter eba(&eventBase, 3000);
554 EXPECT_EQ(client->getMiss(), 1);
555 EXPECT_EQ(client->getHit(), 0);
557 cerr << "SSLClientTest test completed" << endl;
562 * Test SSL client socket session re-use
564 TEST(AsyncSSLSocketTest, SSLClientTestReuse) {
565 // Start listening on a local port
566 WriteCallbackBase writeCallback;
567 ReadCallback readCallback(&writeCallback);
568 HandshakeCallback handshakeCallback(&readCallback);
569 SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
570 TestSSLServer server(&acceptCallback);
574 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
578 EventBaseAborter eba(&eventBase, 3000);
581 EXPECT_EQ(client->getMiss(), 1);
582 EXPECT_EQ(client->getHit(), 9);
584 cerr << "SSLClientTestReuse test completed" << endl;
588 * Test SSL client socket timeout
590 TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) {
591 // Start listening on a local port
592 EmptyReadCallback readCallback;
593 HandshakeCallback handshakeCallback(&readCallback,
594 HandshakeCallback::EXPECT_ERROR);
595 HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
596 TestSSLServer server(&acceptCallback);
600 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
602 client->connect(true /* write before connect completes */);
603 EventBaseAborter eba(&eventBase, 3000);
607 // This is checking that the connectError callback precedes any queued
608 // writeError callbacks. This matches AsyncSocket's behavior
609 EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
610 EXPECT_EQ(client->getErrors(), 1);
611 EXPECT_EQ(client->getMiss(), 0);
612 EXPECT_EQ(client->getHit(), 0);
614 cerr << "SSLClientTimeoutTest test completed" << endl;
619 * Test SSL server async cache
621 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTest) {
622 // Start listening on a local port
623 WriteCallbackBase writeCallback;
624 ReadCallback readCallback(&writeCallback);
625 HandshakeCallback handshakeCallback(&readCallback);
626 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
627 TestSSLAsyncCacheServer server(&acceptCallback);
631 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
635 EventBaseAborter eba(&eventBase, 3000);
638 EXPECT_EQ(server.getAsyncCallbacks(), 18);
639 EXPECT_EQ(server.getAsyncLookups(), 9);
640 EXPECT_EQ(client->getMiss(), 10);
641 EXPECT_EQ(client->getHit(), 0);
643 cerr << "SSLServerAsyncCacheTest test completed" << endl;
648 * Test SSL server accept timeout with cache path
650 TEST(AsyncSSLSocketTest, SSLServerTimeoutTest) {
651 // Start listening on a local port
652 WriteCallbackBase writeCallback;
653 ReadCallback readCallback(&writeCallback);
654 EmptyReadCallback clientReadCallback;
655 HandshakeCallback handshakeCallback(&readCallback);
656 SSLServerAcceptCallback acceptCallback(&handshakeCallback, 50);
657 TestSSLAsyncCacheServer server(&acceptCallback);
661 // only do a TCP connect
662 std::shared_ptr<AsyncSocket> sock = AsyncSocket::newSocket(&eventBase);
663 sock->connect(nullptr, server.getAddress());
664 clientReadCallback.tcpSocket_ = sock;
665 sock->setReadCB(&clientReadCallback);
667 EventBaseAborter eba(&eventBase, 3000);
670 EXPECT_EQ(readCallback.state, STATE_WAITING);
672 cerr << "SSLServerTimeoutTest test completed" << endl;
676 * Test SSL server accept timeout with cache path
678 TEST(AsyncSSLSocketTest, SSLServerAsyncCacheTimeoutTest) {
679 // Start listening on a local port
680 WriteCallbackBase writeCallback;
681 ReadCallback readCallback(&writeCallback);
682 HandshakeCallback handshakeCallback(&readCallback);
683 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback, 50);
684 TestSSLAsyncCacheServer server(&acceptCallback);
688 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
692 EventBaseAborter eba(&eventBase, 3000);
695 EXPECT_EQ(server.getAsyncCallbacks(), 1);
696 EXPECT_EQ(server.getAsyncLookups(), 1);
697 EXPECT_EQ(client->getErrors(), 1);
698 EXPECT_EQ(client->getMiss(), 1);
699 EXPECT_EQ(client->getHit(), 0);
701 cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
705 * Test SSL server accept timeout with cache path
707 TEST(AsyncSSLSocketTest, SSLServerCacheCloseTest) {
708 // Start listening on a local port
709 WriteCallbackBase writeCallback;
710 ReadCallback readCallback(&writeCallback);
711 HandshakeCallback handshakeCallback(&readCallback,
712 HandshakeCallback::EXPECT_ERROR);
713 SSLServerAsyncCacheAcceptCallback acceptCallback(&handshakeCallback);
714 TestSSLAsyncCacheServer server(&acceptCallback, 500);
718 std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
722 EventBaseAborter eba(&eventBase, 3000);
725 server.getEventBase().runInEventBaseThread([&handshakeCallback]{
726 handshakeCallback.closeSocket();});
727 // give time for the cache lookup to come back and find it closed
730 EXPECT_EQ(server.getAsyncCallbacks(), 1);
731 EXPECT_EQ(server.getAsyncLookups(), 1);
732 EXPECT_EQ(client->getErrors(), 1);
733 EXPECT_EQ(client->getMiss(), 1);
734 EXPECT_EQ(client->getHit(), 0);
736 cerr << "SSLServerCacheCloseTest test completed" << endl;
740 * Verify Client Ciphers obtained using SSL MSG Callback.
742 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
744 auto clientCtx = std::make_shared<SSLContext>();
745 auto serverCtx = std::make_shared<SSLContext>();
746 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
747 serverCtx->ciphers("RSA:!SHA:!NULL:!SHA256@STRENGTH");
748 serverCtx->loadPrivateKey(testKey);
749 serverCtx->loadCertificate(testCert);
750 serverCtx->loadTrustedCertificates(testCA);
751 serverCtx->loadClientCAList(testCA);
753 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
754 clientCtx->ciphers("RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5");
755 clientCtx->loadPrivateKey(testKey);
756 clientCtx->loadCertificate(testCert);
757 clientCtx->loadTrustedCertificates(testCA);
762 AsyncSSLSocket::UniquePtr clientSock(
763 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
764 AsyncSSLSocket::UniquePtr serverSock(
765 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
767 SSLHandshakeClient client(std::move(clientSock), true, true);
768 SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
772 EXPECT_EQ(server.clientCiphers_,
773 "RC4-SHA:AES128-SHA:AES256-SHA:RC4-MD5:00ff");
774 EXPECT_TRUE(client.handshakeVerify_);
775 EXPECT_TRUE(client.handshakeSuccess_);
776 EXPECT_TRUE(!client.handshakeError_);
777 EXPECT_TRUE(server.handshakeVerify_);
778 EXPECT_TRUE(server.handshakeSuccess_);
779 EXPECT_TRUE(!server.handshakeError_);
782 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
784 auto ctx = std::make_shared<SSLContext>();
790 uint8_t majorVersion = 18;
791 uint8_t minorVersion = 25;
793 // Create callback buf
794 auto buf = IOBuf::create(bufLen);
796 folly::io::RWPrivateCursor cursor(buf.get());
797 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
798 cursor.write<uint16_t>(0);
799 cursor.write<uint8_t>(38);
800 cursor.write<uint8_t>(majorVersion);
801 cursor.write<uint8_t>(minorVersion);
803 cursor.write<uint32_t>(0);
805 SSL* ssl = ctx->createSSL();
806 AsyncSSLSocket::UniquePtr sock(
807 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
808 sock->enableClientHelloParsing();
810 // Test client hello parsing in one packet
811 AsyncSSLSocket::clientHelloParsingCallback(
812 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
815 auto parsedClientHello = sock->getClientHelloInfo();
816 EXPECT_TRUE(parsedClientHello != nullptr);
817 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
818 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
821 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
823 auto ctx = std::make_shared<SSLContext>();
829 uint8_t majorVersion = 18;
830 uint8_t minorVersion = 25;
832 // Create callback buf
833 auto buf = IOBuf::create(bufLen);
835 folly::io::RWPrivateCursor cursor(buf.get());
836 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
837 cursor.write<uint16_t>(0);
838 cursor.write<uint8_t>(38);
839 cursor.write<uint8_t>(majorVersion);
840 cursor.write<uint8_t>(minorVersion);
842 cursor.write<uint32_t>(0);
844 SSL* ssl = ctx->createSSL();
845 AsyncSSLSocket::UniquePtr sock(
846 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
847 sock->enableClientHelloParsing();
849 // Test parsing with two packets with first packet size < 3
850 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
851 AsyncSSLSocket::clientHelloParsingCallback(
852 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
855 bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
856 AsyncSSLSocket::clientHelloParsingCallback(
857 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
861 auto parsedClientHello = sock->getClientHelloInfo();
862 EXPECT_TRUE(parsedClientHello != nullptr);
863 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
864 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
867 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
869 auto ctx = std::make_shared<SSLContext>();
875 uint8_t majorVersion = 18;
876 uint8_t minorVersion = 25;
878 // Create callback buf
879 auto buf = IOBuf::create(bufLen);
881 folly::io::RWPrivateCursor cursor(buf.get());
882 cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
883 cursor.write<uint16_t>(0);
884 cursor.write<uint8_t>(38);
885 cursor.write<uint8_t>(majorVersion);
886 cursor.write<uint8_t>(minorVersion);
888 cursor.write<uint32_t>(0);
890 SSL* ssl = ctx->createSSL();
891 AsyncSSLSocket::UniquePtr sock(
892 new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
893 sock->enableClientHelloParsing();
895 // Test parsing with multiple small packets
896 for (uint64_t i = 0; i < buf->length(); i += 3) {
897 auto bufCopy = folly::IOBuf::copyBuffer(
898 buf->data() + i, std::min((uint64_t)3, buf->length() - i));
899 AsyncSSLSocket::clientHelloParsingCallback(
900 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
905 auto parsedClientHello = sock->getClientHelloInfo();
906 EXPECT_TRUE(parsedClientHello != nullptr);
907 EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
908 EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
912 * Verify sucessful behavior of SSL certificate validation.
914 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
916 auto clientCtx = std::make_shared<SSLContext>();
917 auto dfServerCtx = std::make_shared<SSLContext>();
921 getctx(clientCtx, dfServerCtx);
923 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
924 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
926 AsyncSSLSocket::UniquePtr clientSock(
927 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
928 AsyncSSLSocket::UniquePtr serverSock(
929 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
931 SSLHandshakeClient client(std::move(clientSock), true, true);
932 clientCtx->loadTrustedCertificates(testCA);
934 SSLHandshakeServer server(std::move(serverSock), true, true);
938 EXPECT_TRUE(client.handshakeVerify_);
939 EXPECT_TRUE(client.handshakeSuccess_);
940 EXPECT_TRUE(!client.handshakeError_);
941 EXPECT_TRUE(!server.handshakeVerify_);
942 EXPECT_TRUE(server.handshakeSuccess_);
943 EXPECT_TRUE(!server.handshakeError_);
947 * Verify that the client's verification callback is able to fail SSL
948 * connection establishment.
950 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
952 auto clientCtx = std::make_shared<SSLContext>();
953 auto dfServerCtx = std::make_shared<SSLContext>();
957 getctx(clientCtx, dfServerCtx);
959 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
960 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
962 AsyncSSLSocket::UniquePtr clientSock(
963 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
964 AsyncSSLSocket::UniquePtr serverSock(
965 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
967 SSLHandshakeClient client(std::move(clientSock), true, false);
968 clientCtx->loadTrustedCertificates(testCA);
970 SSLHandshakeServer server(std::move(serverSock), true, true);
974 EXPECT_TRUE(client.handshakeVerify_);
975 EXPECT_TRUE(!client.handshakeSuccess_);
976 EXPECT_TRUE(client.handshakeError_);
977 EXPECT_TRUE(!server.handshakeVerify_);
978 EXPECT_TRUE(!server.handshakeSuccess_);
979 EXPECT_TRUE(server.handshakeError_);
983 * Verify that the options in SSLContext can be overridden in
984 * sslConnect/Accept.i.e specifying that no validation should be performed
985 * allows an otherwise-invalid certificate to be accepted and doesn't fire
986 * the validation callback.
988 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
990 auto clientCtx = std::make_shared<SSLContext>();
991 auto dfServerCtx = std::make_shared<SSLContext>();
995 getctx(clientCtx, dfServerCtx);
997 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
998 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1000 AsyncSSLSocket::UniquePtr clientSock(
1001 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1002 AsyncSSLSocket::UniquePtr serverSock(
1003 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1005 SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1006 clientCtx->loadTrustedCertificates(testCA);
1008 SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1012 EXPECT_TRUE(!client.handshakeVerify_);
1013 EXPECT_TRUE(client.handshakeSuccess_);
1014 EXPECT_TRUE(!client.handshakeError_);
1015 EXPECT_TRUE(!server.handshakeVerify_);
1016 EXPECT_TRUE(server.handshakeSuccess_);
1017 EXPECT_TRUE(!server.handshakeError_);
1021 * Verify that the options in SSLContext can be overridden in
1022 * sslConnect/Accept. Enable verification even if context says otherwise.
1023 * Test requireClientCert with client cert
1025 TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) {
1026 EventBase eventBase;
1027 auto clientCtx = std::make_shared<SSLContext>();
1028 auto serverCtx = std::make_shared<SSLContext>();
1029 serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1030 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1031 serverCtx->loadPrivateKey(testKey);
1032 serverCtx->loadCertificate(testCert);
1033 serverCtx->loadTrustedCertificates(testCA);
1034 serverCtx->loadClientCAList(testCA);
1036 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1037 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1038 clientCtx->loadPrivateKey(testKey);
1039 clientCtx->loadCertificate(testCert);
1040 clientCtx->loadTrustedCertificates(testCA);
1045 AsyncSSLSocket::UniquePtr clientSock(
1046 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1047 AsyncSSLSocket::UniquePtr serverSock(
1048 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1050 SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1051 SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1055 EXPECT_TRUE(client.handshakeVerify_);
1056 EXPECT_TRUE(client.handshakeSuccess_);
1057 EXPECT_FALSE(client.handshakeError_);
1058 EXPECT_TRUE(server.handshakeVerify_);
1059 EXPECT_TRUE(server.handshakeSuccess_);
1060 EXPECT_FALSE(server.handshakeError_);
1064 * Verify that the client's verification callback is able to override
1065 * the preverification failure and allow a successful connection.
1067 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1068 EventBase eventBase;
1069 auto clientCtx = std::make_shared<SSLContext>();
1070 auto dfServerCtx = std::make_shared<SSLContext>();
1074 getctx(clientCtx, dfServerCtx);
1076 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1077 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1079 AsyncSSLSocket::UniquePtr clientSock(
1080 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1081 AsyncSSLSocket::UniquePtr serverSock(
1082 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1084 SSLHandshakeClient client(std::move(clientSock), false, true);
1085 SSLHandshakeServer server(std::move(serverSock), true, true);
1089 EXPECT_TRUE(client.handshakeVerify_);
1090 EXPECT_TRUE(client.handshakeSuccess_);
1091 EXPECT_TRUE(!client.handshakeError_);
1092 EXPECT_TRUE(!server.handshakeVerify_);
1093 EXPECT_TRUE(server.handshakeSuccess_);
1094 EXPECT_TRUE(!server.handshakeError_);
1098 * Verify that specifying that no validation should be performed allows an
1099 * otherwise-invalid certificate to be accepted and doesn't fire the validation
1102 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1103 EventBase eventBase;
1104 auto clientCtx = std::make_shared<SSLContext>();
1105 auto dfServerCtx = std::make_shared<SSLContext>();
1109 getctx(clientCtx, dfServerCtx);
1111 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1112 dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1114 AsyncSSLSocket::UniquePtr clientSock(
1115 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1116 AsyncSSLSocket::UniquePtr serverSock(
1117 new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1119 SSLHandshakeClient client(std::move(clientSock), false, false);
1120 SSLHandshakeServer server(std::move(serverSock), false, false);
1124 EXPECT_TRUE(!client.handshakeVerify_);
1125 EXPECT_TRUE(client.handshakeSuccess_);
1126 EXPECT_TRUE(!client.handshakeError_);
1127 EXPECT_TRUE(!server.handshakeVerify_);
1128 EXPECT_TRUE(server.handshakeSuccess_);
1129 EXPECT_TRUE(!server.handshakeError_);
1133 * Test requireClientCert with client cert
1135 TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) {
1136 EventBase eventBase;
1137 auto clientCtx = std::make_shared<SSLContext>();
1138 auto serverCtx = std::make_shared<SSLContext>();
1139 serverCtx->setVerificationOption(
1140 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1141 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1142 serverCtx->loadPrivateKey(testKey);
1143 serverCtx->loadCertificate(testCert);
1144 serverCtx->loadTrustedCertificates(testCA);
1145 serverCtx->loadClientCAList(testCA);
1147 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1148 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1149 clientCtx->loadPrivateKey(testKey);
1150 clientCtx->loadCertificate(testCert);
1151 clientCtx->loadTrustedCertificates(testCA);
1156 AsyncSSLSocket::UniquePtr clientSock(
1157 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1158 AsyncSSLSocket::UniquePtr serverSock(
1159 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1161 SSLHandshakeClient client(std::move(clientSock), true, true);
1162 SSLHandshakeServer server(std::move(serverSock), true, true);
1166 EXPECT_TRUE(client.handshakeVerify_);
1167 EXPECT_TRUE(client.handshakeSuccess_);
1168 EXPECT_FALSE(client.handshakeError_);
1169 EXPECT_TRUE(server.handshakeVerify_);
1170 EXPECT_TRUE(server.handshakeSuccess_);
1171 EXPECT_FALSE(server.handshakeError_);
1176 * Test requireClientCert with no client cert
1178 TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) {
1179 EventBase eventBase;
1180 auto clientCtx = std::make_shared<SSLContext>();
1181 auto serverCtx = std::make_shared<SSLContext>();
1182 serverCtx->setVerificationOption(
1183 SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1184 serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1185 serverCtx->loadPrivateKey(testKey);
1186 serverCtx->loadCertificate(testCert);
1187 serverCtx->loadTrustedCertificates(testCA);
1188 serverCtx->loadClientCAList(testCA);
1189 clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1190 clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1195 AsyncSSLSocket::UniquePtr clientSock(
1196 new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1197 AsyncSSLSocket::UniquePtr serverSock(
1198 new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1200 SSLHandshakeClient client(std::move(clientSock), false, false);
1201 SSLHandshakeServer server(std::move(serverSock), false, false);
1205 EXPECT_FALSE(server.handshakeVerify_);
1206 EXPECT_FALSE(server.handshakeSuccess_);
1207 EXPECT_TRUE(server.handshakeError_);
1210 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1213 // Set up SSL context.
1214 auto sslContext = std::make_shared<SSLContext>();
1215 sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1217 // create SSL socket
1218 AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1220 EXPECT_EQ(1500, socket->getMinWriteSize());
1222 socket->setMinWriteSize(0);
1223 EXPECT_EQ(0, socket->getMinWriteSize());
1224 socket->setMinWriteSize(50000);
1225 EXPECT_EQ(50000, socket->getMinWriteSize());
1229 ///////////////////////////////////////////////////////////////////////////
1230 // init_unit_test_suite
1231 ///////////////////////////////////////////////////////////////////////////
1233 struct Initializer {
1235 signal(SIGPIPE, SIG_IGN);
1238 Initializer initializer;