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