2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include "SSLContext.h"
19 #include <folly/Format.h>
20 #include <folly/Memory.h>
21 #include <folly/Random.h>
22 #include <folly/SharedMutex.h>
23 #include <folly/SpinLock.h>
24 #include <folly/ThreadId.h>
25 #include <folly/ssl/Init.h>
27 // ---------------------------------------------------------------------
28 // SSLContext implementation
29 // ---------------------------------------------------------------------
32 // For OpenSSL portability API
33 using namespace folly::ssl;
35 // SSLContext implementation
36 SSLContext::SSLContext(SSLVersion version) {
39 ctx_ = SSL_CTX_new(SSLv23_method());
40 if (ctx_ == nullptr) {
41 throw std::runtime_error("SSL_CTX_new: " + getErrors());
47 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
50 opt = SSL_OP_NO_SSLv2;
53 opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
60 int newOpt = SSL_CTX_set_options(ctx_, opt);
61 DCHECK((newOpt & opt) == opt);
63 SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
65 checkPeerName_ = false;
67 SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION);
69 #if FOLLY_OPENSSL_HAS_SNI
70 SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
71 SSL_CTX_set_tlsext_servername_arg(ctx_, this);
75 SSLContext::~SSLContext() {
76 if (ctx_ != nullptr) {
81 #ifdef OPENSSL_NPN_NEGOTIATED
82 deleteNextProtocolsStrings();
86 void SSLContext::ciphers(const std::string& ciphers) {
87 setCiphersOrThrow(ciphers);
90 void SSLContext::setClientECCurvesList(
91 const std::vector<std::string>& ecCurves) {
92 if (ecCurves.size() == 0) {
95 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
96 std::string ecCurvesList;
97 join(":", ecCurves, ecCurvesList);
98 int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
100 throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
105 void SSLContext::setServerECCurve(const std::string& curveName) {
106 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL && !defined(OPENSSL_NO_ECDH)
107 EC_KEY* ecdh = nullptr;
111 * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
112 * from RFC 4492 section 5.1.1, or explicitly described curves over
113 * binary fields. OpenSSL only supports the "named curves", which provide
114 * maximum interoperability.
117 nid = OBJ_sn2nid(curveName.c_str());
119 LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
121 ecdh = EC_KEY_new_by_curve_name(nid);
122 if (ecdh == nullptr) {
123 LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
126 SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
129 throw std::runtime_error("Elliptic curve encryption not allowed");
133 void SSLContext::setX509VerifyParam(
134 const ssl::X509VerifyParam& x509VerifyParam) {
135 if (!x509VerifyParam) {
138 if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
139 throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
143 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
144 int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
146 throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
148 providedCiphersString_ = ciphers;
151 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
153 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
154 verifyPeer_ = verifyPeer;
157 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
159 CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
160 int mode = SSL_VERIFY_NONE;
162 // case SSLVerifyPeerEnum::USE_CTX: // can't happen
165 case SSLVerifyPeerEnum::VERIFY:
166 mode = SSL_VERIFY_PEER;
169 case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
170 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
173 case SSLVerifyPeerEnum::NO_VERIFY:
174 mode = SSL_VERIFY_NONE;
183 int SSLContext::getVerificationMode() {
184 return getVerificationMode(verifyPeer_);
187 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
188 const std::string& peerName) {
191 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
192 SSL_VERIFY_CLIENT_ONCE;
193 checkPeerName_ = checkPeerName;
194 peerFixedName_ = peerName;
196 mode = SSL_VERIFY_NONE;
197 checkPeerName_ = false; // can't check name without cert!
198 peerFixedName_.clear();
200 SSL_CTX_set_verify(ctx_, mode, nullptr);
203 void SSLContext::loadCertificate(const char* path, const char* format) {
204 if (path == nullptr || format == nullptr) {
205 throw std::invalid_argument(
206 "loadCertificateChain: either <path> or <format> is nullptr");
208 if (strcmp(format, "PEM") == 0) {
209 if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
210 int errnoCopy = errno;
211 std::string reason("SSL_CTX_use_certificate_chain_file: ");
214 reason.append(getErrors(errnoCopy));
215 throw std::runtime_error(reason);
218 throw std::runtime_error(
219 "Unsupported certificate format: " + std::string(format));
223 void SSLContext::loadCertificateFromBufferPEM(folly::StringPiece cert) {
224 if (cert.data() == nullptr) {
225 throw std::invalid_argument("loadCertificate: <cert> is nullptr");
228 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
229 if (bio == nullptr) {
230 throw std::runtime_error("BIO_new: " + getErrors());
233 int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
234 if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
235 throw std::runtime_error("BIO_write: " + getErrors());
238 ssl::X509UniquePtr x509(
239 PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
240 if (x509 == nullptr) {
241 throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
244 if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
245 throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
249 void SSLContext::loadPrivateKey(const char* path, const char* format) {
250 if (path == nullptr || format == nullptr) {
251 throw std::invalid_argument(
252 "loadPrivateKey: either <path> or <format> is nullptr");
254 if (strcmp(format, "PEM") == 0) {
255 if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
256 throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
259 throw std::runtime_error(
260 "Unsupported private key format: " + std::string(format));
264 void SSLContext::loadPrivateKeyFromBufferPEM(folly::StringPiece pkey) {
265 if (pkey.data() == nullptr) {
266 throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
269 ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
270 if (bio == nullptr) {
271 throw std::runtime_error("BIO_new: " + getErrors());
274 int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
275 if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
276 throw std::runtime_error("BIO_write: " + getErrors());
279 ssl::EvpPkeyUniquePtr key(
280 PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
281 if (key == nullptr) {
282 throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
285 if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
286 throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
290 void SSLContext::loadTrustedCertificates(const char* path) {
291 if (path == nullptr) {
292 throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
294 if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
295 throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
300 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
301 SSL_CTX_set_cert_store(ctx_, store);
304 void SSLContext::loadClientCAList(const char* path) {
305 auto clientCAs = SSL_load_client_CA_file(path);
306 if (clientCAs == nullptr) {
307 LOG(ERROR) << "Unable to load ca file: " << path;
310 SSL_CTX_set_client_CA_list(ctx_, clientCAs);
313 void SSLContext::passwordCollector(
314 std::shared_ptr<PasswordCollector> collector) {
315 if (collector == nullptr) {
316 LOG(ERROR) << "passwordCollector: ignore invalid password collector";
319 collector_ = collector;
320 SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
321 SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
324 #if FOLLY_OPENSSL_HAS_SNI
326 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
330 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
331 clientHelloCbs_.push_back(cb);
334 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
335 SSLContext* context = (SSLContext*)data;
337 if (context == nullptr) {
338 return SSL_TLSEXT_ERR_NOACK;
341 for (auto& cb : context->clientHelloCbs_) {
342 // Generic callbacks to happen after we receive the Client Hello.
343 // For example, we use one to switch which cipher we use depending
344 // on the user's TLS version. Because the primary purpose of
345 // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
346 // are side-uses, we ignore any possible failures other than just logging
351 if (!context->serverNameCb_) {
352 return SSL_TLSEXT_ERR_NOACK;
355 ServerNameCallbackResult ret = context->serverNameCb_(ssl);
357 case SERVER_NAME_FOUND:
358 return SSL_TLSEXT_ERR_OK;
359 case SERVER_NAME_NOT_FOUND:
360 return SSL_TLSEXT_ERR_NOACK;
361 case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
362 *al = TLS1_AD_UNRECOGNIZED_NAME;
363 return SSL_TLSEXT_ERR_ALERT_FATAL;
368 return SSL_TLSEXT_ERR_NOACK;
370 #endif // FOLLY_OPENSSL_HAS_SNI
372 #if FOLLY_OPENSSL_HAS_ALPN
373 int SSLContext::alpnSelectCallback(SSL* /* ssl */,
374 const unsigned char** out,
375 unsigned char* outlen,
376 const unsigned char* in,
379 SSLContext* context = (SSLContext*)data;
381 if (context->advertisedNextProtocols_.empty()) {
385 auto i = context->pickNextProtocols();
386 const auto& item = context->advertisedNextProtocols_[i];
387 if (SSL_select_next_proto((unsigned char**)out,
392 inlen) != OPENSSL_NPN_NEGOTIATED) {
393 return SSL_TLSEXT_ERR_NOACK;
396 return SSL_TLSEXT_ERR_OK;
398 #endif // FOLLY_OPENSSL_HAS_ALPN
400 #ifdef OPENSSL_NPN_NEGOTIATED
402 bool SSLContext::setAdvertisedNextProtocols(
403 const std::list<std::string>& protocols, NextProtocolType protocolType) {
404 return setRandomizedAdvertisedNextProtocols({{1, protocols}}, protocolType);
407 bool SSLContext::setRandomizedAdvertisedNextProtocols(
408 const std::list<NextProtocolsItem>& items, NextProtocolType protocolType) {
409 unsetNextProtocols();
410 if (items.size() == 0) {
413 int total_weight = 0;
414 for (const auto &item : items) {
415 if (item.protocols.size() == 0) {
418 AdvertisedNextProtocolsItem advertised_item;
419 advertised_item.length = 0;
420 for (const auto& proto : item.protocols) {
421 ++advertised_item.length;
422 auto protoLength = proto.length();
423 if (protoLength >= 256) {
424 deleteNextProtocolsStrings();
427 advertised_item.length += unsigned(protoLength);
429 advertised_item.protocols = new unsigned char[advertised_item.length];
430 if (!advertised_item.protocols) {
431 throw std::runtime_error("alloc failure");
433 unsigned char* dst = advertised_item.protocols;
434 for (auto& proto : item.protocols) {
435 uint8_t protoLength = uint8_t(proto.length());
436 *dst++ = (unsigned char)protoLength;
437 memcpy(dst, proto.data(), protoLength);
440 total_weight += item.weight;
441 advertisedNextProtocols_.push_back(advertised_item);
442 advertisedNextProtocolWeights_.push_back(item.weight);
444 if (total_weight == 0) {
445 deleteNextProtocolsStrings();
448 nextProtocolDistribution_ =
449 std::discrete_distribution<>(advertisedNextProtocolWeights_.begin(),
450 advertisedNextProtocolWeights_.end());
451 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::NPN) {
452 SSL_CTX_set_next_protos_advertised_cb(
453 ctx_, advertisedNextProtocolCallback, this);
454 SSL_CTX_set_next_proto_select_cb(ctx_, selectNextProtocolCallback, this);
456 #if FOLLY_OPENSSL_HAS_ALPN
457 if ((uint8_t)protocolType & (uint8_t)NextProtocolType::ALPN) {
458 SSL_CTX_set_alpn_select_cb(ctx_, alpnSelectCallback, this);
459 // Client cannot really use randomized alpn
460 SSL_CTX_set_alpn_protos(ctx_,
461 advertisedNextProtocols_[0].protocols,
462 advertisedNextProtocols_[0].length);
468 void SSLContext::deleteNextProtocolsStrings() {
469 for (auto protocols : advertisedNextProtocols_) {
470 delete[] protocols.protocols;
472 advertisedNextProtocols_.clear();
473 advertisedNextProtocolWeights_.clear();
476 void SSLContext::unsetNextProtocols() {
477 deleteNextProtocolsStrings();
478 SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
479 SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
480 #if FOLLY_OPENSSL_HAS_ALPN
481 SSL_CTX_set_alpn_select_cb(ctx_, nullptr, nullptr);
482 SSL_CTX_set_alpn_protos(ctx_, nullptr, 0);
486 size_t SSLContext::pickNextProtocols() {
487 CHECK(!advertisedNextProtocols_.empty()) << "Failed to pickNextProtocols";
488 auto rng = ThreadLocalPRNG();
489 return size_t(nextProtocolDistribution_(rng));
492 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
493 const unsigned char** out, unsigned int* outlen, void* data) {
494 static int nextProtocolsExDataIndex = SSL_get_ex_new_index(
495 0, (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
497 SSLContext* context = (SSLContext*)data;
498 if (context == nullptr || context->advertisedNextProtocols_.empty()) {
501 } else if (context->advertisedNextProtocols_.size() == 1) {
502 *out = context->advertisedNextProtocols_[0].protocols;
503 *outlen = context->advertisedNextProtocols_[0].length;
505 uintptr_t selected_index = reinterpret_cast<uintptr_t>(
506 SSL_get_ex_data(ssl, nextProtocolsExDataIndex));
507 if (selected_index) {
509 *out = context->advertisedNextProtocols_[selected_index].protocols;
510 *outlen = context->advertisedNextProtocols_[selected_index].length;
512 auto i = context->pickNextProtocols();
513 uintptr_t selected = i + 1;
514 SSL_set_ex_data(ssl, nextProtocolsExDataIndex, (void*)selected);
515 *out = context->advertisedNextProtocols_[i].protocols;
516 *outlen = context->advertisedNextProtocols_[i].length;
519 return SSL_TLSEXT_ERR_OK;
522 int SSLContext::selectNextProtocolCallback(SSL* ssl,
524 unsigned char* outlen,
525 const unsigned char* server,
526 unsigned int server_len,
528 (void)ssl; // Make -Wunused-parameters happy
529 SSLContext* ctx = (SSLContext*)data;
530 if (ctx->advertisedNextProtocols_.size() > 1) {
531 VLOG(3) << "SSLContext::selectNextProcolCallback() "
532 << "client should be deterministic in selecting protocols.";
535 unsigned char* client = nullptr;
536 unsigned int client_len = 0;
537 bool filtered = false;
538 auto cpf = ctx->getClientProtocolFilterCallback();
540 filtered = (*cpf)(&client, &client_len, server, server_len);
544 if (ctx->advertisedNextProtocols_.empty()) {
545 client = (unsigned char *) "";
548 client = ctx->advertisedNextProtocols_[0].protocols;
549 client_len = ctx->advertisedNextProtocols_[0].length;
553 int retval = SSL_select_next_proto(out, outlen, server, server_len,
555 if (retval != OPENSSL_NPN_NEGOTIATED) {
556 VLOG(3) << "SSLContext::selectNextProcolCallback() "
557 << "unable to pick a next protocol.";
559 return SSL_TLSEXT_ERR_OK;
561 #endif // OPENSSL_NPN_NEGOTIATED
563 SSL* SSLContext::createSSL() const {
564 SSL* ssl = SSL_new(ctx_);
565 if (ssl == nullptr) {
566 throw std::runtime_error("SSL_new: " + getErrors());
571 void SSLContext::setSessionCacheContext(const std::string& context) {
572 SSL_CTX_set_session_id_context(
574 reinterpret_cast<const unsigned char*>(context.data()),
575 std::min<unsigned int>(
576 static_cast<unsigned int>(context.length()),
577 SSL_MAX_SSL_SESSION_ID_LENGTH));
581 * Match a name with a pattern. The pattern may include wildcard. A single
582 * wildcard "*" can match up to one component in the domain name.
584 * @param host Host name, typically the name of the remote host
585 * @param pattern Name retrieved from certificate
586 * @param size Size of "pattern"
587 * @return True, if "host" matches "pattern". False otherwise.
589 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
592 while (i < size && host[j] != '\0') {
593 if (toupper(pattern[i]) == toupper(host[j])) {
598 if (pattern[i] == '*') {
599 while (host[j] != '.' && host[j] != '\0') {
607 if (i == size && host[j] == '\0') {
613 int SSLContext::passwordCallback(char* password,
617 SSLContext* context = (SSLContext*)data;
618 if (context == nullptr || context->passwordCollector() == nullptr) {
621 std::string userPassword;
622 // call user defined password collector to get password
623 context->passwordCollector()->getPassword(userPassword, size);
624 auto const length = std::min(userPassword.size(), size_t(size));
625 std::memcpy(password, userPassword.data(), length);
629 void SSLContext::setSSLLockTypes(std::map<int, LockType> inLockTypes) {
630 folly::ssl::setLockTypes(inLockTypes);
633 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
634 void SSLContext::enableFalseStart() {
635 SSL_CTX_set_mode(ctx_, SSL_MODE_HANDSHAKE_CUTTHROUGH);
639 void SSLContext::initializeOpenSSL() {
643 void SSLContext::setOptions(long options) {
644 long newOpt = SSL_CTX_set_options(ctx_, options);
645 if ((newOpt & options) != options) {
646 throw std::runtime_error("SSL_CTX_set_options failed");
650 std::string SSLContext::getErrors(int errnoCopy) {
652 unsigned long errorCode;
656 while ((errorCode = ERR_get_error()) != 0) {
657 if (!errors.empty()) {
660 const char* reason = ERR_reason_error_string(errorCode);
661 if (reason == nullptr) {
662 snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
667 if (errors.empty()) {
668 errors = "error code: " + folly::to<std::string>(errnoCopy);
674 operator<<(std::ostream& os, const PasswordCollector& collector) {
675 os << collector.describe();