7ab01c301f8be6d56ed9b35a95a0202330b2773b
[folly.git] / folly / io / async / SSLContext.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
17 #include "SSLContext.h"
18
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #include <openssl/ssl.h>
22 #include <openssl/x509v3.h>
23
24 #include <folly/Format.h>
25 #include <folly/SpinLock.h>
26
27 // ---------------------------------------------------------------------
28 // SSLContext implementation
29 // ---------------------------------------------------------------------
30
31 struct CRYPTO_dynlock_value {
32   std::mutex mutex;
33 };
34
35 namespace folly {
36
37 bool SSLContext::initialized_ = false;
38
39 namespace {
40
41 std::mutex& initMutex() {
42   static std::mutex m;
43   return m;
44 }
45
46 }  // anonymous namespace
47
48 #ifdef OPENSSL_NPN_NEGOTIATED
49 int SSLContext::sNextProtocolsExDataIndex_ = -1;
50 #endif
51
52 // SSLContext implementation
53 SSLContext::SSLContext(SSLVersion version) {
54   {
55     std::lock_guard<std::mutex> g(initMutex());
56     initializeOpenSSLLocked();
57   }
58
59   ctx_ = SSL_CTX_new(SSLv23_method());
60   if (ctx_ == nullptr) {
61     throw std::runtime_error("SSL_CTX_new: " + getErrors());
62   }
63
64   int opt = 0;
65   switch (version) {
66     case TLSv1:
67       opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
68       break;
69     case SSLv3:
70       opt = SSL_OP_NO_SSLv2;
71       break;
72     default:
73       // do nothing
74       break;
75   }
76   int newOpt = SSL_CTX_set_options(ctx_, opt);
77   DCHECK((newOpt & opt) == opt);
78
79   SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
80
81   checkPeerName_ = false;
82
83 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
84   SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
85   SSL_CTX_set_tlsext_servername_arg(ctx_, this);
86 #endif
87 }
88
89 SSLContext::~SSLContext() {
90   if (ctx_ != nullptr) {
91     SSL_CTX_free(ctx_);
92     ctx_ = nullptr;
93   }
94
95 #ifdef OPENSSL_NPN_NEGOTIATED
96   deleteNextProtocolsStrings();
97 #endif
98 }
99
100 void SSLContext::ciphers(const std::string& ciphers) {
101   providedCiphersString_ = ciphers;
102   setCiphersOrThrow(ciphers);
103 }
104
105 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
106   int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
107   if (ERR_peek_error() != 0) {
108     throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
109   }
110   if (rc == 0) {
111     throw std::runtime_error("None of specified ciphers are supported");
112   }
113 }
114
115 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
116     verifyPeer) {
117   CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
118   verifyPeer_ = verifyPeer;
119 }
120
121 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
122     verifyPeer) {
123   CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
124   int mode = SSL_VERIFY_NONE;
125   switch(verifyPeer) {
126     // case SSLVerifyPeerEnum::USE_CTX: // can't happen
127     // break;
128
129     case SSLVerifyPeerEnum::VERIFY:
130       mode = SSL_VERIFY_PEER;
131       break;
132
133     case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
134       mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
135       break;
136
137     case SSLVerifyPeerEnum::NO_VERIFY:
138       mode = SSL_VERIFY_NONE;
139       break;
140
141     default:
142       break;
143   }
144   return mode;
145 }
146
147 int SSLContext::getVerificationMode() {
148   return getVerificationMode(verifyPeer_);
149 }
150
151 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
152                               const std::string& peerName) {
153   int mode;
154   if (checkPeerCert) {
155     mode  = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
156     checkPeerName_ = checkPeerName;
157     peerFixedName_ = peerName;
158   } else {
159     mode = SSL_VERIFY_NONE;
160     checkPeerName_ = false; // can't check name without cert!
161     peerFixedName_.clear();
162   }
163   SSL_CTX_set_verify(ctx_, mode, nullptr);
164 }
165
166 void SSLContext::loadCertificate(const char* path, const char* format) {
167   if (path == nullptr || format == nullptr) {
168     throw std::invalid_argument(
169          "loadCertificateChain: either <path> or <format> is nullptr");
170   }
171   if (strcmp(format, "PEM") == 0) {
172     if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
173       int errnoCopy = errno;
174       std::string reason("SSL_CTX_use_certificate_chain_file: ");
175       reason.append(path);
176       reason.append(": ");
177       reason.append(getErrors(errnoCopy));
178       throw std::runtime_error(reason);
179     }
180   } else {
181     throw std::runtime_error("Unsupported certificate format: " + std::string(format));
182   }
183 }
184
185 void SSLContext::loadPrivateKey(const char* path, const char* format) {
186   if (path == nullptr || format == nullptr) {
187     throw std::invalid_argument(
188          "loadPrivateKey: either <path> or <format> is nullptr");
189   }
190   if (strcmp(format, "PEM") == 0) {
191     if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
192       throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
193     }
194   } else {
195     throw std::runtime_error("Unsupported private key format: " + std::string(format));
196   }
197 }
198
199 void SSLContext::loadTrustedCertificates(const char* path) {
200   if (path == nullptr) {
201     throw std::invalid_argument(
202          "loadTrustedCertificates: <path> is nullptr");
203   }
204   if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
205     throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
206   }
207 }
208
209 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
210   SSL_CTX_set_cert_store(ctx_, store);
211 }
212
213 void SSLContext::loadClientCAList(const char* path) {
214   auto clientCAs = SSL_load_client_CA_file(path);
215   if (clientCAs == nullptr) {
216     LOG(ERROR) << "Unable to load ca file: " << path;
217     return;
218   }
219   SSL_CTX_set_client_CA_list(ctx_, clientCAs);
220 }
221
222 void SSLContext::randomize() {
223   RAND_poll();
224 }
225
226 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
227   if (collector == nullptr) {
228     LOG(ERROR) << "passwordCollector: ignore invalid password collector";
229     return;
230   }
231   collector_ = collector;
232   SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
233   SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
234 }
235
236 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
237
238 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
239   serverNameCb_ = cb;
240 }
241
242 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
243   clientHelloCbs_.push_back(cb);
244 }
245
246 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
247   SSLContext* context = (SSLContext*)data;
248
249   if (context == nullptr) {
250     return SSL_TLSEXT_ERR_NOACK;
251   }
252
253   for (auto& cb : context->clientHelloCbs_) {
254     // Generic callbacks to happen after we receive the Client Hello.
255     // For example, we use one to switch which cipher we use depending
256     // on the user's TLS version.  Because the primary purpose of
257     // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
258     // are side-uses, we ignore any possible failures other than just logging
259     // them.
260     cb(ssl);
261   }
262
263   if (!context->serverNameCb_) {
264     return SSL_TLSEXT_ERR_NOACK;
265   }
266
267   ServerNameCallbackResult ret = context->serverNameCb_(ssl);
268   switch (ret) {
269     case SERVER_NAME_FOUND:
270       return SSL_TLSEXT_ERR_OK;
271     case SERVER_NAME_NOT_FOUND:
272       return SSL_TLSEXT_ERR_NOACK;
273     case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
274       *al = TLS1_AD_UNRECOGNIZED_NAME;
275       return SSL_TLSEXT_ERR_ALERT_FATAL;
276     default:
277       CHECK(false);
278   }
279
280   return SSL_TLSEXT_ERR_NOACK;
281 }
282
283 void SSLContext::switchCiphersIfTLS11(
284     SSL* ssl,
285     const std::string& tls11CipherString) {
286
287   CHECK(!tls11CipherString.empty()) << "Shouldn't call if empty alt ciphers";
288
289   if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
290     // We only do this for TLS v 1.1 and later
291     return;
292   }
293
294   // Prefer AES for TLS versions 1.1 and later since these are not
295   // vulnerable to BEAST attacks on AES.  Note that we're setting the
296   // cipher list on the SSL object, not the SSL_CTX object, so it will
297   // only last for this request.
298   int rc = SSL_set_cipher_list(ssl, tls11CipherString.c_str());
299   if ((rc == 0) || ERR_peek_error() != 0) {
300     // This shouldn't happen since we checked for this when proxygen
301     // started up.
302     LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
303     SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
304   }
305 }
306 #endif
307
308 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
309 int SSLContext::alpnSelectCallback(SSL* ssl,
310                                    const unsigned char** out,
311                                    unsigned char* outlen,
312                                    const unsigned char* in,
313                                    unsigned int inlen,
314                                    void* data) {
315   SSLContext* context = (SSLContext*)data;
316   CHECK(context);
317   if (context->advertisedNextProtocols_.empty()) {
318     *out = nullptr;
319     *outlen = 0;
320   } else {
321     auto i = context->pickNextProtocols();
322     const auto& item = context->advertisedNextProtocols_[i];
323     if (SSL_select_next_proto((unsigned char**)out,
324                               outlen,
325                               item.protocols,
326                               item.length,
327                               in,
328                               inlen) != OPENSSL_NPN_NEGOTIATED) {
329       return SSL_TLSEXT_ERR_NOACK;
330     }
331   }
332   return SSL_TLSEXT_ERR_OK;
333 }
334 #endif
335
336 #ifdef OPENSSL_NPN_NEGOTIATED
337
338 bool SSLContext::setAdvertisedNextProtocols(
339     const std::list<std::string>& protocols, NextProtocolType protocolType) {
340   return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
341 }
342
343 bool SSLContext::setRandomizedAdvertisedNextProtocols(
344     const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
345   unsetNextProtocols();
346   if (items.size() == 0) {
347     return false;
348   }
349   int total_weight = 0;
350   for (const auto &item : items) {
351     if (item.protocols.size() == 0) {
352       continue;
353     }
354     AdvertisedNextProtocolsItem advertised_item;
355     advertised_item.length = 0;
356     for (const auto& proto : item.protocols) {
357       ++advertised_item.length;
358       unsigned protoLength = proto.length();
359       if (protoLength >= 256) {
360         deleteNextProtocolsStrings();
361         return false;
362       }
363       advertised_item.length += protoLength;
364     }
365     advertised_item.protocols = new unsigned char[advertised_item.length];
366     if (!advertised_item.protocols) {
367       throw std::runtime_error("alloc failure");
368     }
369     unsigned char* dst = advertised_item.protocols;
370     for (auto& proto : item.protocols) {
371       unsigned protoLength = proto.length();
372       *dst++ = (unsigned char)protoLength;
373       memcpy(dst, proto.data(), protoLength);
374       dst += protoLength;
375     }
376     total_weight += item.weight;
377     advertised_item.probability = item.weight;
378     advertisedNextProtocols_.push_back(advertised_item);
379   }
380   if (total_weight == 0) {
381     deleteNextProtocolsStrings();
382     return false;
383   }
384   for (auto& advertised_item : advertisedNextProtocols_) {
385     advertised_item.probability /= total_weight;
386   }
387   if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
388     SSL_CTX_set_next_protos_advertised_cb(
389         ctx_, advertisedNextProtocolCallback, this);
390     SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
391   }
392 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
393   if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
394     SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
395     // Client cannot really use randomized alpn
396     SSL_CTX_set_alpn_protos(ctx_,
397                             advertisedNextProtocols_[0].protocols,
398                             advertisedNextProtocols_[0].length);
399   }
400 #endif
401   return true;
402 }
403
404 void SSLContext::deleteNextProtocolsStrings() {
405   for (auto protocols : advertisedNextProtocols_) {
406     delete[] protocols.protocols;
407   }
408   advertisedNextProtocols_.clear();
409 }
410
411 void SSLContext::unsetNextProtocols() {
412   deleteNextProtocolsStrings();
413   SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
414   SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
415 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
416   SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
417   SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
418 #endif
419 }
420
421 size_t SSLContext::pickNextProtocols() {
422   unsigned char random_byte;
423   RAND_bytes(&random_byte, 1);
424   double random_value = random_byte / 255.0;
425   double sum = 0;
426   for (size_t i = 0; i < advertisedNextProtocols_.size(); ++i) {
427     sum += advertisedNextProtocols_[i].probability;
428     if (sum < random_value && i + 1 < advertisedNextProtocols_.size()) {
429       continue;
430     }
431     return i;
432   }
433   CHECK(false) << "Failed to pickNextProtocols";
434 }
435
436 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
437       const unsigned char** out, unsigned int* outlen, void* data) {
438   SSLContext* context = (SSLContext*)data;
439   if (context == nullptr || context->advertisedNextProtocols_.empty()) {
440     *out = nullptr;
441     *outlen = 0;
442   } else if (context->advertisedNextProtocols_.size() == 1) {
443     *out = context->advertisedNextProtocols_[0].protocols;
444     *outlen = context->advertisedNextProtocols_[0].length;
445   } else {
446     uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
447           sNextProtocolsExDataIndex_));
448     if (selected_index) {
449       --selected_index;
450       *out = context->advertisedNextProtocols_[selected_index].protocols;
451       *outlen = context->advertisedNextProtocols_[selected_index].length;
452     } else {
453       auto i = context->pickNextProtocols();
454       uintptr_t selected = i + 1;
455       SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
456       *out = context->advertisedNextProtocols_[i].protocols;
457       *outlen = context->advertisedNextProtocols_[i].length;
458     }
459   }
460   return SSL_TLSEXT_ERR_OK;
461 }
462
463 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
464   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
465 SSLContext::SSLFalseStartChecker::SSLFalseStartChecker() :
466   ciphers_{
467     TLS1_CK_DHE_DSS_WITH_AES_128_SHA,
468     TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
469     TLS1_CK_DHE_DSS_WITH_AES_256_SHA,
470     TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
471     TLS1_CK_DHE_DSS_WITH_AES_128_SHA256,
472     TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
473     TLS1_CK_DHE_DSS_WITH_AES_256_SHA256,
474     TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
475     TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
476     TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
477     TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256,
478     TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384,
479     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
480     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
481     TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
482     TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
483     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
484     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
485     TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256,
486     TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384,
487     TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
488     TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
489     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
490     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
491     TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
492     TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
493   } {
494   length_ = sizeof(ciphers_)/sizeof(ciphers_[0]);
495   width_ = sizeof(ciphers_[0]);
496   qsort(ciphers_, length_, width_, compare_ulong);
497 }
498
499 bool SSLContext::SSLFalseStartChecker::canUseFalseStartWithCipher(
500   const SSL_CIPHER *cipher) {
501   unsigned long cid = cipher->id;
502   unsigned long *r =
503     (unsigned long*)bsearch(&cid, ciphers_, length_, width_, compare_ulong);
504   return r != nullptr;
505 }
506
507 int
508 SSLContext::SSLFalseStartChecker::compare_ulong(const void *x, const void *y) {
509   if (*(unsigned long *)x < *(unsigned long *)y) {
510     return -1;
511   }
512   if (*(unsigned long *)x > *(unsigned long *)y) {
513     return 1;
514   }
515   return 0;
516 };
517
518 bool SSLContext::canUseFalseStartWithCipher(const SSL_CIPHER *cipher) {
519   return falseStartChecker_.canUseFalseStartWithCipher(cipher);
520 }
521 #endif
522
523 int SSLContext::selectNextProtocolCallback(
524   SSL* ssl, unsigned char **out, unsigned char *outlen,
525   const unsigned char *server, unsigned int server_len, void *data) {
526
527   SSLContext* ctx = (SSLContext*)data;
528   if (ctx->advertisedNextProtocols_.size() > 1) {
529     VLOG(3) << "SSLContext::selectNextProcolCallback() "
530             << "client should be deterministic in selecting protocols.";
531   }
532
533   unsigned char *client;
534   unsigned int client_len;
535   bool filtered = false;
536   auto cpf = ctx->getClientProtocolFilterCallback();
537   if (cpf) {
538     filtered = (*cpf)(&client, &client_len, server, server_len);
539   }
540
541   if (!filtered) {
542     if (ctx->advertisedNextProtocols_.empty()) {
543       client = (unsigned char *) "";
544       client_len = 0;
545     } else {
546       client = ctx->advertisedNextProtocols_[0].protocols;
547       client_len = ctx->advertisedNextProtocols_[0].length;
548     }
549   }
550
551   int retval = SSL_select_next_proto(out, outlen, server, server_len,
552                                      client, client_len);
553   if (retval != OPENSSL_NPN_NEGOTIATED) {
554     VLOG(3) << "SSLContext::selectNextProcolCallback() "
555             << "unable to pick a next protocol.";
556 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
557   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
558   } else {
559     const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
560     if (cipher && ctx->canUseFalseStartWithCipher(cipher)) {
561       SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
562     }
563 #endif
564   }
565   return SSL_TLSEXT_ERR_OK;
566 }
567 #endif // OPENSSL_NPN_NEGOTIATED
568
569 SSL* SSLContext::createSSL() const {
570   SSL* ssl = SSL_new(ctx_);
571   if (ssl == nullptr) {
572     throw std::runtime_error("SSL_new: " + getErrors());
573   }
574   return ssl;
575 }
576
577 /**
578  * Match a name with a pattern. The pattern may include wildcard. A single
579  * wildcard "*" can match up to one component in the domain name.
580  *
581  * @param  host    Host name, typically the name of the remote host
582  * @param  pattern Name retrieved from certificate
583  * @param  size    Size of "pattern"
584  * @return True, if "host" matches "pattern". False otherwise.
585  */
586 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
587   bool match = false;
588   int i = 0, j = 0;
589   while (i < size && host[j] != '\0') {
590     if (toupper(pattern[i]) == toupper(host[j])) {
591       i++;
592       j++;
593       continue;
594     }
595     if (pattern[i] == '*') {
596       while (host[j] != '.' && host[j] != '\0') {
597         j++;
598       }
599       i++;
600       continue;
601     }
602     break;
603   }
604   if (i == size && host[j] == '\0') {
605     match = true;
606   }
607   return match;
608 }
609
610 int SSLContext::passwordCallback(char* password,
611                                  int size,
612                                  int,
613                                  void* data) {
614   SSLContext* context = (SSLContext*)data;
615   if (context == nullptr || context->passwordCollector() == nullptr) {
616     return 0;
617   }
618   std::string userPassword;
619   // call user defined password collector to get password
620   context->passwordCollector()->getPassword(userPassword, size);
621   int length = userPassword.size();
622   if (length > size) {
623     length = size;
624   }
625   strncpy(password, userPassword.c_str(), length);
626   return length;
627 }
628
629 struct SSLLock {
630   explicit SSLLock(
631     SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
632       lockType(inLockType) {
633   }
634
635   void lock() {
636     if (lockType == SSLContext::LOCK_MUTEX) {
637       mutex.lock();
638     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
639       spinLock.lock();
640     }
641     // lockType == LOCK_NONE, no-op
642   }
643
644   void unlock() {
645     if (lockType == SSLContext::LOCK_MUTEX) {
646       mutex.unlock();
647     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
648       spinLock.unlock();
649     }
650     // lockType == LOCK_NONE, no-op
651   }
652
653   SSLContext::SSLLockType lockType;
654   folly::SpinLock spinLock{};
655   std::mutex mutex;
656 };
657
658 // Statics are unsafe in environments that call exit().
659 // If one thread calls exit() while another thread is
660 // references a member of SSLContext, bad things can happen.
661 // SSLContext runs in such environments.
662 // Instead of declaring a static member we "new" the static
663 // member so that it won't be destructed on exit().
664 static std::unique_ptr<SSLLock[]>& locks() {
665   static auto locksInst = new std::unique_ptr<SSLLock[]>();
666   return *locksInst;
667 }
668
669 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
670   static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
671   return *lockTypesInst;
672 }
673
674 static void callbackLocking(int mode, int n, const char*, int) {
675   if (mode & CRYPTO_LOCK) {
676     locks()[n].lock();
677   } else {
678     locks()[n].unlock();
679   }
680 }
681
682 static unsigned long callbackThreadID() {
683   return static_cast<unsigned long>(
684 #ifdef __APPLE__
685     pthread_mach_thread_np(pthread_self())
686 #else
687     pthread_self()
688 #endif
689   );
690 }
691
692 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
693   return new CRYPTO_dynlock_value;
694 }
695
696 static void dyn_lock(int mode,
697                      struct CRYPTO_dynlock_value* lock,
698                      const char*, int) {
699   if (lock != nullptr) {
700     if (mode & CRYPTO_LOCK) {
701       lock->mutex.lock();
702     } else {
703       lock->mutex.unlock();
704     }
705   }
706 }
707
708 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
709   delete lock;
710 }
711
712 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
713   lockTypes() = inLockTypes;
714 }
715
716 void SSLContext::markInitialized() {
717   std::lock_guard<std::mutex> g(initMutex());
718   initialized_ = true;
719 }
720
721 void SSLContext::initializeOpenSSL() {
722   std::lock_guard<std::mutex> g(initMutex());
723   initializeOpenSSLLocked();
724 }
725
726 void SSLContext::initializeOpenSSLLocked() {
727   if (initialized_) {
728     return;
729   }
730   SSL_library_init();
731   SSL_load_error_strings();
732   ERR_load_crypto_strings();
733   // static locking
734   locks().reset(new SSLLock[::CRYPTO_num_locks()]);
735   for (auto it: lockTypes()) {
736     locks()[it.first].lockType = it.second;
737   }
738   CRYPTO_set_id_callback(callbackThreadID);
739   CRYPTO_set_locking_callback(callbackLocking);
740   // dynamic locking
741   CRYPTO_set_dynlock_create_callback(dyn_create);
742   CRYPTO_set_dynlock_lock_callback(dyn_lock);
743   CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
744   randomize();
745 #ifdef OPENSSL_NPN_NEGOTIATED
746   sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
747       (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
748 #endif
749   initialized_ = true;
750 }
751
752 void SSLContext::cleanupOpenSSL() {
753   std::lock_guard<std::mutex> g(initMutex());
754   cleanupOpenSSLLocked();
755 }
756
757 void SSLContext::cleanupOpenSSLLocked() {
758   if (!initialized_) {
759     return;
760   }
761
762   CRYPTO_set_id_callback(nullptr);
763   CRYPTO_set_locking_callback(nullptr);
764   CRYPTO_set_dynlock_create_callback(nullptr);
765   CRYPTO_set_dynlock_lock_callback(nullptr);
766   CRYPTO_set_dynlock_destroy_callback(nullptr);
767   CRYPTO_cleanup_all_ex_data();
768   ERR_free_strings();
769   EVP_cleanup();
770   ERR_remove_state(0);
771   locks().reset();
772   initialized_ = false;
773 }
774
775 void SSLContext::setOptions(long options) {
776   long newOpt = SSL_CTX_set_options(ctx_, options);
777   if ((newOpt & options) != options) {
778     throw std::runtime_error("SSL_CTX_set_options failed");
779   }
780 }
781
782 std::string SSLContext::getErrors(int errnoCopy) {
783   std::string errors;
784   unsigned long  errorCode;
785   char   message[256];
786
787   errors.reserve(512);
788   while ((errorCode = ERR_get_error()) != 0) {
789     if (!errors.empty()) {
790       errors += "; ";
791     }
792     const char* reason = ERR_reason_error_string(errorCode);
793     if (reason == nullptr) {
794       snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
795       reason = message;
796     }
797     errors += reason;
798   }
799   if (errors.empty()) {
800     errors = "error code: " + folly::to<std::string>(errnoCopy);
801   }
802   return errors;
803 }
804
805 std::ostream&
806 operator<<(std::ostream& os, const PasswordCollector& collector) {
807   os << collector.describe();
808   return os;
809 }
810
811 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
812                                                   sockaddr_storage* addrStorage,
813                                                   socklen_t* addrLen) {
814   // Grab the ssl idx and then the ssl object so that we can get the peer
815   // name to compare against the ips in the subjectAltName
816   auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
817   auto ssl =
818     reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
819   int fd = SSL_get_fd(ssl);
820   if (fd < 0) {
821     LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
822     return false;
823   }
824
825   *addrLen = sizeof(*addrStorage);
826   if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
827     PLOG(ERROR) << "Unable to get peer name";
828     return false;
829   }
830   CHECK(*addrLen <= sizeof(*addrStorage));
831   return true;
832 }
833
834 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
835                                          const sockaddr* addr,
836                                          socklen_t addrLen) {
837   // Try to extract the names within the SAN extension from the certificate
838   auto altNames =
839     reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
840         X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
841   SCOPE_EXIT {
842     if (altNames != nullptr) {
843       sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
844     }
845   };
846   if (altNames == nullptr) {
847     LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
848     return false;
849   }
850
851   const sockaddr_in* addr4 = nullptr;
852   const sockaddr_in6* addr6 = nullptr;
853   if (addr != nullptr) {
854     if (addr->sa_family == AF_INET) {
855       addr4 = reinterpret_cast<const sockaddr_in*>(addr);
856     } else if (addr->sa_family == AF_INET6) {
857       addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
858     } else {
859       LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
860     }
861   }
862
863
864   for (int i = 0; i < sk_GENERAL_NAME_num(altNames); i++) {
865     auto name = sk_GENERAL_NAME_value(altNames, i);
866     if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
867       // Extra const-ness for paranoia
868       unsigned char const * const rawIpStr = name->d.iPAddress->data;
869       int const rawIpLen = name->d.iPAddress->length;
870
871       if (rawIpLen == 4 && addr4 != nullptr) {
872         if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
873           return true;
874         }
875       } else if (rawIpLen == 16 && addr6 != nullptr) {
876         if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
877           return true;
878         }
879       } else if (rawIpLen != 4 && rawIpLen != 16) {
880         LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
881       }
882     }
883   }
884
885   LOG(WARNING) << "Unable to match client cert against alt name ip";
886   return false;
887 }
888
889
890 } // folly