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 #include <openssl/ssl.h>
28 #include <openssl/tls1.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
33 #include <glog/logging.h>
35 #ifndef FOLLY_NO_CONFIG
36 #include <folly/folly-config.h>
39 #include <folly/Random.h>
40 #include <folly/Range.h>
45 * Override the default password collector.
47 class PasswordCollector {
49 virtual ~PasswordCollector() = default;
51 * Interface for customizing how to collect private key password.
53 * By default, OpenSSL prints a prompt on screen and request for password
54 * while loading private key. To implement a custom password collector,
55 * implement this interface and register it with TSSLSocketFactory.
57 * @param password Pass collected password back to OpenSSL
58 * @param size Maximum length of password including nullptr character
60 virtual void getPassword(std::string& password, int size) = 0;
63 * Return a description of this collector for logging purposes
65 virtual std::string describe() const = 0;
69 * Wrap OpenSSL SSL_CTX into a class.
81 * Defines the way that peers are verified.
83 enum SSLVerifyPeerEnum {
84 // Used by AsyncSSLSocket to delegate to the SSLContext's setting
86 // For server side - request a client certificate and verify the
87 // certificate if it is sent. Does not fail if the client does not present
89 // For client side - validates the server certificate or fails.
91 // For server side - same as VERIFY but will fail if no certificate
93 // For client side - same as VERIFY.
94 VERIFY_REQ_CLIENT_CERT,
95 // No verification is done for both server and client side.
99 struct NextProtocolsItem {
100 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
101 weight(wt), protocols(ptcls) {}
103 std::list<std::string> protocols;
106 // Function that selects a client protocol given the server's list
107 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
108 const unsigned char*, unsigned int);
111 * Convenience function to call getErrors() with the current errno value.
113 * Make sure that you only call this when there was no intervening operation
114 * since the last OpenSSL error that may have changed the current errno value.
116 static std::string getErrors() {
117 return getErrors(errno);
123 * @param version The lowest or oldest SSL version to support.
125 explicit SSLContext(SSLVersion version = TLSv1);
126 virtual ~SSLContext();
129 * Set default ciphers to be used in SSL handshake process.
131 * @param ciphers A list of ciphers to use for TLSv1.0
133 virtual void ciphers(const std::string& ciphers);
136 * Low-level method that attempts to set the provided ciphers on the
137 * SSL_CTX object, and throws if something goes wrong.
139 virtual void setCiphersOrThrow(const std::string& ciphers);
142 * Method to set verification option in the context object.
144 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
147 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
150 * Method to check if peer verfication is set.
152 * @return true if peer verification is required.
155 virtual bool needsPeerVerification() {
156 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
157 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
161 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
162 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
165 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
168 * @return mode flags that can be used with SSL_set_verify
170 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
173 * Method to fetch Verification mode determined by the options
174 * set using setVerificationOption.
176 * @return mode flags that can be used with SSL_set_verify
178 virtual int getVerificationMode();
181 * Enable/Disable authentication. Peer name validation can only be done
182 * if checkPeerCert is true.
184 * @param checkPeerCert If true, require peer to present valid certificate
185 * @param checkPeerName If true, validate that the certificate common name
186 * or alternate name(s) of peer matches the hostname
188 * @param peerName If non-empty, validate that the certificate common
189 * name of peer matches the given string (altername
190 * name(s) are not used in this case).
192 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
193 const std::string& peerName = std::string());
195 * Load server certificate.
197 * @param path Path to the certificate file
198 * @param format Certificate file format
200 virtual void loadCertificate(const char* path, const char* format = "PEM");
202 * Load server certificate from memory.
204 * @param cert A PEM formatted certificate
206 virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
210 * @param path Path to the private key file
211 * @param format Private key file format
213 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
215 * Load private key from memory.
217 * @param pkey A PEM formatted key
219 virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
221 * Load trusted certificates from specified file.
223 * @param path Path to trusted certificate file
225 virtual void loadTrustedCertificates(const char* path);
227 * Load trusted certificates from specified X509 certificate store.
229 * @param store X509 certificate store.
231 virtual void loadTrustedCertificates(X509_STORE* store);
233 * Load a client CA list for validating clients
235 virtual void loadClientCAList(const char* path);
237 * Override default OpenSSL password collector.
239 * @param collector Instance of user defined password collector
241 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
243 * Obtain password collector.
245 * @return User defined password collector
247 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
250 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
252 * Provide SNI support
254 enum ServerNameCallbackResult {
256 SERVER_NAME_NOT_FOUND,
257 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
260 * Callback function from openssl to give the application a
261 * chance to check the tlsext_hostname just right after parsing
262 * the Client Hello or Server Hello message.
264 * It is for the server to switch the SSL to another SSL_CTX
265 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
267 * If the ServerNameCallback returns:
269 * server: Send a tlsext_hostname in the Server Hello
271 * SERVER_NAME_NOT_FOUND:
272 * server: Does not send a tlsext_hostname in Server Hello
273 * and continue the handshake.
275 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
276 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
279 * Quote from RFC 6066:
281 * If the server understood the ClientHello extension but
282 * does not recognize the server name, the server SHOULD take one of two
283 * actions: either abort the handshake by sending a fatal-level
284 * unrecognized_name(112) alert or continue the handshake. It is NOT
285 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
286 * because the client's behavior in response to warning-level alerts is
292 * Set the ServerNameCallback
294 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
295 virtual void setServerNameCallback(const ServerNameCallback& cb);
298 * Generic callbacks that are run after we get the Client Hello (right
299 * before we run the ServerNameCallback)
301 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
302 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
306 * Create an SSL object from this context.
308 SSL* createSSL() const;
311 * Set the options on the SSL_CTX object.
313 void setOptions(long options);
315 enum class NextProtocolType : uint8_t {
321 #ifdef OPENSSL_NPN_NEGOTIATED
323 * Set the list of protocols that this SSL context supports. In server
324 * mode, this is the list of protocols that will be advertised for Next
325 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
326 * (ALPN). In client mode, the first protocol advertised by the server
327 * that is also on this list is chosen. Invoking this function with a list
328 * of length zero causes NPN to be disabled.
330 * @param protocols List of protocol names. This method makes a copy,
331 * so the caller needn't keep the list in scope after
332 * the call completes. The list must have at least
333 * one element to enable NPN. Each element must have
334 * a string length < 256.
335 * @param protocolType What type of protocol negotiation to support.
336 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
338 bool setAdvertisedNextProtocols(
339 const std::list<std::string>& protocols,
340 NextProtocolType protocolType = NextProtocolType::ANY);
342 * Set weighted list of lists of protocols that this SSL context supports.
343 * In server mode, each element of the list contains a list of protocols that
344 * could be advertised for Next Protocol Negotiation (NPN) or Application
345 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
346 * advertised to a client is selected randomly, based on weights of elements.
347 * Client mode doesn't support randomized NPN/ALPN, so this list should
348 * contain only 1 element. The first protocol advertised by the server that
349 * is also on the list of protocols of this element is chosen. Invoking this
350 * function with a list of length zero causes NPN/ALPN to be disabled.
352 * @param items List of NextProtocolsItems, Each item contains a list of
353 * protocol names and weight. After the call of this fucntion
354 * each non-empty list of protocols will be advertised with
355 * probability weight/sum_of_weights. This method makes a copy,
356 * so the caller needn't keep the list in scope after the call
357 * completes. The list must have at least one element with
358 * non-zero weight and non-empty protocols list to enable NPN.
359 * Each name of the protocol must have a string length < 256.
360 * @param protocolType What type of protocol negotiation to support.
361 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
363 bool setRandomizedAdvertisedNextProtocols(
364 const std::list<NextProtocolsItem>& items,
365 NextProtocolType protocolType = NextProtocolType::ANY);
367 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
368 clientProtoFilter_ = cb;
371 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
372 return clientProtoFilter_;
375 * Disables NPN on this SSL context.
377 void unsetNextProtocols();
378 void deleteNextProtocolsStrings();
380 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
381 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
382 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
384 #endif // OPENSSL_NPN_NEGOTIATED
387 * Gets the underlying SSL_CTX for advanced usage
389 SSL_CTX *getSSLCtx() const {
400 * Set preferences for how to treat locks in OpenSSL. This must be
401 * called before the instantiation of any SSLContext objects, otherwise
402 * the defaults will be used.
404 * OpenSSL has a lock for each module rather than for each object or
405 * data that needs locking. Some locks protect only refcounts, and
406 * might be better as spinlocks rather than mutexes. Other locks
407 * may be totally unnecessary if the objects being protected are not
408 * shared between threads in the application.
410 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
411 * may change from version to version and you should know what you are doing
412 * before disabling any locks entirely.
414 * Example: if you don't share SSL sessions between threads in your
415 * application, you may be able to do this
417 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
419 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
422 * Examine OpenSSL's error stack, and return a string description of the
425 * This operation removes the errors from OpenSSL's error stack.
427 static std::string getErrors(int errnoCopy);
430 * We want to vary which cipher we'll use based on the client's TLS version.
432 void switchCiphersIfTLS11(
434 const std::string& tls11CipherString
437 bool checkPeerName() { return checkPeerName_; }
438 std::string peerFixedName() { return peerFixedName_; }
441 * Helper to match a hostname versus a pattern.
443 static bool matchName(const char* host, const char* pattern, int size);
446 * Functions for setting up and cleaning up openssl.
447 * They can be invoked during the start of the application.
449 static void initializeOpenSSL();
450 static void cleanupOpenSSL();
453 * Mark openssl as initialized without actually performing any initialization.
454 * Please use this only if you are using a library which requires that it must
455 * make its own calls to SSL_library_init() and related functions.
457 static void markInitialized();
460 * Default randomize method.
462 static void randomize();
468 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
471 std::string peerFixedName_;
472 std::shared_ptr<PasswordCollector> collector_;
473 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
474 ServerNameCallback serverNameCb_;
475 std::vector<ClientHelloCallback> clientHelloCbs_;
478 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
480 static bool initialized_;
482 #ifdef OPENSSL_NPN_NEGOTIATED
484 struct AdvertisedNextProtocolsItem {
485 unsigned char* protocols;
490 * Wire-format list of advertised protocols for use in NPN.
492 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
493 std::vector<int> advertisedNextProtocolWeights_;
494 std::discrete_distribution<int> nextProtocolDistribution_;
495 Random::DefaultGenerator nextProtocolPicker_;
497 static int sNextProtocolsExDataIndex_;
499 static int advertisedNextProtocolCallback(SSL* ssl,
500 const unsigned char** out, unsigned int* outlen, void* data);
501 static int selectNextProtocolCallback(
502 SSL* ssl, unsigned char **out, unsigned char *outlen,
503 const unsigned char *server, unsigned int server_len, void *args);
505 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
506 static int alpnSelectCallback(SSL* ssl,
507 const unsigned char** out,
508 unsigned char* outlen,
509 const unsigned char* in,
513 size_t pickNextProtocols();
515 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
516 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
517 // This class contains all allowed ciphers for SSL false start. Call its
518 // `canUseFalseStartWithCipher` to check for cipher qualification.
519 class SSLFalseStartChecker {
521 SSLFalseStartChecker();
523 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
526 static int compare_ulong(const void *x, const void *y);
528 // All ciphers that are allowed to use false start.
529 unsigned long ciphers_[47];
530 unsigned int length_;
534 SSLFalseStartChecker falseStartChecker_;
537 #endif // OPENSSL_NPN_NEGOTIATED
539 static int passwordCallback(char* password, int size, int, void* data);
541 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
543 * The function that will be called directly from openssl
544 * in order for the application to get the tlsext_hostname just after
545 * parsing the Client Hello or Server Hello message. It will then call
546 * the serverNameCb_ function object. Hence, it is sort of a
547 * wrapper/proxy between serverNameCb_ and openssl.
549 * The openssl's primary intention is for SNI support, but we also use it
550 * generically for performing logic after the Client Hello comes in.
552 static int baseServerNameOpenSSLCallback(
554 int* al /* alert (return value) */,
559 std::string providedCiphersString_;
561 // Functions are called when locked by the calling function.
562 static void initializeOpenSSLLocked();
563 static void cleanupOpenSSLLocked();
566 typedef std::shared_ptr<SSLContext> SSLContextPtr;
568 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
573 * Validate that the peer certificate's common name or subject alt names
574 * match what we expect. Currently this only checks for IPs within
575 * subject alt names but it could easily be expanded to check common name
576 * and hostnames as well.
578 * @param cert X509* peer certificate
579 * @param addr sockaddr object containing sockaddr to verify
580 * @param addrLen length of sockaddr as returned by getpeername or accept
581 * @return true iff a subject altname IP matches addr
583 // TODO(agartrell): Add support for things like common name when
585 static bool validatePeerCertNames(X509* cert,
586 const sockaddr* addr,
590 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
591 * accept, getsockname, getpeername, etc family of operations, addrLen's
592 * initial value is ignored and reset.
594 * @param ctx Context from which to retrieve peer sockaddr
595 * @param addrStorage out param for address
596 * @param addrLen out param for length of address
597 * @return true on success, false on failure
599 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
600 sockaddr_storage* addrStorage,