proxygen
folly::SSLContext Class Reference

#include <SSLContext.h>

Inheritance diagram for folly::SSLContext:
wangle::ServerSSLContext

Classes

struct  NextProtocolsItem
 

Public Types

enum  SSLVersion { SSLv2, SSLv3, TLSv1, TLSv1_2 }
 
enum  SSLVerifyPeerEnum { USE_CTX, VERIFY, VERIFY_REQ_CLIENT_CERT, NO_VERIFY }
 
using ClientProtocolFilterCallback = bool(*)(unsigned char **, unsigned int *, const unsigned char *, unsigned int)
 

Public Member Functions

 SSLContext (SSLVersion version=TLSv1)
 
virtual ~SSLContext ()
 
virtual void ciphers (const std::string &ciphers)
 
virtual void setCiphersOrThrow (const std::string &ciphers)
 
template<typename Iterator >
void setCipherList (Iterator ibegin, Iterator iend)
 
template<typename Container >
void setCipherList (const Container &cipherList)
 
template<typename Value >
void setCipherList (const std::initializer_list< Value > &cipherList)
 
template<typename Iterator >
void setSignatureAlgorithms (Iterator ibegin, Iterator iend)
 
template<typename Container >
void setSignatureAlgorithms (const Container &sigalgs)
 
template<typename Value >
void setSignatureAlgorithms (const std::initializer_list< Value > &sigalgs)
 
void setClientECCurvesList (const std::vector< std::string > &ecCurves)
 
void setServerECCurve (const std::string &curveName)
 
void setX509VerifyParam (const ssl::X509VerifyParam &x509VerifyParam)
 
virtual void setVerificationOption (const SSLVerifyPeerEnum &verifyPeer)
 
virtual bool needsPeerVerification ()
 
virtual int getVerificationMode ()
 
virtual void authenticate (bool checkPeerCert, bool checkPeerName, const std::string &peerName=std::string())
 
virtual void loadCertificate (const char *path, const char *format="PEM")
 
virtual void loadCertificateFromBufferPEM (folly::StringPiece cert)
 
virtual void loadPrivateKey (const char *path, const char *format="PEM")
 
virtual void loadPrivateKeyFromBufferPEM (folly::StringPiece pkey)
 
virtual void loadCertKeyPairFromBufferPEM (folly::StringPiece cert, folly::StringPiece pkey)
 
virtual void loadCertKeyPairFromFiles (const char *certPath, const char *keyPath, const char *certFormat="PEM", const char *keyFormat="PEM")
 
virtual bool isCertKeyPairValid () const
 
virtual void loadTrustedCertificates (const char *path)
 
virtual void loadTrustedCertificates (X509_STORE *store)
 
virtual void loadClientCAList (const char *path)
 
virtual void passwordCollector (std::shared_ptr< PasswordCollector > collector)
 
virtual std::shared_ptr< PasswordCollectorpasswordCollector ()
 
SSL * createSSL () const
 
void setSessionCacheContext (const std::string &context)
 
void setOptions (long options)
 
SSL_CTX * getSSLCtx () const
 
bool checkPeerName ()
 
std::string peerFixedName ()
 
void sslAcceptRunner (std::unique_ptr< SSLAcceptRunner > runner)
 
const SSLAcceptRunnersslAcceptRunner ()
 

Static Public Member Functions

static std::string getErrors ()
 
static int getVerificationMode (const SSLVerifyPeerEnum &verifyPeer)
 
static std::string getErrors (int errnoCopy)
 
static bool matchName (const char *host, const char *pattern, int size)
 
static void initializeOpenSSL ()
 

Protected Attributes

SSL_CTX * ctx_
 

Static Private Member Functions

static int passwordCallback (char *password, int size, int, void *data)
 

Private Attributes

SSLVerifyPeerEnum verifyPeer_ {SSLVerifyPeerEnum::NO_VERIFY}
 
bool checkPeerName_
 
std::string peerFixedName_
 
std::shared_ptr< PasswordCollectorcollector_
 
ClientProtocolFilterCallback clientProtoFilter_ {nullptr}
 
std::unique_ptr< SSLAcceptRunnersslAcceptRunner_
 
std::string providedCiphersString_
 

Static Private Attributes

static bool initialized_
 

Detailed Description

Wrap OpenSSL SSL_CTX into a class.

Definition at line 89 of file SSLContext.h.

Member Typedef Documentation

using folly::SSLContext::ClientProtocolFilterCallback = bool (*)( unsigned char**, unsigned int*, const unsigned char*, unsigned int)

Definition at line 129 of file SSLContext.h.

Member Enumeration Documentation

