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 bool validCall = false;
153 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL
154 #ifndef OPENSSL_NO_ECDH
159 throw std::runtime_error("Elliptic curve encryption not allowed");
162 EC_KEY* ecdh = nullptr;
166 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
167 * from RFC 4492 section 5.1.1, or explicitly described curves over
168 * binary fields. OpenSSL only supports the "named curves", which provide
169 * maximum interoperability.
172 nid = OBJ_sn2nid(curveName.c_str());
174 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
176 ecdh = EC_KEY_new_by_curve_name(nid);
177 if (ecdh == nullptr) {
178 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
181 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
185 void SSLContext::setX509VerifyParam(
186 const ssl::X509VerifyParam& x509VerifyParam) {
187 if (!x509VerifyParam) {
190 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
191 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
195 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
196 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
198 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
202 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
204 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
205 verifyPeer_ = verifyPeer;
208 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
210 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
211 int mode = SSL_VERIFY_NONE;
213 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
216 case SSLVerifyPeerEnum::VERIFY:
217 mode = SSL_VERIFY_PEER;
220 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
221 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
224 case SSLVerifyPeerEnum::NO_VERIFY:
225 mode = SSL_VERIFY_NONE;
234 int SSLContext::getVerificationMode() {
235 return getVerificationMode(verifyPeer_);
238 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
239 const std::string& peerName) {
242 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
243 checkPeerName_ = checkPeerName;
244 peerFixedName_ = peerName;
246 mode = SSL_VERIFY_NONE;
247 checkPeerName_ = false; // can't check name without cert!
248 peerFixedName_.clear();
250 SSL_CTX_set_verify(ctx_, mode, nullptr);
253 void SSLContext::loadCertificate(const char* path, const char* format) {
254 if (path == nullptr || format == nullptr) {
255 throw std::invalid_argument(
256 "loadCertificateChain: either <path> or <format> is nullptr");
258 if (strcmp(format, "PEM") == 0) {
259 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
260 int errnoCopy = errno;
261 std::string reason("SSL_CTX_use_certificate_chain_file: ");
264 reason.append(getErrors(errnoCopy));
265 throw std::runtime_error(reason);
268 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
272 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
273 if (cert.data() == nullptr) {
274 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
277 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
278 if (bio == nullptr) {
279 throw std::runtime_error("BIO_new: " + getErrors());
282 int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
283 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
284 throw std::runtime_error("BIO_write: " + getErrors());
287 ssl::X509UniquePtr x509(
288 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
289 if (x509 == nullptr) {
290 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
293 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
294 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
298 void SSLContext::loadPrivateKey(const char* path, const char* format) {
299 if (path == nullptr || format == nullptr) {
300 throw std::invalid_argument(
301 "loadPrivateKey: either <path> or <format> is nullptr");
303 if (strcmp(format, "PEM") == 0) {
304 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
305 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
308 throw std::runtime_error("Unsupported private key format: " + std::string(format));
312 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
313 if (pkey.data() == nullptr) {
314 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
317 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
318 if (bio == nullptr) {
319 throw std::runtime_error("BIO_new: " + getErrors());
322 int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
323 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
324 throw std::runtime_error("BIO_write: " + getErrors());
327 ssl::EvpPkeyUniquePtr key(
328 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
329 if (key == nullptr) {
330 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
333 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
334 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
338 void SSLContext::loadTrustedCertificates(const char* path) {
339 if (path == nullptr) {
340 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
342 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
343 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
348 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
349 SSL_CTX_set_cert_store(ctx_, store);
352 void SSLContext::loadClientCAList(const char* path) {
353 auto clientCAs = SSL_load_client_CA_file(path);
354 if (clientCAs == nullptr) {
355 LOG(ERROR) << "Unable to load ca file: " << path;
358 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
361 void SSLContext::randomize() {
365 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
366 if (collector == nullptr) {
367 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
370 collector_ = collector;
371 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
372 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
375 #if FOLLY_OPENSSL_HAS_SNI
377 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
381 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
382 clientHelloCbs_.push_back(cb);
385 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
386 SSLContext* context = (SSLContext*)data;
388 if (context == nullptr) {
389 return SSL_TLSEXT_ERR_NOACK;
392 for (auto& cb : context->clientHelloCbs_) {
393 // Generic callbacks to happen after we receive the Client Hello.
394 // For example, we use one to switch which cipher we use depending
395 // on the user's TLS version. Because the primary purpose of
396 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
397 // are side-uses, we ignore any possible failures other than just logging
402 if (!context->serverNameCb_) {
403 return SSL_TLSEXT_ERR_NOACK;
406 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
408 case SERVER_NAME_FOUND:
409 return SSL_TLSEXT_ERR_OK;
410 case SERVER_NAME_NOT_FOUND:
411 return SSL_TLSEXT_ERR_NOACK;
412 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
413 *al = TLS1_AD_UNRECOGNIZED_NAME;
414 return SSL_TLSEXT_ERR_ALERT_FATAL;
419 return SSL_TLSEXT_ERR_NOACK;
422 void SSLContext::switchCiphersIfTLS11(
424 const std::string& tls11CipherString,
425 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist) {
426 CHECK(!(tls11CipherString.empty() && tls11AltCipherlist.empty()))
427 << "Shouldn't call if empty ciphers / alt ciphers";
429 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
430 // We only do this for TLS v 1.1 and later
434 const std::string* ciphers = &tls11CipherString;
435 if (!tls11AltCipherlist.empty()) {
436 if (!cipherListPicker_) {
437 std::vector<int> weights;
439 tls11AltCipherlist.begin(),
440 tls11AltCipherlist.end(),
441 [&](const std::pair<std::string, int>& e) {
442 weights.push_back(e.second);
444 cipherListPicker_.reset(
445 new std::discrete_distribution<int>(weights.begin(), weights.end()));
447 auto rng = ThreadLocalPRNG();
448 auto index = (*cipherListPicker_)(rng);
449 if ((size_t)index >= tls11AltCipherlist.size()) {
450 LOG(ERROR) << "Trying to pick alt TLS11 cipher index " << index
451 << ", but tls11AltCipherlist is of length "
452 << tls11AltCipherlist.size();
454 ciphers = &tls11AltCipherlist[index].first;
458 // Prefer AES for TLS versions 1.1 and later since these are not
459 // vulnerable to BEAST attacks on AES. Note that we're setting the
460 // cipher list on the SSL object, not the SSL_CTX object, so it will
461 // only last for this request.
462 int rc = SSL_set_cipher_list(ssl, ciphers->c_str());
463 if ((rc == 0) || ERR_peek_error() != 0) {
464 // This shouldn't happen since we checked for this when proxygen
466 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
467 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
470 #endif // FOLLY_OPENSSL_HAS_SNI
472 #if FOLLY_OPENSSL_HAS_ALPN
473 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
474 const unsigned char** out,
475 unsigned char* outlen,
476 const unsigned char* in,
479 SSLContext* context = (SSLContext*)data;
481 if (context->advertisedNextProtocols_.empty()) {
485 auto i = context->pickNextProtocols();
486 const auto& item = context->advertisedNextProtocols_[i];
487 if (SSL_select_next_proto((unsigned char**)out,
492 inlen) != OPENSSL_NPN_NEGOTIATED) {
493 return SSL_TLSEXT_ERR_NOACK;
496 return SSL_TLSEXT_ERR_OK;
498 #endif // FOLLY_OPENSSL_HAS_ALPN
500 #ifdef OPENSSL_NPN_NEGOTIATED
502 bool SSLContext::setAdvertisedNextProtocols(
503 const std::list<std::string>& protocols, NextProtocolType protocolType) {
504 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
507 bool SSLContext::setRandomizedAdvertisedNextProtocols(
508 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
509 unsetNextProtocols();
510 if (items.size() == 0) {
513 int total_weight = 0;
514 for (const auto &item : items) {
515 if (item.protocols.size() == 0) {
518 AdvertisedNextProtocolsItem advertised_item;
519 advertised_item.length = 0;
520 for (const auto& proto : item.protocols) {
521 ++advertised_item.length;
522 auto protoLength = proto.length();
523 if (protoLength >= 256) {
524 deleteNextProtocolsStrings();
527 advertised_item.length += unsigned(protoLength);
529 advertised_item.protocols = new unsigned char[advertised_item.length];
530 if (!advertised_item.protocols) {
531 throw std::runtime_error("alloc failure");
533 unsigned char* dst = advertised_item.protocols;
534 for (auto& proto : item.protocols) {
535 uint8_t protoLength = uint8_t(proto.length());
536 *dst++ = (unsigned char)protoLength;
537 memcpy(dst, proto.data(), protoLength);
540 total_weight += item.weight;
541 advertisedNextProtocols_.push_back(advertised_item);
542 advertisedNextProtocolWeights_.push_back(item.weight);
544 if (total_weight == 0) {
545 deleteNextProtocolsStrings();
548 nextProtocolDistribution_ =
549 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
550 advertisedNextProtocolWeights_.end());
551 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
552 SSL_CTX_set_next_protos_advertised_cb(
553 ctx_, advertisedNextProtocolCallback, this);
554 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
556 #if FOLLY_OPENSSL_HAS_ALPN
557 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
558 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
559 // Client cannot really use randomized alpn
560 SSL_CTX_set_alpn_protos(ctx_,
561 advertisedNextProtocols_[0].protocols,
562 advertisedNextProtocols_[0].length);
568 void SSLContext::deleteNextProtocolsStrings() {
569 for (auto protocols : advertisedNextProtocols_) {
570 delete[] protocols.protocols;
572 advertisedNextProtocols_.clear();
573 advertisedNextProtocolWeights_.clear();
576 void SSLContext::unsetNextProtocols() {
577 deleteNextProtocolsStrings();
578 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
579 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
580 #if FOLLY_OPENSSL_HAS_ALPN
581 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
582 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
586 size_t SSLContext::pickNextProtocols() {
587 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
588 auto rng = ThreadLocalPRNG();
589 return nextProtocolDistribution_(rng);
592 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
593 const unsigned char** out, unsigned int* outlen, void* data) {
594 SSLContext* context = (SSLContext*)data;
595 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
598 } else if (context->advertisedNextProtocols_.size() == 1) {
599 *out = context->advertisedNextProtocols_[0].protocols;
600 *outlen = context->advertisedNextProtocols_[0].length;
602 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
603 sNextProtocolsExDataIndex_));
604 if (selected_index) {
606 *out = context->advertisedNextProtocols_[selected_index].protocols;
607 *outlen = context->advertisedNextProtocols_[selected_index].length;
609 auto i = context->pickNextProtocols();
610 uintptr_t selected = i + 1;
611 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
612 *out = context->advertisedNextProtocols_[i].protocols;
613 *outlen = context->advertisedNextProtocols_[i].length;
616 return SSL_TLSEXT_ERR_OK;
619 int SSLContext::selectNextProtocolCallback(SSL* ssl,
621 unsigned char* outlen,
622 const unsigned char* server,
623 unsigned int server_len,
625 (void)ssl; // Make -Wunused-parameters happy
626 SSLContext* ctx = (SSLContext*)data;
627 if (ctx->advertisedNextProtocols_.size() > 1) {
628 VLOG(3) << "SSLContext::selectNextProcolCallback() "
629 << "client should be deterministic in selecting protocols.";
632 unsigned char* client = nullptr;
633 unsigned int client_len = 0;
634 bool filtered = false;
635 auto cpf = ctx->getClientProtocolFilterCallback();
637 filtered = (*cpf)(&client, &client_len, server, server_len);
641 if (ctx->advertisedNextProtocols_.empty()) {
642 client = (unsigned char *) "";
645 client = ctx->advertisedNextProtocols_[0].protocols;
646 client_len = ctx->advertisedNextProtocols_[0].length;
650 int retval = SSL_select_next_proto(out, outlen, server, server_len,
652 if (retval != OPENSSL_NPN_NEGOTIATED) {
653 VLOG(3) << "SSLContext::selectNextProcolCallback() "
654 << "unable to pick a next protocol.";
656 return SSL_TLSEXT_ERR_OK;
658 #endif // OPENSSL_NPN_NEGOTIATED
660 SSL* SSLContext::createSSL() const {
661 SSL* ssl = SSL_new(ctx_);
662 if (ssl == nullptr) {
663 throw std::runtime_error("SSL_new: " + getErrors());
668 void SSLContext::setSessionCacheContext(const std::string& context) {
669 SSL_CTX_set_session_id_context(
671 reinterpret_cast<const unsigned char*>(context.data()),
673 static_cast<int>(context.length()), SSL_MAX_SSL_SESSION_ID_LENGTH));
677 * Match a name with a pattern. The pattern may include wildcard. A single
678 * wildcard "*" can match up to one component in the domain name.
680 * @param host Host name, typically the name of the remote host
681 * @param pattern Name retrieved from certificate
682 * @param size Size of "pattern"
683 * @return True, if "host" matches "pattern". False otherwise.
685 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
688 while (i < size && host[j] != '\0') {
689 if (toupper(pattern[i]) == toupper(host[j])) {
694 if (pattern[i] == '*') {
695 while (host[j] != '.' && host[j] != '\0') {
703 if (i == size && host[j] == '\0') {
709 int SSLContext::passwordCallback(char* password,
713 SSLContext* context = (SSLContext*)data;
714 if (context == nullptr || context->passwordCollector() == nullptr) {
717 std::string userPassword;
718 // call user defined password collector to get password
719 context->passwordCollector()->getPassword(userPassword, size);
720 auto length = int(userPassword.size());
724 strncpy(password, userPassword.c_str(), length);
730 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
731 lockType(inLockType) {
735 if (lockType == SSLContext::LOCK_MUTEX) {
737 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
740 // lockType == LOCK_NONE, no-op
744 if (lockType == SSLContext::LOCK_MUTEX) {
746 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
749 // lockType == LOCK_NONE, no-op
752 SSLContext::SSLLockType lockType;
753 folly::SpinLock spinLock{};
757 // Statics are unsafe in environments that call exit().
758 // If one thread calls exit() while another thread is
759 // references a member of SSLContext, bad things can happen.
760 // SSLContext runs in such environments.
761 // Instead of declaring a static member we "new" the static
762 // member so that it won't be destructed on exit().
763 static std::unique_ptr<SSLLock[]>& locks() {
764 static auto locksInst = new std::unique_ptr<SSLLock[]>();
768 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
769 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
770 return *lockTypesInst;
773 static void callbackLocking(int mode, int n, const char*, int) {
774 if (mode & CRYPTO_LOCK) {
781 static unsigned long callbackThreadID() {
782 return static_cast<unsigned long>(
784 pthread_mach_thread_np(pthread_self())
786 pthread_getw32threadid_np(pthread_self())
793 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
794 return new CRYPTO_dynlock_value;
797 static void dyn_lock(int mode,
798 struct CRYPTO_dynlock_value* lock,
800 if (lock != nullptr) {
801 if (mode & CRYPTO_LOCK) {
804 lock->mutex.unlock();
809 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
813 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
814 lockTypes() = inLockTypes;
817 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
818 void SSLContext::enableFalseStart() {
819 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
823 void SSLContext::markInitialized() {
824 std::lock_guard<std::mutex> g(initMutex());
828 void SSLContext::initializeOpenSSL() {
829 std::lock_guard<std::mutex> g(initMutex());
830 initializeOpenSSLLocked();
833 void SSLContext::initializeOpenSSLLocked() {
838 SSL_load_error_strings();
839 ERR_load_crypto_strings();
841 locks().reset(new SSLLock[::CRYPTO_num_locks()]);
842 for (auto it: lockTypes()) {
843 locks()[it.first].lockType = it.second;
845 CRYPTO_set_id_callback(callbackThreadID);
846 CRYPTO_set_locking_callback(callbackLocking);
848 CRYPTO_set_dynlock_create_callback(dyn_create);
849 CRYPTO_set_dynlock_lock_callback(dyn_lock);
850 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
852 #ifdef OPENSSL_NPN_NEGOTIATED
853 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
854 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
859 void SSLContext::cleanupOpenSSL() {
860 std::lock_guard<std::mutex> g(initMutex());
861 cleanupOpenSSLLocked();
864 void SSLContext::cleanupOpenSSLLocked() {
869 CRYPTO_set_id_callback(nullptr);
870 CRYPTO_set_locking_callback(nullptr);
871 CRYPTO_set_dynlock_create_callback(nullptr);
872 CRYPTO_set_dynlock_lock_callback(nullptr);
873 CRYPTO_set_dynlock_destroy_callback(nullptr);
874 CRYPTO_cleanup_all_ex_data();
879 initialized_ = false;
882 void SSLContext::setOptions(long options) {
883 long newOpt = SSL_CTX_set_options(ctx_, options);
884 if ((newOpt & options) != options) {
885 throw std::runtime_error("SSL_CTX_set_options failed");
889 std::string SSLContext::getErrors(int errnoCopy) {
891 unsigned long errorCode;
895 while ((errorCode = ERR_get_error()) != 0) {
896 if (!errors.empty()) {
899 const char* reason = ERR_reason_error_string(errorCode);
900 if (reason == nullptr) {
901 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
906 if (errors.empty()) {
907 errors = "error code: " + folly::to<std::string>(errnoCopy);
913 operator<<(std::ostream& os, const PasswordCollector& collector) {
914 os << collector.describe();