Kill fbthrift dep
[folly.git] / folly / io / async / SSLContext.h
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <mutex>
20 #include <list>
21 #include <map>
22 #include <vector>
23 #include <memory>
24 #include <string>
25
26 #include <openssl/ssl.h>
27 #include <openssl/tls1.h>
28
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31
32 #include <glog/logging.h>
33
34 namespace folly {
35
36 /**
37  * Override the default password collector.
38  */
39 class PasswordCollector {
40  public:
41   virtual ~PasswordCollector() {}
42   /**
43    * Interface for customizing how to collect private key password.
44    *
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.
48    *
49    * @param password Pass collected password back to OpenSSL
50    * @param size     Maximum length of password including nullptr character
51    */
52   virtual void getPassword(std::string& password, int size) = 0;
53
54   /**
55    * Return a description of this collector for logging purposes
56    */
57   virtual std::string describe() const = 0;
58 };
59
60 /**
61  * Wrap OpenSSL SSL_CTX into a class.
62  */
63 class SSLContext {
64  public:
65
66   enum SSLVersion {
67      SSLv2,
68      SSLv3,
69      TLSv1
70   };
71
72   enum SSLVerifyPeerEnum{
73     USE_CTX,
74     VERIFY,
75     VERIFY_REQ_CLIENT_CERT,
76     NO_VERIFY
77   };
78
79   struct NextProtocolsItem {
80     int weight;
81     std::list<std::string> protocols;
82   };
83
84   struct AdvertisedNextProtocolsItem {
85     unsigned char *protocols;
86     unsigned length;
87     double probability;
88   };
89
90   /**
91    * Convenience function to call getErrors() with the current errno value.
92    *
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.
95    */
96   static std::string getErrors() {
97     return getErrors(errno);
98   }
99
100   /**
101    * Constructor.
102    *
103    * @param version The lowest or oldest SSL version to support.
104    */
105   explicit SSLContext(SSLVersion version = TLSv1);
106   virtual ~SSLContext();
107
108   /**
109    * Set default ciphers to be used in SSL handshake process.
110    *
111    * @param ciphers A list of ciphers to use for TLSv1.0
112    */
113   virtual void ciphers(const std::string& ciphers);
114
115   /**
116    * Low-level method that attempts to set the provided ciphers on the
117    * SSL_CTX object, and throws if something goes wrong.
118    */
119   virtual void setCiphersOrThrow(const std::string& ciphers);
120
121   /**
122    * Method to set verification option in the context object.
123    *
124    * @param verifyPeer SSLVerifyPeerEnum indicating the verification
125    *                       method to use.
126    */
127   virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
128
129   /**
130    * Method to check if peer verfication is set.
131    *
132    * @return true if peer verification is required.
133    *
134    */
135   virtual bool needsPeerVerification() {
136     return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
137               verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
138   }
139
140   /**
141    * Method to fetch Verification mode for a SSLVerifyPeerEnum.
142    * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
143    * context.
144    *
145    * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
146    *                  to be returned
147    *
148    * @return mode flags that can be used with SSL_set_verify
149    */
150   static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
151
152   /**
153    * Method to fetch Verification mode determined by the options
154    * set using setVerificationOption.
155    *
156    * @return mode flags that can be used with SSL_set_verify
157    */
158   virtual int getVerificationMode();
159
160   /**
161    * Enable/Disable authentication. Peer name validation can only be done
162    * if checkPeerCert is true.
163    *
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
167    *                      used to connect.
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).
171    */
172   virtual void authenticate(bool checkPeerCert, bool checkPeerName,
173                             const std::string& peerName = std::string());
174   /**
175    * Load server certificate.
176    *
177    * @param path   Path to the certificate file
178    * @param format Certificate file format
179    */
180   virtual void loadCertificate(const char* path, const char* format = "PEM");
181   /**
182    * Load private key.
183    *
184    * @param path   Path to the private key file
185    * @param format Private key file format
186    */
187   virtual void loadPrivateKey(const char* path, const char* format = "PEM");
188   /**
189    * Load trusted certificates from specified file.
190    *
191    * @param path Path to trusted certificate file
192    */
193   virtual void loadTrustedCertificates(const char* path);
194   /**
195    * Load trusted certificates from specified X509 certificate store.
196    *
197    * @param store X509 certificate store.
198    */
199   virtual void loadTrustedCertificates(X509_STORE* store);
200   /**
201    * Load a client CA list for validating clients
202    */
203   virtual void loadClientCAList(const char* path);
204   /**
205    * Override default OpenSSL password collector.
206    *
207    * @param collector Instance of user defined password collector
208    */
209   virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
210   /**
211    * Obtain password collector.
212    *
213    * @return User defined password collector
214    */
215   virtual std::shared_ptr<PasswordCollector> passwordCollector() {
216     return collector_;
217   }
218 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
219   /**
220    * Provide SNI support
221    */
222   enum ServerNameCallbackResult {
223     SERVER_NAME_FOUND,
224     SERVER_NAME_NOT_FOUND,
225     SERVER_NAME_NOT_FOUND_ALERT_FATAL,
226   };
227   /**
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.
231    *
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).
234    *
235    * If the ServerNameCallback returns:
236    * SERVER_NAME_FOUND:
237    *    server: Send a tlsext_hostname in the Server Hello
238    *    client: No-effect
239    * SERVER_NAME_NOT_FOUND:
240    *    server: Does not send a tlsext_hostname in Server Hello
241    *            and continue the handshake.
242    *    client: No-effect
243    * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
244    *    server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
245    *                       the peer.
246    *
247    * Quote from RFC 6066:
248    * "...
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
255    * unpredictable.
256    * ..."
257    */
258
259   /**
260    * Set the ServerNameCallback
261    */
262   typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
263   virtual void setServerNameCallback(const ServerNameCallback& cb);
264
265   /**
266    * Generic callbacks that are run after we get the Client Hello (right
267    * before we run the ServerNameCallback)
268    */
269   typedef std::function<void(SSL* ssl)> ClientHelloCallback;
270   virtual void addClientHelloCallback(const ClientHelloCallback& cb);
271 #endif
272
273   /**
274    * Create an SSL object from this context.
275    */
276   SSL* createSSL() const;
277
278   /**
279    * Set the options on the SSL_CTX object.
280    */
281   void setOptions(long options);
282
283 #ifdef OPENSSL_NPN_NEGOTIATED
284   /**
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
290    * to be disabled.
291    *
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.
298    */
299   bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
300   /**
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
309    * to be disabled.
310    *
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.
320    */
321   bool setRandomizedAdvertisedNextProtocols(
322       const std::list<NextProtocolsItem>& items);
323
324   /**
325    * Disables NPN on this SSL context.
326    */
327   void unsetNextProtocols();
328   void deleteNextProtocolsStrings();
329 #endif // OPENSSL_NPN_NEGOTIATED
330
331   /**
332    * Gets the underlying SSL_CTX for advanced usage
333    */
334   SSL_CTX *getSSLCtx() const {
335     return ctx_;
336   }
337
338   enum SSLLockType {
339     LOCK_MUTEX,
340     LOCK_SPINLOCK,
341     LOCK_NONE
342   };
343
344   /**
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.
348    *
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.
354    *
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.
358    *
359    * Example: if you don't share SSL sessions between threads in your
360    * application, you may be able to do this
361    *
362    * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
363    */
364   static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
365
366   /**
367    * Examine OpenSSL's error stack, and return a string description of the
368    * errors.
369    *
370    * This operation removes the errors from OpenSSL's error stack.
371    */
372   static std::string getErrors(int errnoCopy);
373
374   /**
375    * We want to vary which cipher we'll use based on the client's TLS version.
376    */
377   void switchCiphersIfTLS11(
378     SSL* ssl,
379     const std::string& tls11CipherString
380   );
381
382   bool checkPeerName() { return checkPeerName_; }
383   std::string peerFixedName() { return peerFixedName_; }
384
385   /**
386    * Helper to match a hostname versus a pattern.
387    */
388   static bool matchName(const char* host, const char* pattern, int size);
389
390   /**
391    * Functions for setting up and cleaning up openssl.
392    * They can be invoked during the start of the application.
393    */
394   static void initializeOpenSSL();
395   static void cleanupOpenSSL();
396
397   /**
398    * Default randomize method.
399    */
400   static void randomize();
401
402  protected:
403   SSL_CTX* ctx_;
404
405  private:
406   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
407
408   bool checkPeerName_;
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_;
414 #endif
415
416   static std::mutex mutex_;
417   static bool initialized_;
418
419 #ifndef SSLCONTEXT_NO_REFCOUNT
420   static uint64_t count_;
421 #endif
422
423 #ifdef OPENSSL_NPN_NEGOTIATED
424   /**
425    * Wire-format list of advertised protocols for use in NPN.
426    */
427   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
428   static int sNextProtocolsExDataIndex_;
429
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
436
437   static int passwordCallback(char* password, int size, int, void* data);
438
439 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
440   /**
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.
446    *
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.
449    */
450   static int baseServerNameOpenSSLCallback(
451     SSL* ssl,
452     int* al /* alert (return value) */,
453     void* data
454   );
455 #endif
456
457   std::string providedCiphersString_;
458
459   // Functions are called when locked by the calling function.
460   static void initializeOpenSSLLocked();
461   static void cleanupOpenSSLLocked();
462 };
463
464 typedef std::shared_ptr<SSLContext> SSLContextPtr;
465
466 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
467
468 class OpenSSLUtils {
469  public:
470   /**
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.
475    *
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
480    */
481   // TODO(agartrell): Add support for things like common name when
482   // necessary.
483   static bool validatePeerCertNames(X509* cert,
484                                     const sockaddr* addr,
485                                     socklen_t addrLen);
486
487   /**
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.
491    *
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
496    */
497   static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
498                                              sockaddr_storage* addrStorage,
499                                              socklen_t* addrLen);
500
501 };
502
503
504 } // folly