2 * Copyright 2016 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 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 OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
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 providedCiphersString_ = ciphers;
106 setCiphersOrThrow(ciphers);
109 void SSLContext::setCipherList(const std::vector<std::string>& ciphers) {
110 if (ciphers.size() == 0) {
113 std::string opensslCipherList;
114 join(":", ciphers, opensslCipherList);
115 setCiphersOrThrow(opensslCipherList);
118 void SSLContext::setSignatureAlgorithms(
119 const std::vector<std::string>& sigalgs) {
120 if (sigalgs.size() == 0) {
123 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
124 std::string opensslSigAlgsList;
125 join(":", sigalgs, opensslSigAlgsList);
126 int rc = SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str());
128 throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
133 void SSLContext::setClientECCurvesList(
134 const std::vector<std::string>& ecCurves) {
135 if (ecCurves.size() == 0) {
138 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
139 std::string ecCurvesList;
140 join(":", ecCurves, ecCurvesList);
141 int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
143 throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
148 void SSLContext::setServerECCurve(const std::string& curveName) {
149 bool validCall = false;
150 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
151 #ifndef OPENSSL_NO_ECDH
156 throw std::runtime_error("Elliptic curve encryption not allowed");
159 EC_KEY* ecdh = nullptr;
163 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
164 * from RFC 4492 section 5.1.1, or explicitly described curves over
165 * binary fields. OpenSSL only supports the "named curves", which provide
166 * maximum interoperability.
169 nid = OBJ_sn2nid(curveName.c_str());
171 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
174 ecdh = EC_KEY_new_by_curve_name(nid);
175 if (ecdh == nullptr) {
176 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
180 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
184 void SSLContext::setX509VerifyParam(
185 const ssl::X509VerifyParam& x509VerifyParam) {
186 if (!x509VerifyParam) {
189 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
190 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
194 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
195 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
197 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
201 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
203 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
204 verifyPeer_ = verifyPeer;
207 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
209 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
210 int mode = SSL_VERIFY_NONE;
212 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
215 case SSLVerifyPeerEnum::VERIFY:
216 mode = SSL_VERIFY_PEER;
219 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
220 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
223 case SSLVerifyPeerEnum::NO_VERIFY:
224 mode = SSL_VERIFY_NONE;
233 int SSLContext::getVerificationMode() {
234 return getVerificationMode(verifyPeer_);
237 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
238 const std::string& peerName) {
241 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
242 checkPeerName_ = checkPeerName;
243 peerFixedName_ = peerName;
245 mode = SSL_VERIFY_NONE;
246 checkPeerName_ = false; // can't check name without cert!
247 peerFixedName_.clear();
249 SSL_CTX_set_verify(ctx_, mode, nullptr);
252 void SSLContext::loadCertificate(const char* path, const char* format) {
253 if (path == nullptr || format == nullptr) {
254 throw std::invalid_argument(
255 "loadCertificateChain: either <path> or <format> is nullptr");
257 if (strcmp(format, "PEM") == 0) {
258 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
259 int errnoCopy = errno;
260 std::string reason("SSL_CTX_use_certificate_chain_file: ");
263 reason.append(getErrors(errnoCopy));
264 throw std::runtime_error(reason);
267 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
271 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
272 if (cert.data() == nullptr) {
273 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
276 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
277 if (bio == nullptr) {
278 throw std::runtime_error("BIO_new: " + getErrors());
281 int written = BIO_write(bio.get(), cert.data(), cert.size());
282 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
283 throw std::runtime_error("BIO_write: " + getErrors());
286 ssl::X509UniquePtr x509(
287 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
288 if (x509 == nullptr) {
289 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
292 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
293 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
297 void SSLContext::loadPrivateKey(const char* path, const char* format) {
298 if (path == nullptr || format == nullptr) {
299 throw std::invalid_argument(
300 "loadPrivateKey: either <path> or <format> is nullptr");
302 if (strcmp(format, "PEM") == 0) {
303 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
304 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
307 throw std::runtime_error("Unsupported private key format: " + std::string(format));
311 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
312 if (pkey.data() == nullptr) {
313 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
316 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
317 if (bio == nullptr) {
318 throw std::runtime_error("BIO_new: " + getErrors());
321 int written = BIO_write(bio.get(), pkey.data(), pkey.size());
322 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
323 throw std::runtime_error("BIO_write: " + getErrors());
326 ssl::EvpPkeyUniquePtr key(
327 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
328 if (key == nullptr) {
329 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
332 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
333 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
337 void SSLContext::loadTrustedCertificates(const char* path) {
338 if (path == nullptr) {
339 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
341 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
342 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
346 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
347 SSL_CTX_set_cert_store(ctx_, store);
350 void SSLContext::loadClientCAList(const char* path) {
351 auto clientCAs = SSL_load_client_CA_file(path);
352 if (clientCAs == nullptr) {
353 LOG(ERROR) << "Unable to load ca file: " << path;
356 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
359 void SSLContext::randomize() {
363 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
364 if (collector == nullptr) {
365 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
368 collector_ = collector;
369 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
370 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
373 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
375 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
379 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
380 clientHelloCbs_.push_back(cb);
383 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
384 SSLContext* context = (SSLContext*)data;
386 if (context == nullptr) {
387 return SSL_TLSEXT_ERR_NOACK;
390 for (auto& cb : context->clientHelloCbs_) {
391 // Generic callbacks to happen after we receive the Client Hello.
392 // For example, we use one to switch which cipher we use depending
393 // on the user's TLS version. Because the primary purpose of
394 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
395 // are side-uses, we ignore any possible failures other than just logging
400 if (!context->serverNameCb_) {
401 return SSL_TLSEXT_ERR_NOACK;
404 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
406 case SERVER_NAME_FOUND:
407 return SSL_TLSEXT_ERR_OK;
408 case SERVER_NAME_NOT_FOUND:
409 return SSL_TLSEXT_ERR_NOACK;
410 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
411 *al = TLS1_AD_UNRECOGNIZED_NAME;
412 return SSL_TLSEXT_ERR_ALERT_FATAL;
417 return SSL_TLSEXT_ERR_NOACK;
420 void SSLContext::switchCiphersIfTLS11(
422 const std::string& tls11CipherString,
423 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist) {
424 CHECK(!(tls11CipherString.empty() && tls11AltCipherlist.empty()))
425 << "Shouldn't call if empty ciphers / alt ciphers";
427 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
428 // We only do this for TLS v 1.1 and later
432 const std::string* ciphers = &tls11CipherString;
433 if (!tls11AltCipherlist.empty()) {
434 if (!cipherListPicker_) {
435 std::vector<int> weights;
437 tls11AltCipherlist.begin(),
438 tls11AltCipherlist.end(),
439 [&](const std::pair<std::string, int>& e) {
440 weights.push_back(e.second);
442 cipherListPicker_.reset(
443 new std::discrete_distribution<int>(weights.begin(), weights.end()));
445 auto rng = ThreadLocalPRNG();
446 auto index = (*cipherListPicker_)(rng);
447 if ((size_t)index >= tls11AltCipherlist.size()) {
448 LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
449 << ", but tls11AltCipherlist is of length "
450 << tls11AltCipherlist.size();
452 ciphers = &tls11AltCipherlist[index].first;
456 // Prefer AES for TLS versions 1.1 and later since these are not
457 // vulnerable to BEAST attacks on AES. Note that we're setting the
458 // cipher list on the SSL object, not the SSL_CTX object, so it will
459 // only last for this request.
460 int rc = SSL_set_cipher_list(ssl, ciphers->c_str());
461 if ((rc == 0) || ERR_peek_error() != 0) {
462 // This shouldn't happen since we checked for this when proxygen
464 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
465 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
470 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
471 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
472 const unsigned char** out,
473 unsigned char* outlen,
474 const unsigned char* in,
477 SSLContext* context = (SSLContext*)data;
479 if (context->advertisedNextProtocols_.empty()) {
483 auto i = context->pickNextProtocols();
484 const auto& item = context->advertisedNextProtocols_[i];
485 if (SSL_select_next_proto((unsigned char**)out,
490 inlen) != OPENSSL_NPN_NEGOTIATED) {
491 return SSL_TLSEXT_ERR_NOACK;
494 return SSL_TLSEXT_ERR_OK;
498 #ifdef OPENSSL_NPN_NEGOTIATED
500 bool SSLContext::setAdvertisedNextProtocols(
501 const std::list<std::string>& protocols, NextProtocolType protocolType) {
502 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
505 bool SSLContext::setRandomizedAdvertisedNextProtocols(
506 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
507 unsetNextProtocols();
508 if (items.size() == 0) {
511 int total_weight = 0;
512 for (const auto &item : items) {
513 if (item.protocols.size() == 0) {
516 AdvertisedNextProtocolsItem advertised_item;
517 advertised_item.length = 0;
518 for (const auto& proto : item.protocols) {
519 ++advertised_item.length;
520 unsigned protoLength = proto.length();
521 if (protoLength >= 256) {
522 deleteNextProtocolsStrings();
525 advertised_item.length += protoLength;
527 advertised_item.protocols = new unsigned char[advertised_item.length];
528 if (!advertised_item.protocols) {
529 throw std::runtime_error("alloc failure");
531 unsigned char* dst = advertised_item.protocols;
532 for (auto& proto : item.protocols) {
533 unsigned protoLength = proto.length();
534 *dst++ = (unsigned char)protoLength;
535 memcpy(dst, proto.data(), protoLength);
538 total_weight += item.weight;
539 advertisedNextProtocols_.push_back(advertised_item);
540 advertisedNextProtocolWeights_.push_back(item.weight);
542 if (total_weight == 0) {
543 deleteNextProtocolsStrings();
546 nextProtocolDistribution_ =
547 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
548 advertisedNextProtocolWeights_.end());
549 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
550 SSL_CTX_set_next_protos_advertised_cb(
551 ctx_, advertisedNextProtocolCallback, this);
552 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
554 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
555 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
556 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
557 // Client cannot really use randomized alpn
558 SSL_CTX_set_alpn_protos(ctx_,
559 advertisedNextProtocols_[0].protocols,
560 advertisedNextProtocols_[0].length);
566 void SSLContext::deleteNextProtocolsStrings() {
567 for (auto protocols : advertisedNextProtocols_) {
568 delete[] protocols.protocols;
570 advertisedNextProtocols_.clear();
571 advertisedNextProtocolWeights_.clear();
574 void SSLContext::unsetNextProtocols() {
575 deleteNextProtocolsStrings();
576 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
577 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
578 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
579 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
580 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
584 size_t SSLContext::pickNextProtocols() {
585 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
586 auto rng = ThreadLocalPRNG();
587 return nextProtocolDistribution_(rng);
590 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
591 const unsigned char** out, unsigned int* outlen, void* data) {
592 SSLContext* context = (SSLContext*)data;
593 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
596 } else if (context->advertisedNextProtocols_.size() == 1) {
597 *out = context->advertisedNextProtocols_[0].protocols;
598 *outlen = context->advertisedNextProtocols_[0].length;
600 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
601 sNextProtocolsExDataIndex_));
602 if (selected_index) {
604 *out = context->advertisedNextProtocols_[selected_index].protocols;
605 *outlen = context->advertisedNextProtocols_[selected_index].length;
607 auto i = context->pickNextProtocols();
608 uintptr_t selected = i + 1;
609 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
610 *out = context->advertisedNextProtocols_[i].protocols;
611 *outlen = context->advertisedNextProtocols_[i].length;
614 return SSL_TLSEXT_ERR_OK;
617 int SSLContext::selectNextProtocolCallback(SSL* ssl,
619 unsigned char* outlen,
620 const unsigned char* server,
621 unsigned int server_len,
623 (void)ssl; // Make -Wunused-parameters happy
624 SSLContext* ctx = (SSLContext*)data;
625 if (ctx->advertisedNextProtocols_.size() > 1) {
626 VLOG(3) << "SSLContext::selectNextProcolCallback() "
627 << "client should be deterministic in selecting protocols.";
630 unsigned char* client = nullptr;
631 unsigned int client_len = 0;
632 bool filtered = false;
633 auto cpf = ctx->getClientProtocolFilterCallback();
635 filtered = (*cpf)(&client, &client_len, server, server_len);
639 if (ctx->advertisedNextProtocols_.empty()) {
640 client = (unsigned char *) "";
643 client = ctx->advertisedNextProtocols_[0].protocols;
644 client_len = ctx->advertisedNextProtocols_[0].length;
648 int retval = SSL_select_next_proto(out, outlen, server, server_len,
650 if (retval != OPENSSL_NPN_NEGOTIATED) {
651 VLOG(3) << "SSLContext::selectNextProcolCallback() "
652 << "unable to pick a next protocol.";
654 return SSL_TLSEXT_ERR_OK;
656 #endif // OPENSSL_NPN_NEGOTIATED
658 SSL* SSLContext::createSSL() const {
659 SSL* ssl = SSL_new(ctx_);
660 if (ssl == nullptr) {
661 throw std::runtime_error("SSL_new: " + getErrors());
666 void SSLContext::setSessionCacheContext(const std::string& context) {
667 SSL_CTX_set_session_id_context(
669 reinterpret_cast<const unsigned char*>(context.data()),
671 static_cast<int>(context.length()), SSL_MAX_SSL_SESSION_ID_LENGTH));
675 * Match a name with a pattern. The pattern may include wildcard. A single
676 * wildcard "*" can match up to one component in the domain name.
678 * @param host Host name, typically the name of the remote host
679 * @param pattern Name retrieved from certificate
680 * @param size Size of "pattern"
681 * @return True, if "host" matches "pattern". False otherwise.
683 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
686 while (i < size && host[j] != '\0') {
687 if (toupper(pattern[i]) == toupper(host[j])) {
692 if (pattern[i] == '*') {
693 while (host[j] != '.' && host[j] != '\0') {
701 if (i == size && host[j] == '\0') {
707 int SSLContext::passwordCallback(char* password,
711 SSLContext* context = (SSLContext*)data;
712 if (context == nullptr || context->passwordCollector() == nullptr) {
715 std::string userPassword;
716 // call user defined password collector to get password
717 context->passwordCollector()->getPassword(userPassword, size);
718 int length = userPassword.size();
722 strncpy(password, userPassword.c_str(), length);
728 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
729 lockType(inLockType) {
733 if (lockType == SSLContext::LOCK_MUTEX) {
735 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
738 // lockType == LOCK_NONE, no-op
742 if (lockType == SSLContext::LOCK_MUTEX) {
744 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
747 // lockType == LOCK_NONE, no-op
750 SSLContext::SSLLockType lockType;
751 folly::SpinLock spinLock{};
755 // Statics are unsafe in environments that call exit().
756 // If one thread calls exit() while another thread is
757 // references a member of SSLContext, bad things can happen.
758 // SSLContext runs in such environments.
759 // Instead of declaring a static member we "new" the static
760 // member so that it won't be destructed on exit().
761 static std::unique_ptr<SSLLock[]>& locks() {
762 static auto locksInst = new std::unique_ptr<SSLLock[]>();
766 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
767 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
768 return *lockTypesInst;
771 static void callbackLocking(int mode, int n, const char*, int) {
772 if (mode & CRYPTO_LOCK) {
779 static unsigned long callbackThreadID() {
780 return static_cast<unsigned long>(
782 pthread_mach_thread_np(pthread_self())
784 pthread_getw32threadid_np(pthread_self())
791 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
792 return new CRYPTO_dynlock_value;
795 static void dyn_lock(int mode,
796 struct CRYPTO_dynlock_value* lock,
798 if (lock != nullptr) {
799 if (mode & CRYPTO_LOCK) {
802 lock->mutex.unlock();
807 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
811 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
812 lockTypes() = inLockTypes;
815 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
816 void SSLContext::enableFalseStart() {
817 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
821 void SSLContext::markInitialized() {
822 std::lock_guard<std::mutex> g(initMutex());
826 void SSLContext::initializeOpenSSL() {
827 std::lock_guard<std::mutex> g(initMutex());
828 initializeOpenSSLLocked();
831 void SSLContext::initializeOpenSSLLocked() {
836 SSL_load_error_strings();
837 ERR_load_crypto_strings();
839 locks().reset(new SSLLock[::CRYPTO_num_locks()]);
840 for (auto it: lockTypes()) {
841 locks()[it.first].lockType = it.second;
843 CRYPTO_set_id_callback(callbackThreadID);
844 CRYPTO_set_locking_callback(callbackLocking);
846 CRYPTO_set_dynlock_create_callback(dyn_create);
847 CRYPTO_set_dynlock_lock_callback(dyn_lock);
848 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
850 #ifdef OPENSSL_NPN_NEGOTIATED
851 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
852 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
857 void SSLContext::cleanupOpenSSL() {
858 std::lock_guard<std::mutex> g(initMutex());
859 cleanupOpenSSLLocked();
862 void SSLContext::cleanupOpenSSLLocked() {
867 CRYPTO_set_id_callback(nullptr);
868 CRYPTO_set_locking_callback(nullptr);
869 CRYPTO_set_dynlock_create_callback(nullptr);
870 CRYPTO_set_dynlock_lock_callback(nullptr);
871 CRYPTO_set_dynlock_destroy_callback(nullptr);
872 CRYPTO_cleanup_all_ex_data();
877 initialized_ = false;
880 void SSLContext::setOptions(long options) {
881 long newOpt = SSL_CTX_set_options(ctx_, options);
882 if ((newOpt & options) != options) {
883 throw std::runtime_error("SSL_CTX_set_options failed");
887 std::string SSLContext::getErrors(int errnoCopy) {
889 unsigned long errorCode;
893 while ((errorCode = ERR_get_error()) != 0) {
894 if (!errors.empty()) {
897 const char* reason = ERR_reason_error_string(errorCode);
898 if (reason == nullptr) {
899 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
904 if (errors.empty()) {
905 errors = "error code: " + folly::to<std::string>(errnoCopy);
911 operator<<(std::ostream& os, const PasswordCollector& collector) {
912 os << collector.describe();