2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "SSLContext.h"
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #include <openssl/ssl.h>
22 #include <openssl/x509v3.h>
24 #include <folly/Format.h>
25 #include <folly/Memory.h>
26 #include <folly/Random.h>
27 #include <folly/SpinLock.h>
29 // ---------------------------------------------------------------------
30 // SSLContext implementation
31 // ---------------------------------------------------------------------
33 struct CRYPTO_dynlock_value {
39 // For OpenSSL portability API
40 using namespace folly::ssl;
42 bool SSLContext::initialized_ = false;
46 std::mutex& initMutex() {
51 } // anonymous namespace
53 #ifdef OPENSSL_NPN_NEGOTIATED
54 int SSLContext::sNextProtocolsExDataIndex_ = -1;
57 // SSLContext implementation
58 SSLContext::SSLContext(SSLVersion version) {
60 std::lock_guard<std::mutex> g(initMutex());
61 initializeOpenSSLLocked();
64 ctx_ = SSL_CTX_new(SSLv23_method());
65 if (ctx_ == nullptr) {
66 throw std::runtime_error("SSL_CTX_new: " + getErrors());
72 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
75 opt = SSL_OP_NO_SSLv2;
81 int newOpt = SSL_CTX_set_options(ctx_, opt);
82 DCHECK((newOpt & opt) == opt);
84 SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
86 checkPeerName_ = false;
88 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION);
90 #if FOLLY_OPENSSL_HAS_SNI
91 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
92 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
96 SSLContext::~SSLContext() {
97 if (ctx_ != nullptr) {
102 #ifdef OPENSSL_NPN_NEGOTIATED
103 deleteNextProtocolsStrings();
107 void SSLContext::ciphers(const std::string& ciphers) {
108 providedCiphersString_ = ciphers;
109 setCiphersOrThrow(ciphers);
112 void SSLContext::setCipherList(const std::vector<std::string>& ciphers) {
113 if (ciphers.size() == 0) {
116 std::string opensslCipherList;
117 join(":", ciphers, opensslCipherList);
118 setCiphersOrThrow(opensslCipherList);
121 void SSLContext::setSignatureAlgorithms(
122 const std::vector<std::string>& sigalgs) {
123 if (sigalgs.size() == 0) {
126 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
127 std::string opensslSigAlgsList;
128 join(":", sigalgs, opensslSigAlgsList);
129 int rc = SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str());
131 throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
136 void SSLContext::setClientECCurvesList(
137 const std::vector<std::string>& ecCurves) {
138 if (ecCurves.size() == 0) {
141 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
142 std::string ecCurvesList;
143 join(":", ecCurves, ecCurvesList);
144 int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
146 throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
151 void SSLContext::setServerECCurve(const std::string& curveName) {
152 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL && !defined(OPENSSL_NO_ECDH)
153 EC_KEY* ecdh = nullptr;
157 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
158 * from RFC 4492 section 5.1.1, or explicitly described curves over
159 * binary fields. OpenSSL only supports the "named curves", which provide
160 * maximum interoperability.
163 nid = OBJ_sn2nid(curveName.c_str());
165 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
167 ecdh = EC_KEY_new_by_curve_name(nid);
168 if (ecdh == nullptr) {
169 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
172 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
175 throw std::runtime_error("Elliptic curve encryption not allowed");
179 void SSLContext::setX509VerifyParam(
180 const ssl::X509VerifyParam& x509VerifyParam) {
181 if (!x509VerifyParam) {
184 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
185 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
189 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
190 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
192 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
196 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
198 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
199 verifyPeer_ = verifyPeer;
202 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
204 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
205 int mode = SSL_VERIFY_NONE;
207 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
210 case SSLVerifyPeerEnum::VERIFY:
211 mode = SSL_VERIFY_PEER;
214 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
215 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
218 case SSLVerifyPeerEnum::NO_VERIFY:
219 mode = SSL_VERIFY_NONE;
228 int SSLContext::getVerificationMode() {
229 return getVerificationMode(verifyPeer_);
232 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
233 const std::string& peerName) {
236 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
237 checkPeerName_ = checkPeerName;
238 peerFixedName_ = peerName;
240 mode = SSL_VERIFY_NONE;
241 checkPeerName_ = false; // can't check name without cert!
242 peerFixedName_.clear();
244 SSL_CTX_set_verify(ctx_, mode, nullptr);
247 void SSLContext::loadCertificate(const char* path, const char* format) {
248 if (path == nullptr || format == nullptr) {
249 throw std::invalid_argument(
250 "loadCertificateChain: either <path> or <format> is nullptr");
252 if (strcmp(format, "PEM") == 0) {
253 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
254 int errnoCopy = errno;
255 std::string reason("SSL_CTX_use_certificate_chain_file: ");
258 reason.append(getErrors(errnoCopy));
259 throw std::runtime_error(reason);
262 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
266 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
267 if (cert.data() == nullptr) {
268 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
271 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
272 if (bio == nullptr) {
273 throw std::runtime_error("BIO_new: " + getErrors());
276 int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
277 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
278 throw std::runtime_error("BIO_write: " + getErrors());
281 ssl::X509UniquePtr x509(
282 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
283 if (x509 == nullptr) {
284 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
287 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
288 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
292 void SSLContext::loadPrivateKey(const char* path, const char* format) {
293 if (path == nullptr || format == nullptr) {
294 throw std::invalid_argument(
295 "loadPrivateKey: either <path> or <format> is nullptr");
297 if (strcmp(format, "PEM") == 0) {
298 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
299 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
302 throw std::runtime_error("Unsupported private key format: " + std::string(format));
306 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
307 if (pkey.data() == nullptr) {
308 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
311 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
312 if (bio == nullptr) {
313 throw std::runtime_error("BIO_new: " + getErrors());
316 int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
317 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
318 throw std::runtime_error("BIO_write: " + getErrors());
321 ssl::EvpPkeyUniquePtr key(
322 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
323 if (key == nullptr) {
324 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
327 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
328 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
332 void SSLContext::loadTrustedCertificates(const char* path) {
333 if (path == nullptr) {
334 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
336 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
337 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
342 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
343 SSL_CTX_set_cert_store(ctx_, store);
346 void SSLContext::loadClientCAList(const char* path) {
347 auto clientCAs = SSL_load_client_CA_file(path);
348 if (clientCAs == nullptr) {
349 LOG(ERROR) << "Unable to load ca file: " << path;
352 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
355 void SSLContext::randomize() {
359 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
360 if (collector == nullptr) {
361 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
364 collector_ = collector;
365 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
366 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
369 #if FOLLY_OPENSSL_HAS_SNI
371 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
375 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
376 clientHelloCbs_.push_back(cb);
379 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
380 SSLContext* context = (SSLContext*)data;
382 if (context == nullptr) {
383 return SSL_TLSEXT_ERR_NOACK;
386 for (auto& cb : context->clientHelloCbs_) {
387 // Generic callbacks to happen after we receive the Client Hello.
388 // For example, we use one to switch which cipher we use depending
389 // on the user's TLS version. Because the primary purpose of
390 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
391 // are side-uses, we ignore any possible failures other than just logging
396 if (!context->serverNameCb_) {
397 return SSL_TLSEXT_ERR_NOACK;
400 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
402 case SERVER_NAME_FOUND:
403 return SSL_TLSEXT_ERR_OK;
404 case SERVER_NAME_NOT_FOUND:
405 return SSL_TLSEXT_ERR_NOACK;
406 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
407 *al = TLS1_AD_UNRECOGNIZED_NAME;
408 return SSL_TLSEXT_ERR_ALERT_FATAL;
413 return SSL_TLSEXT_ERR_NOACK;
416 void SSLContext::switchCiphersIfTLS11(
418 const std::string& tls11CipherString,
419 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist) {
420 CHECK(!(tls11CipherString.empty() && tls11AltCipherlist.empty()))
421 << "Shouldn't call if empty ciphers / alt ciphers";
423 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
424 // We only do this for TLS v 1.1 and later
428 const std::string* ciphers = &tls11CipherString;
429 if (!tls11AltCipherlist.empty()) {
430 if (!cipherListPicker_) {
431 std::vector<int> weights;
433 tls11AltCipherlist.begin(),
434 tls11AltCipherlist.end(),
435 [&](const std::pair<std::string, int>& e) {
436 weights.push_back(e.second);
438 cipherListPicker_.reset(
439 new std::discrete_distribution<int>(weights.begin(), weights.end()));
441 auto rng = ThreadLocalPRNG();
442 auto index = (*cipherListPicker_)(rng);
443 if ((size_t)index >= tls11AltCipherlist.size()) {
444 LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
445 << ", but tls11AltCipherlist is of length "
446 << tls11AltCipherlist.size();
448 ciphers = &tls11AltCipherlist[size_t(index)].first;
452 // Prefer AES for TLS versions 1.1 and later since these are not
453 // vulnerable to BEAST attacks on AES. Note that we're setting the
454 // cipher list on the SSL object, not the SSL_CTX object, so it will
455 // only last for this request.
456 int rc = SSL_set_cipher_list(ssl, ciphers->c_str());
457 if ((rc == 0) || ERR_peek_error() != 0) {
458 // This shouldn't happen since we checked for this when proxygen
460 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
461 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
464 #endif // FOLLY_OPENSSL_HAS_SNI
466 #if FOLLY_OPENSSL_HAS_ALPN
467 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
468 const unsigned char** out,
469 unsigned char* outlen,
470 const unsigned char* in,
473 SSLContext* context = (SSLContext*)data;
475 if (context->advertisedNextProtocols_.empty()) {
479 auto i = context->pickNextProtocols();
480 const auto& item = context->advertisedNextProtocols_[i];
481 if (SSL_select_next_proto((unsigned char**)out,
486 inlen) != OPENSSL_NPN_NEGOTIATED) {
487 return SSL_TLSEXT_ERR_NOACK;
490 return SSL_TLSEXT_ERR_OK;
492 #endif // FOLLY_OPENSSL_HAS_ALPN
494 #ifdef OPENSSL_NPN_NEGOTIATED
496 bool SSLContext::setAdvertisedNextProtocols(
497 const std::list<std::string>& protocols, NextProtocolType protocolType) {
498 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
501 bool SSLContext::setRandomizedAdvertisedNextProtocols(
502 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
503 unsetNextProtocols();
504 if (items.size() == 0) {
507 int total_weight = 0;
508 for (const auto &item : items) {
509 if (item.protocols.size() == 0) {
512 AdvertisedNextProtocolsItem advertised_item;
513 advertised_item.length = 0;
514 for (const auto& proto : item.protocols) {
515 ++advertised_item.length;
516 auto protoLength = proto.length();
517 if (protoLength >= 256) {
518 deleteNextProtocolsStrings();
521 advertised_item.length += unsigned(protoLength);
523 advertised_item.protocols = new unsigned char[advertised_item.length];
524 if (!advertised_item.protocols) {
525 throw std::runtime_error("alloc failure");
527 unsigned char* dst = advertised_item.protocols;
528 for (auto& proto : item.protocols) {
529 uint8_t protoLength = uint8_t(proto.length());
530 *dst++ = (unsigned char)protoLength;
531 memcpy(dst, proto.data(), protoLength);
534 total_weight += item.weight;
535 advertisedNextProtocols_.push_back(advertised_item);
536 advertisedNextProtocolWeights_.push_back(item.weight);
538 if (total_weight == 0) {
539 deleteNextProtocolsStrings();
542 nextProtocolDistribution_ =
543 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
544 advertisedNextProtocolWeights_.end());
545 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
546 SSL_CTX_set_next_protos_advertised_cb(
547 ctx_, advertisedNextProtocolCallback, this);
548 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
550 #if FOLLY_OPENSSL_HAS_ALPN
551 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
552 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
553 // Client cannot really use randomized alpn
554 SSL_CTX_set_alpn_protos(ctx_,
555 advertisedNextProtocols_[0].protocols,
556 advertisedNextProtocols_[0].length);
562 void SSLContext::deleteNextProtocolsStrings() {
563 for (auto protocols : advertisedNextProtocols_) {
564 delete[] protocols.protocols;
566 advertisedNextProtocols_.clear();
567 advertisedNextProtocolWeights_.clear();
570 void SSLContext::unsetNextProtocols() {
571 deleteNextProtocolsStrings();
572 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
573 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
574 #if FOLLY_OPENSSL_HAS_ALPN
575 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
576 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
580 size_t SSLContext::pickNextProtocols() {
581 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
582 auto rng = ThreadLocalPRNG();
583 return size_t(nextProtocolDistribution_(rng));
586 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
587 const unsigned char** out, unsigned int* outlen, void* data) {
588 SSLContext* context = (SSLContext*)data;
589 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
592 } else if (context->advertisedNextProtocols_.size() == 1) {
593 *out = context->advertisedNextProtocols_[0].protocols;
594 *outlen = context->advertisedNextProtocols_[0].length;
596 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
597 sNextProtocolsExDataIndex_));
598 if (selected_index) {
600 *out = context->advertisedNextProtocols_[selected_index].protocols;
601 *outlen = context->advertisedNextProtocols_[selected_index].length;
603 auto i = context->pickNextProtocols();
604 uintptr_t selected = i + 1;
605 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
606 *out = context->advertisedNextProtocols_[i].protocols;
607 *outlen = context->advertisedNextProtocols_[i].length;
610 return SSL_TLSEXT_ERR_OK;
613 int SSLContext::selectNextProtocolCallback(SSL* ssl,
615 unsigned char* outlen,
616 const unsigned char* server,
617 unsigned int server_len,
619 (void)ssl; // Make -Wunused-parameters happy
620 SSLContext* ctx = (SSLContext*)data;
621 if (ctx->advertisedNextProtocols_.size() > 1) {
622 VLOG(3) << "SSLContext::selectNextProcolCallback() "
623 << "client should be deterministic in selecting protocols.";
626 unsigned char* client = nullptr;
627 unsigned int client_len = 0;
628 bool filtered = false;
629 auto cpf = ctx->getClientProtocolFilterCallback();
631 filtered = (*cpf)(&client, &client_len, server, server_len);
635 if (ctx->advertisedNextProtocols_.empty()) {
636 client = (unsigned char *) "";
639 client = ctx->advertisedNextProtocols_[0].protocols;
640 client_len = ctx->advertisedNextProtocols_[0].length;
644 int retval = SSL_select_next_proto(out, outlen, server, server_len,
646 if (retval != OPENSSL_NPN_NEGOTIATED) {
647 VLOG(3) << "SSLContext::selectNextProcolCallback() "
648 << "unable to pick a next protocol.";
650 return SSL_TLSEXT_ERR_OK;
652 #endif // OPENSSL_NPN_NEGOTIATED
654 SSL* SSLContext::createSSL() const {
655 SSL* ssl = SSL_new(ctx_);
656 if (ssl == nullptr) {
657 throw std::runtime_error("SSL_new: " + getErrors());
662 void SSLContext::setSessionCacheContext(const std::string& context) {
663 SSL_CTX_set_session_id_context(
665 reinterpret_cast<const unsigned char*>(context.data()),
666 std::min<unsigned int>(
667 static_cast<unsigned int>(context.length()),
668 SSL_MAX_SSL_SESSION_ID_LENGTH));
672 * Match a name with a pattern. The pattern may include wildcard. A single
673 * wildcard "*" can match up to one component in the domain name.
675 * @param host Host name, typically the name of the remote host
676 * @param pattern Name retrieved from certificate
677 * @param size Size of "pattern"
678 * @return True, if "host" matches "pattern". False otherwise.
680 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
683 while (i < size && host[j] != '\0') {
684 if (toupper(pattern[i]) == toupper(host[j])) {
689 if (pattern[i] == '*') {
690 while (host[j] != '.' && host[j] != '\0') {
698 if (i == size && host[j] == '\0') {
704 int SSLContext::passwordCallback(char* password,
708 SSLContext* context = (SSLContext*)data;
709 if (context == nullptr || context->passwordCollector() == nullptr) {
712 std::string userPassword;
713 // call user defined password collector to get password
714 context->passwordCollector()->getPassword(userPassword, size);
715 auto length = int(userPassword.size());
719 strncpy(password, userPassword.c_str(), size_t(length));
725 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
726 lockType(inLockType) {
730 if (lockType == SSLContext::LOCK_MUTEX) {
732 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
735 // lockType == LOCK_NONE, no-op
739 if (lockType == SSLContext::LOCK_MUTEX) {
741 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
744 // lockType == LOCK_NONE, no-op
747 SSLContext::SSLLockType lockType;
748 folly::SpinLock spinLock{};
752 // Statics are unsafe in environments that call exit().
753 // If one thread calls exit() while another thread is
754 // references a member of SSLContext, bad things can happen.
755 // SSLContext runs in such environments.
756 // Instead of declaring a static member we "new" the static
757 // member so that it won't be destructed on exit().
758 static std::unique_ptr<SSLLock[]>& locks() {
759 static auto locksInst = new std::unique_ptr<SSLLock[]>();
763 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
764 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
765 return *lockTypesInst;
768 static void callbackLocking(int mode, int n, const char*, int) {
769 if (mode & CRYPTO_LOCK) {
770 locks()[size_t(n)].lock();
772 locks()[size_t(n)].unlock();
776 static unsigned long callbackThreadID() {
777 return static_cast<unsigned long>(
779 pthread_mach_thread_np(pthread_self())
781 pthread_getw32threadid_np(pthread_self())
788 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
789 return new CRYPTO_dynlock_value;
792 static void dyn_lock(int mode,
793 struct CRYPTO_dynlock_value* lock,
795 if (lock != nullptr) {
796 if (mode & CRYPTO_LOCK) {
799 lock->mutex.unlock();
804 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
808 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
809 lockTypes() = inLockTypes;
812 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
813 void SSLContext::enableFalseStart() {
814 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
818 void SSLContext::markInitialized() {
819 std::lock_guard<std::mutex> g(initMutex());
823 void SSLContext::initializeOpenSSL() {
824 std::lock_guard<std::mutex> g(initMutex());
825 initializeOpenSSLLocked();
828 void SSLContext::initializeOpenSSLLocked() {
833 SSL_load_error_strings();
834 ERR_load_crypto_strings();
836 locks().reset(new SSLLock[size_t(CRYPTO_num_locks())]);
837 for (auto it: lockTypes()) {
838 locks()[size_t(it.first)].lockType = it.second;
840 CRYPTO_set_id_callback(callbackThreadID);
841 CRYPTO_set_locking_callback(callbackLocking);
843 CRYPTO_set_dynlock_create_callback(dyn_create);
844 CRYPTO_set_dynlock_lock_callback(dyn_lock);
845 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
847 #ifdef OPENSSL_NPN_NEGOTIATED
848 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
849 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
854 void SSLContext::cleanupOpenSSL() {
855 std::lock_guard<std::mutex> g(initMutex());
856 cleanupOpenSSLLocked();
859 void SSLContext::cleanupOpenSSLLocked() {
864 CRYPTO_set_id_callback(nullptr);
865 CRYPTO_set_locking_callback(nullptr);
866 CRYPTO_set_dynlock_create_callback(nullptr);
867 CRYPTO_set_dynlock_lock_callback(nullptr);
868 CRYPTO_set_dynlock_destroy_callback(nullptr);
869 CRYPTO_cleanup_all_ex_data();
874 initialized_ = false;
877 void SSLContext::setOptions(long options) {
878 long newOpt = SSL_CTX_set_options(ctx_, options);
879 if ((newOpt & options) != options) {
880 throw std::runtime_error("SSL_CTX_set_options failed");
884 std::string SSLContext::getErrors(int errnoCopy) {
886 unsigned long errorCode;
890 while ((errorCode = ERR_get_error()) != 0) {
891 if (!errors.empty()) {
894 const char* reason = ERR_reason_error_string(errorCode);
895 if (reason == nullptr) {
896 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
901 if (errors.empty()) {
902 errors = "error code: " + folly::to<std::string>(errnoCopy);
908 operator<<(std::ostream& os, const PasswordCollector& collector) {
909 os << collector.describe();