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/Range.h>
34 #include <folly/io/async/ssl/OpenSSLUtils.h>
35 #include <folly/portability/OpenSSL.h>
36 #include <folly/ssl/OpenSSLPtrTypes.h>
41 * Override the default password collector.
43 class PasswordCollector {
45 virtual ~PasswordCollector() = default;
47 * Interface for customizing how to collect private key password.
49 * By default, OpenSSL prints a prompt on screen and request for password
50 * while loading private key. To implement a custom password collector,
51 * implement this interface and register it with TSSLSocketFactory.
53 * @param password Pass collected password back to OpenSSL
54 * @param size Maximum length of password including nullptr character
56 virtual void getPassword(std::string& password, int size) const = 0;
59 * Return a description of this collector for logging purposes
61 virtual std::string describe() const = 0;
65 * Wrap OpenSSL SSL_CTX into a class.
77 * Defines the way that peers are verified.
79 enum SSLVerifyPeerEnum {
80 // Used by AsyncSSLSocket to delegate to the SSLContext's setting
82 // For server side - request a client certificate and verify the
83 // certificate if it is sent. Does not fail if the client does not present
85 // For client side - validates the server certificate or fails.
87 // For server side - same as VERIFY but will fail if no certificate
89 // For client side - same as VERIFY.
90 VERIFY_REQ_CLIENT_CERT,
91 // No verification is done for both server and client side.
95 struct NextProtocolsItem {
96 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
97 weight(wt), protocols(ptcls) {}
99 std::list<std::string> protocols;
102 // Function that selects a client protocol given the server's list
103 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
104 const unsigned char*, unsigned int);
107 * Convenience function to call getErrors() with the current errno value.
109 * Make sure that you only call this when there was no intervening operation
110 * since the last OpenSSL error that may have changed the current errno value.
112 static std::string getErrors() {
113 return getErrors(errno);
119 * @param version The lowest or oldest SSL version to support.
121 explicit SSLContext(SSLVersion version = TLSv1);
122 virtual ~SSLContext();
125 * Set default ciphers to be used in SSL handshake process.
127 * @param ciphers A list of ciphers to use for TLSv1.0
129 virtual void ciphers(const std::string& ciphers);
132 * Set default ciphers to be used in SSL handshake process.
134 * @param ciphers A list of ciphers to use for TLS.
136 virtual void setCipherList(const std::vector<std::string>& ciphers);
139 * Low-level method that attempts to set the provided ciphers on the
140 * SSL_CTX object, and throws if something goes wrong.
142 virtual void setCiphersOrThrow(const std::string& ciphers);
145 * Sets the signature algorithms to be used during SSL negotiation
148 * @param sigalgs A list of signature algorithms, eg. RSA+SHA512
150 void setSignatureAlgorithms(const std::vector<std::string>& sigalgs);
153 * Sets the list of EC curves supported by the client.
155 * @param ecCurves A list of ec curves, eg: P-256
157 void setClientECCurvesList(const std::vector<std::string>& ecCurves);
160 * Method to add support for a specific elliptic curve encryption algorithm.
162 * @param curveName: The name of the ec curve to support, eg: prime256v1.
164 void setServerECCurve(const std::string& curveName);
167 * Sets an x509 verification param on the context.
169 void setX509VerifyParam(const ssl::X509VerifyParam& x509VerifyParam);
172 * Method to set verification option in the context object.
174 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
177 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
180 * Method to check if peer verfication is set.
182 * @return true if peer verification is required.
185 virtual bool needsPeerVerification() {
186 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
187 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
191 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
192 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
195 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
198 * @return mode flags that can be used with SSL_set_verify
200 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
203 * Method to fetch Verification mode determined by the options
204 * set using setVerificationOption.
206 * @return mode flags that can be used with SSL_set_verify
208 virtual int getVerificationMode();
211 * Enable/Disable authentication. Peer name validation can only be done
212 * if checkPeerCert is true.
214 * @param checkPeerCert If true, require peer to present valid certificate
215 * @param checkPeerName If true, validate that the certificate common name
216 * or alternate name(s) of peer matches the hostname
218 * @param peerName If non-empty, validate that the certificate common
219 * name of peer matches the given string (altername
220 * name(s) are not used in this case).
222 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
223 const std::string& peerName = std::string());
225 * Load server certificate.
227 * @param path Path to the certificate file
228 * @param format Certificate file format
230 virtual void loadCertificate(const char* path, const char* format = "PEM");
232 * Load server certificate from memory.
234 * @param cert A PEM formatted certificate
236 virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
240 * @param path Path to the private key file
241 * @param format Private key file format
243 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
245 * Load private key from memory.
247 * @param pkey A PEM formatted key
249 virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
251 * Load trusted certificates from specified file.
253 * @param path Path to trusted certificate file
255 virtual void loadTrustedCertificates(const char* path);
257 * Load trusted certificates from specified X509 certificate store.
259 * @param store X509 certificate store.
261 virtual void loadTrustedCertificates(X509_STORE* store);
263 * Load a client CA list for validating clients
265 virtual void loadClientCAList(const char* path);
267 * Override default OpenSSL password collector.
269 * @param collector Instance of user defined password collector
271 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
273 * Obtain password collector.
275 * @return User defined password collector
277 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
280 #if FOLLY_OPENSSL_HAS_SNI
282 * Provide SNI support
284 enum ServerNameCallbackResult {
286 SERVER_NAME_NOT_FOUND,
287 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
290 * Callback function from openssl to give the application a
291 * chance to check the tlsext_hostname just right after parsing
292 * the Client Hello or Server Hello message.
294 * It is for the server to switch the SSL to another SSL_CTX
295 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
297 * If the ServerNameCallback returns:
299 * server: Send a tlsext_hostname in the Server Hello
301 * SERVER_NAME_NOT_FOUND:
302 * server: Does not send a tlsext_hostname in Server Hello
303 * and continue the handshake.
305 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
306 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
309 * Quote from RFC 6066:
311 * If the server understood the ClientHello extension but
312 * does not recognize the server name, the server SHOULD take one of two
313 * actions: either abort the handshake by sending a fatal-level
314 * unrecognized_name(112) alert or continue the handshake. It is NOT
315 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
316 * because the client's behavior in response to warning-level alerts is
322 * Set the ServerNameCallback
324 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
325 virtual void setServerNameCallback(const ServerNameCallback& cb);
328 * Generic callbacks that are run after we get the Client Hello (right
329 * before we run the ServerNameCallback)
331 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
332 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
333 #endif // FOLLY_OPENSSL_HAS_SNI
336 * Create an SSL object from this context.
338 SSL* createSSL() const;
341 * Sets the namespace to use for sessions created from this context.
343 void setSessionCacheContext(const std::string& context);
346 * Set the options on the SSL_CTX object.
348 void setOptions(long options);
350 enum class NextProtocolType : uint8_t {
356 #ifdef OPENSSL_NPN_NEGOTIATED
358 * Set the list of protocols that this SSL context supports. In server
359 * mode, this is the list of protocols that will be advertised for Next
360 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
361 * (ALPN). In client mode, the first protocol advertised by the server
362 * that is also on this list is chosen. Invoking this function with a list
363 * of length zero causes NPN to be disabled.
365 * @param protocols List of protocol names. This method makes a copy,
366 * so the caller needn't keep the list in scope after
367 * the call completes. The list must have at least
368 * one element to enable NPN. Each element must have
369 * a string length < 256.
370 * @param protocolType What type of protocol negotiation to support.
371 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
373 bool setAdvertisedNextProtocols(
374 const std::list<std::string>& protocols,
375 NextProtocolType protocolType = NextProtocolType::ANY);
377 * Set weighted list of lists of protocols that this SSL context supports.
378 * In server mode, each element of the list contains a list of protocols that
379 * could be advertised for Next Protocol Negotiation (NPN) or Application
380 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
381 * advertised to a client is selected randomly, based on weights of elements.
382 * Client mode doesn't support randomized NPN/ALPN, so this list should
383 * contain only 1 element. The first protocol advertised by the server that
384 * is also on the list of protocols of this element is chosen. Invoking this
385 * function with a list of length zero causes NPN/ALPN to be disabled.
387 * @param items List of NextProtocolsItems, Each item contains a list of
388 * protocol names and weight. After the call of this fucntion
389 * each non-empty list of protocols will be advertised with
390 * probability weight/sum_of_weights. This method makes a copy,
391 * so the caller needn't keep the list in scope after the call
392 * completes. The list must have at least one element with
393 * non-zero weight and non-empty protocols list to enable NPN.
394 * Each name of the protocol must have a string length < 256.
395 * @param protocolType What type of protocol negotiation to support.
396 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
398 bool setRandomizedAdvertisedNextProtocols(
399 const std::list<NextProtocolsItem>& items,
400 NextProtocolType protocolType = NextProtocolType::ANY);
402 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
403 clientProtoFilter_ = cb;
406 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
407 return clientProtoFilter_;
411 * Disables NPN on this SSL context.
413 void unsetNextProtocols();
414 void deleteNextProtocolsStrings();
415 #endif // OPENSSL_NPN_NEGOTIATED
418 * Gets the underlying SSL_CTX for advanced usage
420 SSL_CTX *getSSLCtx() const {
424 enum SSLLockType { LOCK_MUTEX, LOCK_SPINLOCK, LOCK_SHAREDMUTEX, LOCK_NONE };
427 * Set preferences for how to treat locks in OpenSSL. This must be
428 * called before the instantiation of any SSLContext objects, otherwise
429 * the defaults will be used.
431 * OpenSSL has a lock for each module rather than for each object or
432 * data that needs locking. Some locks protect only refcounts, and
433 * might be better as spinlocks rather than mutexes. Other locks
434 * may be totally unnecessary if the objects being protected are not
435 * shared between threads in the application.
437 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
438 * may change from version to version and you should know what you are doing
439 * before disabling any locks entirely.
441 * Example: if you don't share SSL sessions between threads in your
442 * application, you may be able to do this
444 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
446 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
449 * Set the lock types and initialize OpenSSL in an atomic fashion. This
450 * aborts if the library has already been initialized.
452 static void setSSLLockTypesAndInitOpenSSL(
453 std::map<int, SSLLockType> lockTypes);
456 * Determine if the SSL lock with the specified id (i.e.
457 * CRYPTO_LOCK_SSL_SESSION) is disabled. This should be called after
458 * initializeOpenSSL. This will only check if the specified lock has been
459 * explicitly set to LOCK_NONE.
461 * This is not safe to call while setSSLLockTypes is being called.
463 static bool isSSLLockDisabled(int lockId);
466 * Examine OpenSSL's error stack, and return a string description of the
469 * This operation removes the errors from OpenSSL's error stack.
471 static std::string getErrors(int errnoCopy);
474 * We want to vary which cipher we'll use based on the client's TLS version.
476 * XXX: The refernces to tls11CipherString and tls11AltCipherlist are reused
477 * for * each >= TLS 1.1 handshake, so we expect these fields to not change.
479 void switchCiphersIfTLS11(
481 const std::string& tls11CipherString,
482 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist);
484 bool checkPeerName() { return checkPeerName_; }
485 std::string peerFixedName() { return peerFixedName_; }
487 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
489 * Enable TLS false start, saving a roundtrip for full handshakes. Will only
490 * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
493 void enableFalseStart();
497 * Helper to match a hostname versus a pattern.
499 static bool matchName(const char* host, const char* pattern, int size);
502 * Functions for setting up and cleaning up openssl.
503 * They can be invoked during the start of the application.
505 static void initializeOpenSSL();
506 static void cleanupOpenSSL();
509 * Mark openssl as initialized without actually performing any initialization.
510 * Please use this only if you are using a library which requires that it must
511 * make its own calls to SSL_library_init() and related functions.
513 static void markInitialized();
516 * Default randomize method.
518 static void randomize();
524 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
527 std::string peerFixedName_;
528 std::shared_ptr<PasswordCollector> collector_;
529 #if FOLLY_OPENSSL_HAS_SNI
530 ServerNameCallback serverNameCb_;
531 std::vector<ClientHelloCallback> clientHelloCbs_;
534 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
536 static bool initialized_;
538 // To provide control over choice of server ciphersuites
539 std::unique_ptr<std::discrete_distribution<int>> cipherListPicker_;
541 #ifdef OPENSSL_NPN_NEGOTIATED
543 struct AdvertisedNextProtocolsItem {
544 unsigned char* protocols;
549 * Wire-format list of advertised protocols for use in NPN.
551 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
552 std::vector<int> advertisedNextProtocolWeights_;
553 std::discrete_distribution<int> nextProtocolDistribution_;
555 static int sNextProtocolsExDataIndex_;
557 static int advertisedNextProtocolCallback(SSL* ssl,
558 const unsigned char** out, unsigned int* outlen, void* data);
559 static int selectNextProtocolCallback(
560 SSL* ssl, unsigned char **out, unsigned char *outlen,
561 const unsigned char *server, unsigned int server_len, void *args);
563 #if FOLLY_OPENSSL_HAS_ALPN
564 static int alpnSelectCallback(SSL* ssl,
565 const unsigned char** out,
566 unsigned char* outlen,
567 const unsigned char* in,
571 size_t pickNextProtocols();
573 #endif // OPENSSL_NPN_NEGOTIATED
575 static int passwordCallback(char* password, int size, int, void* data);
577 #if FOLLY_OPENSSL_HAS_SNI
579 * The function that will be called directly from openssl
580 * in order for the application to get the tlsext_hostname just after
581 * parsing the Client Hello or Server Hello message. It will then call
582 * the serverNameCb_ function object. Hence, it is sort of a
583 * wrapper/proxy between serverNameCb_ and openssl.
585 * The openssl's primary intention is for SNI support, but we also use it
586 * generically for performing logic after the Client Hello comes in.
588 static int baseServerNameOpenSSLCallback(
590 int* al /* alert (return value) */,
595 std::string providedCiphersString_;
597 // Functions are called when locked by the calling function.
598 static void initializeOpenSSLLocked();
599 static void cleanupOpenSSLLocked();
600 static void setSSLLockTypesLocked(std::map<int, SSLLockType> inLockTypes);
603 typedef std::shared_ptr<SSLContext> SSLContextPtr;
605 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);