]> andersk Git - test.git/blame - libhttp/ssl.c
sslSNICallback: Properly disallow invalid characters
[test.git] / libhttp / ssl.c
CommitLineData
7460295f 1// ssl.c -- Support functions that find and load SSL support, if available
bc83b450 2// Copyright (C) 2008-2010 Markus Gutschke <markus@shellinabox.com>
7460295f
MG
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
bdd01e84 47#include "config.h"
7460295f 48
c593cf68
MG
49#define pthread_once x_pthread_once
50#define pthread_sigmask x_pthread_sigmask
51
7460295f
MG
52#include <dlfcn.h>
53#include <errno.h>
ad24d9a9 54#include <fcntl.h>
7460295f
MG
55#include <netdb.h>
56#include <signal.h>
57#include <stdlib.h>
58#include <string.h>
ad24d9a9
MG
59#include <sys/types.h>
60#include <sys/stat.h>
7460295f
MG
61#include <unistd.h>
62
63#include "libhttp/ssl.h"
64#include "libhttp/httpconnection.h"
65#include "logging/logging.h"
66
242e6c5b
MG
67#ifdef HAVE_UNUSED
68#defined ATTR_UNUSED __attribute__((unused))
69#defined UNUSED(x) do { } while (0)
70#else
71#define ATTR_UNUSED
72#define UNUSED(x) do { (void)(x); } while (0)
73#endif
74
c593cf68
MG
75#undef pthread_once
76#undef pthread_sigmask
77
bdd01e84
MG
78#if defined(HAVE_OPENSSL) && !defined(OPENSSL_NO_TLSEXT) && \
79 defined(TLSEXT_NAMETYPE_host_name) && defined(SSL_TLSEXT_ERR_OK)
d04f7ca7
MG
80#define HAVE_TLSEXT
81#endif
82
7460295f
MG
83#if defined(HAVE_PTHREAD_H)
84// Pthread support is optional. Only enable it, if the library has been
85// linked into the program
86#include <pthread.h>
bf1ec4d2 87#if defined(__linux__)
7460295f 88extern int pthread_once(pthread_once_t *, void (*)(void))__attribute__((weak));
bf1ec4d2 89#endif
7460295f
MG
90extern int pthread_sigmask(int, const sigset_t *, sigset_t *)
91 __attribute__((weak));
92
93#endif
94
bf1ec4d2 95#if defined(HAVE_DLOPEN)
7460295f 96// SSL support is optional. Only enable it, if the library can be loaded.
03cd76e1
MG
97long (*BIO_ctrl)(BIO *, int, long, void *);
98BIO_METHOD * (*BIO_f_buffer)(void);
99void (*BIO_free_all)(BIO *);
100BIO * (*BIO_new)(BIO_METHOD *);
101BIO * (*BIO_new_socket)(int, int);
102BIO * (*BIO_pop)(BIO *);
103BIO * (*BIO_push)(BIO *, BIO *);
104void (*ERR_clear_error)(void);
105void (*ERR_clear_error)(void);
106unsigned long (*ERR_peek_error)(void);
107unsigned long (*ERR_peek_error)(void);
108long (*SSL_CTX_callback_ctrl)(SSL_CTX *, int, void (*)(void));
109int (*SSL_CTX_check_private_key)(const SSL_CTX *);
110long (*SSL_CTX_ctrl)(SSL_CTX *, int, long, void *);
111void (*SSL_CTX_free)(SSL_CTX *);
112SSL_CTX * (*SSL_CTX_new)(SSL_METHOD *);
113int (*SSL_CTX_use_PrivateKey_file)(SSL_CTX *, const char *, int);
dc6575f2
MG
114int (*SSL_CTX_use_PrivateKey_ASN1)(int, SSL_CTX *,
115 const unsigned char *, long);
03cd76e1 116int (*SSL_CTX_use_certificate_file)(SSL_CTX *, const char *, int);
dc6575f2
MG
117int (*SSL_CTX_use_certificate_ASN1)(SSL_CTX *, long,
118 const unsigned char *);
03cd76e1
MG
119long (*SSL_ctrl)(SSL *, int, long, void *);
120void (*SSL_free)(SSL *);
121int (*SSL_get_error)(const SSL *, int);
122void * (*SSL_get_ex_data)(const SSL *, int);
123BIO * (*SSL_get_rbio)(const SSL *);
124const char * (*SSL_get_servername)(const SSL *, int);
125BIO * (*SSL_get_wbio)(const SSL *);
126int (*SSL_library_init)(void);
127SSL * (*SSL_new)(SSL_CTX *);
128int (*SSL_read)(SSL *, void *, int);
129SSL_CTX * (*SSL_set_SSL_CTX)(SSL *, SSL_CTX *);
130void (*SSL_set_accept_state)(SSL *);
131void (*SSL_set_bio)(SSL *, BIO *, BIO *);
132int (*SSL_set_ex_data)(SSL *, int, void *);
133int (*SSL_shutdown)(SSL *);
134int (*SSL_write)(SSL *, const void *, int);
135SSL_METHOD * (*SSLv23_server_method)(void);
ad24d9a9
MG
136X509 * (*d2i_X509)(X509 **px, const unsigned char **in, int len);
137void (*X509_free)(X509 *a);
bf1ec4d2 138#endif
7460295f
MG
139
140static void sslDestroyCachedContext(void *ssl_, char *context_) {
141 struct SSLSupport *ssl = (struct SSLSupport *)ssl_;
142 SSL_CTX *context = (SSL_CTX *)context_;
03cd76e1 143#if defined(HAVE_OPENSSL)
7460295f
MG
144 if (context != ssl->sslContext) {
145 SSL_CTX_free(context);
146 }
03cd76e1
MG
147#else
148 check(!context);
149 check(!ssl->sslContext);
150#endif
7460295f
MG
151}
152
153struct SSLSupport *newSSL(void) {
154 struct SSLSupport *ssl;
155 check(ssl = malloc(sizeof(struct SSLSupport)));
156 initSSL(ssl);
157 return ssl;
158}
159
160void initSSL(struct SSLSupport *ssl) {
161 ssl->enabled = serverSupportsSSL();
162 ssl->sslContext = NULL;
163 ssl->sniCertificatePattern = NULL;
164 ssl->generateMissing = 0;
165 initTrie(&ssl->sniContexts, sslDestroyCachedContext, ssl);
166}
167
168void destroySSL(struct SSLSupport *ssl) {
169 if (ssl) {
170 free(ssl->sniCertificatePattern);
171 destroyTrie(&ssl->sniContexts);
03cd76e1 172#if defined(HAVE_OPENSSL)
7460295f
MG
173 if (ssl->sslContext) {
174 dcheck(!ERR_peek_error());
175 SSL_CTX_free(ssl->sslContext);
176 }
03cd76e1
MG
177#else
178 check(!ssl->sslContext);
179#endif
7460295f
MG
180 }
181}
182
183void deleteSSL(struct SSLSupport *ssl) {
184 destroySSL(ssl);
185 free(ssl);
186}
187
bf1ec4d2 188#if defined(HAVE_OPENSSL) && defined(HAVE_DLOPEN)
10d0a6b0
MG
189static int maybeLoadCrypto(void) {
190 // Some operating systems cannot automatically load dependent dynamic
191 // libraries. As libssl.so can depend on libcrypto.so, we try to load
192 // it, iff we haven't tried loading it before and iff libssl.so does not
193 // work by itself.
194 static int crypto;
195 if (!crypto++) {
196#ifdef RTLD_NOLOAD
197 if (dlopen("libcrypto.so", RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD))
198 return 1;
199 else
200#endif
201 if (dlopen("libcrypto.so", RTLD_LAZY|RTLD_GLOBAL))
202 return 1;
203 }
204 return 0;
205}
206
7460295f 207static void *loadSymbol(const char *lib, const char *fn) {
10d0a6b0
MG
208 int err = NOINTR(dup(2));
209 if (err > 2) {
210 int null = NOINTR(open("/dev/null", O_WRONLY));
211 if (null >= 0) {
212 NOINTR(dup2(null, 2));
213 NOINTR(close(null));
214 }
215 }
7460295f
MG
216 void *dl = RTLD_DEFAULT;
217 void *rc = dlsym(dl, fn);
218 if (!rc) {
10d0a6b0 219 for (int i = 0; i < 2; i++) {
47e62a9c 220#ifdef RTLD_NOLOAD
10d0a6b0 221 dl = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD);
47e62a9c 222#else
10d0a6b0 223 dl = NULL;
47e62a9c 224#endif
10d0a6b0
MG
225 if (dl == NULL) {
226 dl = dlopen(lib, RTLD_LAZY|RTLD_GLOBAL);
227 }
228 if (dl != NULL || !maybeLoadCrypto()) {
229 break;
230 }
7460295f
MG
231 }
232 if (dl != NULL) {
10d0a6b0
MG
233 rc = dlsym(RTLD_DEFAULT, fn);
234 if (rc == NULL && maybeLoadCrypto()) {
235 rc = dlsym(RTLD_DEFAULT, fn);
236 }
7460295f
MG
237 }
238 }
10d0a6b0
MG
239 if (err > 2) {
240 NOINTR(dup2(err, 2));
241 }
242 NOINTR(close(err));
7460295f
MG
243 return rc;
244}
245
246static void loadSSL(void) {
247 check(!SSL_library_init);
248 struct {
88b579e2
MG
249 union {
250 void *avoid_gcc_warning_about_type_punning;
251 void **var;
252 };
7460295f
MG
253 const char *fn;
254 } symbols[] = {
03cd76e1
MG
255 { { &BIO_ctrl }, "BIO_ctrl" },
256 { { &BIO_f_buffer }, "BIO_f_buffer" },
257 { { &BIO_free_all }, "BIO_free_all" },
258 { { &BIO_new }, "BIO_new" },
259 { { &BIO_new_socket }, "BIO_new_socket" },
260 { { &BIO_pop }, "BIO_pop" },
261 { { &BIO_push }, "BIO_push" },
262 { { &ERR_clear_error }, "ERR_clear_error" },
263 { { &ERR_clear_error }, "ERR_clear_error" },
264 { { &ERR_peek_error }, "ERR_peek_error" },
265 { { &ERR_peek_error }, "ERR_peek_error" },
266 { { &SSL_CTX_callback_ctrl }, "SSL_CTX_callback_ctrl" },
267 { { &SSL_CTX_check_private_key }, "SSL_CTX_check_private_key" },
268 { { &SSL_CTX_ctrl }, "SSL_CTX_ctrl" },
269 { { &SSL_CTX_free }, "SSL_CTX_free" },
270 { { &SSL_CTX_new }, "SSL_CTX_new" },
271 { { &SSL_CTX_use_PrivateKey_file }, "SSL_CTX_use_PrivateKey_file" },
dc6575f2 272 { { &SSL_CTX_use_PrivateKey_ASN1 }, "SSL_CTX_use_PrivateKey_ASN1" },
03cd76e1 273 { { &SSL_CTX_use_certificate_file },"SSL_CTX_use_certificate_file"},
dc6575f2 274 { { &SSL_CTX_use_certificate_ASN1 },"SSL_CTX_use_certificate_ASN1"},
03cd76e1
MG
275 { { &SSL_ctrl }, "SSL_ctrl" },
276 { { &SSL_free }, "SSL_free" },
277 { { &SSL_get_error }, "SSL_get_error" },
278 { { &SSL_get_ex_data }, "SSL_get_ex_data" },
279 { { &SSL_get_rbio }, "SSL_get_rbio" },
d04f7ca7 280#ifdef HAVE_TLSEXT
03cd76e1 281 { { &SSL_get_servername }, "SSL_get_servername" },
a42d111c 282#endif
03cd76e1
MG
283 { { &SSL_get_wbio }, "SSL_get_wbio" },
284 { { &SSL_library_init }, "SSL_library_init" },
285 { { &SSL_new }, "SSL_new" },
286 { { &SSL_read }, "SSL_read" },
d04f7ca7 287#ifdef HAVE_TLSEXT
03cd76e1 288 { { &SSL_set_SSL_CTX }, "SSL_set_SSL_CTX" },
a42d111c 289#endif
03cd76e1
MG
290 { { &SSL_set_accept_state }, "SSL_set_accept_state" },
291 { { &SSL_set_bio }, "SSL_set_bio" },
292 { { &SSL_set_ex_data }, "SSL_set_ex_data" },
293 { { &SSL_shutdown }, "SSL_shutdown" },
294 { { &SSL_write }, "SSL_write" },
ad24d9a9
MG
295 { { &SSLv23_server_method }, "SSLv23_server_method" },
296 { { &d2i_X509 }, "d2i_X509" },
297 { { &X509_free }, "X509_free" }
7460295f 298 };
bc83b450 299 for (unsigned i = 0; i < sizeof(symbols)/sizeof(symbols[0]); i++) {
7460295f
MG
300 if (!(*symbols[i].var = loadSymbol("libssl.so", symbols[i].fn))) {
301 debug("Failed to load SSL support. Could not find \"%s\"",
302 symbols[i].fn);
bc83b450 303 for (unsigned j = 0; j < sizeof(symbols)/sizeof(symbols[0]); j++) {
7460295f
MG
304 *symbols[j].var = NULL;
305 }
306 return;
307 }
308 }
309 SSL_library_init();
310 dcheck(!ERR_peek_error());
311 debug("Loaded SSL suppport");
312}
313#endif
314
315int serverSupportsSSL(void) {
bf1ec4d2
MG
316#if defined(HAVE_OPENSSL) && !defined(HAVE_DLOPEN)
317 return SSL_library_init();
318#else
7460295f
MG
319#if defined(HAVE_OPENSSL)
320 // We want to call loadSSL() exactly once. For single-threaded applications,
321 // this is straight-forward. For threaded applications, we need to call
322 // pthread_once(), instead. We perform run-time checks for whether we are
323 // single- or multi-threaded, so that the same code can be used.
a3876a41 324 // This currently only works on Linux.
9d758d39 325#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
7460295f
MG
326 if (!!&pthread_once) {
327 static pthread_once_t once = PTHREAD_ONCE_INIT;
328 pthread_once(&once, loadSSL);
329 } else
330#endif
331 {
332 static int initialized;
333 if (!initialized) {
334 initialized = 1;
335 loadSSL();
336 }
337 }
338 return !!SSL_library_init;
339#else
340 return 0;
341#endif
bf1ec4d2 342#endif
7460295f
MG
343}
344
bdd01e84 345#if defined(HAVE_OPENSSL)
39e8401e
MG
346static void sslGenerateCertificate(const char *certificate,
347 const char *serverName) {
7460295f
MG
348 debug("Auto-generating missing certificate \"%s\" for \"%s\"",
349 certificate, serverName);
350 char *cmd = stringPrintf(NULL,
351 "set -e; "
352 "exec 2>/dev/null </dev/null; "
353 "umask 0377; "
10d0a6b0 354 "PATH=/usr/bin:/usr/sbin "
7460295f
MG
355 "openssl req -x509 -nodes -days 7300 -newkey rsa:1024 -keyout /dev/stdout "
356 "-out /dev/stdout -subj '/CN=%s/' | cat>'%s'",
357 serverName, certificate);
358 if (system(cmd)) {
359 warn("Failed to generate self-signed certificate \"%s\"", certificate);
360 }
361 free(cmd);
362}
ad24d9a9
MG
363
364static const unsigned char *sslSecureReadASCIIFileToMem(int fd) {
365 size_t inc = 16384;
366 size_t bufSize = inc;
367 size_t len = 0;
368 unsigned char *buf;
369 check((buf = malloc(bufSize)) != NULL);
370 for (;;) {
371 check(len < bufSize - 1);
bc83b450 372 ssize_t readLen = bufSize - len - 1;
ad24d9a9
MG
373 ssize_t bytesRead = NOINTR(read(fd, buf + len, readLen));
374 if (bytesRead > 0) {
375 len += bytesRead;
376 }
377 if (bytesRead != readLen) {
378 break;
379 }
380
381 // Instead of calling realloc(), allocate a new buffer, copy the data,
382 // and then clear the old buffer. This way, we are not accidentally
383 // leaving key material in memory.
384 unsigned char *newBuf;
385 check((newBuf = malloc(bufSize + inc)) != NULL);
386 memcpy(newBuf, buf, len);
387 memset(buf, 0, bufSize);
388 free(buf);
389 buf = newBuf;
390 bufSize += inc;
391 }
392 check(len < bufSize);
393 buf[len] = '\000';
394 return buf;
395}
396
397static const unsigned char *sslPEMtoASN1(const unsigned char *pem,
398 const char *record,
399 long *size,
400 const unsigned char **eor) {
401 if (eor) {
402 *eor = NULL;
403 }
404 *size = 0;
405 char *marker;
406 check((marker = stringPrintf(NULL, "-----BEGIN %s-----",record))!=NULL);
407 unsigned char *ptr = (unsigned char *)strstr((char *)pem, marker);
408 if (!ptr) {
409 free(marker);
410 return NULL;
411 } else {
412 ptr += strlen(marker);
413 }
414 *marker = '\000';
415 check((marker = stringPrintf(marker, "-----END %s-----",record))!=NULL);
416 unsigned char *end = (unsigned char *)strstr((char *)ptr, marker);
417 if (eor) {
418 *eor = end + strlen(marker);
419 }
420 free(marker);
421 if (!end) {
422 return NULL;
423 }
424 unsigned char *ret;
bc83b450 425 ssize_t maxSize = (((end - ptr)*6)+7)/8;
ad24d9a9
MG
426 check((ret = malloc(maxSize)) != NULL);
427 unsigned char *out = ret;
428 unsigned bits = 0;
429 int count = 0;
430 while (ptr < end) {
431 unsigned char ch = *ptr++;
432 if (ch >= 'A' && ch <= 'Z') {
433 ch -= 'A';
434 } else if (ch >= 'a' && ch <= 'z') {
435 ch -= 'a' - 26;
436 } else if (ch >= '0' && ch <= '9') {
437 ch += 52 - '0';
438 } else if (ch == '+') {
439 ch += 62 - '+';
440 } else if (ch == '/') {
441 ch += 63 - '/';
442 } else if (ch == '=') {
443 while (ptr < end) {
444 if ((ch = *ptr++) != '=' && ch > ' ') {
445 goto err;
446 }
447 }
448 break;
449 } else if (ch <= ' ') {
450 continue;
451 } else {
452 err:
453 free(ret);
454 return NULL;
455 }
456 check(ch <= 63);
457 check(count >= 0);
458 check(count <= 6);
459 bits = (bits << 6) | ch;
460 count += 6;
461 if (count >= 8) {
462 *out++ = (bits >> (count -= 8)) & 0xFF;
463 }
464 }
465 check(out - ret <= maxSize);
466 *size = out - ret;
467 return ret;
468}
469
470static int sslSetCertificateFromFd(SSL_CTX *context, int fd) {
471 int rc = 0;
472 check(serverSupportsSSL());
473 check(fd >= 0);
474 const unsigned char *data = sslSecureReadASCIIFileToMem(fd);
475 check(!NOINTR(close(fd)));
476 long dataSize = (long)strlen((const char *)data);
477 long certSize, rsaSize, dsaSize, ecSize;
478 const unsigned char *record;
479 const unsigned char *cert = sslPEMtoASN1(data, "CERTIFICATE", &certSize,
480 &record);
481 const unsigned char *rsa = sslPEMtoASN1(data, "RSA PRIVATE KEY",&rsaSize,
482 NULL);
483 const unsigned char *dsa = sslPEMtoASN1(data, "DSA PRIVATE KEY",&dsaSize,
484 NULL);
485 const unsigned char *ec = sslPEMtoASN1(data, "EC PRIVATE KEY", &ecSize,
486 NULL);
487 if (certSize && (rsaSize || dsaSize
488#ifdef EVP_PKEY_EC
489 || ecSize
490#endif
491 ) &&
492 SSL_CTX_use_certificate_ASN1(context, certSize, cert) &&
493 (!rsaSize ||
494 SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, context, rsa, rsaSize)) &&
495 (!dsaSize ||
496 SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_DSA, context, dsa, dsaSize))
497#ifdef EVP_PKEY_EC
498 &&
499 (!ecSize ||
500 SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_EC, context, ec, ecSize))
501#endif
502 ) {
503 memset((char *)cert, 0, certSize);
504 free((char *)cert);
505 while (record) {
506 cert = sslPEMtoASN1(record, "CERTIFICATE", &certSize,
507 &record);
508 if (cert) {
509 X509 *x509;
510 const unsigned char *c = cert;
511 check(x509 = d2i_X509(NULL, &c, certSize));
512 memset((char *)cert, 0, certSize);
513 free((char *)cert);
514 if (!SSL_CTX_add_extra_chain_cert(context, x509)) {
515 X509_free(x509);
516 break;
517 }
518 }
519 }
520 if (!record && SSL_CTX_check_private_key(context)) {
521 rc = 1;
522 }
523 dcheck(!ERR_peek_error());
524 ERR_clear_error();
525 } else {
526 memset((char *)cert, 0, certSize);
527 free((char *)cert);
528 }
529 memset((char *)data, 0, dataSize);
530 free((char *)data);
531 memset((char *)rsa, 0, rsaSize);
532 free((char *)rsa);
533 memset((char *)dsa, 0, dsaSize);
534 free((char *)dsa);
535 memset((char *)ec, 0, ecSize);
536 free((char *)ec);
537 return rc;
538}
539
540static int sslSetCertificateFromFile(SSL_CTX *context,
541 const char *filename) {
542 int fd = open(filename, O_RDONLY);
543 if (fd < 0) {
544 return -1;
545 }
546 int rc = sslSetCertificateFromFd(context, fd);
ad24d9a9
MG
547 return rc;
548}
bdd01e84 549#endif
7460295f 550
d04f7ca7 551#ifdef HAVE_TLSEXT
242e6c5b
MG
552static int sslSNICallback(SSL *sslHndl, int *al ATTR_UNUSED,
553 struct SSLSupport *ssl) {
554 UNUSED(al);
7460295f
MG
555 check(!ERR_peek_error());
556 const char *name = SSL_get_servername(sslHndl,
557 TLSEXT_NAMETYPE_host_name);
558 if (name == NULL || !*name) {
559 return SSL_TLSEXT_ERR_OK;
560 }
561 struct HttpConnection *http =
562 (struct HttpConnection *)SSL_get_app_data(sslHndl);
563 debug("Received SNI callback for virtual host \"%s\" from \"%s:%d\"",
564 name, httpGetPeerName(http), httpGetPort(http));
565 char *serverName;
566 check(serverName = malloc(strlen(name)+2));
567 serverName[0] = '-';
568 for (int i = 0;;) {
569 char ch = name[i];
570 if (ch >= 'A' && ch <= 'Z') {
571 ch |= 0x20;
572 } else if (ch != '\000' && ch != '.' && ch != '-' &&
573 (ch < '0' ||(ch > '9' && ch < 'A') || (ch > 'Z' &&
574 ch < 'a')|| ch > 'z')) {
8059075f
AK
575 free(serverName);
576 return SSL_TLSEXT_ERR_OK;
7460295f
MG
577 }
578 serverName[++i] = ch;
579 if (!ch) {
580 break;
581 }
582 }
7460295f
MG
583 SSL_CTX *context = (SSL_CTX *)getFromTrie(&ssl->sniContexts,
584 serverName+1,
585 NULL);
586 if (context == NULL) {
587 check(context = SSL_CTX_new(SSLv23_server_method()));
588 check(ssl->sniCertificatePattern);
9b850878
MG
589 char *certificate = stringPrintfUnchecked(NULL,
590 ssl->sniCertificatePattern,
591 serverName);
ad24d9a9 592 if (sslSetCertificateFromFile(context, certificate) < 0) {
7460295f
MG
593 if (ssl->generateMissing) {
594 sslGenerateCertificate(certificate, serverName + 1);
ad24d9a9
MG
595
596 // No need to check the certificate. If we fail to set it, we will use
597 // the default certificate, instead.
598 sslSetCertificateFromFile(context, certificate);
7460295f 599 } else {
7460295f
MG
600 warn("Could not find matching certificate \"%s\" for \"%s\"",
601 certificate, serverName + 1);
602 SSL_CTX_free(context);
603 context = ssl->sslContext;
604 }
605 }
606 ERR_clear_error();
607 free(certificate);
608 addToTrie(&ssl->sniContexts, serverName+1, (char *)context);
609 }
610 free(serverName);
611 if (context != ssl->sslContext) {
bc83b450 612 check(SSL_set_SSL_CTX(sslHndl, context));
7460295f
MG
613 }
614 check(!ERR_peek_error());
615 return SSL_TLSEXT_ERR_OK;
616}
617#endif
618
4101fea2 619#if defined(HAVE_OPENSSL) && !defined(HAVE_GETHOSTBYNAME_R)
572ac014
MG
620// This is a not-thread-safe replacement for gethostbyname_r()
621#define gethostbyname_r x_gethostbyname_r
622static int gethostbyname_r(const char *name, struct hostent *ret,
242e6c5b 623 char *buf ATTR_UNUSED, size_t buflen ATTR_UNUSED,
572ac014 624 struct hostent **result, int *h_errnop) {
242e6c5b
MG
625 UNUSED(buf);
626 UNUSED(buflen);
572ac014
MG
627 if (result) {
628 *result = NULL;
629 }
630 if (h_errnop) {
631 *h_errnop = ERANGE;
632 }
633 if (!ret) {
634 return -1;
635 }
636 struct hostent *he = gethostbyname(name);
4101fea2
MG
637 if (he) {
638 *ret = *he;
639 if (result) {
640 *result = ret;
641 }
572ac014
MG
642 }
643 if (h_errnop) {
644 *h_errnop = h_errno;
645 }
4101fea2 646 return he ? 0 : -1;
572ac014
MG
647}
648#endif
649
7460295f
MG
650void sslSetCertificate(struct SSLSupport *ssl, const char *filename,
651 int autoGenerateMissing) {
652#if defined(HAVE_OPENSSL)
653 check(serverSupportsSSL());
654
655 char *defaultCertificate;
656 check(defaultCertificate = strdup(filename));
657 char *ptr = strchr(defaultCertificate, '%');
658 if (ptr != NULL) {
659 check(!strchr(ptr+1, '%'));
660 check(ptr[1] == 's');
661 memmove(ptr, ptr + 2, strlen(ptr)-1);
662 }
663
ad24d9a9 664 // Try to set the default certificate. If necessary, (re-)generate it.
7460295f
MG
665 check(ssl->sslContext = SSL_CTX_new(SSLv23_server_method()));
666 if (autoGenerateMissing) {
ad24d9a9 667 if (sslSetCertificateFromFile(ssl->sslContext, defaultCertificate) < 0) {
7460295f
MG
668 char hostname[256], buf[4096];
669 check(!gethostname(hostname, sizeof(hostname)));
670 struct hostent he_buf, *he;
06513c67
JW
671 int h_err = 0;
672 int ret = gethostbyname_r(hostname, &he_buf, buf, sizeof(buf), &he, &h_err);
673 if (!ret && he && he->h_name) {
7460295f 674 sslGenerateCertificate(defaultCertificate, he->h_name);
06513c67
JW
675 } else {
676 if (h_err) {
677 warn("Error getting host information: \"%s\".", hstrerror(h_err));
678 }
679 sslGenerateCertificate(defaultCertificate, hostname);
7460295f
MG
680 }
681 } else {
682 goto valid_certificate;
683 }
684 }
ad24d9a9 685 if (sslSetCertificateFromFile(ssl->sslContext, defaultCertificate) < 0) {
7460295f
MG
686 fatal("Cannot read valid certificate from \"%s\". "
687 "Check file permissions and file format.", defaultCertificate);
688 }
689 valid_certificate:
690 free(defaultCertificate);
691
ad24d9a9
MG
692 // Enable SNI support so that we can set a different certificate, if the
693 // client asked for it.
d04f7ca7 694#ifdef HAVE_TLSEXT
7460295f
MG
695 if (ptr != NULL) {
696 check(ssl->sniCertificatePattern = strdup(filename));
697 check(SSL_CTX_set_tlsext_servername_callback(ssl->sslContext,
698 sslSNICallback));
699 check(SSL_CTX_set_tlsext_servername_arg(ssl->sslContext, ssl));
700 }
701#endif
702 dcheck(!ERR_peek_error());
703 ERR_clear_error();
704
705 ssl->generateMissing = autoGenerateMissing;
706#endif
707}
708
ad24d9a9
MG
709// Convert the file descriptor to a human-readable format. Attempts to
710// retrieve the original file name where possible.
dc6575f2 711#ifdef HAVE_OPENSSL
ad24d9a9
MG
712static char *sslFdToFilename(int fd) {
713 char *proc, *buf;
714 int len = 128;
715 check(proc = stringPrintf(NULL, "/proc/self/fd/%d", fd));
716 check(buf = malloc(len));
dc6575f2 717 for (;;) {
ad24d9a9
MG
718 ssize_t i;
719 if ((i = readlink(proc, buf + 1, len-3)) < 0) {
720 free(proc);
721 free(buf);
722 check(buf = stringPrintf(NULL, "fd %d", fd));
723 return buf;
724 } else if (i >= len-3) {
725 len += 512;
726 check(buf = realloc(buf, len));
dc6575f2 727 } else {
ad24d9a9
MG
728 free(proc);
729 check(i >= 0 && i < len);
730 buf[i+1] = '\000';
731 struct stat sb;
732 if (!stat(buf + 1, &sb) && S_ISREG(sb.st_mode)) {
733 *buf = '"';
734 buf[i + 1] = '"';
735 buf[i + 2] = '\000';
736 return buf;
737 } else {
738 free(buf);
739 check(buf = stringPrintf(NULL, "fd %d", fd));
740 return buf;
741 }
dc6575f2
MG
742 }
743 }
dc6575f2
MG
744}
745#endif
746
747void sslSetCertificateFd(struct SSLSupport *ssl, int fd) {
748#ifdef HAVE_OPENSSL
ad24d9a9 749 check(ssl->sslContext = SSL_CTX_new(SSLv23_server_method()));
48f25965 750 char *filename = sslFdToFilename(fd);
ad24d9a9
MG
751 if (!sslSetCertificateFromFd(ssl->sslContext, fd)) {
752 fatal("Cannot read valid certificate from %s. Check file format.",
48f25965 753 filename);
dc6575f2 754 }
48f25965 755 free(filename);
ad24d9a9 756 ssl->generateMissing = 0;
dc6575f2
MG
757#endif
758}
759
7460295f
MG
760int sslEnable(struct SSLSupport *ssl, int enabled) {
761 int old = ssl->enabled;
762 ssl->enabled = enabled;
763 return old;
764}
765
766void sslBlockSigPipe(void) {
767 sigset_t set;
768 sigemptyset(&set);
769 sigaddset(&set, SIGPIPE);
9d758d39 770#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
c593cf68
MG
771 if (&pthread_sigmask) {
772 dcheck(!pthread_sigmask(SIG_BLOCK, &set, NULL));
9d758d39
MG
773 } else
774#endif
775 {
c593cf68
MG
776 dcheck(!sigprocmask(SIG_BLOCK, &set, NULL));
777 }
7460295f
MG
778}
779
572ac014
MG
780#ifndef HAVE_SIGWAIT
781// This is a non-thread-safe replacement for sigwait()
782static int dummysignalno;
783static void dummysignal(int signo) {
784 dummysignalno = signo;
785}
786
787#define sigwait x_sigwait
788static int sigwait(const sigset_t *set, int *sig) {
789 sigset_t mask, old_mask;
790 sigfillset(&mask);
9d758d39 791#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
572ac014
MG
792 if (&pthread_sigmask) {
793 dcheck(!pthread_sigmask(SIG_BLOCK, &mask, &old_mask));
9d758d39
MG
794 } else
795#endif
796 {
572ac014
MG
797 dcheck(!sigprocmask(SIG_BLOCK, &mask, &old_mask));
798 }
799 #ifndef NSIG
800 #define NSIG 32
801 #endif
802 struct sigaction sa[NSIG];
803 memset(sa, 0, sizeof(sa));
804 sa->sa_handler = dummysignal;
805 for (int i = 1; i <= NSIG; i++) {
806 if (sigismember(set, i)) {
807 sigdelset(&mask, i);
808 sigaction(i, sa, sa + i);
809 }
810 }
811 dummysignalno = -1;
812 sigsuspend(&mask);
9d758d39 813#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
572ac014
MG
814 if (&pthread_sigmask) {
815 dcheck(!pthread_sigmask(SIG_SETMASK, &old_mask, NULL));
9d758d39
MG
816 } else
817#endif
818 {
572ac014
MG
819 dcheck(!sigprocmask(SIG_BLOCK, &old_mask, NULL));
820 }
821 return dummysignalno;
822}
823#endif
824
7460295f
MG
825int sslUnblockSigPipe(void) {
826 int signum = 0;
827 sigset_t set;
828 check(!sigpending(&set));
829 if (sigismember(&set, SIGPIPE)) {
830 sigwait(&set, &signum);
831 }
832 sigemptyset(&set);
833 sigaddset(&set, SIGPIPE);
9d758d39 834#if defined(HAVE_PTHREAD_H) && defined(__linux__) && defined(__i386__)
c593cf68
MG
835 if (&pthread_sigmask) {
836 dcheck(!pthread_sigmask(SIG_UNBLOCK, &set, NULL));
9d758d39
MG
837 } else
838#endif
839 {
c593cf68
MG
840 dcheck(!sigprocmask(SIG_UNBLOCK, &set, NULL));
841 }
7460295f
MG
842 return signum;
843}
844
845int sslPromoteToSSL(struct SSLSupport *ssl, SSL **sslHndl, int fd,
846 const char *buf, int len) {
847#if defined(HAVE_OPENSSL)
848 sslBlockSigPipe();
849 int rc = 0;
850 check(!*sslHndl);
851 dcheck(!ERR_peek_error());
852 dcheck(*sslHndl = SSL_new(ssl->sslContext));
853 if (*sslHndl == NULL) {
854 ERR_clear_error();
855 errno = EINVAL;
856 rc = -1;
857 } else {
858 SSL_set_mode(*sslHndl, SSL_MODE_ENABLE_PARTIAL_WRITE);
859 BIO *writeBIO = BIO_new_socket(fd, 0);
860 BIO *readBIO = writeBIO;
861 if (len > 0) {
862 readBIO = BIO_new(BIO_f_buffer());
863 BIO_push(readBIO, writeBIO);
864 check(BIO_set_buffer_read_data(readBIO, (char *)buf, len));
865 }
866 SSL_set_bio(*sslHndl, readBIO, writeBIO);
867 SSL_set_accept_state(*sslHndl);
868 dcheck(!ERR_peek_error());
869 }
870 sslUnblockSigPipe();
871 return rc;
872#else
873 errno = EINVAL;
874 return -1;
875#endif
876}
877
878void sslFreeHndl(SSL **sslHndl) {
879#if defined(HAVE_OPENSSL)
880 if (*sslHndl) {
881 // OpenSSL does not always correctly perform reference counting for stacked
882 // BIOs. This is particularly a problem if an SSL connection has two
883 // different BIOs for the read and the write end, with one being a stacked
884 // derivative of the other. Unfortunately, this is exactly the scenario
885 // that we set up.
886 // As a work-around, we un-stack the BIOs prior to freeing the SSL
887 // connection.
888 ERR_clear_error();
889 BIO *writeBIO, *readBIO;
890 check(writeBIO = SSL_get_wbio(*sslHndl));
891 check(readBIO = SSL_get_rbio(*sslHndl));
892 if (writeBIO != readBIO) {
893 if (readBIO->next_bio == writeBIO) {
894 // OK, that's exactly the bug we are looking for. We know how to
895 // fix it.
896 check(BIO_pop(readBIO) == writeBIO);
897 check(readBIO->references == 1);
898 check(writeBIO->references == 1);
899 check(!readBIO->next_bio);
900 check(!writeBIO->prev_bio);
901 } else if (readBIO->next_bio == writeBIO->next_bio &&
902 writeBIO->next_bio->prev_bio == writeBIO) {
903 // Things get even more confused, if the SSL handshake is aborted
904 // prematurely.
905 // OpenSSL appears to internally stack a BIO onto the read end that
906 // does not get removed afterwards. We end up with the original
907 // socket BIO having two different BIOs prepended to it (one for
908 // reading and one for writing). In this case, not only is the
909 // reference count wrong, but the chain of next_bio/prev_bio pairs
910 // is corrupted, too.
911 BIO *sockBIO;
912 check(sockBIO = BIO_pop(readBIO));
913 check(sockBIO == BIO_pop(writeBIO));
914 check(readBIO->references == 1);
915 check(writeBIO->references == 1);
916 check(sockBIO->references == 1);
917 check(!readBIO->next_bio);
918 check(!writeBIO->next_bio);
919 check(!sockBIO->prev_bio);
920 BIO_free_all(sockBIO);
921 } else {
922 // We do not know, how to fix this situation. Something must have
923 // changed in the OpenSSL internals. Either, this is a new bug, or
924 // somebody fixed the code in a way that we did not anticipate.
925 fatal("Unexpected corruption of OpenSSL data structures");
926 }
927 }
928 SSL_free(*sslHndl);
929 dcheck(!ERR_peek_error());
930 }
931#endif
932 *sslHndl = NULL;
933}
This page took 0.735861 seconds and 5 git commands to generate.