2 * Copyright 2015 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/SpinLock.h>
27 // ---------------------------------------------------------------------
28 // SSLContext implementation
29 // ---------------------------------------------------------------------
31 struct CRYPTO_dynlock_value {
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 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
84 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
85 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
89 SSLContext::~SSLContext() {
90 if (ctx_ != nullptr) {
95 #ifdef OPENSSL_NPN_NEGOTIATED
96 deleteNextProtocolsStrings();
100 void SSLContext::ciphers(const std::string& ciphers) {
101 providedCiphersString_ = ciphers;
102 setCiphersOrThrow(ciphers);
105 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
106 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
107 if (ERR_peek_error() != 0) {
108 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
111 throw std::runtime_error("None of specified ciphers are supported");
115 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
117 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
118 verifyPeer_ = verifyPeer;
121 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
123 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
124 int mode = SSL_VERIFY_NONE;
126 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
129 case SSLVerifyPeerEnum::VERIFY:
130 mode = SSL_VERIFY_PEER;
133 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
134 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
137 case SSLVerifyPeerEnum::NO_VERIFY:
138 mode = SSL_VERIFY_NONE;
147 int SSLContext::getVerificationMode() {
148 return getVerificationMode(verifyPeer_);
151 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
152 const std::string& peerName) {
155 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
156 checkPeerName_ = checkPeerName;
157 peerFixedName_ = peerName;
159 mode = SSL_VERIFY_NONE;
160 checkPeerName_ = false; // can't check name without cert!
161 peerFixedName_.clear();
163 SSL_CTX_set_verify(ctx_, mode, nullptr);
166 void SSLContext::loadCertificate(const char* path, const char* format) {
167 if (path == nullptr || format == nullptr) {
168 throw std::invalid_argument(
169 "loadCertificateChain: either <path> or <format> is nullptr");
171 if (strcmp(format, "PEM") == 0) {
172 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
173 int errnoCopy = errno;
174 std::string reason("SSL_CTX_use_certificate_chain_file: ");
177 reason.append(getErrors(errnoCopy));
178 throw std::runtime_error(reason);
181 throw std::runtime_error("Unsupported certificate format: " + std::string(format));
185 void SSLContext::loadPrivateKey(const char* path, const char* format) {
186 if (path == nullptr || format == nullptr) {
187 throw std::invalid_argument(
188 "loadPrivateKey: either <path> or <format> is nullptr");
190 if (strcmp(format, "PEM") == 0) {
191 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
192 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
195 throw std::runtime_error("Unsupported private key format: " + std::string(format));
199 void SSLContext::loadTrustedCertificates(const char* path) {
200 if (path == nullptr) {
201 throw std::invalid_argument(
202 "loadTrustedCertificates: <path> is nullptr");
204 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
205 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
209 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
210 SSL_CTX_set_cert_store(ctx_, store);
213 void SSLContext::loadClientCAList(const char* path) {
214 auto clientCAs = SSL_load_client_CA_file(path);
215 if (clientCAs == nullptr) {
216 LOG(ERROR) << "Unable to load ca file: " << path;
219 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
222 void SSLContext::randomize() {
226 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
227 if (collector == nullptr) {
228 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
231 collector_ = collector;
232 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
233 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
236 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
238 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
242 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
243 clientHelloCbs_.push_back(cb);
246 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
247 SSLContext* context = (SSLContext*)data;
249 if (context == nullptr) {
250 return SSL_TLSEXT_ERR_NOACK;
253 for (auto& cb : context->clientHelloCbs_) {
254 // Generic callbacks to happen after we receive the Client Hello.
255 // For example, we use one to switch which cipher we use depending
256 // on the user's TLS version. Because the primary purpose of
257 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
258 // are side-uses, we ignore any possible failures other than just logging
263 if (!context->serverNameCb_) {
264 return SSL_TLSEXT_ERR_NOACK;
267 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
269 case SERVER_NAME_FOUND:
270 return SSL_TLSEXT_ERR_OK;
271 case SERVER_NAME_NOT_FOUND:
272 return SSL_TLSEXT_ERR_NOACK;
273 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
274 *al = TLS1_AD_UNRECOGNIZED_NAME;
275 return SSL_TLSEXT_ERR_ALERT_FATAL;
280 return SSL_TLSEXT_ERR_NOACK;
283 void SSLContext::switchCiphersIfTLS11(
285 const std::string& tls11CipherString) {
287 CHECK(!tls11CipherString.empty()) << "Shouldn't call if empty alt ciphers";
289 if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
290 // We only do this for TLS v 1.1 and later
294 // Prefer AES for TLS versions 1.1 and later since these are not
295 // vulnerable to BEAST attacks on AES. Note that we're setting the
296 // cipher list on the SSL object, not the SSL_CTX object, so it will
297 // only last for this request.
298 int rc = SSL_set_cipher_list(ssl, tls11CipherString.c_str());
299 if ((rc == 0) || ERR_peek_error() != 0) {
300 // This shouldn't happen since we checked for this when proxygen
302 LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
303 SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
308 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
309 int SSLContext::alpnSelectCallback(SSL* ssl,
310 const unsigned char** out,
311 unsigned char* outlen,
312 const unsigned char* in,
315 SSLContext* context = (SSLContext*)data;
317 if (context->advertisedNextProtocols_.empty()) {
321 auto i = context->pickNextProtocols();
322 const auto& item = context->advertisedNextProtocols_[i];
323 if (SSL_select_next_proto((unsigned char**)out,
328 inlen) != OPENSSL_NPN_NEGOTIATED) {
329 return SSL_TLSEXT_ERR_NOACK;
332 return SSL_TLSEXT_ERR_OK;
336 #ifdef OPENSSL_NPN_NEGOTIATED
338 bool SSLContext::setAdvertisedNextProtocols(
339 const std::list<std::string>& protocols, NextProtocolType protocolType) {
340 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
343 bool SSLContext::setRandomizedAdvertisedNextProtocols(
344 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
345 unsetNextProtocols();
346 if (items.size() == 0) {
349 int total_weight = 0;
350 for (const auto &item : items) {
351 if (item.protocols.size() == 0) {
354 AdvertisedNextProtocolsItem advertised_item;
355 advertised_item.length = 0;
356 for (const auto& proto : item.protocols) {
357 ++advertised_item.length;
358 unsigned protoLength = proto.length();
359 if (protoLength >= 256) {
360 deleteNextProtocolsStrings();
363 advertised_item.length += protoLength;
365 advertised_item.protocols = new unsigned char[advertised_item.length];
366 if (!advertised_item.protocols) {
367 throw std::runtime_error("alloc failure");
369 unsigned char* dst = advertised_item.protocols;
370 for (auto& proto : item.protocols) {
371 unsigned protoLength = proto.length();
372 *dst++ = (unsigned char)protoLength;
373 memcpy(dst, proto.data(), protoLength);
376 total_weight += item.weight;
377 advertised_item.probability = item.weight;
378 advertisedNextProtocols_.push_back(advertised_item);
380 if (total_weight == 0) {
381 deleteNextProtocolsStrings();
384 for (auto &advertised_item : advertisedNextProtocols_) {
385 advertised_item.probability /= total_weight;
387 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
388 SSL_CTX_set_next_protos_advertised_cb(
389 ctx_, advertisedNextProtocolCallback, this);
390 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
392 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
393 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
394 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
395 // Client cannot really use randomized alpn
396 SSL_CTX_set_alpn_protos(ctx_,
397 advertisedNextProtocols_[0].protocols,
398 advertisedNextProtocols_[0].length);
404 void SSLContext::deleteNextProtocolsStrings() {
405 for (auto protocols : advertisedNextProtocols_) {
406 delete[] protocols.protocols;
408 advertisedNextProtocols_.clear();
411 void SSLContext::unsetNextProtocols() {
412 deleteNextProtocolsStrings();
413 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
414 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
415 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
416 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
417 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
421 size_t SSLContext::pickNextProtocols() {
422 unsigned char random_byte;
423 RAND_bytes(&random_byte, 1);
424 double random_value = random_byte / 255.0;
426 for (size_t i = 0; i < advertisedNextProtocols_.size(); ++i) {
427 sum += advertisedNextProtocols_[i].probability;
428 if (sum < random_value && i + 1 < advertisedNextProtocols_.size()) {
433 CHECK(false) << "Failed to pickNextProtocols";
436 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
437 const unsigned char** out, unsigned int* outlen, void* data) {
438 SSLContext* context = (SSLContext*)data;
439 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
442 } else if (context->advertisedNextProtocols_.size() == 1) {
443 *out = context->advertisedNextProtocols_[0].protocols;
444 *outlen = context->advertisedNextProtocols_[0].length;
446 uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
447 sNextProtocolsExDataIndex_));
448 if (selected_index) {
450 *out = context->advertisedNextProtocols_[selected_index].protocols;
451 *outlen = context->advertisedNextProtocols_[selected_index].length;
453 auto i = context->pickNextProtocols();
454 uintptr_t selected = i + 1;
455 SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void*)selected);
456 *out = context->advertisedNextProtocols_[i].protocols;
457 *outlen = context->advertisedNextProtocols_[i].length;
460 return SSL_TLSEXT_ERR_OK;
463 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
464 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
465 SSLContext::SSLFalseStartChecker::SSLFalseStartChecker() :
467 TLS1_CK_DHE_DSS_WITH_AES_128_SHA,
468 TLS1_CK_DHE_RSA_WITH_AES_128_SHA,
469 TLS1_CK_DHE_DSS_WITH_AES_256_SHA,
470 TLS1_CK_DHE_RSA_WITH_AES_256_SHA,
471 TLS1_CK_DHE_DSS_WITH_AES_128_SHA256,
472 TLS1_CK_DHE_RSA_WITH_AES_128_SHA256,
473 TLS1_CK_DHE_DSS_WITH_AES_256_SHA256,
474 TLS1_CK_DHE_RSA_WITH_AES_256_SHA256,
475 TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256,
476 TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384,
477 TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256,
478 TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384,
479 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
480 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
481 TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA,
482 TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA,
483 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256,
484 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384,
485 TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256,
486 TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384,
487 TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256,
488 TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384,
489 TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
490 TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
491 TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
492 TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
494 length_ = sizeof(ciphers_)/sizeof(ciphers_[0]);
495 width_ = sizeof(ciphers_[0]);
496 qsort(ciphers_, length_, width_, compare_ulong);
499 bool SSLContext::SSLFalseStartChecker::canUseFalseStartWithCipher(
500 const SSL_CIPHER *cipher) {
501 unsigned long cid = cipher->id;
503 (unsigned long*)bsearch(&cid, ciphers_, length_, width_, compare_ulong);
508 SSLContext::SSLFalseStartChecker::compare_ulong(const void *x, const void *y) {
509 if (*(unsigned long *)x < *(unsigned long *)y) {
512 if (*(unsigned long *)x > *(unsigned long *)y) {
518 bool SSLContext::canUseFalseStartWithCipher(const SSL_CIPHER *cipher) {
519 return falseStartChecker_.canUseFalseStartWithCipher(cipher);
523 int SSLContext::selectNextProtocolCallback(
524 SSL* ssl, unsigned char **out, unsigned char *outlen,
525 const unsigned char *server, unsigned int server_len, void *data) {
527 SSLContext* ctx = (SSLContext*)data;
528 if (ctx->advertisedNextProtocols_.size() > 1) {
529 VLOG(3) << "SSLContext::selectNextProcolCallback() "
530 << "client should be deterministic in selecting protocols.";
533 unsigned char *client;
534 unsigned int client_len;
535 bool filtered = false;
536 auto cpf = ctx->getClientProtocolFilterCallback();
538 filtered = (*cpf)(&client, &client_len, server, server_len);
542 if (ctx->advertisedNextProtocols_.empty()) {
543 client = (unsigned char *) "";
546 client = ctx->advertisedNextProtocols_[0].protocols;
547 client_len = ctx->advertisedNextProtocols_[0].length;
551 int retval = SSL_select_next_proto(out, outlen, server, server_len,
553 if (retval != OPENSSL_NPN_NEGOTIATED) {
554 VLOG(3) << "SSLContext::selectNextProcolCallback() "
555 << "unable to pick a next protocol.";
556 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
557 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
559 const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
560 if (cipher && ctx->canUseFalseStartWithCipher(cipher)) {
561 SSL_set_mode(ssl, SSL_MODE_HANDSHAKE_CUTTHROUGH);
565 return SSL_TLSEXT_ERR_OK;
567 #endif // OPENSSL_NPN_NEGOTIATED
569 SSL* SSLContext::createSSL() const {
570 SSL* ssl = SSL_new(ctx_);
571 if (ssl == nullptr) {
572 throw std::runtime_error("SSL_new: " + getErrors());
578 * Match a name with a pattern. The pattern may include wildcard. A single
579 * wildcard "*" can match up to one component in the domain name.
581 * @param host Host name, typically the name of the remote host
582 * @param pattern Name retrieved from certificate
583 * @param size Size of "pattern"
584 * @return True, if "host" matches "pattern". False otherwise.
586 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
589 while (i < size && host[j] != '\0') {
590 if (toupper(pattern[i]) == toupper(host[j])) {
595 if (pattern[i] == '*') {
596 while (host[j] != '.' && host[j] != '\0') {
604 if (i == size && host[j] == '\0') {
610 int SSLContext::passwordCallback(char* password,
614 SSLContext* context = (SSLContext*)data;
615 if (context == nullptr || context->passwordCollector() == nullptr) {
618 std::string userPassword;
619 // call user defined password collector to get password
620 context->passwordCollector()->getPassword(userPassword, size);
621 int length = userPassword.size();
625 strncpy(password, userPassword.c_str(), length);
631 SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
632 lockType(inLockType) {
636 if (lockType == SSLContext::LOCK_MUTEX) {
638 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
641 // lockType == LOCK_NONE, no-op
645 if (lockType == SSLContext::LOCK_MUTEX) {
647 } else if (lockType == SSLContext::LOCK_SPINLOCK) {
650 // lockType == LOCK_NONE, no-op
653 SSLContext::SSLLockType lockType;
654 folly::SpinLock spinLock{};
658 // Statics are unsafe in environments that call exit().
659 // If one thread calls exit() while another thread is
660 // references a member of SSLContext, bad things can happen.
661 // SSLContext runs in such environments.
662 // Instead of declaring a static member we "new" the static
663 // member so that it won't be destructed on exit().
664 static std::unique_ptr<SSLLock[]>& locks() {
665 static auto locksInst = new std::unique_ptr<SSLLock[]>();
669 static std::map<int, SSLContext::SSLLockType>& lockTypes() {
670 static auto lockTypesInst = new std::map<int, SSLContext::SSLLockType>();
671 return *lockTypesInst;
674 static void callbackLocking(int mode, int n, const char*, int) {
675 if (mode & CRYPTO_LOCK) {
682 static unsigned long callbackThreadID() {
683 return static_cast<unsigned long>(
685 pthread_mach_thread_np(pthread_self())
692 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
693 return new CRYPTO_dynlock_value;
696 static void dyn_lock(int mode,
697 struct CRYPTO_dynlock_value* lock,
699 if (lock != nullptr) {
700 if (mode & CRYPTO_LOCK) {
703 lock->mutex.unlock();
708 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
712 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
713 lockTypes() = inLockTypes;
716 void SSLContext::markInitialized() {
717 std::lock_guard<std::mutex> g(initMutex());
721 void SSLContext::initializeOpenSSL() {
722 std::lock_guard<std::mutex> g(initMutex());
723 initializeOpenSSLLocked();
726 void SSLContext::initializeOpenSSLLocked() {
731 SSL_load_error_strings();
732 ERR_load_crypto_strings();
734 locks().reset(new SSLLock[::CRYPTO_num_locks()]);
735 for (auto it: lockTypes()) {
736 locks()[it.first].lockType = it.second;
738 CRYPTO_set_id_callback(callbackThreadID);
739 CRYPTO_set_locking_callback(callbackLocking);
741 CRYPTO_set_dynlock_create_callback(dyn_create);
742 CRYPTO_set_dynlock_lock_callback(dyn_lock);
743 CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
745 #ifdef OPENSSL_NPN_NEGOTIATED
746 sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
747 (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
752 void SSLContext::cleanupOpenSSL() {
753 std::lock_guard<std::mutex> g(initMutex());
754 cleanupOpenSSLLocked();
757 void SSLContext::cleanupOpenSSLLocked() {
762 CRYPTO_set_id_callback(nullptr);
763 CRYPTO_set_locking_callback(nullptr);
764 CRYPTO_set_dynlock_create_callback(nullptr);
765 CRYPTO_set_dynlock_lock_callback(nullptr);
766 CRYPTO_set_dynlock_destroy_callback(nullptr);
767 CRYPTO_cleanup_all_ex_data();
772 initialized_ = false;
775 void SSLContext::setOptions(long options) {
776 long newOpt = SSL_CTX_set_options(ctx_, options);
777 if ((newOpt & options) != options) {
778 throw std::runtime_error("SSL_CTX_set_options failed");
782 std::string SSLContext::getErrors(int errnoCopy) {
784 unsigned long errorCode;
788 while ((errorCode = ERR_get_error()) != 0) {
789 if (!errors.empty()) {
792 const char* reason = ERR_reason_error_string(errorCode);
793 if (reason == nullptr) {
794 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
799 if (errors.empty()) {
800 errors = "error code: " + folly::to<std::string>(errnoCopy);
806 operator<<(std::ostream& os, const PasswordCollector& collector) {
807 os << collector.describe();
811 bool OpenSSLUtils::getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
812 sockaddr_storage* addrStorage,
813 socklen_t* addrLen) {
814 // Grab the ssl idx and then the ssl object so that we can get the peer
815 // name to compare against the ips in the subjectAltName
816 auto sslIdx = SSL_get_ex_data_X509_STORE_CTX_idx();
818 reinterpret_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, sslIdx));
819 int fd = SSL_get_fd(ssl);
821 LOG(ERROR) << "Inexplicably couldn't get fd from SSL";
825 *addrLen = sizeof(*addrStorage);
826 if (getpeername(fd, reinterpret_cast<sockaddr*>(addrStorage), addrLen) != 0) {
827 PLOG(ERROR) << "Unable to get peer name";
830 CHECK(*addrLen <= sizeof(*addrStorage));
834 bool OpenSSLUtils::validatePeerCertNames(X509* cert,
835 const sockaddr* addr,
837 // Try to extract the names within the SAN extension from the certificate
839 reinterpret_cast<STACK_OF(GENERAL_NAME)*>(
840 X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr));
842 if (altNames != nullptr) {
843 sk_GENERAL_NAME_pop_free(altNames, GENERAL_NAME_free);
846 if (altNames == nullptr) {
847 LOG(WARNING) << "No subjectAltName provided and we only support ip auth";
851 const sockaddr_in* addr4 = nullptr;
852 const sockaddr_in6* addr6 = nullptr;
853 if (addr != nullptr) {
854 if (addr->sa_family == AF_INET) {
855 addr4 = reinterpret_cast<const sockaddr_in*>(addr);
856 } else if (addr->sa_family == AF_INET6) {
857 addr6 = reinterpret_cast<const sockaddr_in6*>(addr);
859 LOG(FATAL) << "Unsupported sockaddr family: " << addr->sa_family;
864 for (int i = 0; i < sk_GENERAL_NAME_num(altNames); i++) {
865 auto name = sk_GENERAL_NAME_value(altNames, i);
866 if ((addr4 != nullptr || addr6 != nullptr) && name->type == GEN_IPADD) {
867 // Extra const-ness for paranoia
868 unsigned char const * const rawIpStr = name->d.iPAddress->data;
869 int const rawIpLen = name->d.iPAddress->length;
871 if (rawIpLen == 4 && addr4 != nullptr) {
872 if (::memcmp(rawIpStr, &addr4->sin_addr, rawIpLen) == 0) {
875 } else if (rawIpLen == 16 && addr6 != nullptr) {
876 if (::memcmp(rawIpStr, &addr6->sin6_addr, rawIpLen) == 0) {
879 } else if (rawIpLen != 4 && rawIpLen != 16) {
880 LOG(WARNING) << "Unexpected IP length: " << rawIpLen;
885 LOG(WARNING) << "Unable to match client cert against alt name ip";