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.
27 #include <glog/logging.h>
29 #ifndef FOLLY_NO_CONFIG
30 #include <folly/folly-config.h>
33 #include <folly/Portability.h>
34 #include <folly/Range.h>
35 #include <folly/String.h>
36 #include <folly/io/async/ssl/OpenSSLUtils.h>
37 #include <folly/portability/OpenSSL.h>
38 #include <folly/ssl/OpenSSLLockTypes.h>
39 #include <folly/ssl/OpenSSLPtrTypes.h>
44 * Override the default password collector.
46 class PasswordCollector {
48 virtual ~PasswordCollector() = default;
50 * Interface for customizing how to collect private key password.
52 * By default, OpenSSL prints a prompt on screen and request for password
53 * while loading private key. To implement a custom password collector,
54 * implement this interface and register it with TSSLSocketFactory.
56 * @param password Pass collected password back to OpenSSL
57 * @param size Maximum length of password including nullptr character
59 virtual void getPassword(std::string& password, int size) const = 0;
62 * Return a description of this collector for logging purposes
64 virtual std::string describe() const = 0;
68 * Wrap OpenSSL SSL_CTX into a class.
75 TLSv1, // support TLS 1.0+
76 TLSv1_2, // support for only TLS 1.2+
80 * Defines the way that peers are verified.
82 enum SSLVerifyPeerEnum {
83 // Used by AsyncSSLSocket to delegate to the SSLContext's setting
85 // For server side - request a client certificate and verify the
86 // certificate if it is sent. Does not fail if the client does not present
88 // For client side - validates the server certificate or fails.
90 // For server side - same as VERIFY but will fail if no certificate
92 // For client side - same as VERIFY.
93 VERIFY_REQ_CLIENT_CERT,
94 // No verification is done for both server and client side.
98 struct NextProtocolsItem {
99 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
100 weight(wt), protocols(ptcls) {}
102 std::list<std::string> protocols;
105 // Function that selects a client protocol given the server's list
106 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
107 const unsigned char*, unsigned int);
110 * Convenience function to call getErrors() with the current errno value.
112 * Make sure that you only call this when there was no intervening operation
113 * since the last OpenSSL error that may have changed the current errno value.
115 static std::string getErrors() {
116 return getErrors(errno);
122 * @param version The lowest or oldest SSL version to support.
124 explicit SSLContext(SSLVersion version = TLSv1);
125 virtual ~SSLContext();
128 * Set default ciphers to be used in SSL handshake process.
130 * @param ciphers A list of ciphers to use for TLSv1.0
132 virtual void ciphers(const std::string& ciphers);
135 * Low-level method that attempts to set the provided ciphers on the
136 * SSL_CTX object, and throws if something goes wrong.
138 virtual void setCiphersOrThrow(const std::string& ciphers);
141 * Set default ciphers to be used in SSL handshake process.
144 template <typename Iterator>
145 void setCipherList(Iterator ibegin, Iterator iend) {
146 if (ibegin != iend) {
147 std::string opensslCipherList;
148 folly::join(":", ibegin, iend, opensslCipherList);
149 setCiphersOrThrow(opensslCipherList);
153 template <typename Container>
154 void setCipherList(const Container& cipherList) {
156 setCipherList(begin(cipherList), end(cipherList));
159 template <typename Value>
160 void setCipherList(const std::initializer_list<Value>& cipherList) {
161 setCipherList(cipherList.begin(), cipherList.end());
165 * Sets the signature algorithms to be used during SSL negotiation
169 template <typename Iterator>
170 void setSignatureAlgorithms(Iterator ibegin, Iterator iend) {
171 if (ibegin != iend) {
172 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL
173 std::string opensslSigAlgsList;
174 join(":", ibegin, iend, opensslSigAlgsList);
175 if (!SSL_CTX_set1_sigalgs_list(ctx_, opensslSigAlgsList.c_str())) {
176 throw std::runtime_error("SSL_CTX_set1_sigalgs_list " + getErrors());
182 template <typename Container>
183 void setSignatureAlgorithms(const Container& sigalgs) {
185 setSignatureAlgorithms(begin(sigalgs), end(sigalgs));
188 template <typename Value>
189 void setSignatureAlgorithms(const std::initializer_list<Value>& sigalgs) {
190 setSignatureAlgorithms(sigalgs.begin(), sigalgs.end());
194 * Sets the list of EC curves supported by the client.
196 * @param ecCurves A list of ec curves, eg: P-256
198 void setClientECCurvesList(const std::vector<std::string>& ecCurves);
201 * Method to add support for a specific elliptic curve encryption algorithm.
203 * @param curveName: The name of the ec curve to support, eg: prime256v1.
205 void setServerECCurve(const std::string& curveName);
208 * Sets an x509 verification param on the context.
210 void setX509VerifyParam(const ssl::X509VerifyParam& x509VerifyParam);
213 * Method to set verification option in the context object.
215 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
218 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
221 * Method to check if peer verfication is set.
223 * @return true if peer verification is required.
226 virtual bool needsPeerVerification() {
227 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
228 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
232 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
233 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
236 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
239 * @return mode flags that can be used with SSL_set_verify
241 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
244 * Method to fetch Verification mode determined by the options
245 * set using setVerificationOption.
247 * @return mode flags that can be used with SSL_set_verify
249 virtual int getVerificationMode();
252 * Enable/Disable authentication. Peer name validation can only be done
253 * if checkPeerCert is true.
255 * @param checkPeerCert If true, require peer to present valid certificate
256 * @param checkPeerName If true, validate that the certificate common name
257 * or alternate name(s) of peer matches the hostname
259 * @param peerName If non-empty, validate that the certificate common
260 * name of peer matches the given string (altername
261 * name(s) are not used in this case).
263 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
264 const std::string& peerName = std::string());
266 * Load server certificate.
268 * @param path Path to the certificate file
269 * @param format Certificate file format
271 virtual void loadCertificate(const char* path, const char* format = "PEM");
273 * Load server certificate from memory.
275 * @param cert A PEM formatted certificate
277 virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
282 * @param path Path to the private key file
283 * @param format Private key file format
285 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
287 * Load private key from memory.
289 * @param pkey A PEM formatted key
291 virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
294 * Load cert and key from PEM buffers. Guaranteed to throw if cert and
295 * private key mismatch so no need to call isCertKeyPairValid.
297 * @param cert A PEM formatted certificate
298 * @param pkey A PEM formatted key
300 virtual void loadCertKeyPairFromBufferPEM(
301 folly::StringPiece cert,
302 folly::StringPiece pkey);
305 * Load cert and key from files. Guaranteed to throw if cert and key mismatch.
306 * Equivalent to calling loadCertificate() and loadPrivateKey().
308 * @param certPath Path to the certificate file
309 * @param keyPath Path to the private key file
310 * @param certFormat Certificate file format
311 * @param keyFormat Private key file format
313 virtual void loadCertKeyPairFromFiles(
314 const char* certPath,
316 const char* certFormat = "PEM",
317 const char* keyFormat = "PEM");
320 * Call after both cert and key are loaded to check if cert matches key.
321 * Must call if private key is loaded before loading the cert.
322 * No need to call if cert is loaded first before private key.
323 * @return true if matches, or false if mismatch.
325 virtual bool isCertKeyPairValid() const;
328 * Load trusted certificates from specified file.
330 * @param path Path to trusted certificate file
332 virtual void loadTrustedCertificates(const char* path);
334 * Load trusted certificates from specified X509 certificate store.
336 * @param store X509 certificate store.
338 virtual void loadTrustedCertificates(X509_STORE* store);
340 * Load a client CA list for validating clients
342 virtual void loadClientCAList(const char* path);
344 * Override default OpenSSL password collector.
346 * @param collector Instance of user defined password collector
348 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
350 * Obtain password collector.
352 * @return User defined password collector
354 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
357 #if FOLLY_OPENSSL_HAS_SNI
359 * Provide SNI support
361 enum ServerNameCallbackResult {
363 SERVER_NAME_NOT_FOUND,
364 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
367 * Callback function from openssl to give the application a
368 * chance to check the tlsext_hostname just right after parsing
369 * the Client Hello or Server Hello message.
371 * It is for the server to switch the SSL to another SSL_CTX
372 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
374 * If the ServerNameCallback returns:
376 * server: Send a tlsext_hostname in the Server Hello
378 * SERVER_NAME_NOT_FOUND:
379 * server: Does not send a tlsext_hostname in Server Hello
380 * and continue the handshake.
382 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
383 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
386 * Quote from RFC 6066:
388 * If the server understood the ClientHello extension but
389 * does not recognize the server name, the server SHOULD take one of two
390 * actions: either abort the handshake by sending a fatal-level
391 * unrecognized_name(112) alert or continue the handshake. It is NOT
392 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
393 * because the client's behavior in response to warning-level alerts is
399 * Set the ServerNameCallback
401 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
402 virtual void setServerNameCallback(const ServerNameCallback& cb);
405 * Generic callbacks that are run after we get the Client Hello (right
406 * before we run the ServerNameCallback)
408 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
409 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
410 #endif // FOLLY_OPENSSL_HAS_SNI
413 * Create an SSL object from this context.
415 SSL* createSSL() const;
418 * Sets the namespace to use for sessions created from this context.
420 void setSessionCacheContext(const std::string& context);
423 * Set the options on the SSL_CTX object.
425 void setOptions(long options);
427 enum class NextProtocolType : uint8_t {
433 #ifdef OPENSSL_NPN_NEGOTIATED
435 * Set the list of protocols that this SSL context supports. In server
436 * mode, this is the list of protocols that will be advertised for Next
437 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
438 * (ALPN). In client mode, the first protocol advertised by the server
439 * that is also on this list is chosen. Invoking this function with a list
440 * of length zero causes NPN to be disabled.
442 * @param protocols List of protocol names. This method makes a copy,
443 * so the caller needn't keep the list in scope after
444 * the call completes. The list must have at least
445 * one element to enable NPN. Each element must have
446 * a string length < 256.
447 * @param protocolType What type of protocol negotiation to support.
448 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
450 bool setAdvertisedNextProtocols(
451 const std::list<std::string>& protocols,
452 NextProtocolType protocolType = NextProtocolType::ANY);
454 * Set weighted list of lists of protocols that this SSL context supports.
455 * In server mode, each element of the list contains a list of protocols that
456 * could be advertised for Next Protocol Negotiation (NPN) or Application
457 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
458 * advertised to a client is selected randomly, based on weights of elements.
459 * Client mode doesn't support randomized NPN/ALPN, so this list should
460 * contain only 1 element. The first protocol advertised by the server that
461 * is also on the list of protocols of this element is chosen. Invoking this
462 * function with a list of length zero causes NPN/ALPN to be disabled.
464 * @param items List of NextProtocolsItems, Each item contains a list of
465 * protocol names and weight. After the call of this fucntion
466 * each non-empty list of protocols will be advertised with
467 * probability weight/sum_of_weights. This method makes a copy,
468 * so the caller needn't keep the list in scope after the call
469 * completes. The list must have at least one element with
470 * non-zero weight and non-empty protocols list to enable NPN.
471 * Each name of the protocol must have a string length < 256.
472 * @param protocolType What type of protocol negotiation to support.
473 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
475 bool setRandomizedAdvertisedNextProtocols(
476 const std::list<NextProtocolsItem>& items,
477 NextProtocolType protocolType = NextProtocolType::ANY);
479 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
480 clientProtoFilter_ = cb;
483 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
484 return clientProtoFilter_;
488 * Disables NPN on this SSL context.
490 void unsetNextProtocols();
491 void deleteNextProtocolsStrings();
492 #endif // OPENSSL_NPN_NEGOTIATED
495 * Gets the underlying SSL_CTX for advanced usage
497 SSL_CTX *getSSLCtx() const {
502 * Examine OpenSSL's error stack, and return a string description of the
505 * This operation removes the errors from OpenSSL's error stack.
507 static std::string getErrors(int errnoCopy);
509 bool checkPeerName() { return checkPeerName_; }
510 std::string peerFixedName() { return peerFixedName_; }
512 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
514 * Enable TLS false start, saving a roundtrip for full handshakes. Will only
515 * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
518 void enableFalseStart();
522 * Helper to match a hostname versus a pattern.
524 static bool matchName(const char* host, const char* pattern, int size);
526 FOLLY_DEPRECATED("Use folly::ssl::init")
527 static void initializeOpenSSL();
533 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
536 std::string peerFixedName_;
537 std::shared_ptr<PasswordCollector> collector_;
538 #if FOLLY_OPENSSL_HAS_SNI
539 ServerNameCallback serverNameCb_;
540 std::vector<ClientHelloCallback> clientHelloCbs_;
543 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
545 static bool initialized_;
547 #ifdef OPENSSL_NPN_NEGOTIATED
549 struct AdvertisedNextProtocolsItem {
550 unsigned char* protocols;
555 * Wire-format list of advertised protocols for use in NPN.
557 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
558 std::vector<int> advertisedNextProtocolWeights_;
559 std::discrete_distribution<int> nextProtocolDistribution_;
561 static int advertisedNextProtocolCallback(SSL* ssl,
562 const unsigned char** out, unsigned int* outlen, void* data);
563 static int selectNextProtocolCallback(
564 SSL* ssl, unsigned char **out, unsigned char *outlen,
565 const unsigned char *server, unsigned int server_len, void *args);
567 #if FOLLY_OPENSSL_HAS_ALPN
568 static int alpnSelectCallback(SSL* ssl,
569 const unsigned char** out,
570 unsigned char* outlen,
571 const unsigned char* in,
575 size_t pickNextProtocols();
577 #endif // OPENSSL_NPN_NEGOTIATED
579 static int passwordCallback(char* password, int size, int, void* data);
581 #if FOLLY_OPENSSL_HAS_SNI
583 * The function that will be called directly from openssl
584 * in order for the application to get the tlsext_hostname just after
585 * parsing the Client Hello or Server Hello message. It will then call
586 * the serverNameCb_ function object. Hence, it is sort of a
587 * wrapper/proxy between serverNameCb_ and openssl.
589 * The openssl's primary intention is for SNI support, but we also use it
590 * generically for performing logic after the Client Hello comes in.
592 static int baseServerNameOpenSSLCallback(
594 int* al /* alert (return value) */,
599 std::string providedCiphersString_;
602 typedef std::shared_ptr<SSLContext> SSLContextPtr;
604 std::ostream& operator<<(
606 const folly::PasswordCollector& collector);