Fix/override bad symbol names
[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 <glog/logging.h>
30
31 namespace folly {
32
33 /**
34  * Override the default password collector.
35  */
36 class PasswordCollector {
37  public:
38   virtual ~PasswordCollector() {}
39   /**
40    * Interface for customizing how to collect private key password.
41    *
42    * By default, OpenSSL prints a prompt on screen and request for password
43    * while loading private key. To implement a custom password collector,
44    * implement this interface and register it with TSSLSocketFactory.
45    *
46    * @param password Pass collected password back to OpenSSL
47    * @param size     Maximum length of password including nullptr character
48    */
49   virtual void getPassword(std::string& password, int size) = 0;
50
51   /**
52    * Return a description of this collector for logging purposes
53    */
54   virtual std::string describe() const = 0;
55 };
56
57 /**
58  * Wrap OpenSSL SSL_CTX into a class.
59  */
60 class SSLContext {
61  public:
62
63   enum SSLVersion {
64      SSLv2,
65      SSLv3,
66      TLSv1
67   };
68
69   enum SSLVerifyPeerEnum{
70     USE_CTX,
71     VERIFY,
72     VERIFY_REQ_CLIENT_CERT,
73     NO_VERIFY
74   };
75
76   struct NextProtocolsItem {
77     int weight;
78     std::list<std::string> protocols;
79   };
80
81   struct AdvertisedNextProtocolsItem {
82     unsigned char *protocols;
83     unsigned length;
84     double probability;
85   };
86
87   /**
88    * Convenience function to call getErrors() with the current errno value.
89    *
90    * Make sure that you only call this when there was no intervening operation
91    * since the last OpenSSL error that may have changed the current errno value.
92    */
93   static std::string getErrors() {
94     return getErrors(errno);
95   }
96
97   /**
98    * Constructor.
99    *
100    * @param version The lowest or oldest SSL version to support.
101    */
102   explicit SSLContext(SSLVersion version = TLSv1);
103   virtual ~SSLContext();
104
105   /**
106    * Set default ciphers to be used in SSL handshake process.
107    *
108    * @param ciphers A list of ciphers to use for TLSv1.0
109    */
110   virtual void ciphers(const std::string& ciphers);
111
112   /**
113    * Low-level method that attempts to set the provided ciphers on the
114    * SSL_CTX object, and throws if something goes wrong.
115    */
116   virtual void setCiphersOrThrow(const std::string& ciphers);
117
118   /**
119    * Method to set verification option in the context object.
120    *
121    * @param verifyPeer SSLVerifyPeerEnum indicating the verification
122    *                       method to use.
123    */
124   virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
125
126   /**
127    * Method to check if peer verfication is set.
128    *
129    * @return true if peer verification is required.
130    *
131    */
132   virtual bool needsPeerVerification() {
133     return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
134               verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
135   }
136
137   /**
138    * Method to fetch Verification mode for a SSLVerifyPeerEnum.
139    * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
140    * context.
141    *
142    * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
143    *                  to be returned
144    *
145    * @return mode flags that can be used with SSL_set_verify
146    */
147   static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
148
149   /**
150    * Method to fetch Verification mode determined by the options
151    * set using setVerificationOption.
152    *
153    * @return mode flags that can be used with SSL_set_verify
154    */
155   virtual int getVerificationMode();
156
157   /**
158    * Enable/Disable authentication. Peer name validation can only be done
159    * if checkPeerCert is true.
160    *
161    * @param checkPeerCert If true, require peer to present valid certificate
162    * @param checkPeerName If true, validate that the certificate common name
163    *                      or alternate name(s) of peer matches the hostname
164    *                      used to connect.
165    * @param peerName      If non-empty, validate that the certificate common
166    *                      name of peer matches the given string (altername
167    *                      name(s) are not used in this case).
168    */
169   virtual void authenticate(bool checkPeerCert, bool checkPeerName,
170                             const std::string& peerName = std::string());
171   /**
172    * Load server certificate.
173    *
174    * @param path   Path to the certificate file
175    * @param format Certificate file format
176    */
177   virtual void loadCertificate(const char* path, const char* format = "PEM");
178   /**
179    * Load private key.
180    *
181    * @param path   Path to the private key file
182    * @param format Private key file format
183    */
184   virtual void loadPrivateKey(const char* path, const char* format = "PEM");
185   /**
186    * Load trusted certificates from specified file.
187    *
188    * @param path Path to trusted certificate file
189    */
190   virtual void loadTrustedCertificates(const char* path);
191   /**
192    * Load trusted certificates from specified X509 certificate store.
193    *
194    * @param store X509 certificate store.
195    */
196   virtual void loadTrustedCertificates(X509_STORE* store);
197   /**
198    * Load a client CA list for validating clients
199    */
200   virtual void loadClientCAList(const char* path);
201   /**
202    * Default randomize method.
203    */
204   virtual void randomize();
205   /**
206    * Override default OpenSSL password collector.
207    *
208    * @param collector Instance of user defined password collector
209    */
210   virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
211   /**
212    * Obtain password collector.
213    *
214    * @return User defined password collector
215    */
216   virtual std::shared_ptr<PasswordCollector> passwordCollector() {
217     return collector_;
218   }
219 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
220   /**
221    * Provide SNI support
222    */
223   enum ServerNameCallbackResult {
224     SERVER_NAME_FOUND,
225     SERVER_NAME_NOT_FOUND,
226     SERVER_NAME_NOT_FOUND_ALERT_FATAL,
227   };
228   /**
229    * Callback function from openssl to give the application a
230    * chance to check the tlsext_hostname just right after parsing
231    * the Client Hello or Server Hello message.
232    *
233    * It is for the server to switch the SSL to another SSL_CTX
234    * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
235    *
236    * If the ServerNameCallback returns:
237    * SERVER_NAME_FOUND:
238    *    server: Send a tlsext_hostname in the Server Hello
239    *    client: No-effect
240    * SERVER_NAME_NOT_FOUND:
241    *    server: Does not send a tlsext_hostname in Server Hello
242    *            and continue the handshake.
243    *    client: No-effect
244    * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
245    *    server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
246    *                       the peer.
247    *
248    * Quote from RFC 6066:
249    * "...
250    * If the server understood the ClientHello extension but
251    * does not recognize the server name, the server SHOULD take one of two
252    * actions: either abort the handshake by sending a fatal-level
253    * unrecognized_name(112) alert or continue the handshake.  It is NOT
254    * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
255    * because the client's behavior in response to warning-level alerts is
256    * unpredictable.
257    * ..."
258    */
259
260   /**
261    * Set the ServerNameCallback
262    */
263   typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
264   virtual void setServerNameCallback(const ServerNameCallback& cb);
265
266   /**
267    * Generic callbacks that are run after we get the Client Hello (right
268    * before we run the ServerNameCallback)
269    */
270   typedef std::function<void(SSL* ssl)> ClientHelloCallback;
271   virtual void addClientHelloCallback(const ClientHelloCallback& cb);
272 #endif
273
274   /**
275    * Create an SSL object from this context.
276    */
277   SSL* createSSL() const;
278
279   /**
280    * Set the options on the SSL_CTX object.
281    */
282   void setOptions(long options);
283
284 #ifdef OPENSSL_NPN_NEGOTIATED
285   /**
286    * Set the list of protocols that this SSL context supports. In server
287    * mode, this is the list of protocols that will be advertised for Next
288    * Protocol Negotiation (NPN). In client mode, the first protocol
289    * advertised by the server that is also on this list is
290    * chosen. Invoking this function with a list of length zero causes NPN
291    * to be disabled.
292    *
293    * @param protocols   List of protocol names. This method makes a copy,
294    *                    so the caller needn't keep the list in scope after
295    *                    the call completes. The list must have at least
296    *                    one element to enable NPN. Each element must have
297    *                    a string length < 256.
298    * @return true if NPN has been activated. False if NPN is disabled.
299    */
300   bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
301   /**
302    * Set weighted list of lists of protocols that this SSL context supports.
303    * In server mode, each element of the list contains a list of protocols that
304    * could be advertised for Next Protocol Negotiation (NPN). The list of
305    * protocols that will be advertised to a client is selected randomly, based
306    * on weights of elements. Client mode doesn't support randomized NPN, so
307    * this list should contain only 1 element. The first protocol advertised
308    * by the server that is also on the list of protocols of this element is
309    * chosen. Invoking this function with a list of length zero causes NPN
310    * to be disabled.
311    *
312    * @param items  List of NextProtocolsItems, Each item contains a list of
313    *               protocol names and weight. After the call of this fucntion
314    *               each non-empty list of protocols will be advertised with
315    *               probability weight/sum_of_weights. This method makes a copy,
316    *               so the caller needn't keep the list in scope after the call
317    *               completes. The list must have at least one element with
318    *               non-zero weight and non-empty protocols list to enable NPN.
319    *               Each name of the protocol must have a string length < 256.
320    * @return true if NPN has been activated. False if NPN is disabled.
321    */
322   bool setRandomizedAdvertisedNextProtocols(
323       const std::list<NextProtocolsItem>& items);
324
325   /**
326    * Disables NPN on this SSL context.
327    */
328   void unsetNextProtocols();
329   void deleteNextProtocolsStrings();
330 #endif // OPENSSL_NPN_NEGOTIATED
331
332   /**
333    * Gets the underlying SSL_CTX for advanced usage
334    */
335   SSL_CTX *getSSLCtx() const {
336     return ctx_;
337   }
338
339   enum SSLLockType {
340     LOCK_MUTEX,
341     LOCK_SPINLOCK,
342     LOCK_NONE
343   };
344
345   /**
346    * Set preferences for how to treat locks in OpenSSL.  This must be
347    * called before the instantiation of any SSLContext objects, otherwise
348    * the defaults will be used.
349    *
350    * OpenSSL has a lock for each module rather than for each object or
351    * data that needs locking.  Some locks protect only refcounts, and
352    * might be better as spinlocks rather than mutexes.  Other locks
353    * may be totally unnecessary if the objects being protected are not
354    * shared between threads in the application.
355    *
356    * By default, all locks are initialized as mutexes.  OpenSSL's lock usage
357    * may change from version to version and you should know what you are doing
358    * before disabling any locks entirely.
359    *
360    * Example: if you don't share SSL sessions between threads in your
361    * application, you may be able to do this
362    *
363    * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
364    */
365   static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
366
367   /**
368    * Examine OpenSSL's error stack, and return a string description of the
369    * errors.
370    *
371    * This operation removes the errors from OpenSSL's error stack.
372    */
373   static std::string getErrors(int errnoCopy);
374
375   /**
376    * We want to vary which cipher we'll use based on the client's TLS version.
377    */
378   void switchCiphersIfTLS11(
379     SSL* ssl,
380     const std::string& tls11CipherString
381   );
382
383   bool checkPeerName() { return checkPeerName_; }
384   std::string peerFixedName() { return peerFixedName_; }
385
386   /**
387    * Helper to match a hostname versus a pattern.
388    */
389   static bool matchName(const char* host, const char* pattern, int size);
390
391  protected:
392   SSL_CTX* ctx_;
393
394  private:
395   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
396
397   bool checkPeerName_;
398   std::string peerFixedName_;
399   std::shared_ptr<PasswordCollector> collector_;
400 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
401   ServerNameCallback serverNameCb_;
402   std::vector<ClientHelloCallback> clientHelloCbs_;
403 #endif
404
405   static std::mutex mutex_;
406   static uint64_t count_;
407
408 #ifdef OPENSSL_NPN_NEGOTIATED
409   /**
410    * Wire-format list of advertised protocols for use in NPN.
411    */
412   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
413   static int sNextProtocolsExDataIndex_;
414
415   static int advertisedNextProtocolCallback(SSL* ssl,
416       const unsigned char** out, unsigned int* outlen, void* data);
417   static int selectNextProtocolCallback(
418     SSL* ssl, unsigned char **out, unsigned char *outlen,
419     const unsigned char *server, unsigned int server_len, void *args);
420 #endif // OPENSSL_NPN_NEGOTIATED
421
422   static int passwordCallback(char* password, int size, int, void* data);
423
424   static void initializeOpenSSL();
425   static void cleanupOpenSSL();
426
427
428 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
429   /**
430    * The function that will be called directly from openssl
431    * in order for the application to get the tlsext_hostname just after
432    * parsing the Client Hello or Server Hello message. It will then call
433    * the serverNameCb_ function object. Hence, it is sort of a
434    * wrapper/proxy between serverNameCb_ and openssl.
435    *
436    * The openssl's primary intention is for SNI support, but we also use it
437    * generically for performing logic after the Client Hello comes in.
438    */
439   static int baseServerNameOpenSSLCallback(
440     SSL* ssl,
441     int* al /* alert (return value) */,
442     void* data
443   );
444 #endif
445
446   std::string providedCiphersString_;
447 };
448
449 typedef std::shared_ptr<SSLContext> SSLContextPtr;
450
451 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
452
453 } // folly