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() {}
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;
97 * Convenience function to call getErrors() with the current errno value.
99 * Make sure that you only call this when there was no intervening operation
100 * since the last OpenSSL error that may have changed the current errno value.
102 static std::string getErrors() {
103 return getErrors(errno);
109 * @param version The lowest or oldest SSL version to support.
111 explicit SSLContext(SSLVersion version = TLSv1);
112 virtual ~SSLContext();
115 * Set default ciphers to be used in SSL handshake process.
117 * @param ciphers A list of ciphers to use for TLSv1.0
119 virtual void ciphers(const std::string& ciphers);
122 * Low-level method that attempts to set the provided ciphers on the
123 * SSL_CTX object, and throws if something goes wrong.
125 virtual void setCiphersOrThrow(const std::string& ciphers);
128 * Method to set verification option in the context object.
130 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
133 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
136 * Method to check if peer verfication is set.
138 * @return true if peer verification is required.
141 virtual bool needsPeerVerification() {
142 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
143 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
147 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
148 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
151 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
154 * @return mode flags that can be used with SSL_set_verify
156 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
159 * Method to fetch Verification mode determined by the options
160 * set using setVerificationOption.
162 * @return mode flags that can be used with SSL_set_verify
164 virtual int getVerificationMode();
167 * Enable/Disable authentication. Peer name validation can only be done
168 * if checkPeerCert is true.
170 * @param checkPeerCert If true, require peer to present valid certificate
171 * @param checkPeerName If true, validate that the certificate common name
172 * or alternate name(s) of peer matches the hostname
174 * @param peerName If non-empty, validate that the certificate common
175 * name of peer matches the given string (altername
176 * name(s) are not used in this case).
178 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
179 const std::string& peerName = std::string());
181 * Load server certificate.
183 * @param path Path to the certificate file
184 * @param format Certificate file format
186 virtual void loadCertificate(const char* path, const char* format = "PEM");
190 * @param path Path to the private key file
191 * @param format Private key file format
193 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
195 * Load trusted certificates from specified file.
197 * @param path Path to trusted certificate file
199 virtual void loadTrustedCertificates(const char* path);
201 * Load trusted certificates from specified X509 certificate store.
203 * @param store X509 certificate store.
205 virtual void loadTrustedCertificates(X509_STORE* store);
207 * Load a client CA list for validating clients
209 virtual void loadClientCAList(const char* path);
211 * Override default OpenSSL password collector.
213 * @param collector Instance of user defined password collector
215 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
217 * Obtain password collector.
219 * @return User defined password collector
221 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
224 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
226 * Provide SNI support
228 enum ServerNameCallbackResult {
230 SERVER_NAME_NOT_FOUND,
231 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
234 * Callback function from openssl to give the application a
235 * chance to check the tlsext_hostname just right after parsing
236 * the Client Hello or Server Hello message.
238 * It is for the server to switch the SSL to another SSL_CTX
239 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
241 * If the ServerNameCallback returns:
243 * server: Send a tlsext_hostname in the Server Hello
245 * SERVER_NAME_NOT_FOUND:
246 * server: Does not send a tlsext_hostname in Server Hello
247 * and continue the handshake.
249 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
250 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
253 * Quote from RFC 6066:
255 * If the server understood the ClientHello extension but
256 * does not recognize the server name, the server SHOULD take one of two
257 * actions: either abort the handshake by sending a fatal-level
258 * unrecognized_name(112) alert or continue the handshake. It is NOT
259 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
260 * because the client's behavior in response to warning-level alerts is
266 * Set the ServerNameCallback
268 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
269 virtual void setServerNameCallback(const ServerNameCallback& cb);
272 * Generic callbacks that are run after we get the Client Hello (right
273 * before we run the ServerNameCallback)
275 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
276 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
280 * Create an SSL object from this context.
282 SSL* createSSL() const;
285 * Set the options on the SSL_CTX object.
287 void setOptions(long options);
289 #ifdef OPENSSL_NPN_NEGOTIATED
291 * Set the list of protocols that this SSL context supports. In server
292 * mode, this is the list of protocols that will be advertised for Next
293 * Protocol Negotiation (NPN). In client mode, the first protocol
294 * advertised by the server that is also on this list is
295 * chosen. Invoking this function with a list of length zero causes NPN
298 * @param protocols List of protocol names. This method makes a copy,
299 * so the caller needn't keep the list in scope after
300 * the call completes. The list must have at least
301 * one element to enable NPN. Each element must have
302 * a string length < 256.
303 * @return true if NPN has been activated. False if NPN is disabled.
305 bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
307 * Set weighted list of lists of protocols that this SSL context supports.
308 * In server mode, each element of the list contains a list of protocols that
309 * could be advertised for Next Protocol Negotiation (NPN). The list of
310 * protocols that will be advertised to a client is selected randomly, based
311 * on weights of elements. Client mode doesn't support randomized NPN, so
312 * this list should contain only 1 element. The first protocol advertised
313 * by the server that is also on the list of protocols of this element is
314 * chosen. Invoking this function with a list of length zero causes NPN
317 * @param items List of NextProtocolsItems, Each item contains a list of
318 * protocol names and weight. After the call of this fucntion
319 * each non-empty list of protocols will be advertised with
320 * probability weight/sum_of_weights. This method makes a copy,
321 * so the caller needn't keep the list in scope after the call
322 * completes. The list must have at least one element with
323 * non-zero weight and non-empty protocols list to enable NPN.
324 * Each name of the protocol must have a string length < 256.
325 * @return true if NPN has been activated. False if NPN is disabled.
327 bool setRandomizedAdvertisedNextProtocols(
328 const std::list<NextProtocolsItem>& items);
331 * Disables NPN on this SSL context.
333 void unsetNextProtocols();
334 void deleteNextProtocolsStrings();
336 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
337 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
338 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
340 #endif // OPENSSL_NPN_NEGOTIATED
343 * Gets the underlying SSL_CTX for advanced usage
345 SSL_CTX *getSSLCtx() const {
356 * Set preferences for how to treat locks in OpenSSL. This must be
357 * called before the instantiation of any SSLContext objects, otherwise
358 * the defaults will be used.
360 * OpenSSL has a lock for each module rather than for each object or
361 * data that needs locking. Some locks protect only refcounts, and
362 * might be better as spinlocks rather than mutexes. Other locks
363 * may be totally unnecessary if the objects being protected are not
364 * shared between threads in the application.
366 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
367 * may change from version to version and you should know what you are doing
368 * before disabling any locks entirely.
370 * Example: if you don't share SSL sessions between threads in your
371 * application, you may be able to do this
373 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
375 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
378 * Examine OpenSSL's error stack, and return a string description of the
381 * This operation removes the errors from OpenSSL's error stack.
383 static std::string getErrors(int errnoCopy);
386 * We want to vary which cipher we'll use based on the client's TLS version.
388 void switchCiphersIfTLS11(
390 const std::string& tls11CipherString
393 bool checkPeerName() { return checkPeerName_; }
394 std::string peerFixedName() { return peerFixedName_; }
397 * Helper to match a hostname versus a pattern.
399 static bool matchName(const char* host, const char* pattern, int size);
402 * Functions for setting up and cleaning up openssl.
403 * They can be invoked during the start of the application.
405 static void initializeOpenSSL();
406 static void cleanupOpenSSL();
409 * Mark openssl as initialized without actually performing any initialization.
410 * Please use this only if you are using a library which requires that it must
411 * make its own calls to SSL_library_init() and related functions.
413 static void markInitialized();
416 * Default randomize method.
418 static void randomize();
424 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
427 std::string peerFixedName_;
428 std::shared_ptr<PasswordCollector> collector_;
429 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
430 ServerNameCallback serverNameCb_;
431 std::vector<ClientHelloCallback> clientHelloCbs_;
434 static std::mutex mutex_;
435 static bool initialized_;
437 #ifdef OPENSSL_NPN_NEGOTIATED
439 * Wire-format list of advertised protocols for use in NPN.
441 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
442 static int sNextProtocolsExDataIndex_;
444 static int advertisedNextProtocolCallback(SSL* ssl,
445 const unsigned char** out, unsigned int* outlen, void* data);
446 static int selectNextProtocolCallback(
447 SSL* ssl, unsigned char **out, unsigned char *outlen,
448 const unsigned char *server, unsigned int server_len, void *args);
450 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
451 FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
452 // This class contains all allowed ciphers for SSL false start. Call its
453 // `canUseFalseStartWithCipher` to check for cipher qualification.
454 class SSLFalseStartChecker {
456 SSLFalseStartChecker();
458 bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
461 static int compare_ulong(const void *x, const void *y);
463 // All ciphers that are allowed to use false start.
464 unsigned long ciphers_[47];
465 unsigned int length_;
469 SSLFalseStartChecker falseStartChecker_;
472 #endif // OPENSSL_NPN_NEGOTIATED
474 static int passwordCallback(char* password, int size, int, void* data);
476 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
478 * The function that will be called directly from openssl
479 * in order for the application to get the tlsext_hostname just after
480 * parsing the Client Hello or Server Hello message. It will then call
481 * the serverNameCb_ function object. Hence, it is sort of a
482 * wrapper/proxy between serverNameCb_ and openssl.
484 * The openssl's primary intention is for SNI support, but we also use it
485 * generically for performing logic after the Client Hello comes in.
487 static int baseServerNameOpenSSLCallback(
489 int* al /* alert (return value) */,
494 std::string providedCiphersString_;
496 // Functions are called when locked by the calling function.
497 static void initializeOpenSSLLocked();
498 static void cleanupOpenSSLLocked();
501 typedef std::shared_ptr<SSLContext> SSLContextPtr;
503 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
508 * Validate that the peer certificate's common name or subject alt names
509 * match what we expect. Currently this only checks for IPs within
510 * subject alt names but it could easily be expanded to check common name
511 * and hostnames as well.
513 * @param cert X509* peer certificate
514 * @param addr sockaddr object containing sockaddr to verify
515 * @param addrLen length of sockaddr as returned by getpeername or accept
516 * @return true iff a subject altname IP matches addr
518 // TODO(agartrell): Add support for things like common name when
520 static bool validatePeerCertNames(X509* cert,
521 const sockaddr* addr,
525 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
526 * accept, getsockname, getpeername, etc family of operations, addrLen's
527 * initial value is ignored and reset.
529 * @param ctx Context from which to retrieve peer sockaddr
530 * @param addrStorage out param for address
531 * @param addrLen out param for length of address
532 * @return true on success, false on failure
534 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
535 sockaddr_storage* addrStorage,