2 * Copyright 2014 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>
37 * Override the default password collector.
39 class PasswordCollector {
41 virtual ~PasswordCollector() {}
43 * Interface for customizing how to collect private key password.
45 * By default, OpenSSL prints a prompt on screen and request for password
46 * while loading private key. To implement a custom password collector,
47 * implement this interface and register it with TSSLSocketFactory.
49 * @param password Pass collected password back to OpenSSL
50 * @param size Maximum length of password including nullptr character
52 virtual void getPassword(std::string& password, int size) = 0;
55 * Return a description of this collector for logging purposes
57 virtual std::string describe() const = 0;
61 * Wrap OpenSSL SSL_CTX into a class.
72 enum SSLVerifyPeerEnum{
75 VERIFY_REQ_CLIENT_CERT,
79 struct NextProtocolsItem {
81 std::list<std::string> protocols;
84 struct AdvertisedNextProtocolsItem {
85 unsigned char *protocols;
91 * Convenience function to call getErrors() with the current errno value.
93 * Make sure that you only call this when there was no intervening operation
94 * since the last OpenSSL error that may have changed the current errno value.
96 static std::string getErrors() {
97 return getErrors(errno);
103 * @param version The lowest or oldest SSL version to support.
105 explicit SSLContext(SSLVersion version = TLSv1);
106 virtual ~SSLContext();
109 * Set default ciphers to be used in SSL handshake process.
111 * @param ciphers A list of ciphers to use for TLSv1.0
113 virtual void ciphers(const std::string& ciphers);
116 * Low-level method that attempts to set the provided ciphers on the
117 * SSL_CTX object, and throws if something goes wrong.
119 virtual void setCiphersOrThrow(const std::string& ciphers);
122 * Method to set verification option in the context object.
124 * @param verifyPeer SSLVerifyPeerEnum indicating the verification
127 virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
130 * Method to check if peer verfication is set.
132 * @return true if peer verification is required.
135 virtual bool needsPeerVerification() {
136 return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
137 verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
141 * Method to fetch Verification mode for a SSLVerifyPeerEnum.
142 * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
145 * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
148 * @return mode flags that can be used with SSL_set_verify
150 static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
153 * Method to fetch Verification mode determined by the options
154 * set using setVerificationOption.
156 * @return mode flags that can be used with SSL_set_verify
158 virtual int getVerificationMode();
161 * Enable/Disable authentication. Peer name validation can only be done
162 * if checkPeerCert is true.
164 * @param checkPeerCert If true, require peer to present valid certificate
165 * @param checkPeerName If true, validate that the certificate common name
166 * or alternate name(s) of peer matches the hostname
168 * @param peerName If non-empty, validate that the certificate common
169 * name of peer matches the given string (altername
170 * name(s) are not used in this case).
172 virtual void authenticate(bool checkPeerCert, bool checkPeerName,
173 const std::string& peerName = std::string());
175 * Load server certificate.
177 * @param path Path to the certificate file
178 * @param format Certificate file format
180 virtual void loadCertificate(const char* path, const char* format = "PEM");
184 * @param path Path to the private key file
185 * @param format Private key file format
187 virtual void loadPrivateKey(const char* path, const char* format = "PEM");
189 * Load trusted certificates from specified file.
191 * @param path Path to trusted certificate file
193 virtual void loadTrustedCertificates(const char* path);
195 * Load trusted certificates from specified X509 certificate store.
197 * @param store X509 certificate store.
199 virtual void loadTrustedCertificates(X509_STORE* store);
201 * Load a client CA list for validating clients
203 virtual void loadClientCAList(const char* path);
205 * Override default OpenSSL password collector.
207 * @param collector Instance of user defined password collector
209 virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
211 * Obtain password collector.
213 * @return User defined password collector
215 virtual std::shared_ptr<PasswordCollector> passwordCollector() {
218 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
220 * Provide SNI support
222 enum ServerNameCallbackResult {
224 SERVER_NAME_NOT_FOUND,
225 SERVER_NAME_NOT_FOUND_ALERT_FATAL,
228 * Callback function from openssl to give the application a
229 * chance to check the tlsext_hostname just right after parsing
230 * the Client Hello or Server Hello message.
232 * It is for the server to switch the SSL to another SSL_CTX
233 * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
235 * If the ServerNameCallback returns:
237 * server: Send a tlsext_hostname in the Server Hello
239 * SERVER_NAME_NOT_FOUND:
240 * server: Does not send a tlsext_hostname in Server Hello
241 * and continue the handshake.
243 * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
244 * server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
247 * Quote from RFC 6066:
249 * If the server understood the ClientHello extension but
250 * does not recognize the server name, the server SHOULD take one of two
251 * actions: either abort the handshake by sending a fatal-level
252 * unrecognized_name(112) alert or continue the handshake. It is NOT
253 * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
254 * because the client's behavior in response to warning-level alerts is
260 * Set the ServerNameCallback
262 typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
263 virtual void setServerNameCallback(const ServerNameCallback& cb);
266 * Generic callbacks that are run after we get the Client Hello (right
267 * before we run the ServerNameCallback)
269 typedef std::function<void(SSL* ssl)> ClientHelloCallback;
270 virtual void addClientHelloCallback(const ClientHelloCallback& cb);
274 * Create an SSL object from this context.
276 SSL* createSSL() const;
279 * Set the options on the SSL_CTX object.
281 void setOptions(long options);
283 #ifdef OPENSSL_NPN_NEGOTIATED
285 * Set the list of protocols that this SSL context supports. In server
286 * mode, this is the list of protocols that will be advertised for Next
287 * Protocol Negotiation (NPN). In client mode, the first protocol
288 * advertised by the server that is also on this list is
289 * chosen. Invoking this function with a list of length zero causes NPN
292 * @param protocols List of protocol names. This method makes a copy,
293 * so the caller needn't keep the list in scope after
294 * the call completes. The list must have at least
295 * one element to enable NPN. Each element must have
296 * a string length < 256.
297 * @return true if NPN has been activated. False if NPN is disabled.
299 bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
301 * Set weighted list of lists of protocols that this SSL context supports.
302 * In server mode, each element of the list contains a list of protocols that
303 * could be advertised for Next Protocol Negotiation (NPN). The list of
304 * protocols that will be advertised to a client is selected randomly, based
305 * on weights of elements. Client mode doesn't support randomized NPN, so
306 * this list should contain only 1 element. The first protocol advertised
307 * by the server that is also on the list of protocols of this element is
308 * chosen. Invoking this function with a list of length zero causes NPN
311 * @param items List of NextProtocolsItems, Each item contains a list of
312 * protocol names and weight. After the call of this fucntion
313 * each non-empty list of protocols will be advertised with
314 * probability weight/sum_of_weights. This method makes a copy,
315 * so the caller needn't keep the list in scope after the call
316 * completes. The list must have at least one element with
317 * non-zero weight and non-empty protocols list to enable NPN.
318 * Each name of the protocol must have a string length < 256.
319 * @return true if NPN has been activated. False if NPN is disabled.
321 bool setRandomizedAdvertisedNextProtocols(
322 const std::list<NextProtocolsItem>& items);
325 * Disables NPN on this SSL context.
327 void unsetNextProtocols();
328 void deleteNextProtocolsStrings();
329 #endif // OPENSSL_NPN_NEGOTIATED
332 * Gets the underlying SSL_CTX for advanced usage
334 SSL_CTX *getSSLCtx() const {
345 * Set preferences for how to treat locks in OpenSSL. This must be
346 * called before the instantiation of any SSLContext objects, otherwise
347 * the defaults will be used.
349 * OpenSSL has a lock for each module rather than for each object or
350 * data that needs locking. Some locks protect only refcounts, and
351 * might be better as spinlocks rather than mutexes. Other locks
352 * may be totally unnecessary if the objects being protected are not
353 * shared between threads in the application.
355 * By default, all locks are initialized as mutexes. OpenSSL's lock usage
356 * may change from version to version and you should know what you are doing
357 * before disabling any locks entirely.
359 * Example: if you don't share SSL sessions between threads in your
360 * application, you may be able to do this
362 * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
364 static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
367 * Examine OpenSSL's error stack, and return a string description of the
370 * This operation removes the errors from OpenSSL's error stack.
372 static std::string getErrors(int errnoCopy);
375 * We want to vary which cipher we'll use based on the client's TLS version.
377 void switchCiphersIfTLS11(
379 const std::string& tls11CipherString
382 bool checkPeerName() { return checkPeerName_; }
383 std::string peerFixedName() { return peerFixedName_; }
386 * Helper to match a hostname versus a pattern.
388 static bool matchName(const char* host, const char* pattern, int size);
391 * Functions for setting up and cleaning up openssl.
392 * They can be invoked during the start of the application.
394 static void initializeOpenSSL();
395 static void cleanupOpenSSL();
398 * Default randomize method.
400 static void randomize();
406 SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
409 std::string peerFixedName_;
410 std::shared_ptr<PasswordCollector> collector_;
411 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
412 ServerNameCallback serverNameCb_;
413 std::vector<ClientHelloCallback> clientHelloCbs_;
416 static std::mutex mutex_;
417 static bool initialized_;
419 #ifndef SSLCONTEXT_NO_REFCOUNT
420 static uint64_t count_;
423 #ifdef OPENSSL_NPN_NEGOTIATED
425 * Wire-format list of advertised protocols for use in NPN.
427 std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
428 static int sNextProtocolsExDataIndex_;
430 static int advertisedNextProtocolCallback(SSL* ssl,
431 const unsigned char** out, unsigned int* outlen, void* data);
432 static int selectNextProtocolCallback(
433 SSL* ssl, unsigned char **out, unsigned char *outlen,
434 const unsigned char *server, unsigned int server_len, void *args);
435 #endif // OPENSSL_NPN_NEGOTIATED
437 static int passwordCallback(char* password, int size, int, void* data);
439 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
441 * The function that will be called directly from openssl
442 * in order for the application to get the tlsext_hostname just after
443 * parsing the Client Hello or Server Hello message. It will then call
444 * the serverNameCb_ function object. Hence, it is sort of a
445 * wrapper/proxy between serverNameCb_ and openssl.
447 * The openssl's primary intention is for SNI support, but we also use it
448 * generically for performing logic after the Client Hello comes in.
450 static int baseServerNameOpenSSLCallback(
452 int* al /* alert (return value) */,
457 std::string providedCiphersString_;
459 // Functions are called when locked by the calling function.
460 static void initializeOpenSSLLocked();
461 static void cleanupOpenSSLLocked();
464 typedef std::shared_ptr<SSLContext> SSLContextPtr;
466 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
471 * Validate that the peer certificate's common name or subject alt names
472 * match what we expect. Currently this only checks for IPs within
473 * subject alt names but it could easily be expanded to check common name
474 * and hostnames as well.
476 * @param cert X509* peer certificate
477 * @param addr sockaddr object containing sockaddr to verify
478 * @param addrLen length of sockaddr as returned by getpeername or accept
479 * @return true iff a subject altname IP matches addr
481 // TODO(agartrell): Add support for things like common name when
483 static bool validatePeerCertNames(X509* cert,
484 const sockaddr* addr,
488 * Get the peer socket address from an X509_STORE_CTX*. Unlike the
489 * accept, getsockname, getpeername, etc family of operations, addrLen's
490 * initial value is ignored and reset.
492 * @param ctx Context from which to retrieve peer sockaddr
493 * @param addrStorage out param for address
494 * @param addrLen out param for length of address
495 * @return true on success, false on failure
497 static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
498 sockaddr_storage* addrStorage,