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