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