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 #ifdef OPENSSL_NPN_NEGOTIATED
295 * Set the list of protocols that this SSL context supports. In server
296 * mode, this is the list of protocols that will be advertised for Next
297 * Protocol Negotiation (NPN). In client mode, the first protocol
298 * advertised by the server that is also on this list is
299 * chosen. Invoking this function with a list of length zero causes NPN
302 * @param protocols List of protocol names. This method makes a copy,
303 * so the caller needn't keep the list in scope after
304 * the call completes. The list must have at least
305 * one element to enable NPN. Each element must have
306 * a string length < 256.
307 * @return true if NPN has been activated. False if NPN is disabled.
309 bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
311 * Set weighted list of lists of protocols that this SSL context supports.
312 * In server mode, each element of the list contains a list of protocols that
313 * could be advertised for Next Protocol Negotiation (NPN). The list of
314 * protocols that will be advertised to a client is selected randomly, based
315 * on weights of elements. Client mode doesn't support randomized NPN, so
316 * this list should contain only 1 element. The first protocol advertised
317 * by the server that is also on the list of protocols of this element is
318 * chosen. Invoking this function with a list of length zero causes NPN
321 * @param items List of NextProtocolsItems, Each item contains a list of
322 * protocol names and weight. After the call of this fucntion
323 * each non-empty list of protocols will be advertised with
324 * probability weight/sum_of_weights. This method makes a copy,
325 * so the caller needn't keep the list in scope after the call
326 * completes. The list must have at least one element with
327 * non-zero weight and non-empty protocols list to enable NPN.
328 * Each name of the protocol must have a string length < 256.
329 * @return true if NPN has been activated. False if NPN is disabled.
331 bool setRandomizedAdvertisedNextProtocols(
332 const std::list<NextProtocolsItem>& items);
334 void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
335 clientProtoFilter_ = cb;
338 ClientProtocolFilterCallback getClientProtocolFilterCallback() {
339 return clientProtoFilter_;
342 * Disables NPN on this SSL context.
344 void unsetNextProtocols();
345 void deleteNextProtocolsStrings();
347 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
348 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
349 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
351 #endif // OPENSSL_NPN_NEGOTIATED
354 * Gets the underlying SSL_CTX for advanced usage
356 SSL_CTX *getSSLCtx() const {
367 * Set preferences for how to treat locks in OpenSSL. This must be
368 * called before the instantiation of any SSLContext objects, otherwise
369 * the defaults will be used.
371 * OpenSSL has a lock for each module rather than for each object or
372 * data that needs locking. Some locks protect only refcounts, and
373 * might be better as spinlocks rather than mutexes. Other locks
374 * may be totally unnecessary if the objects being protected are not
375 * shared between threads in the application.
377 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
378 * may change from version to version and you should know what you are doing
379 * before disabling any locks entirely.
381 * Example: if you don't share SSL sessions between threads in your
382 * application, you may be able to do this
384 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
386 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
389 * Examine OpenSSL's error stack, and return a string description of the
392 * This operation removes the errors from OpenSSL's error stack.
394 static std::string getErrors(int errnoCopy);
397 * We want to vary which cipher we'll use based on the client's TLS version.
399 void switchCiphersIfTLS11(
401 const std::string& tls11CipherString
404 bool checkPeerName() { return checkPeerName_; }
405 std::string peerFixedName() { return peerFixedName_; }
408 * Helper to match a hostname versus a pattern.
410 static bool matchName(const char* host, const char* pattern, int size);
413 * Functions for setting up and cleaning up openssl.
414 * They can be invoked during the start of the application.
416 static void initializeOpenSSL();
417 static void cleanupOpenSSL();
420 * Mark openssl as initialized without actually performing any initialization.
421 * Please use this only if you are using a library which requires that it must
422 * make its own calls to SSL_library_init() and related functions.
424 static void markInitialized();
427 * Default randomize method.
429 static void randomize();
435 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
438 std::string peerFixedName_;
439 std::shared_ptr<PasswordCollector> collector_;
440 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
441 ServerNameCallback serverNameCb_;
442 std::vector<ClientHelloCallback> clientHelloCbs_;
445 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
447 static bool initialized_;
449 #ifdef OPENSSL_NPN_NEGOTIATED
451 * Wire-format list of advertised protocols for use in NPN.
453 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
454 static int sNextProtocolsExDataIndex_;
456 static int advertisedNextProtocolCallback(SSL* ssl,
457 const unsigned char** out, unsigned int* outlen, void* data);
458 static int selectNextProtocolCallback(
459 SSL* ssl, unsigned char **out, unsigned char *outlen,
460 const unsigned char *server, unsigned int server_len, void *args);
462 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
463 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
464 // This class contains all allowed ciphers for SSL false start. Call its
465 // `canUseFalseStartWithCipher` to check for cipher qualification.
466 class SSLFalseStartChecker {
468 SSLFalseStartChecker();
470 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
473 static int compare_ulong(const void *x, const void *y);
475 // All ciphers that are allowed to use false start.
476 unsigned long ciphers_[47];
477 unsigned int length_;
481 SSLFalseStartChecker falseStartChecker_;
484 #endif // OPENSSL_NPN_NEGOTIATED
486 static int passwordCallback(char* password, int size, int, void* data);
488 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
490 * The function that will be called directly from openssl
491 * in order for the application to get the tlsext_hostname just after
492 * parsing the Client Hello or Server Hello message. It will then call
493 * the serverNameCb_ function object. Hence, it is sort of a
494 * wrapper/proxy between serverNameCb_ and openssl.
496 * The openssl's primary intention is for SNI support, but we also use it
497 * generically for performing logic after the Client Hello comes in.
499 static int baseServerNameOpenSSLCallback(
501 int* al /* alert (return value) */,
506 std::string providedCiphersString_;
508 // Functions are called when locked by the calling function.
509 static void initializeOpenSSLLocked();
510 static void cleanupOpenSSLLocked();
513 typedef std::shared_ptr<SSLContext> SSLContextPtr;
515 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
520 * Validate that the peer certificate's common name or subject alt names
521 * match what we expect. Currently this only checks for IPs within
522 * subject alt names but it could easily be expanded to check common name
523 * and hostnames as well.
525 * @param cert X509* peer certificate
526 * @param addr sockaddr object containing sockaddr to verify
527 * @param addrLen length of sockaddr as returned by getpeername or accept
528 * @return true iff a subject altname IP matches addr
530 // TODO(agartrell): Add support for things like common name when
532 static bool validatePeerCertNames(X509* cert,
533 const sockaddr* addr,
537 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
538 * accept, getsockname, getpeername, etc family of operations, addrLen's
539 * initial value is ignored and reset.
541 * @param ctx Context from which to retrieve peer sockaddr
542 * @param addrStorage out param for address
543 * @param addrLen out param for length of address
544 * @return true on success, false on failure
546 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
547 sockaddr_storage* addrStorage,