"Fossies" - the Fresh Open Source Software Archive

Member "shellinabox-2.20/libhttp/ssl.c" (9 Nov 2016, 35736 Bytes) of package /linux/privat/shellinabox-2.20.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "ssl.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.19_vs_2.20.

    1 // ssl.c -- Support functions that find and load SSL support, if available
    2 // Copyright (C) 2008-2010 Markus Gutschke <markus@shellinabox.com>
    3 //
    4 // This program is free software; you can redistribute it and/or modify
    5 // it under the terms of the GNU General Public License version 2 as
    6 // published by the Free Software Foundation.
    7 //
    8 // This program is distributed in the hope that it will be useful,
    9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
   10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   11 // GNU General Public License for more details.
   12 //
   13 // You should have received a copy of the GNU General Public License along
   14 // with this program; if not, write to the Free Software Foundation, Inc.,
   15 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
   16 //
   17 // In addition to these license terms, the author grants the following
   18 // additional rights:
   19 //
   20 // If you modify this program, or any covered work, by linking or
   21 // combining it with the OpenSSL project's OpenSSL library (or a
   22 // modified version of that library), containing parts covered by the
   23 // terms of the OpenSSL or SSLeay licenses, the author
   24 // grants you additional permission to convey the resulting work.
   25 // Corresponding Source for a non-source form of such a combination
   26 // shall include the source code for the parts of OpenSSL used as well
   27 // as that of the covered work.
   28 //
   29 // You may at your option choose to remove this additional permission from
   30 // the work, or from any part of it.
   31 //
   32 // It is possible to build this program in a way that it loads OpenSSL
   33 // libraries at run-time. If doing so, the following notices are required
   34 // by the OpenSSL and SSLeay licenses:
   35 //
   36 // This product includes software developed by the OpenSSL Project
   37 // for use in the OpenSSL Toolkit. (http://www.openssl.org/)
   38 //
   39 // This product includes cryptographic software written by Eric Young
   40 // (eay@cryptsoft.com)
   41 //
   42 //
   43 // The most up-to-date version of this program is always available from
   44 // http://shellinabox.com
   45 
   46 #define _GNU_SOURCE
   47 #include "config.h"
   48 
   49 #define pthread_once    x_pthread_once
   50 #define pthread_sigmask x_pthread_sigmask
   51 
   52 #include <dlfcn.h>
   53 #include <errno.h>
   54 #include <fcntl.h>
   55 #include <netdb.h>
   56 #include <signal.h>
   57 #include <stdlib.h>
   58 #include <string.h>
   59 #include <sys/types.h>
   60 #include <sys/stat.h>
   61 #include <sys/wait.h>
   62 #include <unistd.h>
   63 
   64 #include "libhttp/ssl.h"
   65 #include "libhttp/httpconnection.h"
   66 #include "logging/logging.h"
   67 
   68 #ifdef HAVE_UNUSED
   69 #defined ATTR_UNUSED __attribute__((unused))
   70 #defined UNUSED(x)   do { } while (0)
   71 #else
   72 #define ATTR_UNUSED
   73 #define UNUSED(x)    do { (void)(x); } while (0)
   74 #endif
   75 
   76 #undef pthread_once
   77 #undef pthread_sigmask
   78 
   79 #if defined(HAVE_OPENSSL) && !defined(OPENSSL_NO_TLSEXT) &&                   \
   80     defined(TLSEXT_NAMETYPE_host_name) && defined(SSL_TLSEXT_ERR_OK)
   81 #define HAVE_TLSEXT
   82 #endif
   83 
   84 #if defined(HAVE_PTHREAD_H)
   85 // Pthread support is optional. Only enable it, if the library has been
   86 // linked into the program
   87 #include <pthread.h>
   88 #if defined(__linux__)
   89 extern int pthread_once(pthread_once_t *, void (*)(void))__attribute__((weak));
   90 #endif
   91 extern int pthread_sigmask(int, const sigset_t *, sigset_t *)
   92                                                          __attribute__((weak));
   93 
   94 #endif
   95 
   96 #if defined(HAVE_DLOPEN)
   97 // SSL support is optional. Only enable it, if the library can be loaded.
   98 long          (*BIO_ctrl)(BIO *, int, long, void *);
   99 BIO_METHOD *  (*BIO_f_buffer)(void);
  100 void          (*BIO_free_all)(BIO *);
  101 BIO *         (*BIO_new)(BIO_METHOD *);
  102 BIO *         (*BIO_new_socket)(int, int);
  103 BIO *         (*BIO_next)(BIO *);
  104 BIO *         (*BIO_pop)(BIO *);
  105 BIO *         (*BIO_push)(BIO *, BIO *);
  106 #if defined(HAVE_OPENSSL_EC)
  107 void          (*EC_KEY_free)(EC_KEY *);
  108 EC_KEY *      (*EC_KEY_new_by_curve_name)(int);
  109 #endif
  110 void          (*ERR_clear_error)(void);
  111 unsigned long (*ERR_peek_error)(void);
  112 long          (*SSL_CTX_callback_ctrl)(SSL_CTX *, int, void (*)(void));
  113 int           (*SSL_CTX_check_private_key)(const SSL_CTX *);
  114 long          (*SSL_CTX_ctrl)(SSL_CTX *, int, long, void *);
  115 void          (*SSL_CTX_free)(SSL_CTX *);
  116 SSL_CTX *     (*SSL_CTX_new)(SSL_METHOD *);
  117 int           (*SSL_CTX_set_cipher_list)(SSL_CTX *, const char *);
  118 void          (*SSL_CTX_set_info_callback)(SSL_CTX *,
  119                                            void (*)(const SSL *, int, int));
  120 int           (*SSL_CTX_use_PrivateKey_file)(SSL_CTX *, const char *, int);
  121 int           (*SSL_CTX_use_PrivateKey_ASN1)(int, SSL_CTX *,
  122                                              const unsigned char *, long);
  123 int           (*SSL_CTX_use_certificate_file)(SSL_CTX *, const char *, int);
  124 int           (*SSL_CTX_use_certificate_ASN1)(SSL_CTX *, long,
  125                                               const unsigned char *);
  126 long          (*SSL_ctrl)(SSL *, int, long, void *);
  127 void          (*SSL_free)(SSL *);
  128 int           (*SSL_get_error)(const SSL *, int);
  129 void *        (*SSL_get_ex_data)(const SSL *, int);
  130 BIO *         (*SSL_get_rbio)(const SSL *);
  131 const char *  (*SSL_get_servername)(const SSL *, int);
  132 BIO *         (*SSL_get_wbio)(const SSL *);
  133 int           (*SSL_library_init)(void);
  134 SSL *         (*SSL_new)(SSL_CTX *);
  135 int           (*SSL_read)(SSL *, void *, int);
  136 SSL_CTX *     (*SSL_set_SSL_CTX)(SSL *, SSL_CTX *);
  137 void          (*SSL_set_accept_state)(SSL *);
  138 void          (*SSL_set_bio)(SSL *, BIO *, BIO *);
  139 int           (*SSL_set_ex_data)(SSL *, int, void *);
  140 int           (*SSL_shutdown)(SSL *);
  141 int           (*SSL_write)(SSL *, const void *, int);
  142 SSL_METHOD *  (*SSLv23_server_method)(void);
  143 X509 *        (*d2i_X509)(X509 **px, const unsigned char **in, int len);
  144 void          (*X509_free)(X509 *a);
  145 void          (*x_sk_zero)(void *st);
  146 void *        (*x_SSL_COMP_get_compression_methods)(void);
  147 #endif
  148 
  149 static void sslDestroyCachedContext(void *ssl_, char *context_) {
  150   struct SSLSupport *ssl = (struct SSLSupport *)ssl_;
  151   SSL_CTX *context       = (SSL_CTX *)context_;
  152 #if defined(HAVE_OPENSSL)
  153   if (context != ssl->sslContext) {
  154     SSL_CTX_free(context);
  155   }
  156 #else
  157   check(!context);
  158   check(!ssl->sslContext);
  159 #endif
  160 }
  161 
  162 struct SSLSupport *newSSL(void) {
  163   struct SSLSupport *ssl;
  164   check(ssl = malloc(sizeof(struct SSLSupport)));
  165   initSSL(ssl);
  166   return ssl;
  167 }
  168 
  169 void initSSL(struct SSLSupport *ssl) {
  170   ssl->enabled               = serverSupportsSSL();
  171   ssl->force                 = 0;
  172   ssl->sslContext            = NULL;
  173   ssl->sniCertificatePattern = NULL;
  174   ssl->generateMissing       = 0;
  175   ssl->renegotiationCount    = 0;
  176   initTrie(&ssl->sniContexts, sslDestroyCachedContext, ssl);
  177 }
  178 
  179 void destroySSL(struct SSLSupport *ssl) {
  180   if (ssl) {
  181     free(ssl->sniCertificatePattern);
  182     destroyTrie(&ssl->sniContexts);
  183 #if defined(HAVE_OPENSSL)
  184     if (ssl->sslContext) {
  185       dcheck(!ERR_peek_error());
  186       SSL_CTX_free(ssl->sslContext);
  187     }
  188 #else
  189     check(!ssl->sslContext);
  190 #endif
  191   }
  192 }
  193 
  194 void deleteSSL(struct SSLSupport *ssl) {
  195   destroySSL(ssl);
  196   free(ssl);
  197 }
  198 
  199 #if defined(HAVE_OPENSSL) && defined(HAVE_DLOPEN)
  200 static int maybeLoadCrypto(void) {
  201   // Some operating systems cannot automatically load dependent dynamic
  202   // libraries. As libssl.so can depend on libcrypto.so, we try to load
  203   // it, iff we haven't tried loading it before and iff libssl.so does not
  204   // work by itself.
  205   static int crypto;
  206   // SHELLINABOX_LIBCRYPTO_SO can be used to select the specific
  207   // soname of libcrypto for systems where it is not libcrypto.so.
  208   // The feature is currently disabled.
  209   const char* path_libcrypto = NULL; // getenv ("SHELLINABOX_LIBCRYPTO_SO");
  210   if (path_libcrypto == NULL)
  211     path_libcrypto = "libcrypto.so";
  212 
  213   if (!crypto++) {
  214 #ifdef RTLD_NOLOAD
  215     if (dlopen(path_libcrypto, RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD))
  216       return 1;
  217     else
  218 #endif
  219       if (dlopen(path_libcrypto, RTLD_LAZY|RTLD_GLOBAL))
  220         return 1;
  221   }
  222   return 0;
  223 }
  224 
  225 static void *loadSymbol(const char *lib, const char *fn) {
  226   int err  = NOINTR(dup(2));
  227   if (err > 2) {
  228     int null = NOINTR(open("/dev/null", O_WRONLY));
  229     if (null >= 0) {
  230       NOINTR(dup2(null, 2));
  231       NOINTR(close(null));
  232     }
  233   }
  234   void *dl = RTLD_DEFAULT;
  235   void *rc = dlsym(dl, fn);
  236   if (!rc) {
  237     for (int i = 0; i < 2; i++) {
  238 #ifdef RTLD_NOLOAD
  239       dl   = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD);
  240 #else
  241       dl   = NULL;
  242 #endif
  243       if (dl == NULL) {
  244         dl = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL);
  245       }
  246       if (dl != NULL || !maybeLoadCrypto()) {
  247         break;
  248       }
  249     }
  250     if (dl != NULL) {
  251       rc   = dlsym(RTLD_DEFAULT, fn);
  252       if (rc == NULL && maybeLoadCrypto()) {
  253         rc = dlsym(RTLD_DEFAULT, fn);
  254       }
  255     }
  256   }
  257   if (err > 2) {
  258     NOINTR(dup2(err, 2));
  259   }
  260   NOINTR(close(err));
  261   return rc;
  262 }
  263 
  264 static void loadSSL(void) {
  265   // SHELLINABOX_LIBSSL_SO can be used to select the specific
  266   // soname of libssl for systems where it is not libssl.so.
  267   // The feature is currently disabled.
  268   const char* path_libssl = NULL; // = getenv ("SHELLINABOX_LIBSSL_SO");
  269   if (path_libssl == NULL)
  270     path_libssl = "libssl.so";
  271   check(!SSL_library_init);
  272   struct {
  273     union {
  274       void *avoid_gcc_warning_about_type_punning;
  275       void **var;
  276     };
  277     const char *fn;
  278   } symbols[] = {
  279     { { &BIO_ctrl },                    "BIO_ctrl" },
  280     { { &BIO_f_buffer },                "BIO_f_buffer" },
  281     { { &BIO_free_all },                "BIO_free_all" },
  282     { { &BIO_new },                     "BIO_new" },
  283     { { &BIO_new_socket },              "BIO_new_socket" },
  284     { { &BIO_next },                    "BIO_next" },
  285     { { &BIO_pop },                     "BIO_pop" },
  286     { { &BIO_push },                    "BIO_push" },
  287     { { &ERR_clear_error },             "ERR_clear_error" },
  288     { { &ERR_clear_error },             "ERR_clear_error" },
  289     { { &ERR_peek_error },              "ERR_peek_error" },
  290     { { &ERR_peek_error },              "ERR_peek_error" },
  291 #ifdef HAVE_OPENSSL_EC
  292     { { &EC_KEY_free },                 "EC_KEY_free" },
  293     { { &EC_KEY_new_by_curve_name },    "EC_KEY_new_by_curve_name" },
  294 #endif
  295     { { &SSL_CTX_callback_ctrl },       "SSL_CTX_callback_ctrl" },
  296     { { &SSL_CTX_check_private_key },   "SSL_CTX_check_private_key" },
  297     { { &SSL_CTX_ctrl },                "SSL_CTX_ctrl" },
  298     { { &SSL_CTX_free },                "SSL_CTX_free" },
  299     { { &SSL_CTX_new },                 "SSL_CTX_new" },
  300     { { &SSL_CTX_set_cipher_list },     "SSL_CTX_set_cipher_list" },
  301     { { &SSL_CTX_set_info_callback },   "SSL_CTX_set_info_callback" },
  302     { { &SSL_CTX_use_PrivateKey_file }, "SSL_CTX_use_PrivateKey_file" },
  303     { { &SSL_CTX_use_PrivateKey_ASN1 }, "SSL_CTX_use_PrivateKey_ASN1" },
  304     { { &SSL_CTX_use_certificate_file },"SSL_CTX_use_certificate_file"},
  305     { { &SSL_CTX_use_certificate_ASN1 },"SSL_CTX_use_certificate_ASN1"},
  306     { { &SSL_ctrl },                    "SSL_ctrl" },
  307     { { &SSL_free },                    "SSL_free" },
  308     { { &SSL_get_error },               "SSL_get_error" },
  309     { { &SSL_get_ex_data },             "SSL_get_ex_data" },
  310     { { &SSL_get_rbio },                "SSL_get_rbio" },
  311 #ifdef HAVE_TLSEXT
  312     { { &SSL_get_servername },          "SSL_get_servername" },
  313 #endif
  314     { { &SSL_get_wbio },                "SSL_get_wbio" },
  315     { { &SSL_library_init },            "SSL_library_init" },
  316     { { &SSL_new },                     "SSL_new" },
  317     { { &SSL_read },                    "SSL_read" },
  318 #ifdef HAVE_TLSEXT
  319     { { &SSL_set_SSL_CTX },             "SSL_set_SSL_CTX" },
  320 #endif
  321     { { &SSL_set_accept_state },        "SSL_set_accept_state" },
  322     { { &SSL_set_bio },                 "SSL_set_bio" },
  323     { { &SSL_set_ex_data },             "SSL_set_ex_data" },
  324     { { &SSL_shutdown },                "SSL_shutdown" },
  325     { { &SSL_write },                   "SSL_write" },
  326     { { &SSLv23_server_method },        "SSLv23_server_method" },
  327     { { &d2i_X509 },                    "d2i_X509" },
  328     { { &X509_free },                   "X509_free" },
  329     { { &x_sk_zero },                   "sk_zero" }
  330   };
  331   for (unsigned i = 0; i < sizeof(symbols)/sizeof(symbols[0]); i++) {
  332     if (!(*symbols[i].var = loadSymbol(path_libssl, symbols[i].fn))) {
  333       debug("[ssl] Failed to load SSL support. Could not find \"%s\"!",
  334             symbols[i].fn);
  335       for (unsigned j = 0; j < sizeof(symbols)/sizeof(symbols[0]); j++) {
  336         *symbols[j].var = NULL;
  337       }
  338       return;
  339     }
  340   }
  341   // These are optional
  342   x_SSL_COMP_get_compression_methods = loadSymbol(path_libssl, "SSL_COMP_get_compression_methods");
  343   // ends
  344 
  345 
  346   SSL_library_init();
  347   dcheck(!ERR_peek_error());
  348   debug("[ssl] Loaded SSL suppport...");
  349 }
  350 #endif
  351 
  352 int serverSupportsSSL(void) {
  353 #if defined(HAVE_OPENSSL) && !defined(HAVE_DLOPEN)
  354   return SSL_library_init();
  355 #else
  356 #if defined(HAVE_OPENSSL)
  357   // We want to call loadSSL() exactly once. For single-threaded applications,
  358   // this is straight-forward. For threaded applications, we need to call
  359   // pthread_once(), instead. We perform run-time checks for whether we are
  360   // single- or multi-threaded, so that the same code can be used.
  361   // This currently only works on Linux.
  362 #if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
  363   if (!!&pthread_once) {
  364     static pthread_once_t once = PTHREAD_ONCE_INIT;
  365     pthread_once(&once, loadSSL);
  366   } else
  367 #endif
  368   {
  369     static int initialized;
  370     if (!initialized) {
  371       initialized = 1;
  372       loadSSL();
  373     }
  374   }
  375   return !!SSL_library_init;
  376 #else
  377   return 0;
  378 #endif
  379 #endif
  380 }
  381 
  382 #if defined(HAVE_OPENSSL)
  383 static void sslGenerateCertificate(const char *certificate,
  384                                    const char *serverName) {
  385   info("[ssl] Auto-generating missing certificate \"%s\" for \"%s\"...",
  386         certificate, serverName);
  387 
  388   pid_t pid       = fork();
  389   if (pid == -1) {
  390     warn("[ssl] Failed to generate self-signed certificate \"%s\"!", certificate);
  391   } else if (pid == 0) {
  392     int fd        = NOINTR(open("/dev/null", O_RDONLY));
  393     check(fd != -1);
  394     check(NOINTR(dup2(fd, STDERR_FILENO)) == STDERR_FILENO);
  395     check(NOINTR(close(fd)) == 0);
  396     fd            = NOINTR(open("/dev/null", O_WRONLY));
  397     check(fd != -1);
  398     check(NOINTR(dup2(fd, STDIN_FILENO)) == STDIN_FILENO);
  399     check(NOINTR(close(fd)) == 0);
  400     umask(077);
  401     check(setenv("PATH", "/usr/bin:/usr/sbin", 1) == 0);
  402     char *subject;
  403     check(subject = stringPrintf(NULL, "/CN=%s/", serverName));
  404     if (execlp("openssl", "openssl", "req", "-x509", "-nodes", "-days", "7300",
  405                "-newkey", "rsa:2048", "-keyout", certificate, "-out", certificate,
  406                "-subj", subject, (char *)NULL) < 0) {
  407       warn("[ssl] Failed to generate self-signed certificate \"%s\"!", certificate);
  408       free(subject);
  409     }
  410   } else {
  411     int status;
  412     check(NOINTR(waitpid(pid, &status, 0)) == pid);
  413     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
  414       warn("[ssl] Failed to generate self-signed certificate \"%s\"!", certificate);
  415     } else {
  416       info("[ssl] Certificate successfully generated.");
  417     }
  418   }
  419 }
  420 
  421 static const unsigned char *sslSecureReadASCIIFileToMem(int fd) {
  422   size_t inc          = 16384;
  423   size_t bufSize      = inc;
  424   size_t len          = 0;
  425   unsigned char *buf;
  426   check((buf          = malloc(bufSize)) != NULL);
  427   for (;;) {
  428     check(len < bufSize - 1);
  429     ssize_t readLen   = bufSize - len - 1;
  430     ssize_t bytesRead = NOINTR(read(fd, buf + len, readLen));
  431     if (bytesRead > 0) {
  432       len            += bytesRead;
  433     }
  434     if (bytesRead != readLen) {
  435       break;
  436     }
  437 
  438     // Instead of calling realloc(), allocate a new buffer, copy the data,
  439     // and then clear the old buffer. This way, we are not accidentally
  440     // leaving key material in memory.
  441     unsigned char *newBuf;
  442     check((newBuf     = malloc(bufSize + inc)) != NULL);
  443     memcpy(newBuf, buf, len);
  444     memset(buf, 0, bufSize);
  445     free(buf);
  446     buf               = newBuf;
  447     bufSize          += inc;
  448   }
  449   check(len < bufSize);
  450   buf[len]            = '\000';
  451   return buf;
  452 }
  453 
  454 static const unsigned char *sslPEMtoASN1(const unsigned char *pem,
  455                                          const char *record,
  456                                          long *size,
  457                                          const unsigned char **eor) {
  458   if (eor) {
  459     *eor             = NULL;
  460   }
  461   *size              = 0;
  462   char *marker;
  463   check((marker      = stringPrintf(NULL, "-----BEGIN %s-----",record))!=NULL);
  464   unsigned char *ptr = (unsigned char *)strstr((char *)pem, marker);
  465   if (!ptr) {
  466     free(marker);
  467     return NULL;
  468   } else {
  469     ptr             += strlen(marker);
  470   }
  471   *marker            = '\000';
  472   check((marker      = stringPrintf(marker, "-----END %s-----",record))!=NULL);
  473   unsigned char *end = (unsigned char *)strstr((char *)ptr, marker);
  474   if (eor) {
  475     *eor             = end + strlen(marker);
  476   }
  477   free(marker);
  478   if (!end) {
  479     return NULL;
  480   }
  481   unsigned char *ret;
  482   ssize_t maxSize    = (((end - ptr)*6)+7)/8;
  483   check((ret         = malloc(maxSize)) != NULL);
  484   unsigned char *out = ret;
  485   unsigned bits      = 0;
  486   int count          = 0;
  487   while (ptr < end) {
  488     unsigned char ch = *ptr++;
  489     if (ch >= 'A' && ch <= 'Z') {
  490       ch            -= 'A';
  491     } else if (ch >= 'a' && ch <= 'z') {
  492       ch            -= 'a' - 26;
  493     } else if (ch >= '0' && ch <= '9') {
  494       ch            += 52 - '0';
  495     } else if (ch == '+') {
  496       ch            += 62 - '+';
  497     } else if (ch == '/') {
  498       ch            += 63 - '/';
  499     } else if (ch == '=') {
  500       while (ptr < end) {
  501         if ((ch      = *ptr++) != '=' && ch > ' ') {
  502           goto err;
  503         }
  504       }
  505       break;
  506     } else if (ch <= ' ') {
  507       continue;
  508     } else {
  509    err:
  510       free(ret);
  511       return NULL;
  512     }
  513     check(ch <= 63);
  514     check(count >= 0);
  515     check(count <= 6);
  516     bits             = (bits << 6) | ch;
  517     count           += 6;
  518     if (count >= 8) {
  519       *out++         = (bits >> (count -= 8)) & 0xFF;
  520     }
  521   }
  522   check(out - ret <= maxSize);
  523   *size              = out - ret;
  524   return ret;
  525 }
  526 
  527 static int sslSetCertificateFromFd(SSL_CTX *context, int fd) {
  528   int rc                       = 0;
  529   check(serverSupportsSSL());
  530   check(fd >= 0);
  531   const unsigned char *data    = sslSecureReadASCIIFileToMem(fd);
  532   check(!NOINTR(close(fd)));
  533   long dataSize                = (long)strlen((const char *)data);
  534   long certSize, rsaSize, dsaSize, ecSize, notypeSize;
  535   const unsigned char *record;
  536   const unsigned char *cert    = sslPEMtoASN1(data, "CERTIFICATE", &certSize,
  537                                               &record);
  538   const unsigned char *rsa     = sslPEMtoASN1(data, "RSA PRIVATE KEY",&rsaSize,
  539                                               NULL);
  540   const unsigned char *dsa     = sslPEMtoASN1(data, "DSA PRIVATE KEY",&dsaSize,
  541                                               NULL);
  542   const unsigned char *ec      = sslPEMtoASN1(data, "EC PRIVATE KEY",  &ecSize,
  543                                               NULL);
  544   const unsigned char *notype  = sslPEMtoASN1(data, "PRIVATE KEY", &notypeSize,
  545                                               NULL);
  546   if (certSize && (rsaSize || dsaSize
  547 #ifdef EVP_PKEY_EC
  548                                       || ecSize
  549 #endif
  550                                                 || notypeSize) &&
  551       SSL_CTX_use_certificate_ASN1(context, certSize, cert) &&
  552       (!rsaSize ||
  553        SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, context, rsa, rsaSize)) &&
  554       (!dsaSize ||
  555        SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_DSA, context, dsa, dsaSize)) &&
  556 #ifdef EVP_PKEY_EC
  557       (!ecSize ||
  558        SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC, context, ec, ecSize)) &&
  559 #endif
  560       // Assume a private key is RSA if the header does not specify a type.
  561       // (e.g. BEGIN PRIVATE KEY)
  562       (!notypeSize ||
  563        SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, context, notype, notypeSize))
  564       ) {
  565     memset((char *)cert, 0, certSize);
  566     free((char *)cert);
  567     while (record) {
  568       cert                     = sslPEMtoASN1(record, "CERTIFICATE", &certSize,
  569                                               &record);
  570       if (cert) {
  571         X509 *x509;
  572         const unsigned char *c = cert;
  573         check(x509             = d2i_X509(NULL, &c, certSize));
  574         memset((char *)cert, 0, certSize);
  575         free((char *)cert);
  576         if (!SSL_CTX_add_extra_chain_cert(context, x509)) {
  577           X509_free(x509);
  578           break;
  579         }
  580       }
  581     }
  582     if (!record && SSL_CTX_check_private_key(context)) {
  583       rc                       = 1;
  584     }
  585     dcheck(!ERR_peek_error());
  586     ERR_clear_error();
  587   } else {
  588     memset((char *)cert, 0, certSize);
  589     free((char *)cert);
  590   }
  591   memset((char *)data, 0, dataSize);
  592   free((char *)data);
  593   memset((char *)rsa, 0, rsaSize);
  594   free((char *)rsa);
  595   memset((char *)dsa, 0, dsaSize);
  596   free((char *)dsa);
  597   memset((char *)ec, 0, ecSize);
  598   free((char *)ec);
  599   memset((char *)notype, 0, notypeSize);
  600   free((char *)notype);
  601   return rc;
  602 }
  603 
  604 static int sslSetCertificateFromFile(SSL_CTX *context,
  605                                      const char *filename) {
  606   int fd = open(filename, O_RDONLY);
  607   if (fd < 0) {
  608     return -1;
  609   }
  610   int rc = sslSetCertificateFromFd(context, fd);
  611   return rc;
  612 }
  613 
  614 static void sslInfoCallback(const SSL *sslHndl, int type, int val) {
  615   // Count the number of renegotiations for each SSL session.
  616   if (type & SSL_CB_HANDSHAKE_START) {
  617     struct HttpConnection *http    =
  618                           (struct HttpConnection *) SSL_get_app_data(sslHndl);
  619     http->ssl->renegotiationCount += 1;
  620   }
  621 }
  622 
  623 static SSL_CTX *sslMakeContext(void) {
  624 
  625   SSL_CTX *context;
  626   check(context = SSL_CTX_new(SSLv23_server_method()));
  627 
  628   long options  = SSL_OP_ALL;
  629   options      |= SSL_OP_NO_SSLv2;
  630   options      |= SSL_OP_NO_SSLv3;
  631   options      |= SSL_OP_SINGLE_DH_USE;
  632 
  633 #ifdef SSL_OP_NO_COMPRESSION
  634   options      |= SSL_OP_NO_COMPRESSION;
  635 #endif
  636 
  637 #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  638   options      |= SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;
  639 #endif
  640 
  641   // Set default SSL options.
  642   SSL_CTX_set_options(context, options);
  643 
  644   // Workaround for SSL_OP_NO_COMPRESSION with older OpenSSL versions.
  645 #ifdef HAVE_DLOPEN
  646   if (SSL_COMP_get_compression_methods) {
  647     sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
  648   }
  649 #elif OPENSSL_VERSION_NUMBER >= 0x00908000L
  650   sk_SSL_COMP_zero(SSL_COMP_get_compression_methods());
  651 #endif
  652 
  653   // For Perfect Forward Secrecy (PFS) support we need to enable some additional
  654   // SSL options, provide eliptic curve key object for handshake and add chipers
  655   // suits with ECDHE handshake on top of the ciper list.
  656 #ifdef HAVE_OPENSSL_EC
  657   SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
  658   SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
  659 
  660   EC_KEY *ecKey;
  661   check(ecKey   = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
  662   SSL_CTX_set_tmp_ecdh(context, ecKey);
  663   EC_KEY_free(ecKey);
  664 
  665   debug("[ssl] Support for PFS enabled...");
  666 #endif
  667 
  668   check(SSL_CTX_set_cipher_list(context,
  669     "ECDHE-RSA-AES256-GCM-SHA384:"
  670     "ECDHE-RSA-AES128-GCM-SHA256:"
  671     "ECDHE-RSA-AES256-SHA384:"
  672     "ECDHE-RSA-AES128-SHA256:"
  673     "ECDHE-RSA-AES256-SHA:"
  674     "ECDHE-RSA-AES128-SHA:"
  675     "ECDHE-RSA-DES-CBC3-SHA:"
  676     "HIGH:MEDIUM:!RC4:!aNULL:!MD5"));
  677 
  678   SSL_CTX_set_info_callback(context, sslInfoCallback);
  679 
  680   debug("[ssl] Server context successfully initialized...");
  681   return context;
  682 }
  683 #endif
  684 
  685 #ifdef HAVE_TLSEXT
  686 static int sslSNICallback(SSL *sslHndl, int *al ATTR_UNUSED,
  687                           struct SSLSupport *ssl) {
  688   UNUSED(al);
  689   check(!ERR_peek_error());
  690   const char *name        = SSL_get_servername(sslHndl,
  691                                                TLSEXT_NAMETYPE_host_name);
  692   if (name == NULL || !*name) {
  693     return SSL_TLSEXT_ERR_OK;
  694   }
  695   struct HttpConnection *http =
  696                             (struct HttpConnection *)SSL_get_app_data(sslHndl);
  697   debug("[ssl] Received SNI callback for virtual host \"%s\" from \"%s:%d\"...",
  698         name, httpGetPeerName(http), httpGetPort(http));
  699   char *serverName;
  700   check(serverName        = malloc(strlen(name)+2));
  701   serverName[0]           = '-';
  702   for (int i = 0;;) {
  703     char ch               = name[i];
  704     if (ch >= 'A' && ch <= 'Z') {
  705       ch                 |= 0x20;
  706     } else if (ch != '\000' && ch != '.' && ch != '-' &&
  707                (ch < '0' ||(ch > '9' && ch < 'A') || (ch > 'Z' &&
  708                 ch < 'a')|| ch > 'z')) {
  709       free(serverName);
  710       return SSL_TLSEXT_ERR_OK;
  711     }
  712     serverName[++i]       = ch;
  713     if (!ch) {
  714       break;
  715     }
  716   }
  717   SSL_CTX *context        = (SSL_CTX *)getFromTrie(&ssl->sniContexts,
  718                                                    serverName+1,
  719                                                    NULL);
  720   if (context == NULL) {
  721     context               = sslMakeContext();
  722     check(ssl->sniCertificatePattern);
  723     char *certificate     = stringPrintfUnchecked(NULL,
  724                                                   ssl->sniCertificatePattern,
  725                                                   serverName);
  726     if (sslSetCertificateFromFile(context, certificate) < 0) {
  727       if (ssl->generateMissing) {
  728         sslGenerateCertificate(certificate, serverName + 1);
  729 
  730         // No need to check the certificate. If we fail to set it, we will use
  731         // the default certificate, instead.
  732         sslSetCertificateFromFile(context, certificate);
  733       } else {
  734         warn("[ssl] Could not find matching certificate \"%s\" for \"%s\"",
  735              certificate, serverName + 1);
  736         SSL_CTX_free(context);
  737         context           = ssl->sslContext;
  738       }
  739     }
  740     ERR_clear_error();
  741     free(certificate);
  742     addToTrie(&ssl->sniContexts, serverName+1, (char *)context);
  743   }
  744   free(serverName);
  745   if (context != ssl->sslContext) {
  746     check(SSL_set_SSL_CTX(sslHndl, context));
  747   }
  748   check(!ERR_peek_error());
  749   return SSL_TLSEXT_ERR_OK;
  750 }
  751 #endif
  752 
  753 #if defined(HAVE_OPENSSL) && !defined(HAVE_GETHOSTBYNAME_R)
  754 // This is a not-thread-safe replacement for gethostbyname_r()
  755 #define gethostbyname_r x_gethostbyname_r
  756 static int gethostbyname_r(const char *name, struct hostent *ret,
  757                            char *buf ATTR_UNUSED, size_t buflen ATTR_UNUSED,
  758                            struct hostent **result, int *h_errnop) {
  759   UNUSED(buf);
  760   UNUSED(buflen);
  761   if (result) {
  762     *result          = NULL;
  763   }
  764   if (h_errnop) {
  765     *h_errnop        = ERANGE;
  766   }
  767   if (!ret) {
  768     return -1;
  769   }
  770   struct hostent *he = gethostbyname(name);
  771   if (he) {
  772     *ret             = *he;
  773     if (result) {
  774       *result        = ret;
  775     }
  776   }
  777   if (h_errnop) {
  778     *h_errnop        = h_errno;
  779   }
  780   return he ? 0 : -1;
  781 }
  782 #endif
  783 
  784 void sslSetCertificate(struct SSLSupport *ssl, const char *filename,
  785                        int autoGenerateMissing) {
  786 #if defined(HAVE_OPENSSL)
  787   check(serverSupportsSSL());
  788 
  789   char *defaultCertificate;
  790   check(defaultCertificate           = strdup(filename));
  791   char *ptr                          = strchr(defaultCertificate, '%');
  792   if (ptr != NULL) {
  793     check(!strchr(ptr+1, '%'));
  794     check(ptr[1] == 's');
  795     memmove(ptr, ptr + 2, strlen(ptr)-1);
  796   }
  797 
  798   // Try to set the default certificate. If necessary, (re-)generate it.
  799   ssl->sslContext                    = sslMakeContext();
  800   if (autoGenerateMissing) {
  801     if (sslSetCertificateFromFile(ssl->sslContext, defaultCertificate) < 0) {
  802       char hostname[256], buf[4096];
  803       check(!gethostname(hostname, sizeof(hostname)));
  804       struct hostent he_buf, *he;
  805       int h_err = 0;
  806       int ret = gethostbyname_r(hostname, &he_buf, buf, sizeof(buf), &he, &h_err);
  807       if (!ret && he && he->h_name) {
  808         sslGenerateCertificate(defaultCertificate, he->h_name);
  809       } else {
  810         if (h_err) {
  811           warn("[ssl] Error getting host information: \"%s\".", hstrerror(h_err));
  812         }
  813         sslGenerateCertificate(defaultCertificate, hostname);
  814       }
  815     } else {
  816       goto valid_certificate;
  817     }
  818   }
  819   if (sslSetCertificateFromFile(ssl->sslContext, defaultCertificate) < 0) {
  820     fatal("[ssl] Cannot read valid certificate from \"%s\"! "
  821           "Check file permissions and file format.", defaultCertificate);
  822   }
  823  valid_certificate:
  824   free(defaultCertificate);
  825 
  826   // Enable SNI support so that we can set a different certificate, if the
  827   // client asked for it.
  828 #ifdef HAVE_TLSEXT
  829   if (ptr != NULL) {
  830     check(ssl->sniCertificatePattern = strdup(filename));
  831     check(SSL_CTX_set_tlsext_servername_callback(ssl->sslContext,
  832                                                  sslSNICallback));
  833     check(SSL_CTX_set_tlsext_servername_arg(ssl->sslContext, ssl));
  834   }
  835 #endif
  836   dcheck(!ERR_peek_error());
  837   ERR_clear_error();
  838 
  839   ssl->generateMissing               = autoGenerateMissing;
  840 #endif
  841 }
  842 
  843 // Convert the file descriptor to a human-readable format. Attempts to
  844 // retrieve the original file name where possible.
  845 #ifdef HAVE_OPENSSL
  846 static char *sslFdToFilename(int fd) {
  847   char *proc, *buf;
  848   int  len         = 128;
  849   check(proc       = stringPrintf(NULL, "/proc/self/fd/%d", fd));
  850   check(buf        = malloc(len));
  851   for (;;) {
  852     ssize_t i;
  853     if ((i = readlink(proc, buf + 1, len-3)) < 0) {
  854       free(proc);
  855       free(buf);
  856       check(buf    = stringPrintf(NULL, "fd %d", fd));
  857       return buf;
  858     } else if (i >= len-3) {
  859       len         += 512;
  860       check(buf    = realloc(buf, len));
  861     } else {
  862       free(proc);
  863       check(i >= 0 && i < len);
  864       buf[i+1]     = '\000';
  865       struct stat sb;
  866       if (!stat(buf + 1, &sb) && S_ISREG(sb.st_mode)) {
  867         *buf       = '"';
  868         buf[i + 1] = '"';
  869         buf[i + 2] = '\000';
  870         return buf;
  871       } else {
  872         free(buf);
  873         check(buf  = stringPrintf(NULL, "fd %d", fd));
  874         return buf;
  875       }
  876     }
  877   }
  878 }
  879 #endif
  880 
  881 void sslSetCertificateFd(struct SSLSupport *ssl, int fd) {
  882 #ifdef HAVE_OPENSSL
  883   ssl->sslContext = sslMakeContext();
  884   char *filename = sslFdToFilename(fd);
  885   if (!sslSetCertificateFromFd(ssl->sslContext, fd)) {
  886     fatal("[ssl] Cannot read valid certificate from %s. Check file format.",
  887           filename);
  888   }
  889   free(filename);
  890   ssl->generateMissing  = 0;
  891 #endif
  892 }
  893 
  894 int sslEnable(struct SSLSupport *ssl, int enabled) {
  895   int old      = ssl->enabled;
  896   ssl->enabled = enabled;
  897   return old;
  898 }
  899 
  900 int sslForce(struct SSLSupport *ssl, int force) {
  901   int old      = ssl->force;
  902   ssl->force   = force;
  903   return old;
  904 }
  905 
  906 void sslBlockSigPipe(void) {
  907   sigset_t set;
  908   sigemptyset(&set);
  909   sigaddset(&set, SIGPIPE);
  910 #if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
  911   if (&pthread_sigmask) {
  912     dcheck(!pthread_sigmask(SIG_BLOCK, &set, NULL));
  913   } else
  914 #endif
  915   {
  916     dcheck(!sigprocmask(SIG_BLOCK, &set, NULL));
  917   }
  918 }
  919 
  920 #ifndef HAVE_SIGWAIT
  921 // This is a non-thread-safe replacement for sigwait()
  922 static int dummysignalno;
  923 static void dummysignal(int signo) {
  924   dummysignalno = signo;
  925 }
  926 
  927 #define sigwait x_sigwait
  928 static int sigwait(const sigset_t *set, int *sig) {
  929   sigset_t mask, old_mask;
  930   sigfillset(&mask);
  931 #if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
  932   if (&pthread_sigmask) {
  933     dcheck(!pthread_sigmask(SIG_BLOCK, &mask, &old_mask));
  934   } else
  935 #endif
  936   {
  937     dcheck(!sigprocmask(SIG_BLOCK, &mask, &old_mask));
  938   }
  939   #ifndef NSIG
  940   #define NSIG 32
  941   #endif
  942   struct sigaction sa[NSIG];
  943   memset(sa, 0, sizeof(sa));
  944   sa->sa_handler = dummysignal;
  945   for (int i = 1; i <= NSIG; i++) {
  946     if (sigismember(set, i)) {
  947       sigdelset(&mask, i);
  948       sigaction(i, sa, sa + i);
  949     }
  950   }
  951   dummysignalno = -1;
  952   sigsuspend(&mask);
  953 #if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
  954   if (&pthread_sigmask) {
  955     dcheck(!pthread_sigmask(SIG_SETMASK, &old_mask, NULL));
  956   } else
  957 #endif
  958   {
  959     dcheck(!sigprocmask(SIG_BLOCK, &old_mask, NULL));
  960   }
  961   return dummysignalno;
  962 }
  963 #endif
  964 
  965 int sslUnblockSigPipe(void) {
  966   int signum = 0;
  967   sigset_t set;
  968   check(!sigpending(&set));
  969   if (sigismember(&set, SIGPIPE)) {
  970     sigwait(&set, &signum);
  971   }
  972   sigemptyset(&set);
  973   sigaddset(&set, SIGPIPE);
  974 #if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
  975   if (&pthread_sigmask) {
  976     dcheck(!pthread_sigmask(SIG_UNBLOCK, &set, NULL));
  977   } else
  978 #endif
  979   {
  980     dcheck(!sigprocmask(SIG_UNBLOCK, &set, NULL));
  981   }
  982   return signum;
  983 }
  984 
  985 int sslPromoteToSSL(struct SSLSupport *ssl, SSL **sslHndl, int fd,
  986                     const char *buf, int len) {
  987 #if defined(HAVE_OPENSSL)
  988   sslBlockSigPipe();
  989   int rc          = 0;
  990   check(!*sslHndl);
  991   dcheck(!ERR_peek_error());
  992   dcheck(*sslHndl = SSL_new(ssl->sslContext));
  993   if (*sslHndl == NULL) {
  994     ERR_clear_error();
  995     errno         = EINVAL;
  996     rc            = -1;
  997   } else {
  998     SSL_set_mode(*sslHndl, SSL_MODE_ENABLE_PARTIAL_WRITE);
  999     BIO *writeBIO = BIO_new_socket(fd, 0);
 1000     BIO *readBIO  = writeBIO;
 1001     if (len > 0) {
 1002       readBIO     = BIO_new(BIO_f_buffer());
 1003       BIO_push(readBIO, writeBIO);
 1004       check(BIO_set_buffer_read_data(readBIO, (char *)buf, len));
 1005     }
 1006     SSL_set_bio(*sslHndl, readBIO, writeBIO);
 1007     SSL_set_accept_state(*sslHndl);
 1008     dcheck(!ERR_peek_error());
 1009   }
 1010   sslUnblockSigPipe();
 1011   return rc;
 1012 #else
 1013   errno           = EINVAL;
 1014   return -1;
 1015 #endif
 1016 }
 1017 
 1018 BIO *sslGetNextBIO(BIO *b) {
 1019 #if OPENSSL_VERSION_NUMBER <= 0x10100000L
 1020   return b->next_bio;
 1021 #else
 1022   return BIO_next(b);
 1023 #endif
 1024 }
 1025 
 1026 void sslFreeHndl(SSL **sslHndl) {
 1027 #if defined(HAVE_OPENSSL)
 1028   if (*sslHndl) {
 1029     // OpenSSL does not always correctly perform reference counting for stacked
 1030     // BIOs. This is particularly a problem if an SSL connection has two
 1031     // different BIOs for the read and the write end, with one being a stacked
 1032     // derivative of the other. Unfortunately, this is exactly the scenario
 1033     // that we set up with call to "BIO_push(readBIO, writeBIO)" in function
 1034     // "sslPromoteToSSL()".
 1035     // As a work-around, we un-stack the BIOs prior to freeing the SSL
 1036     // connection.
 1037     debug("[ssl] Freeing SSL handle.");
 1038     ERR_clear_error();
 1039     BIO *writeBIO, *readBIO;
 1040     check(writeBIO    = SSL_get_wbio(*sslHndl));
 1041     check(readBIO     = SSL_get_rbio(*sslHndl));
 1042     if (writeBIO != readBIO) {
 1043       if (sslGetNextBIO(readBIO) == writeBIO) {
 1044         // OK, that's exactly the bug we are looking for. We know that
 1045         // writeBIO needs to be removed from readBIO chain.
 1046         debug("[ssl] Removing stacked write BIO!");
 1047         check(BIO_pop(readBIO) == writeBIO);
 1048         check(!sslGetNextBIO(readBIO));
 1049       } else if (sslGetNextBIO(readBIO) == sslGetNextBIO(writeBIO)) {
 1050         // Things get even more confused, if the SSL handshake is aborted
 1051         // prematurely.
 1052         // OpenSSL appears to internally stack a BIO onto the read end that
 1053         // does not get removed afterwards. We end up with the original
 1054         // socket BIO having two different BIOs prepended to it (one for
 1055         // reading and one for writing). In this case, not only is the
 1056         // reference count wrong, but the chain of next_bio/prev_bio pairs
 1057         // is corrupted, too.
 1058         warn("[ssl] Removing stacked socket BIO!");
 1059         BIO *sockBIO;
 1060         check(sockBIO = BIO_pop(readBIO));
 1061         check(sockBIO == BIO_pop(writeBIO));
 1062         check(!sslGetNextBIO(readBIO));
 1063         check(!sslGetNextBIO(writeBIO));
 1064         check(!sslGetNextBIO(sockBIO));
 1065         BIO_free_all(sockBIO);
 1066       } else {
 1067         // We do not know, how to fix this situation. Something must have
 1068         // changed in the OpenSSL internals. Either, this is a new bug, or
 1069         // somebody fixed the code in a way that we did not anticipate.
 1070         fatal("[ssl] Unexpected corruption of OpenSSL data structures");
 1071       }
 1072     }
 1073     SSL_free(*sslHndl);
 1074     dcheck(!ERR_peek_error());
 1075   }
 1076 #endif
 1077   *sslHndl            = NULL;
 1078 }