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