2 * Copyright 2016 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 // This has to come before SSL.
28 #include <folly/portability/Sockets.h>
30 #include <openssl/ssl.h>
31 #include <openssl/tls1.h>
33 #include <glog/logging.h>
35 #ifndef FOLLY_NO_CONFIG
36 #include <folly/folly-config.h>
39 #include <folly/Range.h>
40 #include <folly/io/async/ssl/OpenSSLPtrTypes.h>
41 #include <folly/io/async/ssl/OpenSSLUtils.h>
46 * Override the default password collector.
48 class PasswordCollector {
50 virtual ~PasswordCollector() = default;
52 * Interface for customizing how to collect private key password.
54 * By default, OpenSSL prints a prompt on screen and request for password
55 * while loading private key. To implement a custom password collector,
56 * implement this interface and register it with TSSLSocketFactory.
58 * @param password Pass collected password back to OpenSSL
59 * @param size Maximum length of password including nullptr character
61 virtual void getPassword(std::string& password, int size) = 0;
64 * Return a description of this collector for logging purposes
66 virtual std::string describe() const = 0;
70 * Wrap OpenSSL SSL_CTX into a class.
82 * Defines the way that peers are verified.
84 enum SSLVerifyPeerEnum {
85 // Used by AsyncSSLSocket to delegate to the SSLContext's setting
87 // For server side - request a client certificate and verify the
88 // certificate if it is sent. Does not fail if the client does not present
90 // For client side - validates the server certificate or fails.
92 // For server side - same as VERIFY but will fail if no certificate
94 // For client side - same as VERIFY.
95 VERIFY_REQ_CLIENT_CERT,
96 // No verification is done for both server and client side.
100 struct NextProtocolsItem {
101 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
102 weight(wt), protocols(ptcls) {}
104 std::list<std::string> protocols;
107 // Function that selects a client protocol given the server's list
108 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
109 const unsigned char*, unsigned int);
112 * Convenience function to call getErrors() with the current errno value.
114 * Make sure that you only call this when there was no intervening operation
115 * since the last OpenSSL error that may have changed the current errno value.
117 static std::string getErrors() {
118 return getErrors(errno);
124 * @param version The lowest or oldest SSL version to support.
126 explicit SSLContext(SSLVersion version = TLSv1);
127 virtual ~SSLContext();
130 * Set default ciphers to be used in SSL handshake process.
132 * @param ciphers A list of ciphers to use for TLSv1.0
134 virtual void ciphers(const std::string& ciphers);
137 * Set default ciphers to be used in SSL handshake process.
139 * @param ciphers A list of ciphers to use for TLS.
141 virtual void setCipherList(const std::vector<std::string>& ciphers);
144 * Low-level method that attempts to set the provided ciphers on the
145 * SSL_CTX object, and throws if something goes wrong.
147 virtual void setCiphersOrThrow(const std::string& ciphers);
150 * Sets the signature algorithms to be used during SSL negotiation
153 * @param sigalgs A list of signature algorithms, eg. RSA+SHA512
155 void setSignatureAlgorithms(const std::vector<std::string>& sigalgs);
158 * Sets the list of EC curves supported by the client.
160 * @param ecCurves A list of ec curves, eg: P-256
162 void setClientECCurvesList(const std::vector<std::string>& ecCurves);
165 * Method to add support for a specific elliptic curve encryption algorithm.
167 * @param curveName: The name of the ec curve to support, eg: prime256v1.
169 void setServerECCurve(const std::string& curveName);
172 * Sets an x509 verification param on the context.
174 void setX509VerifyParam(const ssl::X509VerifyParam& x509VerifyParam);
177 * Method to set verification option in the context object.
179 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
182 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
185 * Method to check if peer verfication is set.
187 * @return true if peer verification is required.
190 virtual bool needsPeerVerification() {
191 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
192 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
196 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
197 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
200 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
203 * @return mode flags that can be used with SSL_set_verify
205 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
208 * Method to fetch Verification mode determined by the options
209 * set using setVerificationOption.
211 * @return mode flags that can be used with SSL_set_verify
213 virtual int getVerificationMode();
216 * Enable/Disable authentication. Peer name validation can only be done
217 * if checkPeerCert is true.
219 * @param checkPeerCert If true, require peer to present valid certificate
220 * @param checkPeerName If true, validate that the certificate common name
221 * or alternate name(s) of peer matches the hostname
223 * @param peerName If non-empty, validate that the certificate common
224 * name of peer matches the given string (altername
225 * name(s) are not used in this case).
227 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
228 const std::string& peerName = std::string());
230 * Load server certificate.
232 * @param path Path to the certificate file
233 * @param format Certificate file format
235 virtual void loadCertificate(const char* path, const char* format = "PEM");
237 * Load server certificate from memory.
239 * @param cert A PEM formatted certificate
241 virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
245 * @param path Path to the private key file
246 * @param format Private key file format
248 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
250 * Load private key from memory.
252 * @param pkey A PEM formatted key
254 virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
256 * Load trusted certificates from specified file.
258 * @param path Path to trusted certificate file
260 virtual void loadTrustedCertificates(const char* path);
262 * Load trusted certificates from specified X509 certificate store.
264 * @param store X509 certificate store.
266 virtual void loadTrustedCertificates(X509_STORE* store);
268 * Load a client CA list for validating clients
270 virtual void loadClientCAList(const char* path);
272 * Override default OpenSSL password collector.
274 * @param collector Instance of user defined password collector
276 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
278 * Obtain password collector.
280 * @return User defined password collector
282 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
285 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
287 * Provide SNI support
289 enum ServerNameCallbackResult {
291 SERVER_NAME_NOT_FOUND,
292 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
295 * Callback function from openssl to give the application a
296 * chance to check the tlsext_hostname just right after parsing
297 * the Client Hello or Server Hello message.
299 * It is for the server to switch the SSL to another SSL_CTX
300 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
302 * If the ServerNameCallback returns:
304 * server: Send a tlsext_hostname in the Server Hello
306 * SERVER_NAME_NOT_FOUND:
307 * server: Does not send a tlsext_hostname in Server Hello
308 * and continue the handshake.
310 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
311 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
314 * Quote from RFC 6066:
316 * If the server understood the ClientHello extension but
317 * does not recognize the server name, the server SHOULD take one of two
318 * actions: either abort the handshake by sending a fatal-level
319 * unrecognized_name(112) alert or continue the handshake. It is NOT
320 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
321 * because the client's behavior in response to warning-level alerts is
327 * Set the ServerNameCallback
329 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
330 virtual void setServerNameCallback(const ServerNameCallback& cb);
333 * Generic callbacks that are run after we get the Client Hello (right
334 * before we run the ServerNameCallback)
336 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
337 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
341 * Create an SSL object from this context.
343 SSL* createSSL() const;
346 * Sets the namespace to use for sessions created from this context.
348 void setSessionCacheContext(const std::string& context);
351 * Set the options on the SSL_CTX object.
353 void setOptions(long options);
355 enum class NextProtocolType : uint8_t {
361 #ifdef OPENSSL_NPN_NEGOTIATED
363 * Set the list of protocols that this SSL context supports. In server
364 * mode, this is the list of protocols that will be advertised for Next
365 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
366 * (ALPN). In client mode, the first protocol advertised by the server
367 * that is also on this list is chosen. Invoking this function with a list
368 * of length zero causes NPN to be disabled.
370 * @param protocols List of protocol names. This method makes a copy,
371 * so the caller needn't keep the list in scope after
372 * the call completes. The list must have at least
373 * one element to enable NPN. Each element must have
374 * a string length < 256.
375 * @param protocolType What type of protocol negotiation to support.
376 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
378 bool setAdvertisedNextProtocols(
379 const std::list<std::string>& protocols,
380 NextProtocolType protocolType = NextProtocolType::ANY);
382 * Set weighted list of lists of protocols that this SSL context supports.
383 * In server mode, each element of the list contains a list of protocols that
384 * could be advertised for Next Protocol Negotiation (NPN) or Application
385 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
386 * advertised to a client is selected randomly, based on weights of elements.
387 * Client mode doesn't support randomized NPN/ALPN, so this list should
388 * contain only 1 element. The first protocol advertised by the server that
389 * is also on the list of protocols of this element is chosen. Invoking this
390 * function with a list of length zero causes NPN/ALPN to be disabled.
392 * @param items List of NextProtocolsItems, Each item contains a list of
393 * protocol names and weight. After the call of this fucntion
394 * each non-empty list of protocols will be advertised with
395 * probability weight/sum_of_weights. This method makes a copy,
396 * so the caller needn't keep the list in scope after the call
397 * completes. The list must have at least one element with
398 * non-zero weight and non-empty protocols list to enable NPN.
399 * Each name of the protocol must have a string length < 256.
400 * @param protocolType What type of protocol negotiation to support.
401 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
403 bool setRandomizedAdvertisedNextProtocols(
404 const std::list<NextProtocolsItem>& items,
405 NextProtocolType protocolType = NextProtocolType::ANY);
407 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
408 clientProtoFilter_ = cb;
411 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
412 return clientProtoFilter_;
416 * Disables NPN on this SSL context.
418 void unsetNextProtocols();
419 void deleteNextProtocolsStrings();
420 #endif // OPENSSL_NPN_NEGOTIATED
423 * Gets the underlying SSL_CTX for advanced usage
425 SSL_CTX *getSSLCtx() const {
436 * Set preferences for how to treat locks in OpenSSL. This must be
437 * called before the instantiation of any SSLContext objects, otherwise
438 * the defaults will be used.
440 * OpenSSL has a lock for each module rather than for each object or
441 * data that needs locking. Some locks protect only refcounts, and
442 * might be better as spinlocks rather than mutexes. Other locks
443 * may be totally unnecessary if the objects being protected are not
444 * shared between threads in the application.
446 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
447 * may change from version to version and you should know what you are doing
448 * before disabling any locks entirely.
450 * Example: if you don't share SSL sessions between threads in your
451 * application, you may be able to do this
453 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
455 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
458 * Examine OpenSSL's error stack, and return a string description of the
461 * This operation removes the errors from OpenSSL's error stack.
463 static std::string getErrors(int errnoCopy);
466 * We want to vary which cipher we'll use based on the client's TLS version.
468 * XXX: The refernces to tls11CipherString and tls11AltCipherlist are reused
469 * for * each >= TLS 1.1 handshake, so we expect these fields to not change.
471 void switchCiphersIfTLS11(
473 const std::string& tls11CipherString,
474 const std::vector<std::pair<std::string, int>>& tls11AltCipherlist);
476 bool checkPeerName() { return checkPeerName_; }
477 std::string peerFixedName() { return peerFixedName_; }
479 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
481 * Enable TLS false start, saving a roundtrip for full handshakes. Will only
482 * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
485 void enableFalseStart();
489 * Helper to match a hostname versus a pattern.
491 static bool matchName(const char* host, const char* pattern, int size);
494 * Functions for setting up and cleaning up openssl.
495 * They can be invoked during the start of the application.
497 static void initializeOpenSSL();
498 static void cleanupOpenSSL();
501 * Mark openssl as initialized without actually performing any initialization.
502 * Please use this only if you are using a library which requires that it must
503 * make its own calls to SSL_library_init() and related functions.
505 static void markInitialized();
508 * Default randomize method.
510 static void randomize();
516 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
519 std::string peerFixedName_;
520 std::shared_ptr<PasswordCollector> collector_;
521 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
522 ServerNameCallback serverNameCb_;
523 std::vector<ClientHelloCallback> clientHelloCbs_;
526 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
528 static bool initialized_;
530 // To provide control over choice of server ciphersuites
531 std::unique_ptr<std::discrete_distribution<int>> cipherListPicker_;
533 #ifdef OPENSSL_NPN_NEGOTIATED
535 struct AdvertisedNextProtocolsItem {
536 unsigned char* protocols;
541 * Wire-format list of advertised protocols for use in NPN.
543 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
544 std::vector<int> advertisedNextProtocolWeights_;
545 std::discrete_distribution<int> nextProtocolDistribution_;
547 static int sNextProtocolsExDataIndex_;
549 static int advertisedNextProtocolCallback(SSL* ssl,
550 const unsigned char** out, unsigned int* outlen, void* data);
551 static int selectNextProtocolCallback(
552 SSL* ssl, unsigned char **out, unsigned char *outlen,
553 const unsigned char *server, unsigned int server_len, void *args);
555 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
556 static int alpnSelectCallback(SSL* ssl,
557 const unsigned char** out,
558 unsigned char* outlen,
559 const unsigned char* in,
563 size_t pickNextProtocols();
565 #endif // OPENSSL_NPN_NEGOTIATED
567 static int passwordCallback(char* password, int size, int, void* data);
569 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
571 * The function that will be called directly from openssl
572 * in order for the application to get the tlsext_hostname just after
573 * parsing the Client Hello or Server Hello message. It will then call
574 * the serverNameCb_ function object. Hence, it is sort of a
575 * wrapper/proxy between serverNameCb_ and openssl.
577 * The openssl's primary intention is for SNI support, but we also use it
578 * generically for performing logic after the Client Hello comes in.
580 static int baseServerNameOpenSSLCallback(
582 int* al /* alert (return value) */,
587 std::string providedCiphersString_;
589 // Functions are called when locked by the calling function.
590 static void initializeOpenSSLLocked();
591 static void cleanupOpenSSLLocked();
594 typedef std::shared_ptr<SSLContext> SSLContextPtr;
596 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);