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