106974b072e5f1bcae861ef763c85b328f4a9d0e
[folly.git] / folly / io / async / SSLContext.cpp
1 /*
2  * Copyright 2014 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 #include "SSLContext.h"
18
19 #include <openssl/err.h>
20 #include <openssl/rand.h>
21 #include <openssl/ssl.h>
22 #include <openssl/x509v3.h>
23
24 #include <folly/Format.h>
25 #include <folly/io/PortableSpinLock.h>
26
27 // ---------------------------------------------------------------------
28 // SSLContext implementation
29 // ---------------------------------------------------------------------
30
31 struct CRYPTO_dynlock_value {
32   std::mutex mutex;
33 };
34
35 namespace folly {
36
37 bool SSLContext::initialized_ = false;
38 std::mutex    SSLContext::mutex_;
39 #ifdef OPENSSL_NPN_NEGOTIATED
40 int SSLContext::sNextProtocolsExDataIndex_ = -1;
41 #endif
42
43 #ifndef SSLCONTEXT_NO_REFCOUNT
44 uint64_t SSLContext::count_ = 0;
45 #endif
46
47 // SSLContext implementation
48 SSLContext::SSLContext(SSLVersion version) {
49   {
50     std::lock_guard<std::mutex> g(mutex_);
51 #ifndef SSLCONTEXT_NO_REFCOUNT
52     count_++;
53 #endif
54     initializeOpenSSLLocked();
55   }
56
57   ctx_ = SSL_CTX_new(SSLv23_method());
58   if (ctx_ == nullptr) {
59     throw std::runtime_error("SSL_CTX_new: " + getErrors());
60   }
61
62   int opt = 0;
63   switch (version) {
64     case TLSv1:
65       opt = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
66       break;
67     case SSLv3:
68       opt = SSL_OP_NO_SSLv2;
69       break;
70     default:
71       // do nothing
72       break;
73   }
74   int newOpt = SSL_CTX_set_options(ctx_, opt);
75   DCHECK((newOpt & opt) == opt);
76
77   SSL_CTX_set_mode(ctx_, SSL_MODE_AUTO_RETRY);
78
79   checkPeerName_ = false;
80
81 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
82   SSL_CTX_set_tlsext_servername_callback(ctx_, baseServerNameOpenSSLCallback);
83   SSL_CTX_set_tlsext_servername_arg(ctx_, this);
84 #endif
85 }
86
87 SSLContext::~SSLContext() {
88   if (ctx_ != nullptr) {
89     SSL_CTX_free(ctx_);
90     ctx_ = nullptr;
91   }
92
93 #ifdef OPENSSL_NPN_NEGOTIATED
94   deleteNextProtocolsStrings();
95 #endif
96
97 #ifndef SSLCONTEXT_NO_REFCOUNT
98   {
99     std::lock_guard<std::mutex> g(mutex_);
100     if (!--count_) {
101       cleanupOpenSSLLocked();
102     }
103   }
104 #endif
105 }
106
107 void SSLContext::ciphers(const std::string& ciphers) {
108   providedCiphersString_ = ciphers;
109   setCiphersOrThrow(ciphers);
110 }
111
112 void SSLContext::setCiphersOrThrow(const std::string& ciphers) {
113   int rc = SSL_CTX_set_cipher_list(ctx_, ciphers.c_str());
114   if (ERR_peek_error() != 0) {
115     throw std::runtime_error("SSL_CTX_set_cipher_list: " + getErrors());
116   }
117   if (rc == 0) {
118     throw std::runtime_error("None of specified ciphers are supported");
119   }
120 }
121
122 void SSLContext::setVerificationOption(const SSLContext::SSLVerifyPeerEnum&
123     verifyPeer) {
124   CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX); // dont recurse
125   verifyPeer_ = verifyPeer;
126 }
127
128 int SSLContext::getVerificationMode(const SSLContext::SSLVerifyPeerEnum&
129     verifyPeer) {
130   CHECK(verifyPeer != SSLVerifyPeerEnum::USE_CTX);
131   int mode = SSL_VERIFY_NONE;
132   switch(verifyPeer) {
133     // case SSLVerifyPeerEnum::USE_CTX: // can't happen
134     // break;
135
136     case SSLVerifyPeerEnum::VERIFY:
137       mode = SSL_VERIFY_PEER;
138       break;
139
140     case SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT:
141       mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
142       break;
143
144     case SSLVerifyPeerEnum::NO_VERIFY:
145       mode = SSL_VERIFY_NONE;
146       break;
147
148     default:
149       break;
150   }
151   return mode;
152 }
153
154 int SSLContext::getVerificationMode() {
155   return getVerificationMode(verifyPeer_);
156 }
157
158 void SSLContext::authenticate(bool checkPeerCert, bool checkPeerName,
159                               const std::string& peerName) {
160   int mode;
161   if (checkPeerCert) {
162     mode  = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
163     checkPeerName_ = checkPeerName;
164     peerFixedName_ = peerName;
165   } else {
166     mode = SSL_VERIFY_NONE;
167     checkPeerName_ = false; // can't check name without cert!
168     peerFixedName_.clear();
169   }
170   SSL_CTX_set_verify(ctx_, mode, nullptr);
171 }
172
173 void SSLContext::loadCertificate(const char* path, const char* format) {
174   if (path == nullptr || format == nullptr) {
175     throw std::invalid_argument(
176          "loadCertificateChain: either <path> or <format> is nullptr");
177   }
178   if (strcmp(format, "PEM") == 0) {
179     if (SSL_CTX_use_certificate_chain_file(ctx_, path) == 0) {
180       int errnoCopy = errno;
181       std::string reason("SSL_CTX_use_certificate_chain_file: ");
182       reason.append(path);
183       reason.append(": ");
184       reason.append(getErrors(errnoCopy));
185       throw std::runtime_error(reason);
186     }
187   } else {
188     throw std::runtime_error("Unsupported certificate format: " + std::string(format));
189   }
190 }
191
192 void SSLContext::loadPrivateKey(const char* path, const char* format) {
193   if (path == nullptr || format == nullptr) {
194     throw std::invalid_argument(
195          "loadPrivateKey: either <path> or <format> is nullptr");
196   }
197   if (strcmp(format, "PEM") == 0) {
198     if (SSL_CTX_use_PrivateKey_file(ctx_, path, SSL_FILETYPE_PEM) == 0) {
199       throw std::runtime_error("SSL_CTX_use_PrivateKey_file: " + getErrors());
200     }
201   } else {
202     throw std::runtime_error("Unsupported private key format: " + std::string(format));
203   }
204 }
205
206 void SSLContext::loadTrustedCertificates(const char* path) {
207   if (path == nullptr) {
208     throw std::invalid_argument(
209          "loadTrustedCertificates: <path> is nullptr");
210   }
211   if (SSL_CTX_load_verify_locations(ctx_, path, nullptr) == 0) {
212     throw std::runtime_error("SSL_CTX_load_verify_locations: " + getErrors());
213   }
214 }
215
216 void SSLContext::loadTrustedCertificates(X509_STORE* store) {
217   SSL_CTX_set_cert_store(ctx_, store);
218 }
219
220 void SSLContext::loadClientCAList(const char* path) {
221   auto clientCAs = SSL_load_client_CA_file(path);
222   if (clientCAs == nullptr) {
223     LOG(ERROR) << "Unable to load ca file: " << path;
224     return;
225   }
226   SSL_CTX_set_client_CA_list(ctx_, clientCAs);
227 }
228
229 void SSLContext::randomize() {
230   RAND_poll();
231 }
232
233 void SSLContext::passwordCollector(std::shared_ptr<PasswordCollector> collector) {
234   if (collector == nullptr) {
235     LOG(ERROR) << "passwordCollector: ignore invalid password collector";
236     return;
237   }
238   collector_ = collector;
239   SSL_CTX_set_default_passwd_cb(ctx_, passwordCallback);
240   SSL_CTX_set_default_passwd_cb_userdata(ctx_, this);
241 }
242
243 #if OPENSSL_VERSION_NUMBER >= 0x1000105fL && !defined(OPENSSL_NO_TLSEXT)
244
245 void SSLContext::setServerNameCallback(const ServerNameCallback& cb) {
246   serverNameCb_ = cb;
247 }
248
249 void SSLContext::addClientHelloCallback(const ClientHelloCallback& cb) {
250   clientHelloCbs_.push_back(cb);
251 }
252
253 int SSLContext::baseServerNameOpenSSLCallback(SSL* ssl, int* al, void* data) {
254   SSLContext* context = (SSLContext*)data;
255
256   if (context == nullptr) {
257     return SSL_TLSEXT_ERR_NOACK;
258   }
259
260   for (auto& cb : context->clientHelloCbs_) {
261     // Generic callbacks to happen after we receive the Client Hello.
262     // For example, we use one to switch which cipher we use depending
263     // on the user's TLS version.  Because the primary purpose of
264     // baseServerNameOpenSSLCallback is for SNI support, and these callbacks
265     // are side-uses, we ignore any possible failures other than just logging
266     // them.
267     cb(ssl);
268   }
269
270   if (!context->serverNameCb_) {
271     return SSL_TLSEXT_ERR_NOACK;
272   }
273
274   ServerNameCallbackResult ret = context->serverNameCb_(ssl);
275   switch (ret) {
276     case SERVER_NAME_FOUND:
277       return SSL_TLSEXT_ERR_OK;
278     case SERVER_NAME_NOT_FOUND:
279       return SSL_TLSEXT_ERR_NOACK;
280     case SERVER_NAME_NOT_FOUND_ALERT_FATAL:
281       *al = TLS1_AD_UNRECOGNIZED_NAME;
282       return SSL_TLSEXT_ERR_ALERT_FATAL;
283     default:
284       CHECK(false);
285   }
286
287   return SSL_TLSEXT_ERR_NOACK;
288 }
289
290 void SSLContext::switchCiphersIfTLS11(
291     SSL* ssl,
292     const std::string& tls11CipherString) {
293
294   CHECK(!tls11CipherString.empty()) << "Shouldn't call if empty alt ciphers";
295
296   if (TLS1_get_client_version(ssl) <= TLS1_VERSION) {
297     // We only do this for TLS v 1.1 and later
298     return;
299   }
300
301   // Prefer AES for TLS versions 1.1 and later since these are not
302   // vulnerable to BEAST attacks on AES.  Note that we're setting the
303   // cipher list on the SSL object, not the SSL_CTX object, so it will
304   // only last for this request.
305   int rc = SSL_set_cipher_list(ssl, tls11CipherString.c_str());
306   if ((rc == 0) || ERR_peek_error() != 0) {
307     // This shouldn't happen since we checked for this when proxygen
308     // started up.
309     LOG(WARNING) << "ssl_cipher: No specified ciphers supported for switch";
310     SSL_set_cipher_list(ssl, providedCiphersString_.c_str());
311   }
312 }
313 #endif
314
315 #ifdef OPENSSL_NPN_NEGOTIATED
316 bool SSLContext::setAdvertisedNextProtocols(const std::list<std::string>& protocols) {
317   return setRandomizedAdvertisedNextProtocols({{1, protocols}});
318 }
319
320 bool SSLContext::setRandomizedAdvertisedNextProtocols(
321     const std::list<NextProtocolsItem>& items) {
322   unsetNextProtocols();
323   if (items.size() == 0) {
324     return false;
325   }
326   int total_weight = 0;
327   for (const auto &item : items) {
328     if (item.protocols.size() == 0) {
329       continue;
330     }
331     AdvertisedNextProtocolsItem advertised_item;
332     advertised_item.length = 0;
333     for (const auto& proto : item.protocols) {
334       ++advertised_item.length;
335       unsigned protoLength = proto.length();
336       if (protoLength >= 256) {
337         deleteNextProtocolsStrings();
338         return false;
339       }
340       advertised_item.length += protoLength;
341     }
342     advertised_item.protocols = new unsigned char[advertised_item.length];
343     if (!advertised_item.protocols) {
344       throw std::runtime_error("alloc failure");
345     }
346     unsigned char* dst = advertised_item.protocols;
347     for (auto& proto : item.protocols) {
348       unsigned protoLength = proto.length();
349       *dst++ = (unsigned char)protoLength;
350       memcpy(dst, proto.data(), protoLength);
351       dst += protoLength;
352     }
353     total_weight += item.weight;
354     advertised_item.probability = item.weight;
355     advertisedNextProtocols_.push_back(advertised_item);
356   }
357   if (total_weight == 0) {
358     deleteNextProtocolsStrings();
359     return false;
360   }
361   for (auto &advertised_item : advertisedNextProtocols_) {
362     advertised_item.probability /= total_weight;
363   }
364   SSL_CTX_set_next_protos_advertised_cb(
365     ctx_, advertisedNextProtocolCallback, this);
366   SSL_CTX_set_next_proto_select_cb(
367     ctx_, selectNextProtocolCallback, this);
368   return true;
369 }
370
371 void SSLContext::deleteNextProtocolsStrings() {
372   for (auto protocols : advertisedNextProtocols_) {
373     delete[] protocols.protocols;
374   }
375   advertisedNextProtocols_.clear();
376 }
377
378 void SSLContext::unsetNextProtocols() {
379   deleteNextProtocolsStrings();
380   SSL_CTX_set_next_protos_advertised_cb(ctx_, nullptr, nullptr);
381   SSL_CTX_set_next_proto_select_cb(ctx_, nullptr, nullptr);
382 }
383
384 int SSLContext::advertisedNextProtocolCallback(SSL* ssl,
385       const unsigned char** out, unsigned int* outlen, void* data) {
386   SSLContext* context = (SSLContext*)data;
387   if (context == nullptr || context->advertisedNextProtocols_.empty()) {
388     *out = nullptr;
389     *outlen = 0;
390   } else if (context->advertisedNextProtocols_.size() == 1) {
391     *out = context->advertisedNextProtocols_[0].protocols;
392     *outlen = context->advertisedNextProtocols_[0].length;
393   } else {
394     uintptr_t selected_index = reinterpret_cast<uintptr_t>(SSL_get_ex_data(ssl,
395           sNextProtocolsExDataIndex_));
396     if (selected_index) {
397       --selected_index;
398       *out = context->advertisedNextProtocols_[selected_index].protocols;
399       *outlen = context->advertisedNextProtocols_[selected_index].length;
400     } else {
401       unsigned char random_byte;
402       RAND_bytes(&random_byte, 1);
403       double random_value = random_byte / 255.0;
404       double sum = 0;
405       for (size_t i = 0; i < context->advertisedNextProtocols_.size(); ++i) {
406         sum += context->advertisedNextProtocols_[i].probability;
407         if (sum < random_value &&
408             i + 1 < context->advertisedNextProtocols_.size()) {
409           continue;
410         }
411         uintptr_t selected = i + 1;
412         SSL_set_ex_data(ssl, sNextProtocolsExDataIndex_, (void *)selected);
413         *out = context->advertisedNextProtocols_[i].protocols;
414         *outlen = context->advertisedNextProtocols_[i].length;
415         break;
416       }
417     }
418   }
419   return SSL_TLSEXT_ERR_OK;
420 }
421
422 int SSLContext::selectNextProtocolCallback(
423   SSL* ssl, unsigned char **out, unsigned char *outlen,
424   const unsigned char *server, unsigned int server_len, void *data) {
425
426   SSLContext* ctx = (SSLContext*)data;
427   if (ctx->advertisedNextProtocols_.size() > 1) {
428     VLOG(3) << "SSLContext::selectNextProcolCallback() "
429             << "client should be deterministic in selecting protocols.";
430   }
431
432   unsigned char *client;
433   int client_len;
434   if (ctx->advertisedNextProtocols_.empty()) {
435     client = (unsigned char *) "";
436     client_len = 0;
437   } else {
438     client = ctx->advertisedNextProtocols_[0].protocols;
439     client_len = ctx->advertisedNextProtocols_[0].length;
440   }
441
442   int retval = SSL_select_next_proto(out, outlen, server, server_len,
443                                      client, client_len);
444   if (retval != OPENSSL_NPN_NEGOTIATED) {
445     VLOG(3) << "SSLContext::selectNextProcolCallback() "
446             << "unable to pick a next protocol.";
447   }
448   return SSL_TLSEXT_ERR_OK;
449 }
450 #endif // OPENSSL_NPN_NEGOTIATED
451
452 SSL* SSLContext::createSSL() const {
453   SSL* ssl = SSL_new(ctx_);
454   if (ssl == nullptr) {
455     throw std::runtime_error("SSL_new: " + getErrors());
456   }
457   return ssl;
458 }
459
460 /**
461  * Match a name with a pattern. The pattern may include wildcard. A single
462  * wildcard "*" can match up to one component in the domain name.
463  *
464  * @param  host    Host name, typically the name of the remote host
465  * @param  pattern Name retrieved from certificate
466  * @param  size    Size of "pattern"
467  * @return True, if "host" matches "pattern". False otherwise.
468  */
469 bool SSLContext::matchName(const char* host, const char* pattern, int size) {
470   bool match = false;
471   int i = 0, j = 0;
472   while (i < size && host[j] != '\0') {
473     if (toupper(pattern[i]) == toupper(host[j])) {
474       i++;
475       j++;
476       continue;
477     }
478     if (pattern[i] == '*') {
479       while (host[j] != '.' && host[j] != '\0') {
480         j++;
481       }
482       i++;
483       continue;
484     }
485     break;
486   }
487   if (i == size && host[j] == '\0') {
488     match = true;
489   }
490   return match;
491 }
492
493 int SSLContext::passwordCallback(char* password,
494                                  int size,
495                                  int,
496                                  void* data) {
497   SSLContext* context = (SSLContext*)data;
498   if (context == nullptr || context->passwordCollector() == nullptr) {
499     return 0;
500   }
501   std::string userPassword;
502   // call user defined password collector to get password
503   context->passwordCollector()->getPassword(userPassword, size);
504   int length = userPassword.size();
505   if (length > size) {
506     length = size;
507   }
508   strncpy(password, userPassword.c_str(), length);
509   return length;
510 }
511
512 struct SSLLock {
513   explicit SSLLock(
514     SSLContext::SSLLockType inLockType = SSLContext::LOCK_MUTEX) :
515       lockType(inLockType) {
516   }
517
518   void lock() {
519     if (lockType == SSLContext::LOCK_MUTEX) {
520       mutex.lock();
521     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
522       spinLock.lock();
523     }
524     // lockType == LOCK_NONE, no-op
525   }
526
527   void unlock() {
528     if (lockType == SSLContext::LOCK_MUTEX) {
529       mutex.unlock();
530     } else if (lockType == SSLContext::LOCK_SPINLOCK) {
531       spinLock.unlock();
532     }
533     // lockType == LOCK_NONE, no-op
534   }
535
536   SSLContext::SSLLockType lockType;
537   folly::io::PortableSpinLock spinLock{};
538   std::mutex mutex;
539 };
540
541 static std::map<int, SSLContext::SSLLockType> lockTypes;
542 static std::unique_ptr<SSLLock[]> locks;
543
544 static void callbackLocking(int mode, int n, const char*, int) {
545   if (mode & CRYPTO_LOCK) {
546     locks[n].lock();
547   } else {
548     locks[n].unlock();
549   }
550 }
551
552 static unsigned long callbackThreadID() {
553   return static_cast<unsigned long>(
554 #ifdef __APPLE__
555     pthread_mach_thread_np(pthread_self())
556 #else
557     pthread_self()
558 #endif
559   );
560 }
561
562 static CRYPTO_dynlock_value* dyn_create(const char*, int) {
563   return new CRYPTO_dynlock_value;
564 }
565
566 static void dyn_lock(int mode,
567                      struct CRYPTO_dynlock_value* lock,
568                      const char*, int) {
569   if (lock != nullptr) {
570     if (mode & CRYPTO_LOCK) {
571       lock->mutex.lock();
572     } else {
573       lock->mutex.unlock();
574     }
575   }
576 }
577
578 static void dyn_destroy(struct CRYPTO_dynlock_value* lock, const char*, int) {
579   delete lock;
580 }
581
582 void SSLContext::setSSLLockTypes(std::map<int, SSLLockType> inLockTypes) {
583   lockTypes = inLockTypes;
584 }
585
586 void SSLContext::initializeOpenSSL() {
587   std::lock_guard<std::mutex> g(mutex_);
588   initializeOpenSSLLocked();
589 }
590
591 void SSLContext::initializeOpenSSLLocked() {
592   if (initialized_) {
593     return;
594   }
595   SSL_library_init();
596   SSL_load_error_strings();
597   ERR_load_crypto_strings();
598   // static locking
599   locks.reset(new SSLLock[::CRYPTO_num_locks()]);
600   for (auto it: lockTypes) {
601     locks[it.first].lockType = it.second;
602   }
603   CRYPTO_set_id_callback(callbackThreadID);
604   CRYPTO_set_locking_callback(callbackLocking);
605   // dynamic locking
606   CRYPTO_set_dynlock_create_callback(dyn_create);
607   CRYPTO_set_dynlock_lock_callback(dyn_lock);
608   CRYPTO_set_dynlock_destroy_callback(dyn_destroy);
609   randomize();
610 #ifdef OPENSSL_NPN_NEGOTIATED
611   sNextProtocolsExDataIndex_ = SSL_get_ex_new_index(0,
612       (void*)"Advertised next protocol index", nullptr, nullptr, nullptr);
613 #endif
614   initialized_ = true;
615 }
616
617 void SSLContext::cleanupOpenSSL() {
618   std::lock_guard<std::mutex> g(mutex_);
619   cleanupOpenSSLLocked();
620 }
621
622 void SSLContext::cleanupOpenSSLLocked() {
623   if (!initialized_) {
624     return;
625   }
626
627   CRYPTO_set_id_callback(nullptr);
628   CRYPTO_set_locking_callback(nullptr);
629   CRYPTO_set_dynlock_create_callback(nullptr);
630   CRYPTO_set_dynlock_lock_callback(nullptr);
631   CRYPTO_set_dynlock_destroy_callback(nullptr);
632   CRYPTO_cleanup_all_ex_data();
633   ERR_free_strings();
634   EVP_cleanup();
635   ERR_remove_state(0);
636   locks.reset();
637   initialized_ = false;
638 }
639
640 void SSLContext::setOptions(long options) {
641   long newOpt = SSL_CTX_set_options(ctx_, options);
642   if ((newOpt & options) != options) {
643     throw std::runtime_error("SSL_CTX_set_options failed");
644   }
645 }
646
647 std::string SSLContext::getErrors(int errnoCopy) {
648   std::string errors;
649   unsigned long  errorCode;
650   char   message[256];
651
652   errors.reserve(512);
653   while ((errorCode = ERR_get_error()) != 0) {
654     if (!errors.empty()) {
655       errors += "; ";
656     }
657     const char* reason = ERR_reason_error_string(errorCode);
658     if (reason == nullptr) {
659       snprintf(message, sizeof(message) - 1, "SSL error # %lu", errorCode);
660       reason = message;
661     }
662     errors += reason;
663   }
664   if (errors.empty()) {
665     errors = "error code: " + folly::to<std::string>(errnoCopy);
666   }
667   return errors;
668 }
669
670 std::ostream&
671 operator<<(std::ostream& os, const PasswordCollector& collector) {
672   os << collector.describe();
673   return os;
674 }
675
676 } // folly