Make MIN_WRITE_SIZE configurable for AsyncSSLSocket.
[folly.git] / folly / io / async / test / AsyncSSLSocketTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 #include <folly/io/async/test/AsyncSSLSocketTest.h>
17
18 #include <signal.h>
19 #include <pthread.h>
20
21 #include <folly/io/async/AsyncSSLSocket.h>
22 #include <folly/io/async/EventBase.h>
23 #include <folly/SocketAddress.h>
24
25 #include <folly/io/async/test/BlockingSocket.h>
26
27 #include <gtest/gtest.h>
28 #include <iostream>
29 #include <list>
30 #include <set>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <poll.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <netinet/tcp.h>
37 #include <folly/io/Cursor.h>
38
39 using std::string;
40 using std::vector;
41 using std::min;
42 using std::cerr;
43 using std::endl;
44 using std::list;
45
46 namespace folly {
47 uint32_t TestSSLAsyncCacheServer::asyncCallbacks_ = 0;
48 uint32_t TestSSLAsyncCacheServer::asyncLookups_ = 0;
49 uint32_t TestSSLAsyncCacheServer::lookupDelay_ = 0;
50
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";
54
55 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase *acb) :
56 ctx_(new folly::SSLContext),
57     acb_(acb),
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");
63
64   acb_->ctx_ = ctx_;
65   acb_->base_ = &evb_;
66
67   //set up the listening socket
68   socket_->bind(0);
69   socket_->getAddress(&address_);
70   socket_->listen(100);
71   socket_->addAcceptCallback(acb_, &evb_);
72   socket_->startAccepting();
73
74   int ret = pthread_create(&thread_, nullptr, Main, this);
75   assert(ret == 0);
76
77   std::cerr << "Accepting connections on " << address_ << std::endl;
78 }
79
80 void getfds(int fds[2]) {
81   if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
82     FAIL() << "failed to create socketpair: " << strerror(errno);
83   }
84   for (int idx = 0; idx < 2; ++idx) {
85     int flags = fcntl(fds[idx], F_GETFL, 0);
86     if (flags == -1) {
87       FAIL() << "failed to get flags for socket " << idx << ": "
88              << strerror(errno);
89     }
90     if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
91       FAIL() << "failed to put socket " << idx << " in non-blocking mode: "
92              << strerror(errno);
93     }
94   }
95 }
96
97 void getctx(
98   std::shared_ptr<folly::SSLContext> clientCtx,
99   std::shared_ptr<folly::SSLContext> serverCtx) {
100   clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
101
102   serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
103   serverCtx->loadCertificate(
104       testCert);
105   serverCtx->loadPrivateKey(
106       testKey);
107 }
108
109 void sslsocketpair(
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>();
115   int fds[2];
116   getfds(fds);
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));
122
123   // (*clientSock)->setSendTimeout(100);
124   // (*serverSock)->setSendTimeout(100);
125 }
126
127
128 /**
129  * Test connecting to, writing to, reading from, and closing the
130  * connection to the SSL server.
131  */
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);
139
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);
145
146   // connect
147   auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
148                                                  sslContext);
149   socket->open();
150
151   // write()
152   uint8_t buf[128];
153   memset(buf, 'a', sizeof(buf));
154   socket->write(buf, sizeof(buf));
155
156   // read()
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);
161
162   // close()
163   socket->close();
164
165   cerr << "ConnectWriteReadClose test completed" << endl;
166 }
167
168 /**
169  * Negative test for handshakeError().
170  */
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);
178
179   // Set up SSL context.
180   std::shared_ptr<SSLContext> sslContext(new SSLContext());
181   sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
182
183   // connect
184   auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
185                                                  sslContext);
186   // read()
187   bool ex = false;
188   try {
189     socket->open();
190
191     uint8_t readbuf[128];
192     uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
193   } catch (AsyncSocketException &e) {
194     ex = true;
195   }
196   EXPECT_TRUE(ex);
197
198   // close()
199   socket->close();
200   cerr << "HandshakeError test completed" << endl;
201 }
202
203 /**
204  * Negative test for readError().
205  */
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);
213
214   // Set up SSL context.
215   std::shared_ptr<SSLContext> sslContext(new SSLContext());
216   sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
217
218   // connect
219   auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
220                                                  sslContext);
221   socket->open();
222
223   // write something to trigger ssl handshake
224   uint8_t buf[128];
225   memset(buf, 'a', sizeof(buf));
226   socket->write(buf, sizeof(buf));
227
228   socket->close();
229   cerr << "ReadError test completed" << endl;
230 }
231
232 /**
233  * Negative test for writeError().
234  */
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);
242
243   // Set up SSL context.
244   std::shared_ptr<SSLContext> sslContext(new SSLContext());
245   sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
246
247   // connect
248   auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
249                                                  sslContext);
250   socket->open();
251
252   // write something to trigger ssl handshake
253   uint8_t buf[128];
254   memset(buf, 'a', sizeof(buf));
255   socket->write(buf, sizeof(buf));
256
257   socket->close();
258   cerr << "WriteError test completed" << endl;
259 }
260
261 /**
262  * Test a socket with TCP_NODELAY unset.
263  */
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);
271
272   // Set up SSL context.
273   std::shared_ptr<SSLContext> sslContext(new SSLContext());
274   sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
275
276   // connect
277   auto socket = std::make_shared<BlockingSocket>(server.getAddress(),
278                                                  sslContext);
279   socket->open();
280
281   // write()
282   uint8_t buf[128];
283   memset(buf, 'a', sizeof(buf));
284   socket->write(buf, sizeof(buf));
285
286   // read()
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);
291
292   // close()
293   socket->close();
294
295   cerr << "SocketWithDelay test completed" << endl;
296 }
297
298 TEST(AsyncSSLSocketTest, NpnTestOverlap) {
299   EventBase eventBase;
300   std::shared_ptr<SSLContext> clientCtx(new SSLContext);
301   std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
302   int fds[2];
303   getfds(fds);
304   getctx(clientCtx, serverCtx);
305
306   clientCtx->setAdvertisedNextProtocols({"blub","baz"});
307   serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
308
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));
315
316   eventBase.loop();
317
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);
324 }
325
326 TEST(AsyncSSLSocketTest, NpnTestUnset) {
327   // Identical to above test, except that we want unset NPN before
328   // looping.
329   EventBase eventBase;
330   std::shared_ptr<SSLContext> clientCtx(new SSLContext);
331   std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
332   int fds[2];
333   getfds(fds);
334   getctx(clientCtx, serverCtx);
335
336   clientCtx->setAdvertisedNextProtocols({"blub","baz"});
337   serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
338
339   AsyncSSLSocket::UniquePtr clientSock(
340     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
341   AsyncSSLSocket::UniquePtr serverSock(
342     new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
343
344   // unsetting NPN for any of [client, server] is enought to make NPN not
345   // work
346   clientCtx->unsetNextProtocols();
347
348   NpnClient client(std::move(clientSock));
349   NpnServer server(std::move(serverSock));
350
351   eventBase.loop();
352
353   EXPECT_TRUE(client.nextProtoLength == 0);
354   EXPECT_TRUE(server.nextProtoLength == 0);
355   EXPECT_TRUE(client.nextProto == nullptr);
356   EXPECT_TRUE(server.nextProto == nullptr);
357 }
358
359 TEST(AsyncSSLSocketTest, NpnTestNoOverlap) {
360   EventBase eventBase;
361   std::shared_ptr<SSLContext> clientCtx(new SSLContext);
362   std::shared_ptr<SSLContext> serverCtx(new SSLContext);;
363   int fds[2];
364   getfds(fds);
365   getctx(clientCtx, serverCtx);
366
367   clientCtx->setAdvertisedNextProtocols({"blub"});
368   serverCtx->setAdvertisedNextProtocols({"foo","bar","baz"});
369
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));
376
377   eventBase.loop();
378
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);
385 }
386
387 TEST(AsyncSSLSocketTest, RandomizedNpnTest) {
388   // Probability that this test will fail is 2^-64, which could be considered
389   // as negligible.
390   const int kTries = 64;
391
392   std::set<string> selectedProtocols;
393   for (int i = 0; i < kTries; ++i) {
394     EventBase eventBase;
395     std::shared_ptr<SSLContext> clientCtx = std::make_shared<SSLContext>();
396     std::shared_ptr<SSLContext> serverCtx = std::make_shared<SSLContext>();
397     int fds[2];
398     getfds(fds);
399     getctx(clientCtx, serverCtx);
400
401     clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"});
402     serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}},
403         {1, {"bar"}}});
404
405
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));
412
413     eventBase.loop();
414
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);
421   }
422   EXPECT_EQ(selectedProtocols.size(), 2);
423 }
424
425
426 #ifndef OPENSSL_NO_TLSEXT
427 /**
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.
432  */
433 TEST(AsyncSSLSocketTest, SNITestMatch) {
434   EventBase eventBase;
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");
441   int fds[2];
442   getfds(fds);
443   getctx(clientCtx, dfServerCtx);
444
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),
451                    dfServerCtx,
452                    hskServerCtx,
453                    serverName);
454
455   eventBase.loop();
456
457   EXPECT_TRUE(client.serverNameMatch);
458   EXPECT_TRUE(server.serverNameMatch);
459 }
460
461 /**
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.
466  */
467 TEST(AsyncSSLSocketTest, SNITestNotMatch) {
468   EventBase eventBase;
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");
476
477   int fds[2];
478   getfds(fds);
479   getctx(clientCtx, dfServerCtx);
480
481   AsyncSSLSocket::UniquePtr clientSock(
482     new AsyncSSLSocket(clientCtx,
483                         &eventBase,
484                         fds[0],
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),
490                    dfServerCtx,
491                    hskServerCtx,
492                    serverExpectedServerName);
493
494   eventBase.loop();
495
496   EXPECT_TRUE(!client.serverNameMatch);
497   EXPECT_TRUE(!server.serverNameMatch);
498 }
499
500 /**
501  * 1. Client does not send TLSEXT_HOSTNAME in client hello.
502  * 2. Server does not send back TLSEXT_HOSTNAME in server hello.
503  */
504 TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) {
505   EventBase eventBase;
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");
512
513   int fds[2];
514   getfds(fds);
515   getctx(clientCtx, dfServerCtx);
516
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),
523                    dfServerCtx,
524                    hskServerCtx,
525                    serverExpectedServerName);
526
527   eventBase.loop();
528
529   EXPECT_TRUE(!client.serverNameMatch);
530   EXPECT_TRUE(!server.serverNameMatch);
531 }
532
533 #endif
534 /**
535  * Test SSL client socket
536  */
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);
544
545   // Set up SSL client
546   EventBase eventBase;
547   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
548                                              1));
549
550   client->connect();
551   EventBaseAborter eba(&eventBase, 3000);
552   eventBase.loop();
553
554   EXPECT_EQ(client->getMiss(), 1);
555   EXPECT_EQ(client->getHit(), 0);
556
557   cerr << "SSLClientTest test completed" << endl;
558 }
559
560
561 /**
562  * Test SSL client socket session re-use
563  */
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);
571
572   // Set up SSL client
573   EventBase eventBase;
574   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
575                                              10));
576
577   client->connect();
578   EventBaseAborter eba(&eventBase, 3000);
579   eventBase.loop();
580
581   EXPECT_EQ(client->getMiss(), 1);
582   EXPECT_EQ(client->getHit(), 9);
583
584   cerr << "SSLClientTestReuse test completed" << endl;
585 }
586
587 /**
588  * Test SSL client socket timeout
589  */
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);
597
598   // Set up SSL client
599   EventBase eventBase;
600   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
601                                              1, 10));
602   client->connect(true /* write before connect completes */);
603   EventBaseAborter eba(&eventBase, 3000);
604   eventBase.loop();
605
606   usleep(100000);
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);
613
614   cerr << "SSLClientTimeoutTest test completed" << endl;
615 }
616
617
618 /**
619  * Test SSL server async cache
620  */
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);
628
629   // Set up SSL client
630   EventBase eventBase;
631   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
632                                              10, 500));
633
634   client->connect();
635   EventBaseAborter eba(&eventBase, 3000);
636   eventBase.loop();
637
638   EXPECT_EQ(server.getAsyncCallbacks(), 18);
639   EXPECT_EQ(server.getAsyncLookups(), 9);
640   EXPECT_EQ(client->getMiss(), 10);
641   EXPECT_EQ(client->getHit(), 0);
642
643   cerr << "SSLServerAsyncCacheTest test completed" << endl;
644 }
645
646
647 /**
648  * Test SSL server accept timeout with cache path
649  */
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);
658
659   // Set up SSL client
660   EventBase eventBase;
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);
666
667   EventBaseAborter eba(&eventBase, 3000);
668   eventBase.loop();
669
670   EXPECT_EQ(readCallback.state, STATE_WAITING);
671
672   cerr << "SSLServerTimeoutTest test completed" << endl;
673 }
674
675 /**
676  * Test SSL server accept timeout with cache path
677  */
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);
685
686   // Set up SSL client
687   EventBase eventBase;
688   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
689                                              2));
690
691   client->connect();
692   EventBaseAborter eba(&eventBase, 3000);
693   eventBase.loop();
694
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);
700
701   cerr << "SSLServerAsyncCacheTimeoutTest test completed" << endl;
702 }
703
704 /**
705  * Test SSL server accept timeout with cache path
706  */
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);
715
716   // Set up SSL client
717   EventBase eventBase;
718   std::shared_ptr<SSLClient> client(new SSLClient(&eventBase, server.getAddress(),
719                                              2, 100));
720
721   client->connect();
722   EventBaseAborter eba(&eventBase, 3000);
723   eventBase.loop();
724
725   server.getEventBase().runInEventBaseThread([&handshakeCallback]{
726       handshakeCallback.closeSocket();});
727   // give time for the cache lookup to come back and find it closed
728   usleep(500000);
729
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);
735
736   cerr << "SSLServerCacheCloseTest test completed" << endl;
737 }
738
739 /**
740  * Verify Client Ciphers obtained using SSL MSG Callback.
741  */
742 TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) {
743   EventBase eventBase;
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);
752
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);
758
759   int fds[2];
760   getfds(fds);
761
762   AsyncSSLSocket::UniquePtr clientSock(
763       new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
764   AsyncSSLSocket::UniquePtr serverSock(
765       new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
766
767   SSLHandshakeClient client(std::move(clientSock), true, true);
768   SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
769
770   eventBase.loop();
771
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_);
780 }
781
782 TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) {
783   EventBase eventBase;
784   auto ctx = std::make_shared<SSLContext>();
785
786   int fds[2];
787   getfds(fds);
788
789   int bufLen = 42;
790   uint8_t majorVersion = 18;
791   uint8_t minorVersion = 25;
792
793   // Create callback buf
794   auto buf = IOBuf::create(bufLen);
795   buf->append(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);
802   cursor.skip(32);
803   cursor.write<uint32_t>(0);
804
805   SSL* ssl = ctx->createSSL();
806   AsyncSSLSocket::UniquePtr sock(
807       new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
808   sock->enableClientHelloParsing();
809
810   // Test client hello parsing in one packet
811   AsyncSSLSocket::clientHelloParsingCallback(
812       0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
813   buf.reset();
814
815   auto parsedClientHello = sock->getClientHelloInfo();
816   EXPECT_TRUE(parsedClientHello != nullptr);
817   EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
818   EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
819 }
820
821 TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) {
822   EventBase eventBase;
823   auto ctx = std::make_shared<SSLContext>();
824
825   int fds[2];
826   getfds(fds);
827
828   int bufLen = 42;
829   uint8_t majorVersion = 18;
830   uint8_t minorVersion = 25;
831
832   // Create callback buf
833   auto buf = IOBuf::create(bufLen);
834   buf->append(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);
841   cursor.skip(32);
842   cursor.write<uint32_t>(0);
843
844   SSL* ssl = ctx->createSSL();
845   AsyncSSLSocket::UniquePtr sock(
846       new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
847   sock->enableClientHelloParsing();
848
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(),
853       ssl, sock.get());
854   bufCopy.reset();
855   bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
856   AsyncSSLSocket::clientHelloParsingCallback(
857       0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(),
858       ssl, sock.get());
859   bufCopy.reset();
860
861   auto parsedClientHello = sock->getClientHelloInfo();
862   EXPECT_TRUE(parsedClientHello != nullptr);
863   EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
864   EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
865 }
866
867 TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) {
868   EventBase eventBase;
869   auto ctx = std::make_shared<SSLContext>();
870
871   int fds[2];
872   getfds(fds);
873
874   int bufLen = 42;
875   uint8_t majorVersion = 18;
876   uint8_t minorVersion = 25;
877
878   // Create callback buf
879   auto buf = IOBuf::create(bufLen);
880   buf->append(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);
887   cursor.skip(32);
888   cursor.write<uint32_t>(0);
889
890   SSL* ssl = ctx->createSSL();
891   AsyncSSLSocket::UniquePtr sock(
892       new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
893   sock->enableClientHelloParsing();
894
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(),
901         ssl, sock.get());
902     bufCopy.reset();
903   }
904
905   auto parsedClientHello = sock->getClientHelloInfo();
906   EXPECT_TRUE(parsedClientHello != nullptr);
907   EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
908   EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
909 }
910
911 /**
912  * Verify sucessful behavior of SSL certificate validation.
913  */
914 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) {
915   EventBase eventBase;
916   auto clientCtx = std::make_shared<SSLContext>();
917   auto dfServerCtx = std::make_shared<SSLContext>();
918
919   int fds[2];
920   getfds(fds);
921   getctx(clientCtx, dfServerCtx);
922
923   clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
924   dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
925
926   AsyncSSLSocket::UniquePtr clientSock(
927     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
928   AsyncSSLSocket::UniquePtr serverSock(
929     new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
930
931   SSLHandshakeClient client(std::move(clientSock), true, true);
932   clientCtx->loadTrustedCertificates(testCA);
933
934   SSLHandshakeServer server(std::move(serverSock), true, true);
935
936   eventBase.loop();
937
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_);
944 }
945
946 /**
947  * Verify that the client's verification callback is able to fail SSL
948  * connection establishment.
949  */
950 TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) {
951   EventBase eventBase;
952   auto clientCtx = std::make_shared<SSLContext>();
953   auto dfServerCtx = std::make_shared<SSLContext>();
954
955   int fds[2];
956   getfds(fds);
957   getctx(clientCtx, dfServerCtx);
958
959   clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
960   dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
961
962   AsyncSSLSocket::UniquePtr clientSock(
963     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
964   AsyncSSLSocket::UniquePtr serverSock(
965     new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
966
967   SSLHandshakeClient client(std::move(clientSock), true, false);
968   clientCtx->loadTrustedCertificates(testCA);
969
970   SSLHandshakeServer server(std::move(serverSock), true, true);
971
972   eventBase.loop();
973
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_);
980 }
981
982 /**
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.
987  */
988 TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) {
989   EventBase eventBase;
990   auto clientCtx = std::make_shared<SSLContext>();
991   auto dfServerCtx = std::make_shared<SSLContext>();
992
993   int fds[2];
994   getfds(fds);
995   getctx(clientCtx, dfServerCtx);
996
997   clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
998   dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
999
1000   AsyncSSLSocket::UniquePtr clientSock(
1001     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1002   AsyncSSLSocket::UniquePtr serverSock(
1003     new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1004
1005   SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1006   clientCtx->loadTrustedCertificates(testCA);
1007
1008   SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1009
1010   eventBase.loop();
1011
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_);
1018 }
1019
1020 /**
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
1024  */
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);
1035
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);
1041
1042   int fds[2];
1043   getfds(fds);
1044
1045   AsyncSSLSocket::UniquePtr clientSock(
1046       new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1047   AsyncSSLSocket::UniquePtr serverSock(
1048       new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1049
1050   SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1051   SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1052
1053   eventBase.loop();
1054
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_);
1061 }
1062
1063 /**
1064  * Verify that the client's verification callback is able to override
1065  * the preverification failure and allow a successful connection.
1066  */
1067 TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) {
1068   EventBase eventBase;
1069   auto clientCtx = std::make_shared<SSLContext>();
1070   auto dfServerCtx = std::make_shared<SSLContext>();
1071
1072   int fds[2];
1073   getfds(fds);
1074   getctx(clientCtx, dfServerCtx);
1075
1076   clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1077   dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1078
1079   AsyncSSLSocket::UniquePtr clientSock(
1080     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1081   AsyncSSLSocket::UniquePtr serverSock(
1082     new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1083
1084   SSLHandshakeClient client(std::move(clientSock), false, true);
1085   SSLHandshakeServer server(std::move(serverSock), true, true);
1086
1087   eventBase.loop();
1088
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_);
1095 }
1096
1097 /**
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
1100  * callback.
1101  */
1102 TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) {
1103   EventBase eventBase;
1104   auto clientCtx = std::make_shared<SSLContext>();
1105   auto dfServerCtx = std::make_shared<SSLContext>();
1106
1107   int fds[2];
1108   getfds(fds);
1109   getctx(clientCtx, dfServerCtx);
1110
1111   clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1112   dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1113
1114   AsyncSSLSocket::UniquePtr clientSock(
1115     new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1116   AsyncSSLSocket::UniquePtr serverSock(
1117     new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1118
1119   SSLHandshakeClient client(std::move(clientSock), false, false);
1120   SSLHandshakeServer server(std::move(serverSock), false, false);
1121
1122   eventBase.loop();
1123
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_);
1130 }
1131
1132 /**
1133  * Test requireClientCert with client cert
1134  */
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);
1146
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);
1152
1153   int fds[2];
1154   getfds(fds);
1155
1156   AsyncSSLSocket::UniquePtr clientSock(
1157       new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1158   AsyncSSLSocket::UniquePtr serverSock(
1159       new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1160
1161   SSLHandshakeClient client(std::move(clientSock), true, true);
1162   SSLHandshakeServer server(std::move(serverSock), true, true);
1163
1164   eventBase.loop();
1165
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_);
1172 }
1173
1174
1175 /**
1176  * Test requireClientCert with no client cert
1177  */
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");
1191
1192   int fds[2];
1193   getfds(fds);
1194
1195   AsyncSSLSocket::UniquePtr clientSock(
1196       new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1197   AsyncSSLSocket::UniquePtr serverSock(
1198       new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1199
1200   SSLHandshakeClient client(std::move(clientSock), false, false);
1201   SSLHandshakeServer server(std::move(serverSock), false, false);
1202
1203   eventBase.loop();
1204
1205   EXPECT_FALSE(server.handshakeVerify_);
1206   EXPECT_FALSE(server.handshakeSuccess_);
1207   EXPECT_TRUE(server.handshakeError_);
1208 }
1209
1210 TEST(AsyncSSLSocketTest, MinWriteSizeTest) {
1211   EventBase eb;
1212
1213   // Set up SSL context.
1214   auto sslContext = std::make_shared<SSLContext>();
1215   sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1216
1217   // create SSL socket
1218   AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1219
1220   EXPECT_EQ(1500, socket->getMinWriteSize());
1221
1222   socket->setMinWriteSize(0);
1223   EXPECT_EQ(0, socket->getMinWriteSize());
1224   socket->setMinWriteSize(50000);
1225   EXPECT_EQ(50000, socket->getMinWriteSize());
1226 }
1227 }
1228
1229 ///////////////////////////////////////////////////////////////////////////
1230 // init_unit_test_suite
1231 ///////////////////////////////////////////////////////////////////////////
1232 namespace {
1233 struct Initializer {
1234   Initializer() {
1235     signal(SIGPIPE, SIG_IGN);
1236   }
1237 };
1238 Initializer initializer;
1239 } // anonymous