7426e237bdb63cbb0765d1b5495dbbb2df3dad50
[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 #ifdef OPENSSL_NPN_NEGOTIATED
309 bool SSLContext::setAdvertisedNextProtocols(const std::list<std::string>& protocols) {
310   return setRandomizedAdvertisedNextProtocols({{1, protocols}});
311 }
312
313 bool SSLContext::setRandomizedAdvertisedNextProtocols(
314     const std::list<NextProtocolsItem>& items) {
315   unsetNextProtocols();
316   if (items.size() == 0) {
317     return false;
318   }
319   int total_weight = 0;
320   for (const auto &item : items) {
321     if (item.protocols.size() == 0) {
322       continue;
323     }
324     AdvertisedNextProtocolsItem advertised_item;
325     advertised_item.length = 0;
326     for (const auto& proto : item.protocols) {
327       ++advertised_item.length;
328       unsigned protoLength = proto.length();
329       if (protoLength >= 256) {
330         deleteNextProtocolsStrings();
331         return false;
332       }
333       advertised_item.length += protoLength;
334     }
335     advertised_item.protocols = new unsigned char[advertised_item.length];
336     if (!advertised_item.protocols) {
337       throw std::runtime_error("alloc failure");
338     }
339     unsigned char* dst = advertised_item.protocols;
340     for (auto& proto : item.protocols) {
341       unsigned protoLength = proto.length();
342       *dst++ = (unsigned char)protoLength;
343       memcpy(dst, proto.data(), protoLength);
344       dst += protoLength;
345     }
346     total_weight += item.weight;
347     advertised_item.probability = item.weight;
348     advertisedNextProtocols_.push_back(advertised_item);
349   }
350   if (total_weight == 0) {
351     deleteNextProtocolsStrings();
352     return false;
353   }
354   for (auto &advertised_item : advertisedNextProtocols_) {
355     advertised_item.probability /= total_weight;
356   }
357   SSL_CTX_set_next_protos_advertised_cb(
358     ctx_, advertisedNextProtocolCallback, this);
359   SSL_CTX_set_next_proto_select_cb(
360     ctx_, selectNextProtocolCallback, this);
361   return true;
362 }
363
364 void SSLContext::deleteNextProtocolsStrings() {
365   for (auto protocols : advertisedNextProtocols_) {
366     delete[] protocols.protocols;
367   }
368   advertisedNextProtocols_.clear();
369 }
370
371 void SSLContext::unsetNextProtocols() {
372   deleteNextProtocolsStrings();
373   SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
374   SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
375 }
376
377 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
378       const unsigned char** out, unsigned int* outlen, void* data) {
379   SSLContext* context = (SSLContext*)data;
380   if (context == nullptr || context->advertisedNextProtocols_.empty()) {
381     *out = nullptr;
382     *outlen = 0;
383   } else if (context->advertisedNextProtocols_.size() == 1) {
384     *out = context->advertisedNextProtocols_[0].protocols;
385     *outlen = context->advertisedNextProtocols_[0].length;
386   } else {
387     uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
388           sNextProtocolsExDataIndex_));
389     if (selected_index) {
390       --selected_index;
391       *out = context->advertisedNextProtocols_[selected_index].protocols;
392       *outlen = context->advertisedNextProtocols_[selected_index].length;
393     } else {
394       unsigned char random_byte;
395       RAND_bytes(&random_byte, 1);
396       double random_value = random_byte / 255.0;
397       double sum = 0;
398       for (size_t i = 0; i < context->advertisedNextProtocols_.size(); ++i) {
399         sum += context->advertisedNextProtocols_[i].probability;
400         if (sum < random_value &&
401             i + 1 < context->advertisedNextProtocols_.size()) {
402           continue;
403         }
404         uintptr_t selected = i + 1;
405         SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void *)selected);
406         *out = context->advertisedNextProtocols_[i].protocols;
407         *outlen = context->advertisedNextProtocols_[i].length;
408         break;
409       }
410     }
411   }
412   return SSL_TLSEXT_ERR_OK;
413 }
414
415 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
416   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
417 SSLContext::SSLFalseStartChecker::SSLFalseStartChecker() :
418   ciphers_{
419     TLS1_CK_DHE_DSS_WITH_AES_128_SHA,
420     TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
421     TLS1_CK_DHE_DSS_WITH_AES_256_SHA,
422     TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
423     TLS1_CK_DHE_DSS_WITH_AES_128_SHA256,
424     TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
425     TLS1_CK_DHE_DSS_WITH_AES_256_SHA256,
426     TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
427     TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
428     TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
429     TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256,
430     TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384,
431     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
432     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
433     TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
434     TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
435     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
436     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
437     TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256,
438     TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384,
439     TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
440     TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
441     TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
442     TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
443     TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
444     TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
445   } {
446   length_ = sizeof(ciphers_)/sizeof(ciphers_[0]);
447   width_ = sizeof(ciphers_[0]);
448   qsort(ciphers_, length_, width_, compare_ulong);
449 }
450
451 bool SSLContext::SSLFalseStartChecker::canUseFalseStartWithCipher(
452   const SSL_CIPHER *cipher) {
453   unsigned long cid = cipher->id;
454   unsigned long *r =
455     (unsigned long*)bsearch(&cid, ciphers_, length_, width_, compare_ulong);
456   return r != nullptr;
457 }
458
459 int
460 SSLContext::SSLFalseStartChecker::compare_ulong(const void *x, const void *y) {
461   if (*(unsigned long *)x < *(unsigned long *)y) {
462     return -1;
463   }
464   if (*(unsigned long *)x > *(unsigned long *)y) {
465     return 1;
466   }
467   return 0;
468 };
469
470 bool SSLContext::canUseFalseStartWithCipher(const SSL_CIPHER *cipher) {
471   return falseStartChecker_.canUseFalseStartWithCipher(cipher);
472 }
473 #endif
474
475 int SSLContext::selectNextProtocolCallback(
476   SSL* ssl, unsigned char **out, unsigned char *outlen,
477   const unsigned char *server, unsigned int server_len, void *data) {
478
479   SSLContext* ctx = (SSLContext*)data;
480   if (ctx->advertisedNextProtocols_.size() > 1) {
481     VLOG(3) << "SSLContext::selectNextProcolCallback() "
482             << "client should be deterministic in selecting protocols.";
483   }
484
485   unsigned char *client;
486   unsigned int client_len;
487   bool filtered = false;
488   auto cpf = ctx->getClientProtocolFilterCallback();
489   if (cpf) {
490     filtered = (*cpf)(&client, &client_len, server, server_len);
491   }
492
493   if (!filtered) {
494     if (ctx->advertisedNextProtocols_.empty()) {
495       client = (unsigned char *) "";
496       client_len = 0;
497     } else {
498       client = ctx->advertisedNextProtocols_[0].protocols;
499       client_len = ctx->advertisedNextProtocols_[0].length;
500     }
501   }
502
503   int retval = SSL_select_next_proto(out, outlen, server, server_len,
504                                      client, client_len);
505   if (retval != OPENSSL_NPN_NEGOTIATED) {
506     VLOG(3) << "SSLContext::selectNextProcolCallback() "
507             << "unable to pick a next protocol.";
508 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
509   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
510   } else {
511     const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
512     if (cipher && ctx->canUseFalseStartWithCipher(cipher)) {
513       SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
514     }
515 #endif
516   }
517   return SSL_TLSEXT_ERR_OK;
518 }
519 #endif // OPENSSL_NPN_NEGOTIATED
520
521 SSL* SSLContext::createSSL() const {
522   SSL* ssl = SSL_new(ctx_);
523   if (ssl == nullptr) {
524     throw std::runtime_error("SSL_new: " + getErrors());
525   }
526   return ssl;
527 }
528
529 /**
530  * Match a name with a pattern. The pattern may include wildcard. A single
531  * wildcard "*" can match up to one component in the domain name.
532  *
533  * @param  host    Host name, typically the name of the remote host
534  * @param  pattern Name retrieved from certificate
535  * @param  size    Size of "pattern"
536  * @return True, if "host" matches "pattern". False otherwise.
537  */
538 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
539   bool match = false;
540   int i = 0, j = 0;
541   while (i < size && host[j] != '\0') {
542     if (toupper(pattern[i]) == toupper(host[j])) {
543       i++;
544       j++;
545       continue;
546     }
547     if (pattern[i] == '*') {
548       while (host[j] != '.' && host[j] != '\0') {
549         j++;
550       }
551       i++;
552       continue;
553     }
554     break;
555   }
556   if (i == size && host[j] == '\0') {
557     match = true;
558   }
559   return match;
560 }
561
562 int SSLContext::passwordCallback(char* password,
563                                  int size,
564                                  int,
565                                  void* data) {
566   SSLContext* context = (SSLContext*)data;
567   if (context == nullptr || context->passwordCollector() == nullptr) {
568     return 0;
569   }
570   std::string userPassword;
571   // call user defined password collector to get password
572   context->passwordCollector()->getPassword(userPassword, size);
573   int length = userPassword.size();
574   if (length > size) {
575     length = size;
576   }
577   strncpy(password, userPassword.c_str(), length);
578   return length;
579 }
580
581 struct SSLLock {
582   explicit SSLLock(
583     SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
584       lockType(inLockType) {
585   }
586
587   void lock() {
588     if (lockType == SSLContext::LOCK_MUTEX) {
589       mutex.lock();
590     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
591       spinLock.lock();
592     }
593     // lockType == LOCK_NONE, no-op
594   }
595
596   void unlock() {
597     if (lockType == SSLContext::LOCK_MUTEX) {
598       mutex.unlock();
599     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
600       spinLock.unlock();
601     }
602     // lockType == LOCK_NONE, no-op
603   }
604
605   SSLContext::SSLLockType lockType;
606   folly::SpinLock spinLock{};
607   std::mutex mutex;
608 };
609
610 // Statics are unsafe in environments that call exit().
611 // If one thread calls exit() while another thread is
612 // references a member of SSLContext, bad things can happen.
613 // SSLContext runs in such environments.
614 // Instead of declaring a static member we "new" the static
615 // member so that it won't be destructed on exit().
616 static std::unique_ptr<SSLLock[]>& locks() {
617   static auto locksInst = new std::unique_ptr<SSLLock[]>();
618   return *locksInst;
619 }
620
621 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
622   static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
623   return *lockTypesInst;
624 }
625
626 static void callbackLocking(int mode, int n, const char*, int) {
627   if (mode & CRYPTO_LOCK) {
628     locks()[n].lock();
629   } else {
630     locks()[n].unlock();
631   }
632 }
633
634 static unsigned long callbackThreadID() {
635   return static_cast<unsigned long>(
636 #ifdef __APPLE__
637     pthread_mach_thread_np(pthread_self())
638 #else
639     pthread_self()
640 #endif
641   );
642 }
643
644 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
645   return new CRYPTO_dynlock_value;
646 }
647
648 static void dyn_lock(int mode,
649                      struct CRYPTO_dynlock_value* lock,
650                      const char*, int) {
651   if (lock != nullptr) {
652     if (mode & CRYPTO_LOCK) {
653       lock->mutex.lock();
654     } else {
655       lock->mutex.unlock();
656     }
657   }
658 }
659
660 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
661   delete lock;
662 }
663
664 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
665   lockTypes() = inLockTypes;
666 }
667
668 void SSLContext::markInitialized() {
669   std::lock_guard<std::mutex> g(initMutex());
670   initialized_ = true;
671 }
672
673 void SSLContext::initializeOpenSSL() {
674   std::lock_guard<std::mutex> g(initMutex());
675   initializeOpenSSLLocked();
676 }
677
678 void SSLContext::initializeOpenSSLLocked() {
679   if (initialized_) {
680     return;
681   }
682   SSL_library_init();
683   SSL_load_error_strings();
684   ERR_load_crypto_strings();
685   // static locking
686   locks().reset(new SSLLock[::CRYPTO_num_locks()]);
687   for (auto it: lockTypes()) {
688     locks()[it.first].lockType = it.second;
689   }
690   CRYPTO_set_id_callback(callbackThreadID);
691   CRYPTO_set_locking_callback(callbackLocking);
692   // dynamic locking
693   CRYPTO_set_dynlock_create_callback(dyn_create);
694   CRYPTO_set_dynlock_lock_callback(dyn_lock);
695   CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
696   randomize();
697 #ifdef OPENSSL_NPN_NEGOTIATED
698   sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
699       (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
700 #endif
701   initialized_ = true;
702 }
703
704 void SSLContext::cleanupOpenSSL() {
705   std::lock_guard<std::mutex> g(initMutex());
706   cleanupOpenSSLLocked();
707 }
708
709 void SSLContext::cleanupOpenSSLLocked() {
710   if (!initialized_) {
711     return;
712   }
713
714   CRYPTO_set_id_callback(nullptr);
715   CRYPTO_set_locking_callback(nullptr);
716   CRYPTO_set_dynlock_create_callback(nullptr);
717   CRYPTO_set_dynlock_lock_callback(nullptr);
718   CRYPTO_set_dynlock_destroy_callback(nullptr);
719   CRYPTO_cleanup_all_ex_data();
720   ERR_free_strings();
721   EVP_cleanup();
722   ERR_remove_state(0);
723   locks().reset();
724   initialized_ = false;
725 }
726
727 void SSLContext::setOptions(long options) {
728   long newOpt = SSL_CTX_set_options(ctx_, options);
729   if ((newOpt & options) != options) {
730     throw std::runtime_error("SSL_CTX_set_options failed");
731   }
732 }
733
734 std::string SSLContext::getErrors(int errnoCopy) {
735   std::string errors;
736   unsigned long  errorCode;
737   char   message[256];
738
739   errors.reserve(512);
740   while ((errorCode = ERR_get_error()) != 0) {
741     if (!errors.empty()) {
742       errors += "; ";
743     }
744     const char* reason = ERR_reason_error_string(errorCode);
745     if (reason == nullptr) {
746       snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
747       reason = message;
748     }
749     errors += reason;
750   }
751   if (errors.empty()) {
752     errors = "error code: " + folly::to<std::string>(errnoCopy);
753   }
754   return errors;
755 }
756
757 std::ostream&
758 operator<<(std::ostream& os, const PasswordCollector& collector) {
759   os << collector.describe();
760   return os;
761 }
762
763 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
764                                                   sockaddr_storage* addrStorage,
765                                                   socklen_t* addrLen) {
766   // Grab the ssl idx and then the ssl object so that we can get the peer
767   // name to compare against the ips in the subjectAltName
768   auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
769   auto ssl =
770     reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
771   int fd = SSL_get_fd(ssl);
772   if (fd < 0) {
773     LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
774     return false;
775   }
776
777   *addrLen = sizeof(*addrStorage);
778   if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
779     PLOG(ERROR) << "Unable to get peer name";
780     return false;
781   }
782   CHECK(*addrLen <= sizeof(*addrStorage));
783   return true;
784 }
785
786 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
787                                          const sockaddr* addr,
788                                          socklen_t addrLen) {
789   // Try to extract the names within the SAN extension from the certificate
790   auto altNames =
791     reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
792         X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
793   SCOPE_EXIT {
794     if (altNames != nullptr) {
795       sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
796     }
797   };
798   if (altNames == nullptr) {
799     LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
800     return false;
801   }
802
803   const sockaddr_in* addr4 = nullptr;
804   const sockaddr_in6* addr6 = nullptr;
805   if (addr != nullptr) {
806     if (addr->sa_family == AF_INET) {
807       addr4 = reinterpret_cast<const sockaddr_in*>(addr);
808     } else if (addr->sa_family == AF_INET6) {
809       addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
810     } else {
811       LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
812     }
813   }
814
815
816   for (int i = 0; i < sk_GENERAL_NAME_num(altNames); i++) {
817     auto name = sk_GENERAL_NAME_value(altNames, i);
818     if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
819       // Extra const-ness for paranoia
820       unsigned char const * const rawIpStr = name->d.iPAddress->data;
821       int const rawIpLen = name->d.iPAddress->length;
822
823       if (rawIpLen == 4 && addr4 != nullptr) {
824         if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
825           return true;
826         }
827       } else if (rawIpLen == 16 && addr6 != nullptr) {
828         if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
829           return true;
830         }
831       } else if (rawIpLen != 4 && rawIpLen != 16) {
832         LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
833       }
834     }
835   }
836
837   LOG(WARNING) << "Unable to match client cert against alt name ip";
838   return false;
839 }
840
841
842 } // folly