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 <folly/Format.h>
20 #include <folly/Memory.h>
21 #include <folly/Random.h>
22 #include <folly/SharedMutex.h>
23 #include <folly/SpinLock.h>
24 #include <folly/ThreadId.h>
26 // ---------------------------------------------------------------------
27 // SSLContext implementation
28 // ---------------------------------------------------------------------
30 struct CRYPTO_dynlock_value {
36 // For OpenSSL portability API
37 using namespace folly::ssl;
39 bool SSLContext::initialized_ = false;
43 std::mutex& initMutex() {
48 } // anonymous namespace
50 #ifdef OPENSSL_NPN_NEGOTIATED
51 int SSLContext::sNextProtocolsExDataIndex_ = -1;
54 // SSLContext implementation
55 SSLContext::SSLContext(SSLVersion version) {
57 std::lock_guard<std::mutex> g(initMutex());
58 initializeOpenSSLLocked();
61 ctx_ = SSL_CTX_new(SSLv23_method());
62 if (ctx_ == nullptr) {
63 throw std::runtime_error("SSL_CTX_new: " + getErrors());
69 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
72 opt = SSL_OP_NO_SSLv2;
78 int newOpt = SSL_CTX_set_options(ctx_, opt);
79 DCHECK((newOpt & opt) == opt);
81 SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
83 checkPeerName_ = false;
85 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION);
87 #if FOLLY_OPENSSL_HAS_SNI
88 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
89 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
93 SSLContext::~SSLContext() {
94 if (ctx_ != nullptr) {
99 #ifdef OPENSSL_NPN_NEGOTIATED
100 deleteNextProtocolsStrings();
104 void SSLContext::ciphers(const std::string& ciphers) {
105 setCiphersOrThrow(ciphers);
108 void SSLContext::setCipherList(const std::vector<std::string>& ciphers) {
109 if (ciphers.size() == 0) {
112 std::string opensslCipherList;
113 join(":", ciphers, opensslCipherList);
114 setCiphersOrThrow(opensslCipherList);
117 void SSLContext::setSignatureAlgorithms(
118 const std::vector<std::string>& sigalgs) {
119 if (sigalgs.size() == 0) {
122 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
123 std::string opensslSigAlgsList;
124 join(":", sigalgs, opensslSigAlgsList);
125 int rc = SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str());
127 throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
132 void SSLContext::setClientECCurvesList(
133 const std::vector<std::string>& ecCurves) {
134 if (ecCurves.size() == 0) {
137 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
138 std::string ecCurvesList;
139 join(":", ecCurves, ecCurvesList);
140 int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
142 throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
147 void SSLContext::setServerECCurve(const std::string& curveName) {
148 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL && !defined(OPENSSL_NO_ECDH)
149 EC_KEY* ecdh = nullptr;
153 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
154 * from RFC 4492 section 5.1.1, or explicitly described curves over
155 * binary fields. OpenSSL only supports the "named curves", which provide
156 * maximum interoperability.
159 nid = OBJ_sn2nid(curveName.c_str());
161 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
163 ecdh = EC_KEY_new_by_curve_name(nid);
164 if (ecdh == nullptr) {
165 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
168 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
171 throw std::runtime_error("Elliptic curve encryption not allowed");
175 void SSLContext::setX509VerifyParam(
176 const ssl::X509VerifyParam& x509VerifyParam) {
177 if (!x509VerifyParam) {
180 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
181 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
185 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
186 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
188 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
190 providedCiphersString_ = ciphers;
193 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
195 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
196 verifyPeer_ = verifyPeer;
199 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
201 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
202 int mode = SSL_VERIFY_NONE;
204 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
207 case SSLVerifyPeerEnum::VERIFY:
208 mode = SSL_VERIFY_PEER;
211 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
212 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
215 case SSLVerifyPeerEnum::NO_VERIFY:
216 mode = SSL_VERIFY_NONE;
225 int SSLContext::getVerificationMode() {
226 return getVerificationMode(verifyPeer_);
229 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
230 const std::string& peerName) {
233 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
234 checkPeerName_ = checkPeerName;
235 peerFixedName_ = peerName;
237 mode = SSL_VERIFY_NONE;
238 checkPeerName_ = false; // can't check name without cert!
239 peerFixedName_.clear();
241 SSL_CTX_set_verify(ctx_, mode, nullptr);
244 void SSLContext::loadCertificate(const char* path, const char* format) {
245 if (path == nullptr || format == nullptr) {
246 throw std::invalid_argument(
247 "loadCertificateChain: either <path> or <format> is nullptr");
249 if (strcmp(format, "PEM") == 0) {
250 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
251 int errnoCopy = errno;
252 std::string reason("SSL_CTX_use_certificate_chain_file: ");
255 reason.append(getErrors(errnoCopy));
256 throw std::runtime_error(reason);
259 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
263 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
264 if (cert.data() == nullptr) {
265 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
268 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
269 if (bio == nullptr) {
270 throw std::runtime_error("BIO_new: " + getErrors());
273 int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
274 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
275 throw std::runtime_error("BIO_write: " + getErrors());
278 ssl::X509UniquePtr x509(
279 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
280 if (x509 == nullptr) {
281 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
284 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
285 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
289 void SSLContext::loadPrivateKey(const char* path, const char* format) {
290 if (path == nullptr || format == nullptr) {
291 throw std::invalid_argument(
292 "loadPrivateKey: either <path> or <format> is nullptr");
294 if (strcmp(format, "PEM") == 0) {
295 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
296 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
299 throw std::runtime_error("Unsupported private key format: " + std::string(format));
303 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
304 if (pkey.data() == nullptr) {
305 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
308 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
309 if (bio == nullptr) {
310 throw std::runtime_error("BIO_new: " + getErrors());
313 int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
314 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
315 throw std::runtime_error("BIO_write: " + getErrors());
318 ssl::EvpPkeyUniquePtr key(
319 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
320 if (key == nullptr) {
321 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
324 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
325 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
329 void SSLContext::loadTrustedCertificates(const char* path) {
330 if (path == nullptr) {
331 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
333 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
334 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
339 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
340 SSL_CTX_set_cert_store(ctx_, store);
343 void SSLContext::loadClientCAList(const char* path) {
344 auto clientCAs = SSL_load_client_CA_file(path);
345 if (clientCAs == nullptr) {
346 LOG(ERROR) << "Unable to load ca file: " << path;
349 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
352 void SSLContext::randomize() {
356 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
357 if (collector == nullptr) {
358 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
361 collector_ = collector;
362 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
363 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
366 #if FOLLY_OPENSSL_HAS_SNI
368 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
372 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
373 clientHelloCbs_.push_back(cb);
376 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
377 SSLContext* context = (SSLContext*)data;
379 if (context == nullptr) {
380 return SSL_TLSEXT_ERR_NOACK;
383 for (auto& cb : context->clientHelloCbs_) {
384 // Generic callbacks to happen after we receive the Client Hello.
385 // For example, we use one to switch which cipher we use depending
386 // on the user's TLS version. Because the primary purpose of
387 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
388 // are side-uses, we ignore any possible failures other than just logging
393 if (!context->serverNameCb_) {
394 return SSL_TLSEXT_ERR_NOACK;
397 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
399 case SERVER_NAME_FOUND:
400 return SSL_TLSEXT_ERR_OK;
401 case SERVER_NAME_NOT_FOUND:
402 return SSL_TLSEXT_ERR_NOACK;
403 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
404 *al = TLS1_AD_UNRECOGNIZED_NAME;
405 return SSL_TLSEXT_ERR_ALERT_FATAL;
410 return SSL_TLSEXT_ERR_NOACK;
413 void SSLContext::switchCiphersIfTLS11(
415 const std::string& tls11CipherString,
416 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist) {
417 CHECK(!(tls11CipherString.empty() && tls11AltCipherlist.empty()))
418 << "Shouldn't call if empty ciphers / alt ciphers";
420 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
421 // We only do this for TLS v 1.1 and later
425 const std::string* ciphers = &tls11CipherString;
426 if (!tls11AltCipherlist.empty()) {
427 if (!cipherListPicker_) {
428 std::vector<int> weights;
430 tls11AltCipherlist.begin(),
431 tls11AltCipherlist.end(),
432 [&](const std::pair<std::string, int>& e) {
433 weights.push_back(e.second);
435 cipherListPicker_.reset(
436 new std::discrete_distribution<int>(weights.begin(), weights.end()));
438 auto rng = ThreadLocalPRNG();
439 auto index = (*cipherListPicker_)(rng);
440 if ((size_t)index >= tls11AltCipherlist.size()) {
441 LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
442 << ", but tls11AltCipherlist is of length "
443 << tls11AltCipherlist.size();
445 ciphers = &tls11AltCipherlist[size_t(index)].first;
449 // Prefer AES for TLS versions 1.1 and later since these are not
450 // vulnerable to BEAST attacks on AES. Note that we're setting the
451 // cipher list on the SSL object, not the SSL_CTX object, so it will
452 // only last for this request.
453 int rc = SSL_set_cipher_list(ssl, ciphers->c_str());
454 if ((rc == 0) || ERR_peek_error() != 0) {
455 // This shouldn't happen since we checked for this when proxygen
457 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
458 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
461 #endif // FOLLY_OPENSSL_HAS_SNI
463 #if FOLLY_OPENSSL_HAS_ALPN
464 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
465 const unsigned char** out,
466 unsigned char* outlen,
467 const unsigned char* in,
470 SSLContext* context = (SSLContext*)data;
472 if (context->advertisedNextProtocols_.empty()) {
476 auto i = context->pickNextProtocols();
477 const auto& item = context->advertisedNextProtocols_[i];
478 if (SSL_select_next_proto((unsigned char**)out,
483 inlen) != OPENSSL_NPN_NEGOTIATED) {
484 return SSL_TLSEXT_ERR_NOACK;
487 return SSL_TLSEXT_ERR_OK;
489 #endif // FOLLY_OPENSSL_HAS_ALPN
491 #ifdef OPENSSL_NPN_NEGOTIATED
493 bool SSLContext::setAdvertisedNextProtocols(
494 const std::list<std::string>& protocols, NextProtocolType protocolType) {
495 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
498 bool SSLContext::setRandomizedAdvertisedNextProtocols(
499 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
500 unsetNextProtocols();
501 if (items.size() == 0) {
504 int total_weight = 0;
505 for (const auto &item : items) {
506 if (item.protocols.size() == 0) {
509 AdvertisedNextProtocolsItem advertised_item;
510 advertised_item.length = 0;
511 for (const auto& proto : item.protocols) {
512 ++advertised_item.length;
513 auto protoLength = proto.length();
514 if (protoLength >= 256) {
515 deleteNextProtocolsStrings();
518 advertised_item.length += unsigned(protoLength);
520 advertised_item.protocols = new unsigned char[advertised_item.length];
521 if (!advertised_item.protocols) {
522 throw std::runtime_error("alloc failure");
524 unsigned char* dst = advertised_item.protocols;
525 for (auto& proto : item.protocols) {
526 uint8_t protoLength = uint8_t(proto.length());
527 *dst++ = (unsigned char)protoLength;
528 memcpy(dst, proto.data(), protoLength);
531 total_weight += item.weight;
532 advertisedNextProtocols_.push_back(advertised_item);
533 advertisedNextProtocolWeights_.push_back(item.weight);
535 if (total_weight == 0) {
536 deleteNextProtocolsStrings();
539 nextProtocolDistribution_ =
540 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
541 advertisedNextProtocolWeights_.end());
542 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
543 SSL_CTX_set_next_protos_advertised_cb(
544 ctx_, advertisedNextProtocolCallback, this);
545 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
547 #if FOLLY_OPENSSL_HAS_ALPN
548 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
549 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
550 // Client cannot really use randomized alpn
551 SSL_CTX_set_alpn_protos(ctx_,
552 advertisedNextProtocols_[0].protocols,
553 advertisedNextProtocols_[0].length);
559 void SSLContext::deleteNextProtocolsStrings() {
560 for (auto protocols : advertisedNextProtocols_) {
561 delete[] protocols.protocols;
563 advertisedNextProtocols_.clear();
564 advertisedNextProtocolWeights_.clear();
567 void SSLContext::unsetNextProtocols() {
568 deleteNextProtocolsStrings();
569 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
570 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
571 #if FOLLY_OPENSSL_HAS_ALPN
572 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
573 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
577 size_t SSLContext::pickNextProtocols() {
578 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
579 auto rng = ThreadLocalPRNG();
580 return size_t(nextProtocolDistribution_(rng));
583 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
584 const unsigned char** out, unsigned int* outlen, void* data) {
585 SSLContext* context = (SSLContext*)data;
586 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
589 } else if (context->advertisedNextProtocols_.size() == 1) {
590 *out = context->advertisedNextProtocols_[0].protocols;
591 *outlen = context->advertisedNextProtocols_[0].length;
593 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
594 sNextProtocolsExDataIndex_));
595 if (selected_index) {
597 *out = context->advertisedNextProtocols_[selected_index].protocols;
598 *outlen = context->advertisedNextProtocols_[selected_index].length;
600 auto i = context->pickNextProtocols();
601 uintptr_t selected = i + 1;
602 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
603 *out = context->advertisedNextProtocols_[i].protocols;
604 *outlen = context->advertisedNextProtocols_[i].length;
607 return SSL_TLSEXT_ERR_OK;
610 int SSLContext::selectNextProtocolCallback(SSL* ssl,
612 unsigned char* outlen,
613 const unsigned char* server,
614 unsigned int server_len,
616 (void)ssl; // Make -Wunused-parameters happy
617 SSLContext* ctx = (SSLContext*)data;
618 if (ctx->advertisedNextProtocols_.size() > 1) {
619 VLOG(3) << "SSLContext::selectNextProcolCallback() "
620 << "client should be deterministic in selecting protocols.";
623 unsigned char* client = nullptr;
624 unsigned int client_len = 0;
625 bool filtered = false;
626 auto cpf = ctx->getClientProtocolFilterCallback();
628 filtered = (*cpf)(&client, &client_len, server, server_len);
632 if (ctx->advertisedNextProtocols_.empty()) {
633 client = (unsigned char *) "";
636 client = ctx->advertisedNextProtocols_[0].protocols;
637 client_len = ctx->advertisedNextProtocols_[0].length;
641 int retval = SSL_select_next_proto(out, outlen, server, server_len,
643 if (retval != OPENSSL_NPN_NEGOTIATED) {
644 VLOG(3) << "SSLContext::selectNextProcolCallback() "
645 << "unable to pick a next protocol.";
647 return SSL_TLSEXT_ERR_OK;
649 #endif // OPENSSL_NPN_NEGOTIATED
651 SSL* SSLContext::createSSL() const {
652 SSL* ssl = SSL_new(ctx_);
653 if (ssl == nullptr) {
654 throw std::runtime_error("SSL_new: " + getErrors());
659 void SSLContext::setSessionCacheContext(const std::string& context) {
660 SSL_CTX_set_session_id_context(
662 reinterpret_cast<const unsigned char*>(context.data()),
663 std::min<unsigned int>(
664 static_cast<unsigned int>(context.length()),
665 SSL_MAX_SSL_SESSION_ID_LENGTH));
669 * Match a name with a pattern. The pattern may include wildcard. A single
670 * wildcard "*" can match up to one component in the domain name.
672 * @param host Host name, typically the name of the remote host
673 * @param pattern Name retrieved from certificate
674 * @param size Size of "pattern"
675 * @return True, if "host" matches "pattern". False otherwise.
677 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
680 while (i < size && host[j] != '\0') {
681 if (toupper(pattern[i]) == toupper(host[j])) {
686 if (pattern[i] == '*') {
687 while (host[j] != '.' && host[j] != '\0') {
695 if (i == size && host[j] == '\0') {
701 int SSLContext::passwordCallback(char* password,
705 SSLContext* context = (SSLContext*)data;
706 if (context == nullptr || context->passwordCollector() == nullptr) {
709 std::string userPassword;
710 // call user defined password collector to get password
711 context->passwordCollector()->getPassword(userPassword, size);
712 auto length = int(userPassword.size());
716 strncpy(password, userPassword.c_str(), size_t(length));
722 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
723 lockType(inLockType) {
726 void lock(bool read) {
727 if (lockType == SSLContext::LOCK_MUTEX) {
729 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
731 } else if (lockType == SSLContext::LOCK_SHAREDMUTEX) {
733 sharedMutex.lock_shared();
738 // lockType == LOCK_NONE, no-op
741 void unlock(bool read) {
742 if (lockType == SSLContext::LOCK_MUTEX) {
744 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
746 } else if (lockType == SSLContext::LOCK_SHAREDMUTEX) {
748 sharedMutex.unlock_shared();
750 sharedMutex.unlock();
753 // lockType == LOCK_NONE, no-op
756 SSLContext::SSLLockType lockType;
757 folly::SpinLock spinLock{};
759 SharedMutex sharedMutex;
762 // Statics are unsafe in environments that call exit().
763 // If one thread calls exit() while another thread is
764 // references a member of SSLContext, bad things can happen.
765 // SSLContext runs in such environments.
766 // Instead of declaring a static member we "new" the static
767 // member so that it won't be destructed on exit().
768 static std::unique_ptr<SSLLock[]>& locks() {
769 static auto locksInst = new std::unique_ptr<SSLLock[]>();
773 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
774 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
775 return *lockTypesInst;
778 static void callbackLocking(int mode, int n, const char*, int) {
779 if (mode & CRYPTO_LOCK) {
780 locks()[size_t(n)].lock(mode & CRYPTO_READ);
782 locks()[size_t(n)].unlock(mode & CRYPTO_READ);
786 static unsigned long callbackThreadID() {
787 return static_cast<unsigned long>(folly::getCurrentThreadID());
790 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
791 return new CRYPTO_dynlock_value;
794 static void dyn_lock(int mode,
795 struct CRYPTO_dynlock_value* lock,
797 if (lock != nullptr) {
798 if (mode & CRYPTO_LOCK) {
801 lock->mutex.unlock();
806 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
810 void SSLContext::setSSLLockTypesLocked(std::map<int, SSLLockType> inLockTypes) {
811 lockTypes() = inLockTypes;
814 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
815 std::lock_guard<std::mutex> g(initMutex());
817 // We set the locks on initialization, so if we are already initialized
818 // this would have no affect.
819 LOG(INFO) << "Ignoring setSSLLockTypes after initialization";
822 setSSLLockTypesLocked(std::move(inLockTypes));
825 void SSLContext::setSSLLockTypesAndInitOpenSSL(
826 std::map<int, SSLLockType> inLockTypes) {
827 std::lock_guard<std::mutex> g(initMutex());
828 CHECK(!initialized_) << "OpenSSL is already initialized";
829 setSSLLockTypesLocked(std::move(inLockTypes));
830 initializeOpenSSLLocked();
833 bool SSLContext::isSSLLockDisabled(int lockId) {
834 std::lock_guard<std::mutex> g(initMutex());
835 CHECK(initialized_) << "OpenSSL is not initialized yet";
836 const auto& sslLocks = lockTypes();
837 const auto it = sslLocks.find(lockId);
838 return it != sslLocks.end() &&
839 it->second == SSLContext::SSLLockType::LOCK_NONE;
842 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
843 void SSLContext::enableFalseStart() {
844 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
848 void SSLContext::markInitialized() {
849 std::lock_guard<std::mutex> g(initMutex());
853 void SSLContext::initializeOpenSSL() {
854 std::lock_guard<std::mutex> g(initMutex());
855 initializeOpenSSLLocked();
858 void SSLContext::initializeOpenSSLLocked() {
863 SSL_load_error_strings();
864 ERR_load_crypto_strings();
866 locks().reset(new SSLLock[size_t(CRYPTO_num_locks())]);
867 for (auto it: lockTypes()) {
868 locks()[size_t(it.first)].lockType = it.second;
870 CRYPTO_set_id_callback(callbackThreadID);
871 CRYPTO_set_locking_callback(callbackLocking);
873 CRYPTO_set_dynlock_create_callback(dyn_create);
874 CRYPTO_set_dynlock_lock_callback(dyn_lock);
875 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
877 #ifdef OPENSSL_NPN_NEGOTIATED
878 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
879 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
884 void SSLContext::cleanupOpenSSL() {
885 std::lock_guard<std::mutex> g(initMutex());
886 cleanupOpenSSLLocked();
889 void SSLContext::cleanupOpenSSLLocked() {
894 CRYPTO_set_id_callback(nullptr);
895 CRYPTO_set_locking_callback(nullptr);
896 CRYPTO_set_dynlock_create_callback(nullptr);
897 CRYPTO_set_dynlock_lock_callback(nullptr);
898 CRYPTO_set_dynlock_destroy_callback(nullptr);
899 CRYPTO_cleanup_all_ex_data();
904 initialized_ = false;
907 void SSLContext::setOptions(long options) {
908 long newOpt = SSL_CTX_set_options(ctx_, options);
909 if ((newOpt & options) != options) {
910 throw std::runtime_error("SSL_CTX_set_options failed");
914 std::string SSLContext::getErrors(int errnoCopy) {
916 unsigned long errorCode;
920 while ((errorCode = ERR_get_error()) != 0) {
921 if (!errors.empty()) {
924 const char* reason = ERR_reason_error_string(errorCode);
925 if (reason == nullptr) {
926 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
931 if (errors.empty()) {
932 errors = "error code: " + folly::to<std::string>(errnoCopy);
938 operator<<(std::ostream& os, const PasswordCollector& collector) {
939 os << collector.describe();