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