Commit d908fe0b authored by Andrew Huang's avatar Andrew Huang Committed by Facebook GitHub Bot

Add SSLContext to OpenSSL SSL_CTX ex data

Summary: Adding SSLContext members to SSL_CTX ex data to access them inside callbacks attached to SSL_CTX (e.g. session callbacks)

Reviewed By: yfeldblum, mingtaoy

Differential Revision: D21021353

fbshipit-source-id: 6aa3995f7d719ca7e87bad798876a92dd5765b86
parent aee68ea3
......@@ -27,6 +27,20 @@
// ---------------------------------------------------------------------
// SSLContext implementation
// ---------------------------------------------------------------------
namespace {
int getExDataIndex() {
static auto index =
SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
return index;
}
void setExData(folly::SSLContext* context, SSL_CTX* ctx) {
SSL_CTX_set_ex_data(ctx, getExDataIndex(), context);
}
} // namespace
namespace folly {
//
// For OpenSSL portability API
......@@ -78,6 +92,8 @@ SSLContext::SSLContext(SSLVersion version) {
sslAcceptRunner_ = std::make_unique<SSLAcceptRunner>();
setExData(this, ctx_);
#if FOLLY_OPENSSL_HAS_SNI
SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
SSL_CTX_set_tlsext_servername_arg(ctx_, this);
......@@ -143,6 +159,7 @@ void SSLContext::setServerECCurve(const std::string& curveName) {
}
SSLContext::SSLContext(SSL_CTX* ctx) : ctx_(ctx) {
setExData(this, ctx);
if (SSL_CTX_up_ref(ctx) == 0) {
throw std::runtime_error("Failed to increment SSL_CTX refcount");
}
......@@ -655,6 +672,10 @@ void SSLContext::enableTLS13() {
#endif
}
SSLContext* SSLContext::getFromSSLCtx(const SSL_CTX* ctx) {
return static_cast<SSLContext*>(SSL_CTX_get_ex_data(ctx, getExDataIndex()));
}
std::ostream& operator<<(std::ostream& os, const PasswordCollector& collector) {
os << collector.describe();
return os;
......
......@@ -559,6 +559,11 @@ class SSLContext {
*/
void enableTLS13();
/**
* Get SSLContext from the ex data of a SSL_CTX.
*/
static SSLContext* getFromSSLCtx(const SSL_CTX* ctx);
[[deprecated("Use folly::ssl::init")]] static void initializeOpenSSL();
protected:
......
......@@ -179,4 +179,15 @@ TEST_F(SSLContextTest, TestLoadCertificateChain) {
EXPECT_EQ(1, sk_X509_num(stack));
}
TEST_F(SSLContextTest, TestGetFromSSLCtx) {
// Positive test
SSLContext* contextPtr = SSLContext::getFromSSLCtx(ctx.getSSLCtx());
EXPECT_EQ(contextPtr, &ctx);
// Negative test
SSL_CTX* randomCtx = SSL_CTX_new(SSLv23_method());
EXPECT_EQ(nullptr, SSLContext::getFromSSLCtx(randomCtx));
SSL_CTX_free(randomCtx);
}
} // namespace folly
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment