90c96ca681e63e0f9fd2518728373b766ea47bbe
[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 #ifdef OPENSSL_NPN_NEGOTIATED
294   /**
295    * Set the list of protocols that this SSL context supports. In server
296    * mode, this is the list of protocols that will be advertised for Next
297    * Protocol Negotiation (NPN). In client mode, the first protocol
298    * advertised by the server that is also on this list is
299    * chosen. Invoking this function with a list of length zero causes NPN
300    * to be disabled.
301    *
302    * @param protocols   List of protocol names. This method makes a copy,
303    *                    so the caller needn't keep the list in scope after
304    *                    the call completes. The list must have at least
305    *                    one element to enable NPN. Each element must have
306    *                    a string length < 256.
307    * @return true if NPN has been activated. False if NPN is disabled.
308    */
309   bool setAdvertisedNextProtocols(const std::list<std::string>& protocols);
310   /**
311    * Set weighted list of lists of protocols that this SSL context supports.
312    * In server mode, each element of the list contains a list of protocols that
313    * could be advertised for Next Protocol Negotiation (NPN). The list of
314    * protocols that will be advertised to a client is selected randomly, based
315    * on weights of elements. Client mode doesn't support randomized NPN, so
316    * this list should contain only 1 element. The first protocol advertised
317    * by the server that is also on the list of protocols of this element is
318    * chosen. Invoking this function with a list of length zero causes NPN
319    * to be disabled.
320    *
321    * @param items  List of NextProtocolsItems, Each item contains a list of
322    *               protocol names and weight. After the call of this fucntion
323    *               each non-empty list of protocols will be advertised with
324    *               probability weight/sum_of_weights. This method makes a copy,
325    *               so the caller needn't keep the list in scope after the call
326    *               completes. The list must have at least one element with
327    *               non-zero weight and non-empty protocols list to enable NPN.
328    *               Each name of the protocol must have a string length < 256.
329    * @return true if NPN has been activated. False if NPN is disabled.
330    */
331   bool setRandomizedAdvertisedNextProtocols(
332       const std::list<NextProtocolsItem>& items);
333
334   void setClientProtocolFilterCallback(ClientProtocolFilterCallback cb) {
335     clientProtoFilter_ = cb;
336   }
337
338   ClientProtocolFilterCallback getClientProtocolFilterCallback() {
339     return clientProtoFilter_;
340   }
341   /**
342    * Disables NPN on this SSL context.
343    */
344   void unsetNextProtocols();
345   void deleteNextProtocolsStrings();
346
347 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
348   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
349   bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
350 #endif
351 #endif // OPENSSL_NPN_NEGOTIATED
352
353   /**
354    * Gets the underlying SSL_CTX for advanced usage
355    */
356   SSL_CTX *getSSLCtx() const {
357     return ctx_;
358   }
359
360   enum SSLLockType {
361     LOCK_MUTEX,
362     LOCK_SPINLOCK,
363     LOCK_NONE
364   };
365
366   /**
367    * Set preferences for how to treat locks in OpenSSL.  This must be
368    * called before the instantiation of any SSLContext objects, otherwise
369    * the defaults will be used.
370    *
371    * OpenSSL has a lock for each module rather than for each object or
372    * data that needs locking.  Some locks protect only refcounts, and
373    * might be better as spinlocks rather than mutexes.  Other locks
374    * may be totally unnecessary if the objects being protected are not
375    * shared between threads in the application.
376    *
377    * By default, all locks are initialized as mutexes.  OpenSSL's lock usage
378    * may change from version to version and you should know what you are doing
379    * before disabling any locks entirely.
380    *
381    * Example: if you don't share SSL sessions between threads in your
382    * application, you may be able to do this
383    *
384    * setSSLLockTypes({{CRYPTO_LOCK_SSL_SESSION, SSLContext::LOCK_NONE}})
385    */
386   static void setSSLLockTypes(std::map<int, SSLLockType> lockTypes);
387
388   /**
389    * Examine OpenSSL's error stack, and return a string description of the
390    * errors.
391    *
392    * This operation removes the errors from OpenSSL's error stack.
393    */
394   static std::string getErrors(int errnoCopy);
395
396   /**
397    * We want to vary which cipher we'll use based on the client's TLS version.
398    */
399   void switchCiphersIfTLS11(
400     SSL* ssl,
401     const std::string& tls11CipherString
402   );
403
404   bool checkPeerName() { return checkPeerName_; }
405   std::string peerFixedName() { return peerFixedName_; }
406
407   /**
408    * Helper to match a hostname versus a pattern.
409    */
410   static bool matchName(const char* host, const char* pattern, int size);
411
412   /**
413    * Functions for setting up and cleaning up openssl.
414    * They can be invoked during the start of the application.
415    */
416   static void initializeOpenSSL();
417   static void cleanupOpenSSL();
418
419   /**
420    * Mark openssl as initialized without actually performing any initialization.
421    * Please use this only if you are using a library which requires that it must
422    * make its own calls to SSL_library_init() and related functions.
423    */
424   static void markInitialized();
425
426   /**
427    * Default randomize method.
428    */
429   static void randomize();
430
431  protected:
432   SSL_CTX* ctx_;
433
434  private:
435   SSLVerifyPeerEnum verifyPeer_{SSLVerifyPeerEnum::NO_VERIFY};
436
437   bool checkPeerName_;
438   std::string peerFixedName_;
439   std::shared_ptr<PasswordCollector> collector_;
440 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
441   ServerNameCallback serverNameCb_;
442   std::vector<ClientHelloCallback> clientHelloCbs_;
443 #endif
444
445   ClientProtocolFilterCallback clientProtoFilter_{nullptr};
446
447   static bool initialized_;
448
449 #ifdef OPENSSL_NPN_NEGOTIATED
450   /**
451    * Wire-format list of advertised protocols for use in NPN.
452    */
453   std::vector<AdvertisedNextProtocolsItem> advertisedNextProtocols_;
454   static int sNextProtocolsExDataIndex_;
455
456   static int advertisedNextProtocolCallback(SSL* ssl,
457       const unsigned char** out, unsigned int* outlen, void* data);
458   static int selectNextProtocolCallback(
459     SSL* ssl, unsigned char **out, unsigned char *outlen,
460     const unsigned char *server, unsigned int server_len, void *args);
461
462 #if defined(SSL_MODE_HANDSHAKE_CUTTHROUGH) && \
463   FOLLY_SSLCONTEXT_USE_TLS_FALSE_START
464   // This class contains all allowed ciphers for SSL false start. Call its
465   // `canUseFalseStartWithCipher` to check for cipher qualification.
466   class SSLFalseStartChecker {
467    public:
468     SSLFalseStartChecker();
469
470     bool canUseFalseStartWithCipher(const SSL_CIPHER *cipher);
471
472    private:
473     static int compare_ulong(const void *x, const void *y);
474
475     // All ciphers that are allowed to use false start.
476     unsigned long ciphers_[47];
477     unsigned int length_;
478     unsigned int width_;
479   };
480
481   SSLFalseStartChecker falseStartChecker_;
482 #endif
483
484 #endif // OPENSSL_NPN_NEGOTIATED
485
486   static int passwordCallback(char* password, int size, int, void* data);
487
488 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
489   /**
490    * The function that will be called directly from openssl
491    * in order for the application to get the tlsext_hostname just after
492    * parsing the Client Hello or Server Hello message. It will then call
493    * the serverNameCb_ function object. Hence, it is sort of a
494    * wrapper/proxy between serverNameCb_ and openssl.
495    *
496    * The openssl's primary intention is for SNI support, but we also use it
497    * generically for performing logic after the Client Hello comes in.
498    */
499   static int baseServerNameOpenSSLCallback(
500     SSL* ssl,
501     int* al /* alert (return value) */,
502     void* data
503   );
504 #endif
505
506   std::string providedCiphersString_;
507
508   // Functions are called when locked by the calling function.
509   static void initializeOpenSSLLocked();
510   static void cleanupOpenSSLLocked();
511 };
512
513 typedef std::shared_ptr<SSLContext> SSLContextPtr;
514
515 std::ostream& operator<<(std::ostream& os, const folly::PasswordCollector& collector);
516
517 class OpenSSLUtils {
518  public:
519   /**
520    * Validate that the peer certificate's common name or subject alt names
521    * match what we expect.  Currently this only checks for IPs within
522    * subject alt names but it could easily be expanded to check common name
523    * and hostnames as well.
524    *
525    * @param cert    X509* peer certificate
526    * @param addr    sockaddr object containing sockaddr to verify
527    * @param addrLen length of sockaddr as returned by getpeername or accept
528    * @return true iff a subject altname IP matches addr
529    */
530   // TODO(agartrell): Add support for things like common name when
531   // necessary.
532   static bool validatePeerCertNames(X509* cert,
533                                     const sockaddr* addr,
534                                     socklen_t addrLen);
535
536   /**
537    * Get the peer socket address from an X509_STORE_CTX*.  Unlike the
538    * accept, getsockname, getpeername, etc family of operations, addrLen's
539    * initial value is ignored and reset.
540    *
541    * @param ctx         Context from which to retrieve peer sockaddr
542    * @param addrStorage out param for address
543    * @param addrLen     out param for length of address
544    * @return true on success, false on failure
545    */
546   static bool getPeerAddressFromX509StoreCtx(X509_STORE_CTX* ctx,
547                                              sockaddr_storage* addrStorage,
548                                              socklen_t* addrLen);
549
550 };
551
552
553 } // folly