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