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();
379 #endif // OPENSSL_NPN_NEGOTIATED
382 * Gets the underlying SSL_CTX for advanced usage
384 SSL_CTX *getSSLCtx() const {
395 * Set preferences for how to treat locks in OpenSSL. This must be
396 * called before the instantiation of any SSLContext objects, otherwise
397 * the defaults will be used.
399 * OpenSSL has a lock for each module rather than for each object or
400 * data that needs locking. Some locks protect only refcounts, and
401 * might be better as spinlocks rather than mutexes. Other locks
402 * may be totally unnecessary if the objects being protected are not
403 * shared between threads in the application.
405 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
406 * may change from version to version and you should know what you are doing
407 * before disabling any locks entirely.
409 * Example: if you don't share SSL sessions between threads in your
410 * application, you may be able to do this
412 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
414 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
417 * Examine OpenSSL's error stack, and return a string description of the
420 * This operation removes the errors from OpenSSL's error stack.
422 static std::string getErrors(int errnoCopy);
425 * We want to vary which cipher we'll use based on the client's TLS version.
427 void switchCiphersIfTLS11(
429 const std::string& tls11CipherString
432 bool checkPeerName() { return checkPeerName_; }
433 std::string peerFixedName() { return peerFixedName_; }
435 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
437 * Enable TLS false start, saving a roundtrip for full handshakes. Will only
438 * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
441 void enableFalseStart();
445 * Helper to match a hostname versus a pattern.
447 static bool matchName(const char* host, const char* pattern, int size);
450 * Functions for setting up and cleaning up openssl.
451 * They can be invoked during the start of the application.
453 static void initializeOpenSSL();
454 static void cleanupOpenSSL();
457 * Mark openssl as initialized without actually performing any initialization.
458 * Please use this only if you are using a library which requires that it must
459 * make its own calls to SSL_library_init() and related functions.
461 static void markInitialized();
464 * Default randomize method.
466 static void randomize();
472 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
475 std::string peerFixedName_;
476 std::shared_ptr<PasswordCollector> collector_;
477 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
478 ServerNameCallback serverNameCb_;
479 std::vector<ClientHelloCallback> clientHelloCbs_;
482 ClientProtocolFilterCallback clientProtoFilter_{nullptr};
484 static bool initialized_;
486 #ifdef OPENSSL_NPN_NEGOTIATED
488 struct AdvertisedNextProtocolsItem {
489 unsigned char* protocols;
494 * Wire-format list of advertised protocols for use in NPN.
496 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
497 std::vector<int> advertisedNextProtocolWeights_;
498 std::discrete_distribution<int> nextProtocolDistribution_;
499 Random::DefaultGenerator nextProtocolPicker_;
501 static int sNextProtocolsExDataIndex_;
503 static int advertisedNextProtocolCallback(SSL* ssl,
504 const unsigned char** out, unsigned int* outlen, void* data);
505 static int selectNextProtocolCallback(
506 SSL* ssl, unsigned char **out, unsigned char *outlen,
507 const unsigned char *server, unsigned int server_len, void *args);
509 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
510 static int alpnSelectCallback(SSL* ssl,
511 const unsigned char** out,
512 unsigned char* outlen,
513 const unsigned char* in,
517 size_t pickNextProtocols();
519 #endif // OPENSSL_NPN_NEGOTIATED
521 static int passwordCallback(char* password, int size, int, void* data);
523 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
525 * The function that will be called directly from openssl
526 * in order for the application to get the tlsext_hostname just after
527 * parsing the Client Hello or Server Hello message. It will then call
528 * the serverNameCb_ function object. Hence, it is sort of a
529 * wrapper/proxy between serverNameCb_ and openssl.
531 * The openssl's primary intention is for SNI support, but we also use it
532 * generically for performing logic after the Client Hello comes in.
534 static int baseServerNameOpenSSLCallback(
536 int* al /* alert (return value) */,
541 std::string providedCiphersString_;
543 // Functions are called when locked by the calling function.
544 static void initializeOpenSSLLocked();
545 static void cleanupOpenSSLLocked();
548 typedef std::shared_ptr<SSLContext> SSLContextPtr;
550 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
555 * Validate that the peer certificate's common name or subject alt names
556 * match what we expect. Currently this only checks for IPs within
557 * subject alt names but it could easily be expanded to check common name
558 * and hostnames as well.
560 * @param cert X509* peer certificate
561 * @param addr sockaddr object containing sockaddr to verify
562 * @param addrLen length of sockaddr as returned by getpeername or accept
563 * @return true iff a subject altname IP matches addr
565 // TODO(agartrell): Add support for things like common name when
567 static bool validatePeerCertNames(X509* cert,
568 const sockaddr* addr,
572 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
573 * accept, getsockname, getpeername, etc family of operations, addrLen's
574 * initial value is ignored and reset.
576 * @param ctx Context from which to retrieve peer sockaddr
577 * @param addrStorage out param for address
578 * @param addrLen out param for length of address
579 * @return true on success, false on failure
581 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
582 sockaddr_storage* addrStorage,