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