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