Defines the way that peers are verified.

Enumerator
USE_CTX 
VERIFY 
VERIFY_REQ_CLIENT_CERT 
NO_VERIFY 

Definition at line 101 of file SSLContext.h.

101  {
102  // Used by AsyncSSLSocket to delegate to the SSLContext's setting
103  USE_CTX,
104  // For server side - request a client certificate and verify the
105  // certificate if it is sent. Does not fail if the client does not present
106  // a certificate.
107  // For client side - validates the server certificate or fails.
108  VERIFY,
109  // For server side - same as VERIFY but will fail if no certificate
110  // is sent.
111  // For client side - same as VERIFY.
113  // No verification is done for both server and client side.
114  NO_VERIFY
115  };
Enumerator
SSLv2 
SSLv3 
TLSv1 
TLSv1_2 

Definition at line 91 of file SSLContext.h.

91  {
92  SSLv2,
93  SSLv3,
94  TLSv1, // support TLS 1.0+
95  TLSv1_2, // support for only TLS 1.2+
96  };

Constructor & Destructor Documentation

folly::SSLContext::SSLContext ( SSLVersion  version = TLSv1)
explicit

Constructor.

Parameters
versionThe lowest or oldest SSL version to support.

Definition at line 36 of file SSLContext.cpp.

References ctx_, and folly::ssl::init().

