2 * Copyright 2015 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.
26 #include <openssl/ssl.h>
27 #include <openssl/tls1.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
32 #include <glog/logging.h>
34 #ifndef FOLLY_NO_CONFIG
35 #include <folly/folly-config.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) = 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.
76 enum SSLVerifyPeerEnum{
79 VERIFY_REQ_CLIENT_CERT,
83 struct NextProtocolsItem {
84 NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
85 weight(wt), protocols(ptcls) {}
87 std::list<std::string> protocols;
90 struct AdvertisedNextProtocolsItem {
91 unsigned char *protocols;
96 // Function that selects a client protocol given the server's list
97 using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
98 const unsigned char*, unsigned int);
101 * Convenience function to call getErrors() with the current errno value.
103 * Make sure that you only call this when there was no intervening operation
104 * since the last OpenSSL error that may have changed the current errno value.
106 static std::string getErrors() {
107 return getErrors(errno);
113 * @param version The lowest or oldest SSL version to support.
115 explicit SSLContext(SSLVersion version = TLSv1);
116 virtual ~SSLContext();
119 * Set default ciphers to be used in SSL handshake process.
121 * @param ciphers A list of ciphers to use for TLSv1.0
123 virtual void ciphers(const std::string& ciphers);
126 * Low-level method that attempts to set the provided ciphers on the
127 * SSL_CTX object, and throws if something goes wrong.
129 virtual void setCiphersOrThrow(const std::string& ciphers);
132 * Method to set verification option in the context object.
134 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
137 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
140 * Method to check if peer verfication is set.
142 * @return true if peer verification is required.
145 virtual bool needsPeerVerification() {
146 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
147 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
151 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
152 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
155 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
158 * @return mode flags that can be used with SSL_set_verify
160 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
163 * Method to fetch Verification mode determined by the options
164 * set using setVerificationOption.
166 * @return mode flags that can be used with SSL_set_verify
168 virtual int getVerificationMode();
171 * Enable/Disable authentication. Peer name validation can only be done
172 * if checkPeerCert is true.
174 * @param checkPeerCert If true, require peer to present valid certificate
175 * @param checkPeerName If true, validate that the certificate common name
176 * or alternate name(s) of peer matches the hostname
178 * @param peerName If non-empty, validate that the certificate common
179 * name of peer matches the given string (altername
180 * name(s) are not used in this case).
182 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
183 const std::string& peerName = std::string());
185 * Load server certificate.
187 * @param path Path to the certificate file
188 * @param format Certificate file format
190 virtual void loadCertificate(const char* path, const char* format = "PEM");
194 * @param path Path to the private key file
195 * @param format Private key file format
197 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
199 * Load trusted certificates from specified file.
201 * @param path Path to trusted certificate file
203 virtual void loadTrustedCertificates(const char* path);
205 * Load trusted certificates from specified X509 certificate store.
207 * @param store X509 certificate store.
209 virtual void loadTrustedCertificates(X509_STORE* store);
211 * Load a client CA list for validating clients
213 virtual void loadClientCAList(const char* path);
215 * Override default OpenSSL password collector.
217 * @param collector Instance of user defined password collector
219 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
221 * Obtain password collector.
223 * @return User defined password collector
225 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
228 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
230 * Provide SNI support
232 enum ServerNameCallbackResult {
234 SERVER_NAME_NOT_FOUND,
235 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
238 * Callback function from openssl to give the application a
239 * chance to check the tlsext_hostname just right after parsing
240 * the Client Hello or Server Hello message.
242 * It is for the server to switch the SSL to another SSL_CTX
243 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
245 * If the ServerNameCallback returns:
247 * server: Send a tlsext_hostname in the Server Hello
249 * SERVER_NAME_NOT_FOUND:
250 * server: Does not send a tlsext_hostname in Server Hello
251 * and continue the handshake.
253 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
254 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
257 * Quote from RFC 6066:
259 * If the server understood the ClientHello extension but
260 * does not recognize the server name, the server SHOULD take one of two
261 * actions: either abort the handshake by sending a fatal-level
262 * unrecognized_name(112) alert or continue the handshake. It is NOT
263 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
264 * because the client's behavior in response to warning-level alerts is
270 * Set the ServerNameCallback
272 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
273 virtual void setServerNameCallback(const ServerNameCallback& cb);
276 * Generic callbacks that are run after we get the Client Hello (right
277 * before we run the ServerNameCallback)
279 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
280 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
284 * Create an SSL object from this context.
286 SSL* createSSL() const;
289 * Set the options on the SSL_CTX object.
291 void setOptions(long options);
293 enum class NextProtocolType : uint8_t {
299 #ifdef OPENSSL_NPN_NEGOTIATED
301 * Set the list of protocols that this SSL context supports. In server
302 * mode, this is the list of protocols that will be advertised for Next
303 * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
304 * (ALPN). In client mode, the first protocol advertised by the server
305 * that is also on this list is chosen. Invoking this function with a list
306 * of length zero causes NPN to be disabled.
308 * @param protocols List of protocol names. This method makes a copy,
309 * so the caller needn't keep the list in scope after
310 * the call completes. The list must have at least
311 * one element to enable NPN. Each element must have
312 * a string length < 256.
313 * @param protocolType What type of protocol negotiation to support.
314 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
316 bool setAdvertisedNextProtocols(
317 const std::list<std::string>& protocols,
318 NextProtocolType protocolType = NextProtocolType::ANY);
320 * Set weighted list of lists of protocols that this SSL context supports.
321 * In server mode, each element of the list contains a list of protocols that
322 * could be advertised for Next Protocol Negotiation (NPN) or Application
323 * Layer Protocol Negotiation (ALPN). The list of protocols that will be
324 * advertised to a client is selected randomly, based on weights of elements.
325 * Client mode doesn't support randomized NPN/ALPN, so this list should
326 * contain only 1 element. The first protocol advertised by the server that
327 * is also on the list of protocols of this element is chosen. Invoking this
328 * function with a list of length zero causes NPN/ALPN to be disabled.
330 * @param items List of NextProtocolsItems, Each item contains a list of
331 * protocol names and weight. After the call of this fucntion
332 * each non-empty list of protocols will be advertised with
333 * probability weight/sum_of_weights. This method makes a copy,
334 * so the caller needn't keep the list in scope after the call
335 * completes. The list must have at least one element with
336 * non-zero weight and non-empty protocols list to enable NPN.
337 * Each name of the protocol must have a string length < 256.
338 * @param protocolType What type of protocol negotiation to support.
339 * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
341 bool setRandomizedAdvertisedNextProtocols(
342 const std::list<NextProtocolsItem>& items,
343 NextProtocolType protocolType = NextProtocolType::ANY);
345 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
346 clientProtoFilter_ = cb;
349 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
350 return clientProtoFilter_;
353 * Disables NPN on this SSL context.
355 void unsetNextProtocols();
356 void deleteNextProtocolsStrings();
358 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
359 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
360 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
362 #endif // OPENSSL_NPN_NEGOTIATED
365 * Gets the underlying SSL_CTX for advanced usage
367 SSL_CTX *getSSLCtx() const {
378 * Set preferences for how to treat locks in OpenSSL. This must be
379 * called before the instantiation of any SSLContext objects, otherwise
380 * the defaults will be used.
382 * OpenSSL has a lock for each module rather than for each object or
383 * data that needs locking. Some locks protect only refcounts, and
384 * might be better as spinlocks rather than mutexes. Other locks
385 * may be totally unnecessary if the objects being protected are not
386 * shared between threads in the application.
388 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
389 * may change from version to version and you should know what you are doing
390 * before disabling any locks entirely.
392 * Example: if you don't share SSL sessions between threads in your
393 * application, you may be able to do this
395 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
397 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
400 * Examine OpenSSL's error stack, and return a string description of the
403 * This operation removes the errors from OpenSSL's error stack.
405 static std::string getErrors(int errnoCopy);
408 * We want to vary which cipher we'll use based on the client's TLS version.
410 void switchCiphersIfTLS11(
412 const std::string& tls11CipherString
415 bool checkPeerName() { return checkPeerName_; }
416 std::string peerFixedName() { return peerFixedName_; }
419 * Helper to match a hostname versus a pattern.
421 static bool matchName(const char* host, const char* pattern, int size);
424 * Functions for setting up and cleaning up openssl.
425 * They can be invoked during the start of the application.
427 static void initializeOpenSSL();
428 static void cleanupOpenSSL();
431 * Mark openssl as initialized without actually performing any initialization.
432 * Please use this only if you are using a library which requires that it must
433 * make its own calls to SSL_library_init() and related functions.
435 static void markInitialized();
438 * Default randomize method.
440 static void randomize();
446 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
449 std::string peerFixedName_;
450 std::shared_ptr<PasswordCollector> collector_;
451 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
452 ServerNameCallback serverNameCb_;
453 std::vector<ClientHelloCallback> clientHelloCbs_;
456 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
458 static bool initialized_;
460 #ifdef OPENSSL_NPN_NEGOTIATED
462 * Wire-format list of advertised protocols for use in NPN.
464 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
465 static int sNextProtocolsExDataIndex_;
467 static int advertisedNextProtocolCallback(SSL* ssl,
468 const unsigned char** out, unsigned int* outlen, void* data);
469 static int selectNextProtocolCallback(
470 SSL* ssl, unsigned char **out, unsigned char *outlen,
471 const unsigned char *server, unsigned int server_len, void *args);
473 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
474 static int alpnSelectCallback(SSL* ssl,
475 const unsigned char** out,
476 unsigned char* outlen,
477 const unsigned char* in,
481 size_t pickNextProtocols();
483 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
484 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
485 // This class contains all allowed ciphers for SSL false start. Call its
486 // `canUseFalseStartWithCipher` to check for cipher qualification.
487 class SSLFalseStartChecker {
489 SSLFalseStartChecker();
491 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
494 static int compare_ulong(const void *x, const void *y);
496 // All ciphers that are allowed to use false start.
497 unsigned long ciphers_[47];
498 unsigned int length_;
502 SSLFalseStartChecker falseStartChecker_;
505 #endif // OPENSSL_NPN_NEGOTIATED
507 static int passwordCallback(char* password, int size, int, void* data);
509 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
511 * The function that will be called directly from openssl
512 * in order for the application to get the tlsext_hostname just after
513 * parsing the Client Hello or Server Hello message. It will then call
514 * the serverNameCb_ function object. Hence, it is sort of a
515 * wrapper/proxy between serverNameCb_ and openssl.
517 * The openssl's primary intention is for SNI support, but we also use it
518 * generically for performing logic after the Client Hello comes in.
520 static int baseServerNameOpenSSLCallback(
522 int* al /* alert (return value) */,
527 std::string providedCiphersString_;
529 // Functions are called when locked by the calling function.
530 static void initializeOpenSSLLocked();
531 static void cleanupOpenSSLLocked();
534 typedef std::shared_ptr<SSLContext> SSLContextPtr;
536 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
541 * Validate that the peer certificate's common name or subject alt names
542 * match what we expect. Currently this only checks for IPs within
543 * subject alt names but it could easily be expanded to check common name
544 * and hostnames as well.
546 * @param cert X509* peer certificate
547 * @param addr sockaddr object containing sockaddr to verify
548 * @param addrLen length of sockaddr as returned by getpeername or accept
549 * @return true iff a subject altname IP matches addr
551 // TODO(agartrell): Add support for things like common name when
553 static bool validatePeerCertNames(X509* cert,
554 const sockaddr* addr,
558 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
559 * accept, getsockname, getpeername, etc family of operations, addrLen's
560 * initial value is ignored and reset.
562 * @param ctx Context from which to retrieve peer sockaddr
563 * @param addrStorage out param for address
564 * @param addrLen out param for length of address
565 * @return true on success, false on failure
567 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
568 sockaddr_storage* addrStorage,