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/io/async/ssl/OpenSSLUtils.h>
36 #include <folly/portability/OpenSSL.h>
37 #include <folly/ssl/OpenSSLLockTypes.h>
38 #include <folly/ssl/OpenSSLPtrTypes.h>
43 * Override the default password collector.
45 class PasswordCollector {
47 virtual ~PasswordCollector() = default;
49 * Interface for customizing how to collect private key password.
51 * By default, OpenSSL prints a prompt on screen and request for password
52 * while loading private key. To implement a custom password collector,
53 * implement this interface and register it with TSSLSocketFactory.
55 * @param password Pass collected password back to OpenSSL
56 * @param size Maximum length of password including nullptr character
58 virtual void getPassword(std::string& password, int size) const = 0;
61 * Return a description of this collector for logging purposes
63 virtual std::string describe() const = 0;
67 * Wrap OpenSSL SSL_CTX into a class.
79 * Defines the way that peers are verified.
81 enum SSLVerifyPeerEnum {
82 // Used by AsyncSSLSocket to delegate to the SSLContext's setting
84 // For server side - request a client certificate and verify the
85 // certificate if it is sent. Does not fail if the client does not present
87 // For client side - validates the server certificate or fails.
89 // For server side - same as VERIFY but will fail if no certificate
91 // For client side - same as VERIFY.
92 VERIFY_REQ_CLIENT_CERT,
93 // No verification is done for both server and client side.
97 struct NextProtocolsItem {
98 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
99 weight(wt), protocols(ptcls) {}
101 std::list<std::string> protocols;
104 // Function that selects a client protocol given the server's list
105 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
106 const unsigned char*, unsigned int);
109 * Convenience function to call getErrors() with the current errno value.
111 * Make sure that you only call this when there was no intervening operation
112 * since the last OpenSSL error that may have changed the current errno value.
114 static std::string getErrors() {
115 return getErrors(errno);
121 * @param version The lowest or oldest SSL version to support.
123 explicit SSLContext(SSLVersion version = TLSv1);
124 virtual ~SSLContext();
127 * Set default ciphers to be used in SSL handshake process.
129 * @param ciphers A list of ciphers to use for TLSv1.0
131 virtual void ciphers(const std::string& ciphers);
134 * Set default ciphers to be used in SSL handshake process.
136 * @param ciphers A list of ciphers to use for TLS.
138 virtual void setCipherList(const std::vector<std::string>& ciphers);
141 * Low-level method that attempts to set the provided ciphers on the
142 * SSL_CTX object, and throws if something goes wrong.
144 virtual void setCiphersOrThrow(const std::string& ciphers);
147 * Sets the signature algorithms to be used during SSL negotiation
150 * @param sigalgs A list of signature algorithms, eg. RSA+SHA512
152 void setSignatureAlgorithms(const std::vector<std::string>& sigalgs);
155 * Sets the list of EC curves supported by the client.
157 * @param ecCurves A list of ec curves, eg: P-256
159 void setClientECCurvesList(const std::vector<std::string>& ecCurves);
162 * Method to add support for a specific elliptic curve encryption algorithm.
164 * @param curveName: The name of the ec curve to support, eg: prime256v1.
166 void setServerECCurve(const std::string& curveName);
169 * Sets an x509 verification param on the context.
171 void setX509VerifyParam(const ssl::X509VerifyParam& x509VerifyParam);
174 * Method to set verification option in the context object.
176 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
179 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
182 * Method to check if peer verfication is set.
184 * @return true if peer verification is required.
187 virtual bool needsPeerVerification() {
188 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
189 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
193 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
194 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
197 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
200 * @return mode flags that can be used with SSL_set_verify
202 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
205 * Method to fetch Verification mode determined by the options
206 * set using setVerificationOption.
208 * @return mode flags that can be used with SSL_set_verify
210 virtual int getVerificationMode();
213 * Enable/Disable authentication. Peer name validation can only be done
214 * if checkPeerCert is true.
216 * @param checkPeerCert If true, require peer to present valid certificate
217 * @param checkPeerName If true, validate that the certificate common name
218 * or alternate name(s) of peer matches the hostname
220 * @param peerName If non-empty, validate that the certificate common
221 * name of peer matches the given string (altername
222 * name(s) are not used in this case).
224 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
225 const std::string& peerName = std::string());
227 * Load server certificate.
229 * @param path Path to the certificate file
230 * @param format Certificate file format
232 virtual void loadCertificate(const char* path, const char* format = "PEM");
234 * Load server certificate from memory.
236 * @param cert A PEM formatted certificate
238 virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
242 * @param path Path to the private key file
243 * @param format Private key file format
245 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
247 * Load private key from memory.
249 * @param pkey A PEM formatted key
251 virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
253 * Load trusted certificates from specified file.
255 * @param path Path to trusted certificate file
257 virtual void loadTrustedCertificates(const char* path);
259 * Load trusted certificates from specified X509 certificate store.
261 * @param store X509 certificate store.
263 virtual void loadTrustedCertificates(X509_STORE* store);
265 * Load a client CA list for validating clients
267 virtual void loadClientCAList(const char* path);
269 * Override default OpenSSL password collector.
271 * @param collector Instance of user defined password collector
273 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
275 * Obtain password collector.
277 * @return User defined password collector
279 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
282 #if FOLLY_OPENSSL_HAS_SNI
284 * Provide SNI support
286 enum ServerNameCallbackResult {
288 SERVER_NAME_NOT_FOUND,
289 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
292 * Callback function from openssl to give the application a
293 * chance to check the tlsext_hostname just right after parsing
294 * the Client Hello or Server Hello message.
296 * It is for the server to switch the SSL to another SSL_CTX
297 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
299 * If the ServerNameCallback returns:
301 * server: Send a tlsext_hostname in the Server Hello
303 * SERVER_NAME_NOT_FOUND:
304 * server: Does not send a tlsext_hostname in Server Hello
305 * and continue the handshake.
307 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
308 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
311 * Quote from RFC 6066:
313 * If the server understood the ClientHello extension but
314 * does not recognize the server name, the server SHOULD take one of two
315 * actions: either abort the handshake by sending a fatal-level
316 * unrecognized_name(112) alert or continue the handshake. It is NOT
317 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
318 * because the client's behavior in response to warning-level alerts is
324 * Set the ServerNameCallback
326 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
327 virtual void setServerNameCallback(const ServerNameCallback& cb);
330 * Generic callbacks that are run after we get the Client Hello (right
331 * before we run the ServerNameCallback)
333 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
334 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
335 #endif // FOLLY_OPENSSL_HAS_SNI
338 * Create an SSL object from this context.
340 SSL* createSSL() const;
343 * Sets the namespace to use for sessions created from this context.
345 void setSessionCacheContext(const std::string& context);
348 * Set the options on the SSL_CTX object.
350 void setOptions(long options);
352 enum class NextProtocolType : uint8_t {
358 #ifdef OPENSSL_NPN_NEGOTIATED
360 * Set the list of protocols that this SSL context supports. In server
361 * mode, this is the list of protocols that will be advertised for Next
362 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
363 * (ALPN). In client mode, the first protocol advertised by the server
364 * that is also on this list is chosen. Invoking this function with a list
365 * of length zero causes NPN to be disabled.
367 * @param protocols List of protocol names. This method makes a copy,
368 * so the caller needn't keep the list in scope after
369 * the call completes. The list must have at least
370 * one element to enable NPN. Each element must have
371 * a string length < 256.
372 * @param protocolType What type of protocol negotiation to support.
373 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
375 bool setAdvertisedNextProtocols(
376 const std::list<std::string>& protocols,
377 NextProtocolType protocolType = NextProtocolType::ANY);
379 * Set weighted list of lists of protocols that this SSL context supports.
380 * In server mode, each element of the list contains a list of protocols that
381 * could be advertised for Next Protocol Negotiation (NPN) or Application
382 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
383 * advertised to a client is selected randomly, based on weights of elements.
384 * Client mode doesn't support randomized NPN/ALPN, so this list should
385 * contain only 1 element. The first protocol advertised by the server that
386 * is also on the list of protocols of this element is chosen. Invoking this
387 * function with a list of length zero causes NPN/ALPN to be disabled.
389 * @param items List of NextProtocolsItems, Each item contains a list of
390 * protocol names and weight. After the call of this fucntion
391 * each non-empty list of protocols will be advertised with
392 * probability weight/sum_of_weights. This method makes a copy,
393 * so the caller needn't keep the list in scope after the call
394 * completes. The list must have at least one element with
395 * non-zero weight and non-empty protocols list to enable NPN.
396 * Each name of the protocol must have a string length < 256.
397 * @param protocolType What type of protocol negotiation to support.
398 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
400 bool setRandomizedAdvertisedNextProtocols(
401 const std::list<NextProtocolsItem>& items,
402 NextProtocolType protocolType = NextProtocolType::ANY);
404 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
405 clientProtoFilter_ = cb;
408 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
409 return clientProtoFilter_;
413 * Disables NPN on this SSL context.
415 void unsetNextProtocols();
416 void deleteNextProtocolsStrings();
417 #endif // OPENSSL_NPN_NEGOTIATED
420 * Gets the underlying SSL_CTX for advanced usage
422 SSL_CTX *getSSLCtx() const {
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 FOLLY_DEPRECATED("Use folly::ssl::setLockTypes")
447 static void setSSLLockTypes(std::map<int, ssl::LockType> lockTypes);
450 * Examine OpenSSL's error stack, and return a string description of the
453 * This operation removes the errors from OpenSSL's error stack.
455 static std::string getErrors(int errnoCopy);
457 bool checkPeerName() { return checkPeerName_; }
458 std::string peerFixedName() { return peerFixedName_; }
460 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
462 * Enable TLS false start, saving a roundtrip for full handshakes. Will only
463 * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
466 void enableFalseStart();
470 * Helper to match a hostname versus a pattern.
472 static bool matchName(const char* host, const char* pattern, int size);
474 FOLLY_DEPRECATED("Use folly::ssl::init")
475 static void initializeOpenSSL();
481 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
484 std::string peerFixedName_;
485 std::shared_ptr<PasswordCollector> collector_;
486 #if FOLLY_OPENSSL_HAS_SNI
487 ServerNameCallback serverNameCb_;
488 std::vector<ClientHelloCallback> clientHelloCbs_;
491 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
493 static bool initialized_;
495 #ifdef OPENSSL_NPN_NEGOTIATED
497 struct AdvertisedNextProtocolsItem {
498 unsigned char* protocols;
503 * Wire-format list of advertised protocols for use in NPN.
505 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
506 std::vector<int> advertisedNextProtocolWeights_;
507 std::discrete_distribution<int> nextProtocolDistribution_;
509 static int advertisedNextProtocolCallback(SSL* ssl,
510 const unsigned char** out, unsigned int* outlen, void* data);
511 static int selectNextProtocolCallback(
512 SSL* ssl, unsigned char **out, unsigned char *outlen,
513 const unsigned char *server, unsigned int server_len, void *args);
515 #if FOLLY_OPENSSL_HAS_ALPN
516 static int alpnSelectCallback(SSL* ssl,
517 const unsigned char** out,
518 unsigned char* outlen,
519 const unsigned char* in,
523 size_t pickNextProtocols();
525 #endif // OPENSSL_NPN_NEGOTIATED
527 static int passwordCallback(char* password, int size, int, void* data);
529 #if FOLLY_OPENSSL_HAS_SNI
531 * The function that will be called directly from openssl
532 * in order for the application to get the tlsext_hostname just after
533 * parsing the Client Hello or Server Hello message. It will then call
534 * the serverNameCb_ function object. Hence, it is sort of a
535 * wrapper/proxy between serverNameCb_ and openssl.
537 * The openssl's primary intention is for SNI support, but we also use it
538 * generically for performing logic after the Client Hello comes in.
540 static int baseServerNameOpenSSLCallback(
542 int* al /* alert (return value) */,
547 std::string providedCiphersString_;
550 typedef std::shared_ptr<SSLContext> SSLContextPtr;
552 std::ostream& operator<<(
554 const folly::PasswordCollector& collector);