36  {
38 
39  ctx_ = SSL_CTX_new(SSLv23_method());
40  if (ctx_ == nullptr) {
41  throw std::runtime_error("SSL_CTX_new: " + getErrors());
42  }
43 
44  int opt = 0;
45  switch (version) {
46  case TLSv1:
47  opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
48  break;
49  case SSLv3:
50  opt = SSL_OP_NO_SSLv2;
51  break;
52  case TLSv1_2:
53  opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
54  SSL_OP_NO_TLSv1_1;
55  break;
56  default:
57  // do nothing
58  break;
59  }
60  int newOpt = SSL_CTX_set_options(ctx_, opt);
61  DCHECK((newOpt & opt) == opt);
62 
63  SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
64 
65  checkPeerName_ = false;
66 
67  SSL_CTX_set_options(ctx_, SSL_OP_NO_COMPRESSION);
68 
69  sslAcceptRunner_ = std::make_unique<SSLAcceptRunner>();
70 
71 #if FOLLY_OPENSSL_HAS_SNI
72  SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
73  SSL_CTX_set_tlsext_servername_arg(ctx_, this);
74 #endif
75 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
void init()
Definition: Init.cpp:54
ProtocolVersion version
std::unique_ptr< SSLAcceptRunner > sslAcceptRunner_
Definition: SSLContext.h:572
folly::SSLContext::~SSLContext ( )
virtual

Definition at line 77 of file SSLContext.cpp.

References ctx_.

77  {
78  if (ctx_ != nullptr) {
79  SSL_CTX_free(ctx_);
80  ctx_ = nullptr;
81  }
82 
83 #if FOLLY_OPENSSL_HAS_ALPN
84  deleteNextProtocolsStrings();
85 #endif
86 }
SSL_CTX * ctx_
Definition: SSLContext.h:555

Member Function Documentation

void folly::SSLContext::authenticate ( bool  checkPeerCert,
bool  checkPeerName,
const std::string peerName = std::string() 
)
virtual

Enable/Disable authentication. Peer name validation can only be done if checkPeerCert is true.

Parameters
checkPeerCertIf true, require peer to present valid certificate
checkPeerNameIf true, validate that the certificate common name or alternate name(s) of peer matches the hostname used to connect.
peerNameIf non-empty, validate that the certificate common name of peer matches the given string (altername name(s) are not used in this case).

Definition at line 189 of file SSLContext.cpp.

References folly::Optional< Value >::clear(), ctx_, and mode.

192  {
193  int mode;
194  if (checkPeerCert) {
195  mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
196  SSL_VERIFY_CLIENT_ONCE;
198  peerFixedName_ = peerName;
199  } else {
200  mode = SSL_VERIFY_NONE;
201  checkPeerName_ = false; // can't check name without cert!
202  peerFixedName_.clear();
203  }
204  SSL_CTX_set_verify(ctx_, mode, nullptr);
205 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
bool checkPeerName()
Definition: SSLContext.h:515
folly::Optional< PskKeyExchangeMode > mode
std::string peerFixedName_
Definition: SSLContext.h:561
bool folly::SSLContext::checkPeerName ( )
inline

Definition at line 515 of file SSLContext.h.

515  {
516  return checkPeerName_;
517  }
void folly::SSLContext::ciphers ( const std::string ciphers)
virtual

Set default ciphers to be used in SSL handshake process.

Parameters
ciphersA list of ciphers to use for TLSv1.0

Definition at line 88 of file SSLContext.cpp.

88  {
90 }
virtual void setCiphersOrThrow(const std::string &ciphers)
Definition: SSLContext.cpp:145
virtual void ciphers(const std::string &ciphers)
Definition: SSLContext.cpp:88
SSL * folly::SSLContext::createSSL ( ) const

Create an SSL object from this context.

Definition at line 518 of file SSLContext.cpp.

References ctx_.

Referenced by folly::TEST_F().

518  {
519  SSL* ssl = SSL_new(ctx_);
520  if (ssl == nullptr) {
521  throw std::runtime_error("SSL_new: " + getErrors());
522  }
523  return ssl;
524 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
static std::string folly::SSLContext::getErrors ( )
inlinestatic

Convenience function to call getErrors() with the current errno value.

Make sure that you only call this when there was no intervening operation since the last OpenSSL error that may have changed the current errno value.

Definition at line 137 of file SSLContext.h.

References string, and version.

137  {
138  return getErrors(errno);
139  }
static std::string getErrors()
Definition: SSLContext.h:137
std::string folly::SSLContext::getErrors ( int  errnoCopy)
static

Examine OpenSSL's error stack, and return a string description of the errors.

This operation removes the errors from OpenSSL's error stack.

Definition at line 597 of file SSLContext.cpp.

References message, and string.

597  {
598  std::string errors;
599  unsigned long errorCode;
600  char message[256];
601 
602  errors.reserve(512);
603  while ((errorCode = ERR_get_error()) != 0) {
604  if (!errors.empty()) {
605  errors += "; ";
606  }
607  const char* reason = ERR_reason_error_string(errorCode);
608  if (reason == nullptr) {
609  snprintf(message, sizeof(message) - 1, "SSL error # %08lX", errorCode);
610  reason = message;
611  }
612  errors += reason;
613  }
614  if (errors.empty()) {
615  errors = "error code: " + folly::to<std::string>(errnoCopy);
616  }
617  return errors;
618 }
Definition: test.c:42
std::string message
Definition: SPDYCodec.cpp:133
const char * string
Definition: Conv.cpp:212
SSL_CTX* folly::SSLContext::getSSLCtx ( ) const
inline

Gets the underlying SSL_CTX for advanced usage

Definition at line 503 of file SSLContext.h.

References ctx_, and string.

Referenced by wangle::ServerSSLContext::setupSessionCache(), folly::AsyncSSLSocket::sslAccept(), wangle::SSLSessionCacheManager::SSLSessionCacheManager(), wangle::SSLSessionCacheManager::storeCacheRecord(), and TEST().

503  {
504  return ctx_;
505  }
SSL_CTX * ctx_
Definition: SSLContext.h:555
int folly::SSLContext::getVerificationMode ( const SSLVerifyPeerEnum verifyPeer)
static

Method to fetch Verification mode for a SSLVerifyPeerEnum. verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no context.

Parameters
verifyPeerSSLVerifyPeerEnum for which the flags need to to be returned
Returns
mode flags that can be used with SSL_set_verify

Definition at line 159 of file SSLContext.cpp.

References mode.

160  {
161  CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
162  int mode = SSL_VERIFY_NONE;
163  switch (verifyPeer) {
164  // case SSLVerifyPeerEnum::USE_CTX: // can't happen
165  // break;
166 
167  case SSLVerifyPeerEnum::VERIFY:
168  mode = SSL_VERIFY_PEER;
169  break;
170 
171  case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
172  mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
173  break;
174 
175  case SSLVerifyPeerEnum::NO_VERIFY:
176  mode = SSL_VERIFY_NONE;
177  break;
178 
179  default:
180  break;
181  }
182  return mode;
183 }
folly::Optional< PskKeyExchangeMode > mode
int folly::SSLContext::getVerificationMode ( )
virtual

Method to fetch Verification mode determined by the options set using setVerificationOption.

Returns
mode flags that can be used with SSL_set_verify

Definition at line 185 of file SSLContext.cpp.

Referenced by folly::AsyncSSLSocket::applyVerificationOptions().

185  {
187 }
virtual int getVerificationMode()
Definition: SSLContext.cpp:185
SSLVerifyPeerEnum verifyPeer_
Definition: SSLContext.h:558
void folly::SSLContext::initializeOpenSSL ( )
static

Definition at line 586 of file SSLContext.cpp.

References folly::ssl::init().

586  {
588 }
void init()
Definition: Init.cpp:54
bool folly::SSLContext::isCertKeyPairValid ( ) const
virtual

Call after both cert and key are loaded to check if cert matches key. Must call if private key is loaded before loading the cert. No need to call if cert is loaded first before private key.

Returns
true if matches, or false if mismatch.

Definition at line 316 of file SSLContext.cpp.

References ctx_.

Referenced by folly::TEST_F().

316  {
317  return SSL_CTX_check_private_key(ctx_) == 1;
318 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::loadCertificate ( const char *  path,
const char *  format = "PEM" 
)
virtual

Load server certificate.

Parameters
pathPath to the certificate file
formatCertificate file format

Definition at line 207 of file SSLContext.cpp.

References ctx_, and string.

Referenced by folly::TEST_F().

207  {
208  if (path == nullptr || format == nullptr) {
209  throw std::invalid_argument(
210  "loadCertificateChain: either <path> or <format> is nullptr");
211  }
212  if (strcmp(format, "PEM") == 0) {
213  if (SSL_CTX_use_certificate_chain_file(ctx_, path) != 1) {
214  int errnoCopy = errno;
215  std::string reason("SSL_CTX_use_certificate_chain_file: ");
216  reason.append(path);
217  reason.append(": ");
218  reason.append(getErrors(errnoCopy));
219  throw std::runtime_error(reason);
220  }
221  } else {
222  throw std::runtime_error(
223  "Unsupported certificate format: " + std::string(format));
224  }
225 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
const char * string
Definition: Conv.cpp:212
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
void folly::SSLContext::loadCertificateFromBufferPEM ( folly::StringPiece  cert)
virtual

Load server certificate from memory.

Parameters
certA PEM formatted certificate

Definition at line 227 of file SSLContext.cpp.

References ctx_, folly::Range< Iter >::data(), and folly::Range< Iter >::size().

Referenced by folly::TEST_F().

227  {
228  if (cert.data() == nullptr) {
229  throw std::invalid_argument("loadCertificate: <cert> is nullptr");
230  }
231 
232  ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
233  if (bio == nullptr) {
234  throw std::runtime_error("BIO_new: " + getErrors());
235  }
236 
237  int written = BIO_write(bio.get(), cert.data(), int(cert.size()));
238  if (written <= 0 || static_cast<unsigned>(written) != cert.size()) {
239  throw std::runtime_error("BIO_write: " + getErrors());
240  }
241 
242  ssl::X509UniquePtr x509(
243  PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
244  if (x509 == nullptr) {
245  throw std::runtime_error("PEM_read_bio_X509: " + getErrors());
246  }
247 
248  if (SSL_CTX_use_certificate(ctx_, x509.get()) == 0) {
249  throw std::runtime_error("SSL_CTX_use_certificate: " + getErrors());
250  }
251 }
static std::string getErrors()
Definition: SSLContext.h:137
std::unique_ptr< X509, X509Deleter > X509UniquePtr
std::unique_ptr< BIO, BioDeleter > BioUniquePtr
SSL_CTX * ctx_
Definition: SSLContext.h:555
constexpr size_type size() const
Definition: Range.h:431
constexpr Iter data() const
Definition: Range.h:446
void folly::SSLContext::loadCertKeyPairFromBufferPEM ( folly::StringPiece  cert,
folly::StringPiece  pkey 
)
virtual

Load cert and key from PEM buffers. Guaranteed to throw if cert and private key mismatch so no need to call isCertKeyPairValid.

Parameters
certA PEM formatted certificate
pkeyA PEM formatted key

Definition at line 294 of file SSLContext.cpp.

Referenced by folly::TEST_F().

296  {
299  if (!isCertKeyPairValid()) {
300  throw std::runtime_error("SSL certificate and private key do not match");
301  }
302 }
virtual void loadCertificateFromBufferPEM(folly::StringPiece cert)
Definition: SSLContext.cpp:227
virtual bool isCertKeyPairValid() const
Definition: SSLContext.cpp:316
virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey)
Definition: SSLContext.cpp:268
void folly::SSLContext::loadCertKeyPairFromFiles ( const char *  certPath,
const char *  keyPath,
const char *  certFormat = "PEM",
const char *  keyFormat = "PEM" 
)
virtual

Load cert and key from files. Guaranteed to throw if cert and key mismatch. Equivalent to calling loadCertificate() and loadPrivateKey().

Parameters
certPathPath to the certificate file
keyPathPath to the private key file
certFormatCertificate file format
keyFormatPrivate key file format

Definition at line 304 of file SSLContext.cpp.

Referenced by folly::TEST_F().

308  {
309  loadCertificate(certPath, certFormat);
310  loadPrivateKey(keyPath, keyFormat);
311  if (!isCertKeyPairValid()) {
312  throw std::runtime_error("SSL certificate and private key do not match");
313  }
314 }
virtual bool isCertKeyPairValid() const
Definition: SSLContext.cpp:316
virtual void loadPrivateKey(const char *path, const char *format="PEM")
Definition: SSLContext.cpp:253
virtual void loadCertificate(const char *path, const char *format="PEM")
Definition: SSLContext.cpp:207
void folly::SSLContext::loadClientCAList ( const char *  path)
virtual

Load a client CA list for validating clients

Definition at line 334 of file SSLContext.cpp.

References ctx_.

334  {
335  auto clientCAs = SSL_load_client_CA_file(path);
336  if (clientCAs == nullptr) {
337  LOG(ERROR) << "Unable to load ca file: " << path << " " << getErrors();
338  return;
339  }
340  SSL_CTX_set_client_CA_list(ctx_, clientCAs);
341 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::loadPrivateKey ( const char *  path,
const char *  format = "PEM" 
)
virtual

Load private key.

Parameters
pathPath to the private key file
formatPrivate key file format

Definition at line 253 of file SSLContext.cpp.

References ctx_, and string.

Referenced by folly::TEST_F().

253  {
254  if (path == nullptr || format == nullptr) {
255  throw std::invalid_argument(
256  "loadPrivateKey: either <path> or <format> is nullptr");
257  }
258  if (strcmp(format, "PEM") == 0) {
259  if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
260  throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
261  }
262  } else {
263  throw std::runtime_error(
264  "Unsupported private key format: " + std::string(format));
265  }
266 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
const char * string
Definition: Conv.cpp:212
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
void folly::SSLContext::loadPrivateKeyFromBufferPEM ( folly::StringPiece  pkey)
virtual

Load private key from memory.

Parameters
pkeyA PEM formatted key

Definition at line 268 of file SSLContext.cpp.

References ctx_, folly::Range< Iter >::data(), and folly::Range< Iter >::size().

Referenced by folly::TEST_F().

268  {
269  if (pkey.data() == nullptr) {
270  throw std::invalid_argument("loadPrivateKey: <pkey> is nullptr");
271  }
272 
273  ssl::BioUniquePtr bio(BIO_new(BIO_s_mem()));
274  if (bio == nullptr) {
275  throw std::runtime_error("BIO_new: " + getErrors());
276  }
277 
278  int written = BIO_write(bio.get(), pkey.data(), int(pkey.size()));
279  if (written <= 0 || static_cast<unsigned>(written) != pkey.size()) {
280  throw std::runtime_error("BIO_write: " + getErrors());
281  }
282 
284  PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
285  if (key == nullptr) {
286  throw std::runtime_error("PEM_read_bio_PrivateKey: " + getErrors());
287  }
288 
289  if (SSL_CTX_use_PrivateKey(ctx_, key.get()) == 0) {
290  throw std::runtime_error("SSL_CTX_use_PrivateKey: " + getErrors());
291  }
292 }
static std::string getErrors()
Definition: SSLContext.h:137
std::unique_ptr< BIO, BioDeleter > BioUniquePtr
SSL_CTX * ctx_
Definition: SSLContext.h:555
constexpr size_type size() const
Definition: Range.h:431
std::unique_ptr< EVP_PKEY, EvpPkeyDeleter > EvpPkeyUniquePtr
constexpr Iter data() const
Definition: Range.h:446
void folly::SSLContext::loadTrustedCertificates ( const char *  path)
virtual

Load trusted certificates from specified file.

Parameters
pathPath to trusted certificate file

Definition at line 320 of file SSLContext.cpp.

References ctx_.

320  {
321  if (path == nullptr) {
322  throw std::invalid_argument("loadTrustedCertificates: <path> is nullptr");
323  }
324  if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
325  throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
326  }
327  ERR_clear_error();
328 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::loadTrustedCertificates ( X509_STORE *  store)
virtual

Load trusted certificates from specified X509 certificate store.

Parameters
storeX509 certificate store.

Definition at line 330 of file SSLContext.cpp.

References ctx_.

330  {
331  SSL_CTX_set_cert_store(ctx_, store);
332 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
bool folly::SSLContext::matchName ( const char *  host,
const char *  pattern,
int  size 
)
static

Helper to match a hostname versus a pattern.

Match a name with a pattern. The pattern may include wildcard. A single wildcard "*" can match up to one component in the domain name.

Parameters
hostHost name, typically the name of the remote host
patternName retrieved from certificate
sizeSize of "pattern"
Returns
True, if "host" matches "pattern". False otherwise.

Definition at line 543 of file SSLContext.cpp.

References i.

543  {
544  bool match = false;
545  int i = 0, j = 0;
546  while (i < size && host[j] != '\0') {
547  if (toupper(pattern[i]) == toupper(host[j])) {
548  i++;
549  j++;
550  continue;
551  }
552  if (pattern[i] == '*') {
553  while (host[j] != '.' && host[j] != '\0') {
554  j++;
555  }
556  i++;
557  continue;
558  }
559  break;
560  }
561  if (i == size && host[j] == '\0') {
562  match = true;
563  }
564  return match;
565 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
virtual bool folly::SSLContext::needsPeerVerification ( )
inlinevirtual

Method to check if peer verfication is set.

Returns
true if peer verification is required.

Definition at line 248 of file SSLContext.h.

References folly::format(), and string.

248  {
249  return (
250  verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
251  verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
252  }
SSLVerifyPeerEnum verifyPeer_
Definition: SSLContext.h:558
int folly::SSLContext::passwordCallback ( char *  password,
int  size,
int  ,
void *  data 
)
staticprivate

Definition at line 567 of file SSLContext.cpp.

References context, ctx_, min, passwordCollector(), and string.

567  {
569  if (context == nullptr || context->passwordCollector() == nullptr) {
570  return 0;
571  }
572  std::string userPassword;
573  // call user defined password collector to get password
574  context->passwordCollector()->getPassword(userPassword, size);
575  auto const length = std::min(userPassword.size(), size_t(size));
576  std::memcpy(password, userPassword.data(), length);
577  return int(length);
578 }
context
Definition: CMakeCache.txt:563
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
LogLevel min
Definition: LogLevel.cpp:30
constexpr auto data(C &c) -> decltype(c.data())
Definition: Access.h:71
SSLContext(SSLVersion version=TLSv1)
Definition: SSLContext.cpp:36
const char * string
Definition: Conv.cpp:212
void folly::SSLContext::passwordCollector ( std::shared_ptr< PasswordCollector collector)
virtual

Override default OpenSSL password collector.

Parameters
collectorInstance of user defined password collector

Definition at line 343 of file SSLContext.cpp.

References context, ctx_, folly::data(), i, fizz::passwordCallback(), rng, and uint8_t.

Referenced by passwordCallback().

344  {
345  if (collector == nullptr) {
346  LOG(ERROR) << "passwordCollector: ignore invalid password collector";
347  return;
348  }
349  collector_ = collector;
350  SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
351  SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
352 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
std::shared_ptr< PasswordCollector > collector_
Definition: SSLContext.h:562
static int passwordCallback(char *password, int size, int, void *data)
Definition: SSLContext.cpp:567
virtual std::shared_ptr<PasswordCollector> folly::SSLContext::passwordCollector ( )
inlinevirtual

Obtain password collector.

Returns
User defined password collector

Definition at line 379 of file SSLContext.h.

References context, and string.

379  {
380  return collector_;
381  }
std::shared_ptr< PasswordCollector > collector_
Definition: SSLContext.h:562
std::string folly::SSLContext::peerFixedName ( )
inline

Definition at line 518 of file SSLContext.h.

518  {
519  return peerFixedName_;
520  }
std::string peerFixedName_
Definition: SSLContext.h:561
template<typename Iterator >
void folly::SSLContext::setCipherList ( Iterator  ibegin,
Iterator  iend 
)
inline

Set default ciphers to be used in SSL handshake process.

Definition at line 167 of file SSLContext.h.

References folly::join(), and string.

Referenced by folly::ssl::setCipherSuites().

167  {
168  if (ibegin != iend) {
169  std::string opensslCipherList;
170  folly::join(":", ibegin, iend, opensslCipherList);
171  setCiphersOrThrow(opensslCipherList);
172  }
173  }
virtual void setCiphersOrThrow(const std::string &ciphers)
Definition: SSLContext.cpp:145
const char * string
Definition: Conv.cpp:212
void join(const Delim &delimiter, Iterator begin, Iterator end, String &output)
Definition: String-inl.h:498
template<typename Container >
void folly::SSLContext::setCipherList ( const Container &  cipherList)
inline

Definition at line 176 of file SSLContext.h.

References folly::test::begin(), and folly::test::end().

176  {
177  using namespace std;
178  setCipherList(begin(cipherList), end(cipherList));
179  }
void setCipherList(Iterator ibegin, Iterator iend)
Definition: SSLContext.h:167
STL namespace.
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
template<typename Value >
void folly::SSLContext::setCipherList ( const std::initializer_list< Value > &  cipherList)
inline

Definition at line 182 of file SSLContext.h.

182  {
183  setCipherList(cipherList.begin(), cipherList.end());
184  }
void setCipherList(Iterator ibegin, Iterator iend)
Definition: SSLContext.h:167
void folly::SSLContext::setCiphersOrThrow ( const std::string ciphers)
virtual

Low-level method that attempts to set the provided ciphers on the SSL_CTX object, and throws if something goes wrong.

Definition at line 145 of file SSLContext.cpp.

References ctx_.

145  {
146  int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
147  if (rc == 0) {
148  throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
149  }
151 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
virtual void ciphers(const std::string &ciphers)
Definition: SSLContext.cpp:88
std::string providedCiphersString_
Definition: SSLContext.h:625
void folly::SSLContext::setClientECCurvesList ( const std::vector< std::string > &  ecCurves)

Sets the list of EC curves supported by the client.

Parameters
ecCurvesA list of ec curves, eg: P-256

Definition at line 92 of file SSLContext.cpp.

References ctx_, folly::join(), and string.

Referenced by folly::ssl::SSLCommonOptions::setClientOptions().

93  {
94  if (ecCurves.size() == 0) {
95  return;
96  }
97 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
98  std::string ecCurvesList;
99  join(":", ecCurves, ecCurvesList);
100  int rc = SSL_CTX_set1_curves_list(ctx_, ecCurvesList.c_str());
101  if (rc == 0) {
102  throw std::runtime_error("SSL_CTX_set1_curves_list " + getErrors());
103  }
104 #endif
105 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
const char * string
Definition: Conv.cpp:212
void join(const Delim &delimiter, Iterator begin, Iterator end, String &output)
Definition: String-inl.h:498
void folly::SSLContext::setOptions ( long  options)

Set the options on the SSL_CTX object.

Definition at line 590 of file SSLContext.cpp.

References ctx_.

Referenced by wangle::ServerSSLContext::setupTicketManager().

590  {
591  long newOpt = SSL_CTX_set_options(ctx_, options);
592  if ((newOpt & options) != options) {
593  throw std::runtime_error("SSL_CTX_set_options failed");
594  }
595 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::setServerECCurve ( const std::string curveName)

Method to add support for a specific elliptic curve encryption algorithm.

Parameters
curveNameThe name of the ec curve to support, eg: prime256v1.

Definition at line 107 of file SSLContext.cpp.

References ctx_, and folly::FATAL.

107  {
108 #if OPENSSL_VERSION_NUMBER >= 0x0090800fL && !defined(OPENSSL_NO_ECDH)
109  EC_KEY* ecdh = nullptr;
110  int nid;
111 
112  /*
113  * Elliptic-Curve Diffie-Hellman parameters are either "named curves"
114  * from RFC 4492 section 5.1.1, or explicitly described curves over
115  * binary fields. OpenSSL only supports the "named curves", which provide
116  * maximum interoperability.
117  */
118 
119  nid = OBJ_sn2nid(curveName.c_str());
120  if (nid == 0) {
121  LOG(FATAL) << "Unknown curve name:" << curveName.c_str();
122  }
123  ecdh = EC_KEY_new_by_curve_name(nid);
124  if (ecdh == nullptr) {
125  LOG(FATAL) << "Unable to create curve:" << curveName.c_str();
126  }
127 
128  SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
129  EC_KEY_free(ecdh);
130 #else
131  throw std::runtime_error("Elliptic curve encryption not allowed");
132 #endif
133 }
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::setSessionCacheContext ( const std::string context)

Sets the namespace to use for sessions created from this context.

Definition at line 526 of file SSLContext.cpp.

References ctx_.

Referenced by wangle::ServerSSLContext::ServerSSLContext(), and wangle::SSLSessionCacheManager::SSLSessionCacheManager().

526  {
527  SSL_CTX_set_session_id_context(
528  ctx_,
529  reinterpret_cast<const unsigned char*>(context.data()),
530  std::min<unsigned int>(
531  static_cast<unsigned int>(context.length()), SSL_MAX_SID_CTX_LENGTH));
532 }
context
Definition: CMakeCache.txt:563
SSL_CTX * ctx_
Definition: SSLContext.h:555
template<typename Iterator >
void folly::SSLContext::setSignatureAlgorithms ( Iterator  ibegin,
Iterator  iend 
)
inline

Sets the signature algorithms to be used during SSL negotiation for TLS1.2+.

Definition at line 192 of file SSLContext.h.

References ctx_, folly::join(), and string.

Referenced by folly::ssl::setSignatureAlgorithms().

192  {
193  if (ibegin != iend) {
194 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
195  std::string opensslSigAlgsList;
196  join(":", ibegin, iend, opensslSigAlgsList);
197  if (!SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str())) {
198  throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
199  }
200 #endif
201  }
202  }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
const char * string
Definition: Conv.cpp:212
void join(const Delim &delimiter, Iterator begin, Iterator end, String &output)
Definition: String-inl.h:498
template<typename Container >
void folly::SSLContext::setSignatureAlgorithms ( const Container &  sigalgs)
inline

Definition at line 205 of file SSLContext.h.

References folly::test::begin(), folly::test::end(), and folly::ssl::setSignatureAlgorithms().

205  {
206  using namespace std;
207  setSignatureAlgorithms(begin(sigalgs), end(sigalgs));
208  }
STL namespace.
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
void setSignatureAlgorithms(Iterator ibegin, Iterator iend)
Definition: SSLContext.h:192
template<typename Value >
void folly::SSLContext::setSignatureAlgorithms ( const std::initializer_list< Value > &  sigalgs)
inline

Definition at line 211 of file SSLContext.h.

References folly::ssl::setSignatureAlgorithms(), and string.

211  {
212  setSignatureAlgorithms(sigalgs.begin(), sigalgs.end());
213  }
void setSignatureAlgorithms(Iterator ibegin, Iterator iend)
Definition: SSLContext.h:192
void folly::SSLContext::setVerificationOption ( const SSLVerifyPeerEnum verifyPeer)
virtual

Method to set verification option in the context object.

Parameters
verifyPeerSSLVerifyPeerEnum indicating the verification method to use.

Definition at line 153 of file SSLContext.cpp.

154  {
155  CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
156  verifyPeer_ = verifyPeer;
157 }
SSLVerifyPeerEnum verifyPeer_
Definition: SSLContext.h:558
void folly::SSLContext::setX509VerifyParam ( const ssl::X509VerifyParam x509VerifyParam)

Sets an x509 verification param on the context.

Definition at line 135 of file SSLContext.cpp.

References ctx_.

Referenced by folly::ssl::SSLCommonOptions::setClientOptions().

136  {
137  if (!x509VerifyParam) {
138  return;
139  }
140  if (SSL_CTX_set1_param(ctx_, x509VerifyParam.get()) != 1) {
141  throw std::runtime_error("SSL_CTX_set1_param " + getErrors());
142  }
143 }
static std::string getErrors()
Definition: SSLContext.h:137
SSL_CTX * ctx_
Definition: SSLContext.h:555
void folly::SSLContext::sslAcceptRunner ( std::unique_ptr< SSLAcceptRunner runner)
inline

Sets the runner used for SSL_accept. If none is given, the accept will be done directly.

Definition at line 535 of file SSLContext.h.

References folly::gen::move.

535  {
536  if (nullptr == runner) {
537  LOG(ERROR) << "Ignore invalid runner";
538  return;
539  }
540  sslAcceptRunner_ = std::move(runner);
541  }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::unique_ptr< SSLAcceptRunner > sslAcceptRunner_
Definition: SSLContext.h:572
const SSLAcceptRunner* folly::SSLContext::sslAcceptRunner ( )
inline

Definition at line 543 of file SSLContext.h.

References folly::size().

543  {
544  return sslAcceptRunner_.get();
545  }
std::unique_ptr< SSLAcceptRunner > sslAcceptRunner_
Definition: SSLContext.h:572

Member Data Documentation

bool folly::SSLContext::checkPeerName_
private

Definition at line 560 of file SSLContext.h.

ClientProtocolFilterCallback folly::SSLContext::clientProtoFilter_ {nullptr}
private

Definition at line 568 of file SSLContext.h.

std::shared_ptr<PasswordCollector> folly::SSLContext::collector_
private

Definition at line 562 of file SSLContext.h.

SSL_CTX* folly::SSLContext::ctx_
protected

Definition at line 555 of file SSLContext.h.

bool folly::SSLContext::initialized_
staticprivate

Definition at line 570 of file SSLContext.h.

std::string folly::SSLContext::peerFixedName_
private

Definition at line 561 of file SSLContext.h.

std::string folly::SSLContext::providedCiphersString_
private

Definition at line 625 of file SSLContext.h.

std::unique_ptr<SSLAcceptRunner> folly::SSLContext::sslAcceptRunner_
private

Definition at line 572 of file SSLContext.h.

SSLVerifyPeerEnum folly::SSLContext::verifyPeer_ {SSLVerifyPeerEnum::NO_VERIFY}
private

Definition at line 558 of file SSLContext.h.


The documentation for this class was generated from the following files: