Add support for probabilistically choosing server ciphers
[folly.git] / folly / io / async / SSLContext.h
1 /*
2  * Copyright 2016 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 #include <random>
26
27 #include <openssl/ssl.h>
28 #include <openssl/tls1.h>
29
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32
33 #include <glog/logging.h>
34
35 #ifndef FOLLY_NO_CONFIG
36 #include <folly/folly-config.h>
37 #endif
38
39 #include <folly/Random.h>
40 #include <folly/Range.h>
41 #include <folly/io/async/ssl/OpenSSLPtrTypes.h>
42 #include <folly/io/async/ssl/OpenSSLUtils.h>
43
44 namespace folly {
45
46 /**
47  * Override the default password collector.
48  */
49 class PasswordCollector {
50  public:
51   virtual ~PasswordCollector() = default;
52   /**
53    * Interface for customizing how to collect private key password.
54    *
55    * By default, OpenSSL prints a prompt on screen and request for password
56    * while loading private key. To implement a custom password collector,
57    * implement this interface and register it with TSSLSocketFactory.
58    *
59    * @param password Pass collected password back to OpenSSL
60    * @param size     Maximum length of password including nullptr character
61    */
62   virtual void getPassword(std::string& password, int size) = 0;
63
64   /**
65    * Return a description of this collector for logging purposes
66    */
67   virtual std::string describe() const = 0;
68 };
69
70 /**
71  * Wrap OpenSSL SSL_CTX into a class.
72  */
73 class SSLContext {
74  public:
75
76   enum SSLVersion {
77      SSLv2,
78      SSLv3,
79      TLSv1
80   };
81
82   /**
83    * Defines the way that peers are verified.
84    **/
85   enum SSLVerifyPeerEnum {
86     // Used by AsyncSSLSocket to delegate to the SSLContext's setting
87     USE_CTX,
88     // For server side - request a client certificate and verify the
89     // certificate if it is sent.  Does not fail if the client does not present
90     // a certificate.
91     // For client side - validates the server certificate or fails.
92     VERIFY,
93     // For server side - same as VERIFY but will fail if no certificate
94     // is sent.
95     // For client side - same as VERIFY.
96     VERIFY_REQ_CLIENT_CERT,
97     // No verification is done for both server and client side.
98     NO_VERIFY
99   };
100
101   struct NextProtocolsItem {
102     NextProtocolsItem(int wt, const std::list<std::string>& ptcls):
103       weight(wt), protocols(ptcls) {}
104     int weight;
105     std::list<std::string> protocols;
106   };
107
108   // Function that selects a client protocol given the server's list
109   using ClientProtocolFilterCallback = bool (*)(unsigned char**, unsigned int*,
110                                         const unsigned char*, unsigned int);
111
112   /**
113    * Convenience function to call getErrors() with the current errno value.
114    *
115    * Make sure that you only call this when there was no intervening operation
116    * since the last OpenSSL error that may have changed the current errno value.
117    */
118   static std::string getErrors() {
119     return getErrors(errno);
120   }
121
122   /**
123    * Constructor.
124    *
125    * @param version The lowest or oldest SSL version to support.
126    */
127   explicit SSLContext(SSLVersion version = TLSv1);
128   virtual ~SSLContext();
129
130   /**
131    * Set default ciphers to be used in SSL handshake process.
132    *
133    * @param ciphers A list of ciphers to use for TLSv1.0
134    */
135   virtual void ciphers(const std::string& ciphers);
136
137   /**
138    * Low-level method that attempts to set the provided ciphers on the
139    * SSL_CTX object, and throws if something goes wrong.
140    */
141   virtual void setCiphersOrThrow(const std::string& ciphers);
142
143   /**
144    * Method to set verification option in the context object.
145    *
146    * @param verifyPeer SSLVerifyPeerEnum indicating the verification
147    *                       method to use.
148    */
149   virtual void setVerificationOption(const SSLVerifyPeerEnum& verifyPeer);
150
151   /**
152    * Method to check if peer verfication is set.
153    *
154    * @return true if peer verification is required.
155    *
156    */
157   virtual bool needsPeerVerification() {
158     return (verifyPeer_ == SSLVerifyPeerEnum::VERIFY ||
159               verifyPeer_ == SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
160   }
161
162   /**
163    * Method to fetch Verification mode for a SSLVerifyPeerEnum.
164    * verifyPeer cannot be SSLVerifyPeerEnum::USE_CTX since there is no
165    * context.
166    *
167    * @param verifyPeer SSLVerifyPeerEnum for which the flags need to
168    *                  to be returned
169    *
170    * @return mode flags that can be used with SSL_set_verify
171    */
172   static int getVerificationMode(const SSLVerifyPeerEnum& verifyPeer);
173
174   /**
175    * Method to fetch Verification mode determined by the options
176    * set using setVerificationOption.
177    *
178    * @return mode flags that can be used with SSL_set_verify
179    */
180   virtual int getVerificationMode();
181
182   /**
183    * Enable/Disable authentication. Peer name validation can only be done
184    * if checkPeerCert is true.
185    *
186    * @param checkPeerCert If true, require peer to present valid certificate
187    * @param checkPeerName If true, validate that the certificate common name
188    *                      or alternate name(s) of peer matches the hostname
189    *                      used to connect.
190    * @param peerName      If non-empty, validate that the certificate common
191    *                      name of peer matches the given string (altername
192    *                      name(s) are not used in this case).
193    */
194   virtual void authenticate(bool checkPeerCert, bool checkPeerName,
195                             const std::string& peerName = std::string());
196   /**
197    * Load server certificate.
198    *
199    * @param path   Path to the certificate file
200    * @param format Certificate file format
201    */
202   virtual void loadCertificate(const char* path, const char* format = "PEM");
203   /**
204    * Load server certificate from memory.
205    *
206    * @param cert  A PEM formatted certificate
207    */
208   virtual void loadCertificateFromBufferPEM(folly::StringPiece cert);
209   /**
210    * Load private key.
211    *
212    * @param path   Path to the private key file
213    * @param format Private key file format
214    */
215   virtual void loadPrivateKey(const char* path, const char* format = "PEM");
216   /**
217    * Load private key from memory.
218    *
219    * @param pkey  A PEM formatted key
220    */
221   virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
222   /**
223    * Load trusted certificates from specified file.
224    *
225    * @param path Path to trusted certificate file
226    */
227   virtual void loadTrustedCertificates(const char* path);
228   /**
229    * Load trusted certificates from specified X509 certificate store.
230    *
231    * @param store X509 certificate store.
232    */
233   virtual void loadTrustedCertificates(X509_STORE* store);
234   /**
235    * Load a client CA list for validating clients
236    */
237   virtual void loadClientCAList(const char* path);
238   /**
239    * Override default OpenSSL password collector.
240    *
241    * @param collector Instance of user defined password collector
242    */
243   virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
244   /**
245    * Obtain password collector.
246    *
247    * @return User defined password collector
248    */
249   virtual std::shared_ptr<PasswordCollector> passwordCollector() {
250     return collector_;
251   }
252 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
253   /**
254    * Provide SNI support
255    */
256   enum ServerNameCallbackResult {
257     SERVER_NAME_FOUND,
258     SERVER_NAME_NOT_FOUND,
259     SERVER_NAME_NOT_FOUND_ALERT_FATAL,
260   };
261   /**
262    * Callback function from openssl to give the application a
263    * chance to check the tlsext_hostname just right after parsing
264    * the Client Hello or Server Hello message.
265    *
266    * It is for the server to switch the SSL to another SSL_CTX
267    * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
268    *
269    * If the ServerNameCallback returns:
270    * SERVER_NAME_FOUND:
271    *    server: Send a tlsext_hostname in the Server Hello
272    *    client: No-effect
273    * SERVER_NAME_NOT_FOUND:
274    *    server: Does not send a tlsext_hostname in Server Hello
275    *            and continue the handshake.
276    *    client: No-effect
277    * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
278    *    server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
279    *                       the peer.
280    *
281    * Quote from RFC 6066:
282    * "...
283    * If the server understood the ClientHello extension but
284    * does not recognize the server name, the server SHOULD take one of two
285    * actions: either abort the handshake by sending a fatal-level
286    * unrecognized_name(112) alert or continue the handshake.  It is NOT
287    * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
288    * because the client's behavior in response to warning-level alerts is
289    * unpredictable.
290    * ..."
291    */
292
293   /**
294    * Set the ServerNameCallback
295    */
296   typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
297   virtual void setServerNameCallback(const ServerNameCallback& cb);
298
299   /**
300    * Generic callbacks that are run after we get the Client Hello (right
301    * before we run the ServerNameCallback)
302    */
303   typedef std::function<void(SSL* ssl)> ClientHelloCallback;
304   virtual void addClientHelloCallback(const ClientHelloCallback& cb);
305 #endif
306
307   /**
308    * Create an SSL object from this context.
309    */
310   SSL* createSSL() const;
311
312   /**
313    * Sets the namespace to use for sessions created from this context.
314    */
315   void setSessionCacheContext(const std::string& context);
316
317   /**
318    * Set the options on the SSL_CTX object.
319    */
320   void setOptions(long options);
321
322   enum class NextProtocolType : uint8_t {
323     NPN = 0x1,
324     ALPN = 0x2,
325     ANY = NPN | ALPN
326   };
327
328 #ifdef OPENSSL_NPN_NEGOTIATED
329   /**
330    * Set the list of protocols that this SSL context supports. In server
331    * mode, this is the list of protocols that will be advertised for Next
332    * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
333    * (ALPN). In client mode, the first protocol advertised by the server
334    * that is also on this list is chosen. Invoking this function with a list
335    * of length zero causes NPN to be disabled.
336    *
337    * @param protocols   List of protocol names. This method makes a copy,
338    *                    so the caller needn't keep the list in scope after
339    *                    the call completes. The list must have at least
340    *                    one element to enable NPN. Each element must have
341    *                    a string length < 256.
342    * @param protocolType  What type of protocol negotiation to support.
343    * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
344    */
345   bool setAdvertisedNextProtocols(
346       const std::list<std::string>& protocols,
347       NextProtocolType protocolType = NextProtocolType::ANY);
348   /**
349    * Set weighted list of lists of protocols that this SSL context supports.
350    * In server mode, each element of the list contains a list of protocols that
351    * could be advertised for Next Protocol Negotiation (NPN) or Application
352    * Layer Protocol Negotiation (ALPN). The list of protocols that will be
353    * advertised to a client is selected randomly, based on weights of elements.
354    * Client mode doesn't support randomized NPN/ALPN, so this list should
355    * contain only 1 element. The first protocol advertised by the server that
356    * is also on the list of protocols of this element is chosen. Invoking this
357    * function with a list of length zero causes NPN/ALPN to be disabled.
358    *
359    * @param items  List of NextProtocolsItems, Each item contains a list of
360    *               protocol names and weight. After the call of this fucntion
361    *               each non-empty list of protocols will be advertised with
362    *               probability weight/sum_of_weights. This method makes a copy,
363    *               so the caller needn't keep the list in scope after the call
364    *               completes. The list must have at least one element with
365    *               non-zero weight and non-empty protocols list to enable NPN.
366    *               Each name of the protocol must have a string length < 256.
367    * @param protocolType  What type of protocol negotiation to support.
368    * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
369    */
370   bool setRandomizedAdvertisedNextProtocols(
371       const std::list<NextProtocolsItem>& items,
372       NextProtocolType protocolType = NextProtocolType::ANY);
373
374   void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
375     clientProtoFilter_ = cb;
376   }
377
378   ClientProtocolFilterCallback getClientProtocolFilterCallback() {
379     return clientProtoFilter_;
380   }
381
382   /**
383    * Disables NPN on this SSL context.
384    */
385   void unsetNextProtocols();
386   void deleteNextProtocolsStrings();
387 #endif // OPENSSL_NPN_NEGOTIATED
388
389   /**
390    * Gets the underlying SSL_CTX for advanced usage
391    */
392   SSL_CTX *getSSLCtx() const {
393     return ctx_;
394   }
395
396   enum SSLLockType {
397     LOCK_MUTEX,
398     LOCK_SPINLOCK,
399     LOCK_NONE
400   };
401
402   /**
403    * Set preferences for how to treat locks in OpenSSL.  This must be
404    * called before the instantiation of any SSLContext objects, otherwise
405    * the defaults will be used.
406    *
407    * OpenSSL has a lock for each module rather than for each object or
408    * data that needs locking.  Some locks protect only refcounts, and
409    * might be better as spinlocks rather than mutexes.  Other locks
410    * may be totally unnecessary if the objects being protected are not
411    * shared between threads in the application.
412    *
413    * By default, all locks are initialized as mutexes.  OpenSSL's lock usage
414    * may change from version to version and you should know what you are doing
415    * before disabling any locks entirely.
416    *
417    * Example: if you don't share SSL sessions between threads in your
418    * application, you may be able to do this
419    *
420    * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
421    */
422   static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
423
424   /**
425    * Examine OpenSSL's error stack, and return a string description of the
426    * errors.
427    *
428    * This operation removes the errors from OpenSSL's error stack.
429    */
430   static std::string getErrors(int errnoCopy);
431
432   /**
433    * We want to vary which cipher we'll use based on the client's TLS version.
434    *
435    * XXX: The refernces to tls11CipherString and tls11AltCipherlist are reused
436    * for * each >= TLS 1.1 handshake, so we expect these fields to not change.
437    */
438   void switchCiphersIfTLS11(
439       SSL* ssl,
440       const std::string& tls11CipherString,
441       const std::vector<std::pair<std::string, int>>& tls11AltCipherlist);
442
443   bool checkPeerName() { return checkPeerName_; }
444   std::string peerFixedName() { return peerFixedName_; }
445
446 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
447   /**
448    * Enable TLS false start, saving a roundtrip for full handshakes. Will only
449    * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
450    * is negotiated.
451    */
452   void enableFalseStart();
453 #endif
454
455   /**
456    * Helper to match a hostname versus a pattern.
457    */
458   static bool matchName(const char* host, const char* pattern, int size);
459
460   /**
461    * Functions for setting up and cleaning up openssl.
462    * They can be invoked during the start of the application.
463    */
464   static void initializeOpenSSL();
465   static void cleanupOpenSSL();
466
467   /**
468    * Mark openssl as initialized without actually performing any initialization.
469    * Please use this only if you are using a library which requires that it must
470    * make its own calls to SSL_library_init() and related functions.
471    */
472   static void markInitialized();
473
474   /**
475    * Default randomize method.
476    */
477   static void randomize();
478
479  protected:
480   SSL_CTX* ctx_;
481
482  private:
483   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
484
485   bool checkPeerName_;
486   std::string peerFixedName_;
487   std::shared_ptr<PasswordCollector> collector_;
488 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
489   ServerNameCallback serverNameCb_;
490   std::vector<ClientHelloCallback> clientHelloCbs_;
491 #endif
492
493   ClientProtocolFilterCallback clientProtoFilter_{nullptr};
494
495   static bool initialized_;
496
497   // Used in randomized next-proto pick / randomized cipherlist
498   Random::DefaultGenerator randomGenerator_;
499   // To provide control over choice of server ciphersuites
500   std::unique_ptr<std::discrete_distribution<int>> cipherListPicker_;
501
502 #ifdef OPENSSL_NPN_NEGOTIATED
503
504   struct AdvertisedNextProtocolsItem {
505     unsigned char* protocols;
506     unsigned length;
507   };
508
509   /**
510    * Wire-format list of advertised protocols for use in NPN.
511    */
512   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
513   std::vector<int> advertisedNextProtocolWeights_;
514   std::discrete_distribution<int> nextProtocolDistribution_;
515
516   static int sNextProtocolsExDataIndex_;
517
518   static int advertisedNextProtocolCallback(SSL* ssl,
519       const unsigned char** out, unsigned int* outlen, void* data);
520   static int selectNextProtocolCallback(
521     SSL* ssl, unsigned char **out, unsigned char *outlen,
522     const unsigned char *server, unsigned int server_len, void *args);
523
524 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
525   static int alpnSelectCallback(SSL* ssl,
526                                 const unsigned char** out,
527                                 unsigned char* outlen,
528                                 const unsigned char* in,
529                                 unsigned int inlen,
530                                 void* data);
531 #endif
532   size_t pickNextProtocols();
533
534 #endif // OPENSSL_NPN_NEGOTIATED
535
536   static int passwordCallback(char* password, int size, int, void* data);
537
538 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
539   /**
540    * The function that will be called directly from openssl
541    * in order for the application to get the tlsext_hostname just after
542    * parsing the Client Hello or Server Hello message. It will then call
543    * the serverNameCb_ function object. Hence, it is sort of a
544    * wrapper/proxy between serverNameCb_ and openssl.
545    *
546    * The openssl's primary intention is for SNI support, but we also use it
547    * generically for performing logic after the Client Hello comes in.
548    */
549   static int baseServerNameOpenSSLCallback(
550     SSL* ssl,
551     int* al /* alert (return value) */,
552     void* data
553   );
554 #endif
555
556   std::string providedCiphersString_;
557
558   // Functions are called when locked by the calling function.
559   static void initializeOpenSSLLocked();
560   static void cleanupOpenSSLLocked();
561 };
562
563 typedef std::shared_ptr<SSLContext> SSLContextPtr;
564
565 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
566
567
568 } // folly