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/SpinLock.h>
24 // ---------------------------------------------------------------------
25 // SSLContext implementation
26 // ---------------------------------------------------------------------
28 struct CRYPTO_dynlock_value {
34 // For OpenSSL portability API
35 using namespace folly::ssl;
37 bool SSLContext::initialized_ = false;
41 std::mutex& initMutex() {
46 } // anonymous namespace
48 #ifdef OPENSSL_NPN_NEGOTIATED
49 int SSLContext::sNextProtocolsExDataIndex_ = -1;
52 // SSLContext implementation
53 SSLContext::SSLContext(SSLVersion version) {
55 std::lock_guard<std::mutex> g(initMutex());
56 initializeOpenSSLLocked();
59 ctx_ = SSL_CTX_new(SSLv23_method());
60 if (ctx_ == nullptr) {
61 throw std::runtime_error("SSL_CTX_new: " + getErrors());
67 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
70 opt = SSL_OP_NO_SSLv2;
76 int newOpt = SSL_CTX_set_options(ctx_, opt);
77 DCHECK((newOpt & opt) == opt);
79 SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
81 checkPeerName_ = false;
83 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION);
85 #if FOLLY_OPENSSL_HAS_SNI
86 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
87 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
91 SSLContext::~SSLContext() {
92 if (ctx_ != nullptr) {
97 #ifdef OPENSSL_NPN_NEGOTIATED
98 deleteNextProtocolsStrings();
102 void SSLContext::ciphers(const std::string& ciphers) {
103 providedCiphersString_ = ciphers;
104 setCiphersOrThrow(ciphers);
107 void SSLContext::setCipherList(const std::vector<std::string>& ciphers) {
108 if (ciphers.size() == 0) {
111 std::string opensslCipherList;
112 join(":", ciphers, opensslCipherList);
113 setCiphersOrThrow(opensslCipherList);
116 void SSLContext::setSignatureAlgorithms(
117 const std::vector<std::string>& sigalgs) {
118 if (sigalgs.size() == 0) {
121 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
122 std::string opensslSigAlgsList;
123 join(":", sigalgs, opensslSigAlgsList);
124 int rc = SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str());
126 throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
131 void SSLContext::setClientECCurvesList(
132 const std::vector<std::string>& ecCurves) {
133 if (ecCurves.size() == 0) {
136 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
137 std::string ecCurvesList;
138 join(":", ecCurves, ecCurvesList);
139 int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
141 throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
146 void SSLContext::setServerECCurve(const std::string& curveName) {
147 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL && !defined(OPENSSL_NO_ECDH)
148 EC_KEY* ecdh = nullptr;
152 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
153 * from RFC 4492 section 5.1.1, or explicitly described curves over
154 * binary fields. OpenSSL only supports the "named curves", which provide
155 * maximum interoperability.
158 nid = OBJ_sn2nid(curveName.c_str());
160 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
162 ecdh = EC_KEY_new_by_curve_name(nid);
163 if (ecdh == nullptr) {
164 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
167 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
170 throw std::runtime_error("Elliptic curve encryption not allowed");
174 void SSLContext::setX509VerifyParam(
175 const ssl::X509VerifyParam& x509VerifyParam) {
176 if (!x509VerifyParam) {
179 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
180 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
184 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
185 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
187 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
191 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
193 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
194 verifyPeer_ = verifyPeer;
197 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
199 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
200 int mode = SSL_VERIFY_NONE;
202 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
205 case SSLVerifyPeerEnum::VERIFY:
206 mode = SSL_VERIFY_PEER;
209 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
210 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
213 case SSLVerifyPeerEnum::NO_VERIFY:
214 mode = SSL_VERIFY_NONE;
223 int SSLContext::getVerificationMode() {
224 return getVerificationMode(verifyPeer_);
227 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
228 const std::string& peerName) {
231 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
232 checkPeerName_ = checkPeerName;
233 peerFixedName_ = peerName;
235 mode = SSL_VERIFY_NONE;
236 checkPeerName_ = false; // can't check name without cert!
237 peerFixedName_.clear();
239 SSL_CTX_set_verify(ctx_, mode, nullptr);
242 void SSLContext::loadCertificate(const char* path, const char* format) {
243 if (path == nullptr || format == nullptr) {
244 throw std::invalid_argument(
245 "loadCertificateChain: either <path> or <format> is nullptr");
247 if (strcmp(format, "PEM") == 0) {
248 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
249 int errnoCopy = errno;
250 std::string reason("SSL_CTX_use_certificate_chain_file: ");
253 reason.append(getErrors(errnoCopy));
254 throw std::runtime_error(reason);
257 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
261 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
262 if (cert.data() == nullptr) {
263 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
266 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
267 if (bio == nullptr) {
268 throw std::runtime_error("BIO_new: " + getErrors());
271 int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
272 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
273 throw std::runtime_error("BIO_write: " + getErrors());
276 ssl::X509UniquePtr x509(
277 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
278 if (x509 == nullptr) {
279 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
282 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
283 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
287 void SSLContext::loadPrivateKey(const char* path, const char* format) {
288 if (path == nullptr || format == nullptr) {
289 throw std::invalid_argument(
290 "loadPrivateKey: either <path> or <format> is nullptr");
292 if (strcmp(format, "PEM") == 0) {
293 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
294 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
297 throw std::runtime_error("Unsupported private key format: " + std::string(format));
301 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
302 if (pkey.data() == nullptr) {
303 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
306 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
307 if (bio == nullptr) {
308 throw std::runtime_error("BIO_new: " + getErrors());
311 int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
312 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
313 throw std::runtime_error("BIO_write: " + getErrors());
316 ssl::EvpPkeyUniquePtr key(
317 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
318 if (key == nullptr) {
319 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
322 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
323 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
327 void SSLContext::loadTrustedCertificates(const char* path) {
328 if (path == nullptr) {
329 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
331 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
332 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
337 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
338 SSL_CTX_set_cert_store(ctx_, store);
341 void SSLContext::loadClientCAList(const char* path) {
342 auto clientCAs = SSL_load_client_CA_file(path);
343 if (clientCAs == nullptr) {
344 LOG(ERROR) << "Unable to load ca file: " << path;
347 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
350 void SSLContext::randomize() {
354 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
355 if (collector == nullptr) {
356 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
359 collector_ = collector;
360 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
361 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
364 #if FOLLY_OPENSSL_HAS_SNI
366 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
370 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
371 clientHelloCbs_.push_back(cb);
374 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
375 SSLContext* context = (SSLContext*)data;
377 if (context == nullptr) {
378 return SSL_TLSEXT_ERR_NOACK;
381 for (auto& cb : context->clientHelloCbs_) {
382 // Generic callbacks to happen after we receive the Client Hello.
383 // For example, we use one to switch which cipher we use depending
384 // on the user's TLS version. Because the primary purpose of
385 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
386 // are side-uses, we ignore any possible failures other than just logging
391 if (!context->serverNameCb_) {
392 return SSL_TLSEXT_ERR_NOACK;
395 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
397 case SERVER_NAME_FOUND:
398 return SSL_TLSEXT_ERR_OK;
399 case SERVER_NAME_NOT_FOUND:
400 return SSL_TLSEXT_ERR_NOACK;
401 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
402 *al = TLS1_AD_UNRECOGNIZED_NAME;
403 return SSL_TLSEXT_ERR_ALERT_FATAL;
408 return SSL_TLSEXT_ERR_NOACK;
411 void SSLContext::switchCiphersIfTLS11(
413 const std::string& tls11CipherString,
414 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist) {
415 CHECK(!(tls11CipherString.empty() && tls11AltCipherlist.empty()))
416 << "Shouldn't call if empty ciphers / alt ciphers";
418 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
419 // We only do this for TLS v 1.1 and later
423 const std::string* ciphers = &tls11CipherString;
424 if (!tls11AltCipherlist.empty()) {
425 if (!cipherListPicker_) {
426 std::vector<int> weights;
428 tls11AltCipherlist.begin(),
429 tls11AltCipherlist.end(),
430 [&](const std::pair<std::string, int>& e) {
431 weights.push_back(e.second);
433 cipherListPicker_.reset(
434 new std::discrete_distribution<int>(weights.begin(), weights.end()));
436 auto rng = ThreadLocalPRNG();
437 auto index = (*cipherListPicker_)(rng);
438 if ((size_t)index >= tls11AltCipherlist.size()) {
439 LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
440 << ", but tls11AltCipherlist is of length "
441 << tls11AltCipherlist.size();
443 ciphers = &tls11AltCipherlist[size_t(index)].first;
447 // Prefer AES for TLS versions 1.1 and later since these are not
448 // vulnerable to BEAST attacks on AES. Note that we're setting the
449 // cipher list on the SSL object, not the SSL_CTX object, so it will
450 // only last for this request.
451 int rc = SSL_set_cipher_list(ssl, ciphers->c_str());
452 if ((rc == 0) || ERR_peek_error() != 0) {
453 // This shouldn't happen since we checked for this when proxygen
455 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
456 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
459 #endif // FOLLY_OPENSSL_HAS_SNI
461 #if FOLLY_OPENSSL_HAS_ALPN
462 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
463 const unsigned char** out,
464 unsigned char* outlen,
465 const unsigned char* in,
468 SSLContext* context = (SSLContext*)data;
470 if (context->advertisedNextProtocols_.empty()) {
474 auto i = context->pickNextProtocols();
475 const auto& item = context->advertisedNextProtocols_[i];
476 if (SSL_select_next_proto((unsigned char**)out,
481 inlen) != OPENSSL_NPN_NEGOTIATED) {
482 return SSL_TLSEXT_ERR_NOACK;
485 return SSL_TLSEXT_ERR_OK;
487 #endif // FOLLY_OPENSSL_HAS_ALPN
489 #ifdef OPENSSL_NPN_NEGOTIATED
491 bool SSLContext::setAdvertisedNextProtocols(
492 const std::list<std::string>& protocols, NextProtocolType protocolType) {
493 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
496 bool SSLContext::setRandomizedAdvertisedNextProtocols(
497 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
498 unsetNextProtocols();
499 if (items.size() == 0) {
502 int total_weight = 0;
503 for (const auto &item : items) {
504 if (item.protocols.size() == 0) {
507 AdvertisedNextProtocolsItem advertised_item;
508 advertised_item.length = 0;
509 for (const auto& proto : item.protocols) {
510 ++advertised_item.length;
511 auto protoLength = proto.length();
512 if (protoLength >= 256) {
513 deleteNextProtocolsStrings();
516 advertised_item.length += unsigned(protoLength);
518 advertised_item.protocols = new unsigned char[advertised_item.length];
519 if (!advertised_item.protocols) {
520 throw std::runtime_error("alloc failure");
522 unsigned char* dst = advertised_item.protocols;
523 for (auto& proto : item.protocols) {
524 uint8_t protoLength = uint8_t(proto.length());
525 *dst++ = (unsigned char)protoLength;
526 memcpy(dst, proto.data(), protoLength);
529 total_weight += item.weight;
530 advertisedNextProtocols_.push_back(advertised_item);
531 advertisedNextProtocolWeights_.push_back(item.weight);
533 if (total_weight == 0) {
534 deleteNextProtocolsStrings();
537 nextProtocolDistribution_ =
538 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
539 advertisedNextProtocolWeights_.end());
540 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
541 SSL_CTX_set_next_protos_advertised_cb(
542 ctx_, advertisedNextProtocolCallback, this);
543 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
545 #if FOLLY_OPENSSL_HAS_ALPN
546 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
547 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
548 // Client cannot really use randomized alpn
549 SSL_CTX_set_alpn_protos(ctx_,
550 advertisedNextProtocols_[0].protocols,
551 advertisedNextProtocols_[0].length);
557 void SSLContext::deleteNextProtocolsStrings() {
558 for (auto protocols : advertisedNextProtocols_) {
559 delete[] protocols.protocols;
561 advertisedNextProtocols_.clear();
562 advertisedNextProtocolWeights_.clear();
565 void SSLContext::unsetNextProtocols() {
566 deleteNextProtocolsStrings();
567 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
568 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
569 #if FOLLY_OPENSSL_HAS_ALPN
570 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
571 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
575 size_t SSLContext::pickNextProtocols() {
576 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
577 auto rng = ThreadLocalPRNG();
578 return size_t(nextProtocolDistribution_(rng));
581 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
582 const unsigned char** out, unsigned int* outlen, void* data) {
583 SSLContext* context = (SSLContext*)data;
584 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
587 } else if (context->advertisedNextProtocols_.size() == 1) {
588 *out = context->advertisedNextProtocols_[0].protocols;
589 *outlen = context->advertisedNextProtocols_[0].length;
591 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
592 sNextProtocolsExDataIndex_));
593 if (selected_index) {
595 *out = context->advertisedNextProtocols_[selected_index].protocols;
596 *outlen = context->advertisedNextProtocols_[selected_index].length;
598 auto i = context->pickNextProtocols();
599 uintptr_t selected = i + 1;
600 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
601 *out = context->advertisedNextProtocols_[i].protocols;
602 *outlen = context->advertisedNextProtocols_[i].length;
605 return SSL_TLSEXT_ERR_OK;
608 int SSLContext::selectNextProtocolCallback(SSL* ssl,
610 unsigned char* outlen,
611 const unsigned char* server,
612 unsigned int server_len,
614 (void)ssl; // Make -Wunused-parameters happy
615 SSLContext* ctx = (SSLContext*)data;
616 if (ctx->advertisedNextProtocols_.size() > 1) {
617 VLOG(3) << "SSLContext::selectNextProcolCallback() "
618 << "client should be deterministic in selecting protocols.";
621 unsigned char* client = nullptr;
622 unsigned int client_len = 0;
623 bool filtered = false;
624 auto cpf = ctx->getClientProtocolFilterCallback();
626 filtered = (*cpf)(&client, &client_len, server, server_len);
630 if (ctx->advertisedNextProtocols_.empty()) {
631 client = (unsigned char *) "";
634 client = ctx->advertisedNextProtocols_[0].protocols;
635 client_len = ctx->advertisedNextProtocols_[0].length;
639 int retval = SSL_select_next_proto(out, outlen, server, server_len,
641 if (retval != OPENSSL_NPN_NEGOTIATED) {
642 VLOG(3) << "SSLContext::selectNextProcolCallback() "
643 << "unable to pick a next protocol.";
645 return SSL_TLSEXT_ERR_OK;
647 #endif // OPENSSL_NPN_NEGOTIATED
649 SSL* SSLContext::createSSL() const {
650 SSL* ssl = SSL_new(ctx_);
651 if (ssl == nullptr) {
652 throw std::runtime_error("SSL_new: " + getErrors());
657 void SSLContext::setSessionCacheContext(const std::string& context) {
658 SSL_CTX_set_session_id_context(
660 reinterpret_cast<const unsigned char*>(context.data()),
661 std::min<unsigned int>(
662 static_cast<unsigned int>(context.length()),
663 SSL_MAX_SSL_SESSION_ID_LENGTH));
667 * Match a name with a pattern. The pattern may include wildcard. A single
668 * wildcard "*" can match up to one component in the domain name.
670 * @param host Host name, typically the name of the remote host
671 * @param pattern Name retrieved from certificate
672 * @param size Size of "pattern"
673 * @return True, if "host" matches "pattern". False otherwise.
675 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
678 while (i < size && host[j] != '\0') {
679 if (toupper(pattern[i]) == toupper(host[j])) {
684 if (pattern[i] == '*') {
685 while (host[j] != '.' && host[j] != '\0') {
693 if (i == size && host[j] == '\0') {
699 int SSLContext::passwordCallback(char* password,
703 SSLContext* context = (SSLContext*)data;
704 if (context == nullptr || context->passwordCollector() == nullptr) {
707 std::string userPassword;
708 // call user defined password collector to get password
709 context->passwordCollector()->getPassword(userPassword, size);
710 auto length = int(userPassword.size());
714 strncpy(password, userPassword.c_str(), size_t(length));
720 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
721 lockType(inLockType) {
725 if (lockType == SSLContext::LOCK_MUTEX) {
727 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
730 // lockType == LOCK_NONE, no-op
734 if (lockType == SSLContext::LOCK_MUTEX) {
736 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
739 // lockType == LOCK_NONE, no-op
742 SSLContext::SSLLockType lockType;
743 folly::SpinLock spinLock{};
747 // Statics are unsafe in environments that call exit().
748 // If one thread calls exit() while another thread is
749 // references a member of SSLContext, bad things can happen.
750 // SSLContext runs in such environments.
751 // Instead of declaring a static member we "new" the static
752 // member so that it won't be destructed on exit().
753 static std::unique_ptr<SSLLock[]>& locks() {
754 static auto locksInst = new std::unique_ptr<SSLLock[]>();
758 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
759 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
760 return *lockTypesInst;
763 static void callbackLocking(int mode, int n, const char*, int) {
764 if (mode & CRYPTO_LOCK) {
765 locks()[size_t(n)].lock();
767 locks()[size_t(n)].unlock();
771 static unsigned long callbackThreadID() {
772 return static_cast<unsigned long>(
774 pthread_mach_thread_np(pthread_self())
776 pthread_getw32threadid_np(pthread_self())
783 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
784 return new CRYPTO_dynlock_value;
787 static void dyn_lock(int mode,
788 struct CRYPTO_dynlock_value* lock,
790 if (lock != nullptr) {
791 if (mode & CRYPTO_LOCK) {
794 lock->mutex.unlock();
799 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
803 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
804 lockTypes() = inLockTypes;
807 bool SSLContext::isSSLLockDisabled(int lockId) {
808 const auto& sslLocks = lockTypes();
809 const auto it = sslLocks.find(lockId);
810 return it != sslLocks.end() &&
811 it->second == SSLContext::SSLLockType::LOCK_NONE;
814 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
815 void SSLContext::enableFalseStart() {
816 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
820 void SSLContext::markInitialized() {
821 std::lock_guard<std::mutex> g(initMutex());
825 void SSLContext::initializeOpenSSL() {
826 std::lock_guard<std::mutex> g(initMutex());
827 initializeOpenSSLLocked();
830 void SSLContext::initializeOpenSSLLocked() {
835 SSL_load_error_strings();
836 ERR_load_crypto_strings();
838 locks().reset(new SSLLock[size_t(CRYPTO_num_locks())]);
839 for (auto it: lockTypes()) {
840 locks()[size_t(it.first)].lockType = it.second;
842 CRYPTO_set_id_callback(callbackThreadID);
843 CRYPTO_set_locking_callback(callbackLocking);
845 CRYPTO_set_dynlock_create_callback(dyn_create);
846 CRYPTO_set_dynlock_lock_callback(dyn_lock);
847 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
849 #ifdef OPENSSL_NPN_NEGOTIATED
850 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
851 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
856 void SSLContext::cleanupOpenSSL() {
857 std::lock_guard<std::mutex> g(initMutex());
858 cleanupOpenSSLLocked();
861 void SSLContext::cleanupOpenSSLLocked() {
866 CRYPTO_set_id_callback(nullptr);
867 CRYPTO_set_locking_callback(nullptr);
868 CRYPTO_set_dynlock_create_callback(nullptr);
869 CRYPTO_set_dynlock_lock_callback(nullptr);
870 CRYPTO_set_dynlock_destroy_callback(nullptr);
871 CRYPTO_cleanup_all_ex_data();
876 initialized_ = false;
879 void SSLContext::setOptions(long options) {
880 long newOpt = SSL_CTX_set_options(ctx_, options);
881 if ((newOpt & options) != options) {
882 throw std::runtime_error("SSL_CTX_set_options failed");
886 std::string SSLContext::getErrors(int errnoCopy) {
888 unsigned long errorCode;
892 while ((errorCode = ERR_get_error()) != 0) {
893 if (!errors.empty()) {
896 const char* reason = ERR_reason_error_string(errorCode);
897 if (reason == nullptr) {
898 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
903 if (errors.empty()) {
904 errors = "error code: " + folly::to<std::string>(errnoCopy);
910 operator<<(std::ostream& os, const PasswordCollector& collector) {
911 os << collector.describe();