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