Adds writer test case for RCU
[folly.git] / folly / io / async / SSLContext.h
1 /*
2  * Copyright 2014-present 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   /**
280    * Load private key.
281    *
282    * @param path   Path to the private key file
283    * @param format Private key file format
284    */
285   virtual void loadPrivateKey(const char* path, const char* format = "PEM");
286   /**
287    * Load private key from memory.
288    *
289    * @param pkey  A PEM formatted key
290    */
291   virtual void loadPrivateKeyFromBufferPEM(folly::StringPiece pkey);
292
293   /**
294    * Load cert and key from PEM buffers. Guaranteed to throw if cert and
295    * private key mismatch so no need to call isCertKeyPairValid.
296    *
297    * @param cert A PEM formatted certificate
298    * @param pkey A PEM formatted key
299    */
300   virtual void loadCertKeyPairFromBufferPEM(
301       folly::StringPiece cert,
302       folly::StringPiece pkey);
303
304   /**
305    * Load cert and key from files. Guaranteed to throw if cert and key mismatch.
306    * Equivalent to calling loadCertificate() and loadPrivateKey().
307    *
308    * @param certPath   Path to the certificate file
309    * @param keyPath   Path to the private key file
310    * @param certFormat Certificate file format
311    * @param keyFormat Private key file format
312    */
313   virtual void loadCertKeyPairFromFiles(
314       const char* certPath,
315       const char* keyPath,
316       const char* certFormat = "PEM",
317       const char* keyFormat = "PEM");
318
319   /**
320    * Call after both cert and key are loaded to check if cert matches key.
321    * Must call if private key is loaded before loading the cert.
322    * No need to call if cert is loaded first before private key.
323    * @return true if matches, or false if mismatch.
324    */
325   virtual bool isCertKeyPairValid() const;
326
327   /**
328    * Load trusted certificates from specified file.
329    *
330    * @param path Path to trusted certificate file
331    */
332   virtual void loadTrustedCertificates(const char* path);
333   /**
334    * Load trusted certificates from specified X509 certificate store.
335    *
336    * @param store X509 certificate store.
337    */
338   virtual void loadTrustedCertificates(X509_STORE* store);
339   /**
340    * Load a client CA list for validating clients
341    */
342   virtual void loadClientCAList(const char* path);
343   /**
344    * Override default OpenSSL password collector.
345    *
346    * @param collector Instance of user defined password collector
347    */
348   virtual void passwordCollector(std::shared_ptr<PasswordCollector> collector);
349   /**
350    * Obtain password collector.
351    *
352    * @return User defined password collector
353    */
354   virtual std::shared_ptr<PasswordCollector> passwordCollector() {
355     return collector_;
356   }
357 #if FOLLY_OPENSSL_HAS_SNI
358   /**
359    * Provide SNI support
360    */
361   enum ServerNameCallbackResult {
362     SERVER_NAME_FOUND,
363     SERVER_NAME_NOT_FOUND,
364     SERVER_NAME_NOT_FOUND_ALERT_FATAL,
365   };
366   /**
367    * Callback function from openssl to give the application a
368    * chance to check the tlsext_hostname just right after parsing
369    * the Client Hello or Server Hello message.
370    *
371    * It is for the server to switch the SSL to another SSL_CTX
372    * to continue the handshake. (i.e. Server Name Indication, SNI, in RFC6066).
373    *
374    * If the ServerNameCallback returns:
375    * SERVER_NAME_FOUND:
376    *    server: Send a tlsext_hostname in the Server Hello
377    *    client: No-effect
378    * SERVER_NAME_NOT_FOUND:
379    *    server: Does not send a tlsext_hostname in Server Hello
380    *            and continue the handshake.
381    *    client: No-effect
382    * SERVER_NAME_NOT_FOUND_ALERT_FATAL:
383    *    server and client: Send fatal TLS1_AD_UNRECOGNIZED_NAME alert to
384    *                       the peer.
385    *
386    * Quote from RFC 6066:
387    * "...
388    * If the server understood the ClientHello extension but
389    * does not recognize the server name, the server SHOULD take one of two
390    * actions: either abort the handshake by sending a fatal-level
391    * unrecognized_name(112) alert or continue the handshake.  It is NOT
392    * RECOMMENDED to send a warning-level unrecognized_name(112) alert,
393    * because the client's behavior in response to warning-level alerts is
394    * unpredictable.
395    * ..."
396    */
397
398   /**
399    * Set the ServerNameCallback
400    */
401   typedef std::function<ServerNameCallbackResult(SSL* ssl)> ServerNameCallback;
402   virtual void setServerNameCallback(const ServerNameCallback& cb);
403
404   /**
405    * Generic callbacks that are run after we get the Client Hello (right
406    * before we run the ServerNameCallback)
407    */
408   typedef std::function<void(SSL* ssl)> ClientHelloCallback;
409   virtual void addClientHelloCallback(const ClientHelloCallback& cb);
410 #endif // FOLLY_OPENSSL_HAS_SNI
411
412   /**
413    * Create an SSL object from this context.
414    */
415   SSL* createSSL() const;
416
417   /**
418    * Sets the namespace to use for sessions created from this context.
419    */
420   void setSessionCacheContext(const std::string& context);
421
422   /**
423    * Set the options on the SSL_CTX object.
424    */
425   void setOptions(long options);
426
427   enum class NextProtocolType : uint8_t {
428     NPN = 0x1,
429     ALPN = 0x2,
430     ANY = NPN | ALPN
431   };
432
433 #ifdef OPENSSL_NPN_NEGOTIATED
434   /**
435    * Set the list of protocols that this SSL context supports. In server
436    * mode, this is the list of protocols that will be advertised for Next
437    * Protocol Negotiation (NPN) or Application Layer Protocol Negotiation
438    * (ALPN). In client mode, the first protocol advertised by the server
439    * that is also on this list is chosen. Invoking this function with a list
440    * of length zero causes NPN to be disabled.
441    *
442    * @param protocols   List of protocol names. This method makes a copy,
443    *                    so the caller needn't keep the list in scope after
444    *                    the call completes. The list must have at least
445    *                    one element to enable NPN. Each element must have
446    *                    a string length < 256.
447    * @param protocolType  What type of protocol negotiation to support.
448    * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
449    */
450   bool setAdvertisedNextProtocols(
451       const std::list<std::string>& protocols,
452       NextProtocolType protocolType = NextProtocolType::ANY);
453   /**
454    * Set weighted list of lists of protocols that this SSL context supports.
455    * In server mode, each element of the list contains a list of protocols that
456    * could be advertised for Next Protocol Negotiation (NPN) or Application
457    * Layer Protocol Negotiation (ALPN). The list of protocols that will be
458    * advertised to a client is selected randomly, based on weights of elements.
459    * Client mode doesn't support randomized NPN/ALPN, so this list should
460    * contain only 1 element. The first protocol advertised by the server that
461    * is also on the list of protocols of this element is chosen. Invoking this
462    * function with a list of length zero causes NPN/ALPN to be disabled.
463    *
464    * @param items  List of NextProtocolsItems, Each item contains a list of
465    *               protocol names and weight. After the call of this fucntion
466    *               each non-empty list of protocols will be advertised with
467    *               probability weight/sum_of_weights. This method makes a copy,
468    *               so the caller needn't keep the list in scope after the call
469    *               completes. The list must have at least one element with
470    *               non-zero weight and non-empty protocols list to enable NPN.
471    *               Each name of the protocol must have a string length < 256.
472    * @param protocolType  What type of protocol negotiation to support.
473    * @return true if NPN/ALPN has been activated. False if NPN/ALPN is disabled.
474    */
475   bool setRandomizedAdvertisedNextProtocols(
476       const std::list<NextProtocolsItem>& items,
477       NextProtocolType protocolType = NextProtocolType::ANY);
478
479   void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
480     clientProtoFilter_ = cb;
481   }
482
483   ClientProtocolFilterCallback getClientProtocolFilterCallback() {
484     return clientProtoFilter_;
485   }
486
487   /**
488    * Disables NPN on this SSL context.
489    */
490   void unsetNextProtocols();
491   void deleteNextProtocolsStrings();
492 #endif // OPENSSL_NPN_NEGOTIATED
493
494   /**
495    * Gets the underlying SSL_CTX for advanced usage
496    */
497   SSL_CTX *getSSLCtx() const {
498     return ctx_;
499   }
500
501   /**
502    * Examine OpenSSL's error stack, and return a string description of the
503    * errors.
504    *
505    * This operation removes the errors from OpenSSL's error stack.
506    */
507   static std::string getErrors(int errnoCopy);
508
509   bool checkPeerName() { return checkPeerName_; }
510   std::string peerFixedName() { return peerFixedName_; }
511
512 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH)
513   /**
514    * Enable TLS false start, saving a roundtrip for full handshakes. Will only
515    * be used if the server uses NPN or ALPN, and a strong forward-secure cipher
516    * is negotiated.
517    */
518   void enableFalseStart();
519 #endif
520
521   /**
522    * Helper to match a hostname versus a pattern.
523    */
524   static bool matchName(const char* host, const char* pattern, int size);
525
526   FOLLY_DEPRECATED("Use folly::ssl::init")
527   static void initializeOpenSSL();
528
529  protected:
530   SSL_CTX* ctx_;
531
532  private:
533   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
534
535   bool checkPeerName_;
536   std::string peerFixedName_;
537   std::shared_ptr<PasswordCollector> collector_;
538 #if FOLLY_OPENSSL_HAS_SNI
539   ServerNameCallback serverNameCb_;
540   std::vector<ClientHelloCallback> clientHelloCbs_;
541 #endif
542
543   ClientProtocolFilterCallback clientProtoFilter_{nullptr};
544
545   static bool initialized_;
546
547 #ifdef OPENSSL_NPN_NEGOTIATED
548
549   struct AdvertisedNextProtocolsItem {
550     unsigned char* protocols;
551     unsigned length;
552   };
553
554   /**
555    * Wire-format list of advertised protocols for use in NPN.
556    */
557   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
558   std::vector<int> advertisedNextProtocolWeights_;
559   std::discrete_distribution<int> nextProtocolDistribution_;
560
561   static int advertisedNextProtocolCallback(SSL* ssl,
562       const unsigned char** out, unsigned int* outlen, void* data);
563   static int selectNextProtocolCallback(
564     SSL* ssl, unsigned char **out, unsigned char *outlen,
565     const unsigned char *server, unsigned int server_len, void *args);
566
567 #if FOLLY_OPENSSL_HAS_ALPN
568   static int alpnSelectCallback(SSL* ssl,
569                                 const unsigned char** out,
570                                 unsigned char* outlen,
571                                 const unsigned char* in,
572                                 unsigned int inlen,
573                                 void* data);
574 #endif
575   size_t pickNextProtocols();
576
577 #endif // OPENSSL_NPN_NEGOTIATED
578
579   static int passwordCallback(char* password, int size, int, void* data);
580
581 #if FOLLY_OPENSSL_HAS_SNI
582   /**
583    * The function that will be called directly from openssl
584    * in order for the application to get the tlsext_hostname just after
585    * parsing the Client Hello or Server Hello message. It will then call
586    * the serverNameCb_ function object. Hence, it is sort of a
587    * wrapper/proxy between serverNameCb_ and openssl.
588    *
589    * The openssl's primary intention is for SNI support, but we also use it
590    * generically for performing logic after the Client Hello comes in.
591    */
592   static int baseServerNameOpenSSLCallback(
593     SSL* ssl,
594     int* al /* alert (return value) */,
595     void* data
596   );
597 #endif
598
599   std::string providedCiphersString_;
600 };
601
602 typedef std::shared_ptr<SSLContext> SSLContextPtr;
603
604 std::ostream& operator<<(
605     std::ostream& os,
606     const folly::PasswordCollector& collector);
607
608 } // namespace folly