Comments for SSLVerifyPeerEnum
[folly.git] / folly / io / async / SSLContext.h
1 /*
2  * Copyright 2015 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
380 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
381   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
382   bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
383 #endif
384 #endif // OPENSSL_NPN_NEGOTIATED
385
386   /**
387    * Gets the underlying SSL_CTX for advanced usage
388    */
389   SSL_CTX *getSSLCtx() const {
390     return ctx_;
391   }
392
393   enum SSLLockType {
394     LOCK_MUTEX,
395     LOCK_SPINLOCK,
396     LOCK_NONE
397   };
398
399   /**
400    * Set preferences for how to treat locks in OpenSSL.  This must be
401    * called before the instantiation of any SSLContext objects, otherwise
402    * the defaults will be used.
403    *
404    * OpenSSL has a lock for each module rather than for each object or
405    * data that needs locking.  Some locks protect only refcounts, and
406    * might be better as spinlocks rather than mutexes.  Other locks
407    * may be totally unnecessary if the objects being protected are not
408    * shared between threads in the application.
409    *
410    * By default, all locks are initialized as mutexes.  OpenSSL's lock usage
411    * may change from version to version and you should know what you are doing
412    * before disabling any locks entirely.
413    *
414    * Example: if you don't share SSL sessions between threads in your
415    * application, you may be able to do this
416    *
417    * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
418    */
419   static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
420
421   /**
422    * Examine OpenSSL's error stack, and return a string description of the
423    * errors.
424    *
425    * This operation removes the errors from OpenSSL's error stack.
426    */
427   static std::string getErrors(int errnoCopy);
428
429   /**
430    * We want to vary which cipher we'll use based on the client's TLS version.
431    */
432   void switchCiphersIfTLS11(
433     SSL* ssl,
434     const std::string& tls11CipherString
435   );
436
437   bool checkPeerName() { return checkPeerName_; }
438   std::string peerFixedName() { return peerFixedName_; }
439
440   /**
441    * Helper to match a hostname versus a pattern.
442    */
443   static bool matchName(const char* host, const char* pattern, int size);
444
445   /**
446    * Functions for setting up and cleaning up openssl.
447    * They can be invoked during the start of the application.
448    */
449   static void initializeOpenSSL();
450   static void cleanupOpenSSL();
451
452   /**
453    * Mark openssl as initialized without actually performing any initialization.
454    * Please use this only if you are using a library which requires that it must
455    * make its own calls to SSL_library_init() and related functions.
456    */
457   static void markInitialized();
458
459   /**
460    * Default randomize method.
461    */
462   static void randomize();
463
464  protected:
465   SSL_CTX* ctx_;
466
467  private:
468   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
469
470   bool checkPeerName_;
471   std::string peerFixedName_;
472   std::shared_ptr<PasswordCollector> collector_;
473 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
474   ServerNameCallback serverNameCb_;
475   std::vector<ClientHelloCallback> clientHelloCbs_;
476 #endif
477
478   ClientProtocolFilterCallback clientProtoFilter_{nullptr};
479
480   static bool initialized_;
481
482 #ifdef OPENSSL_NPN_NEGOTIATED
483
484   struct AdvertisedNextProtocolsItem {
485     unsigned char* protocols;
486     unsigned length;
487   };
488
489   /**
490    * Wire-format list of advertised protocols for use in NPN.
491    */
492   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
493   std::vector<int> advertisedNextProtocolWeights_;
494   std::discrete_distribution<int> nextProtocolDistribution_;
495   Random::DefaultGenerator nextProtocolPicker_;
496
497   static int sNextProtocolsExDataIndex_;
498
499   static int advertisedNextProtocolCallback(SSL* ssl,
500       const unsigned char** out, unsigned int* outlen, void* data);
501   static int selectNextProtocolCallback(
502     SSL* ssl, unsigned char **out, unsigned char *outlen,
503     const unsigned char *server, unsigned int server_len, void *args);
504
505 #if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
506   static int alpnSelectCallback(SSL* ssl,
507                                 const unsigned char** out,
508                                 unsigned char* outlen,
509                                 const unsigned char* in,
510                                 unsigned int inlen,
511                                 void* data);
512 #endif
513   size_t pickNextProtocols();
514
515 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
516   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
517   // This class contains all allowed ciphers for SSL false start. Call its
518   // `canUseFalseStartWithCipher` to check for cipher qualification.
519   class SSLFalseStartChecker {
520    public:
521     SSLFalseStartChecker();
522
523     bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
524
525    private:
526     static int compare_ulong(const void *x, const void *y);
527
528     // All ciphers that are allowed to use false start.
529     unsigned long ciphers_[47];
530     unsigned int length_;
531     unsigned int width_;
532   };
533
534   SSLFalseStartChecker falseStartChecker_;
535 #endif
536
537 #endif // OPENSSL_NPN_NEGOTIATED
538
539   static int passwordCallback(char* password, int size, int, void* data);
540
541 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
542   /**
543    * The function that will be called directly from openssl
544    * in order for the application to get the tlsext_hostname just after
545    * parsing the Client Hello or Server Hello message. It will then call
546    * the serverNameCb_ function object. Hence, it is sort of a
547    * wrapper/proxy between serverNameCb_ and openssl.
548    *
549    * The openssl's primary intention is for SNI support, but we also use it
550    * generically for performing logic after the Client Hello comes in.
551    */
552   static int baseServerNameOpenSSLCallback(
553     SSL* ssl,
554     int* al /* alert (return value) */,
555     void* data
556   );
557 #endif
558
559   std::string providedCiphersString_;
560
561   // Functions are called when locked by the calling function.
562   static void initializeOpenSSLLocked();
563   static void cleanupOpenSSLLocked();
564 };
565
566 typedef std::shared_ptr<SSLContext> SSLContextPtr;
567
568 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
569
570 class OpenSSLUtils {
571  public:
572   /**
573    * Validate that the peer certificate's common name or subject alt names
574    * match what we expect.  Currently this only checks for IPs within
575    * subject alt names but it could easily be expanded to check common name
576    * and hostnames as well.
577    *
578    * @param cert    X509* peer certificate
579    * @param addr    sockaddr object containing sockaddr to verify
580    * @param addrLen length of sockaddr as returned by getpeername or accept
581    * @return true iff a subject altname IP matches addr
582    */
583   // TODO(agartrell): Add support for things like common name when
584   // necessary.
585   static bool validatePeerCertNames(X509* cert,
586                                     const sockaddr* addr,
587                                     socklen_t addrLen);
588
589   /**
590    * Get the peer socket address from an X509_STORE_CTX*.  Unlike the
591    * accept, getsockname, getpeername, etc family of operations, addrLen's
592    * initial value is ignored and reset.
593    *
594    * @param ctx         Context from which to retrieve peer sockaddr
595    * @param addrStorage out param for address
596    * @param addrLen     out param for length of address
597    * @return true on success, false on failure
598    */
599   static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
600                                              sockaddr_storage* addrStorage,
601                                              socklen_t* addrLen);
602
603 };
604
605
606 } // folly