2 ashd - A Sane HTTP Daemon
3 Copyright (C) 2008 Fredrik Tolf <fredrik@dolda2000.com>
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
42 #include <gnutls/gnutls.h>
43 #include <gnutls/x509.h>
47 gnutls_certificate_credentials_t creds;
51 struct namedcreds **b;
58 gnutls_certificate_credentials_t creds;
59 gnutls_priority_t ciphers;
60 struct namedcreds **ncreds;
66 struct sockaddr_storage name;
67 gnutls_session_t sess;
72 struct savedsess *next, *prev;
73 gnutls_datum_t key, value;
76 static int numconn = 0, numsess = 0;
77 static struct btree *sessidx = NULL;
78 static struct savedsess *sesslistf = NULL, *sesslistl = NULL;
80 static int sesscmp(void *ap, void *bp)
82 struct savedsess *a = ap, *b = bp;
84 if(a->key.size != b->key.size)
85 return(a->key.size - b->key.size);
86 return(memcmp(a->key.data, b->key.data, a->key.size));
89 static gnutls_datum_t sessdbfetch(void *uudata, gnutls_datum_t key)
91 struct savedsess *sess, lkey;
94 memset(&ret, 0, sizeof(ret));
96 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
98 ret.data = memcpy(gnutls_malloc(ret.size = sess->value.size), sess->value.data, sess->value.size);
102 static void freesess(struct savedsess *sess)
104 bbtreedel(&sessidx, sess, sesscmp);
106 sess->next->prev = sess->prev;
108 sess->prev->next = sess->next;
109 if(sess == sesslistf)
110 sesslistf = sess->next;
111 if(sess == sesslistl)
112 sesslistl = sess->prev;
113 free(sess->key.data);
114 free(sess->value.data);
119 static int sessdbdel(void *uudata, gnutls_datum_t key)
121 struct savedsess *sess, lkey;
124 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
130 static void cleansess(void)
132 while(numsess > (max(numconn, 1) * 100))
136 static int sessdbstore(void *uudata, gnutls_datum_t key, gnutls_datum_t value)
139 struct savedsess *sess, lkey;
141 if((value.data == NULL) || (value.size == 0)) {
142 sessdbdel(NULL, key);
146 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL) {
148 sess->key.data = memcpy(smalloc(sess->key.size = key.size), key.data, key.size);
149 sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
150 bbtreeput(&sessidx, sess, sesscmp);
152 sess->next = sesslistf;
154 sesslistf->prev = sess;
156 if(sesslistl == NULL)
160 free(sess->value.data);
161 sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
162 if(sess != sesslistf) {
164 sess->next->prev = sess->prev;
166 sess->prev->next = sess->next;
167 if(sess == sesslistl)
168 sesslistl = sess->prev;
170 sess->next = sesslistf;
172 sesslistf->prev = sess;
183 static int tlsblock(int fd, gnutls_session_t sess, time_t to)
185 if(gnutls_record_get_direction(sess))
186 return(block(fd, EV_WRITE, to));
188 return(block(fd, EV_READ, to));
191 static ssize_t sslread(void *cookie, char *buf, size_t len)
193 struct sslconn *ssl = cookie;
197 while(ssl->in.d == 0) {
198 sizebuf(ssl->in, ssl->in.d + 1024);
199 ret = gnutls_record_recv(ssl->sess, ssl->in.b + ssl->in.d, ssl->in.s - ssl->in.d);
200 if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
201 if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
208 } else if(ret == 0) {
214 xf = min(ssl->in.d, len);
215 memcpy(buf, ssl->in.b, xf);
216 memmove(ssl->in.b, ssl->in.b + xf, ssl->in.d -= xf);
220 static ssize_t sslwrite(void *cookie, const char *buf, size_t len)
222 struct sslconn *ssl = cookie;
228 ret = gnutls_record_send(ssl->sess, buf + off, len - off);
229 if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
230 if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
250 static int sslclose(void *cookie)
252 struct sslconn *ssl = cookie;
258 static cookie_io_functions_t iofuns = {
264 static int initreq(struct conn *conn, struct hthead *req)
266 struct sslconn *ssl = conn->pdata;
267 struct sockaddr_storage sa;
271 headappheader(req, "X-Ash-Address", formathaddress((struct sockaddr *)&ssl->name, sizeof(sa)));
272 if(ssl->name.ss_family == AF_INET) {
273 headappheader(req, "X-Ash-Address", inet_ntop(AF_INET, &((struct sockaddr_in *)&ssl->name)->sin_addr, nmbuf, sizeof(nmbuf)));
274 headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in *)&ssl->name)->sin_port)));
275 } else if(ssl->name.ss_family == AF_INET6) {
276 headappheader(req, "X-Ash-Address", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&ssl->name)->sin6_addr, nmbuf, sizeof(nmbuf)));
277 headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in6 *)&ssl->name)->sin6_port)));
280 if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen))
281 headappheader(req, "X-Ash-Server-Address", formathaddress((struct sockaddr *)&sa, sizeof(sa)));
282 headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
283 headappheader(req, "X-Ash-Protocol", "https");
287 static void servessl(struct muth *muth, va_list args)
290 vavar(struct sockaddr_storage, name);
291 vavar(struct sslport *, pd);
294 gnutls_session_t sess;
298 int setcreds(gnutls_session_t sess)
306 namlen = sizeof(nambuf);
307 if(gnutls_server_name_get(sess, nambuf, &namlen, &ntype, i) != 0)
309 if(ntype != GNUTLS_NAME_DNS)
311 for(o = 0; pd->ncreds[o] != NULL; o++) {
312 for(u = 0; pd->ncreds[o]->names[u] != NULL; u++) {
313 if(!strcmp(pd->ncreds[o]->names[u], nambuf)) {
314 gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->ncreds[o]->creds);
315 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
321 gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->creds);
322 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
327 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
328 gnutls_init(&sess, GNUTLS_SERVER);
329 gnutls_priority_set(sess, pd->ciphers);
330 gnutls_db_set_retrieve_function(sess, sessdbfetch);
331 gnutls_db_set_store_function(sess, sessdbstore);
332 gnutls_db_set_remove_function(sess, sessdbdel);
333 gnutls_db_set_ptr(sess, NULL);
334 gnutls_handshake_set_post_client_hello_function(sess, setcreds);
335 gnutls_transport_set_ptr(sess, (gnutls_transport_ptr_t)(intptr_t)fd);
336 while((ret = gnutls_handshake(sess)) != 0) {
337 if((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN))
339 if(tlsblock(fd, sess, 60) <= 0)
342 memset(&conn, 0, sizeof(conn));
343 memset(&ssl, 0, sizeof(ssl));
345 conn.initreq = initreq;
351 in = fopencookie(&ssl, "r+", iofuns);
360 static void listenloop(struct muth *muth, va_list args)
362 vavar(struct sslport *, pd);
364 struct sockaddr_storage name;
367 fcntl(pd->fd, F_SETFL, fcntl(pd->fd, F_GETFL) | O_NONBLOCK);
369 namelen = sizeof(name);
370 if(block(pd->fd, EV_READ, 0) == 0)
374 ns = accept(pd->fd, (struct sockaddr *)&name, &namelen);
378 if(errno == ECONNABORTED)
380 flog(LOG_ERR, "accept: %s", strerror(errno));
383 mustart(servessl, ns, name, pd);
392 for(i = 0; i < listeners.d; i++) {
393 if(listeners.b[i] == muth)
394 bufdel(listeners, i);
398 static gnutls_dh_params_t dhparams(void)
400 static int inited = 0;
401 static gnutls_dh_params_t pars;
405 if(((ret = gnutls_dh_params_init(&pars)) != 0) ||
406 ((ret = gnutls_dh_params_generate2(pars, 2048)) != 0)) {
407 flog(LOG_ERR, "GnuTLS could not generate Diffie-Hellman parameters: %s", gnutls_strerror(ret));
415 static void init(void)
417 static int inited = 0;
423 if((ret = gnutls_global_init()) != 0) {
424 flog(LOG_ERR, "could not initialize GnuTLS: %s", gnutls_strerror(ret));
429 static struct namedcreds *readncreds(char *file)
432 struct namedcreds *nc;
433 gnutls_x509_crt_t crt;
434 gnutls_x509_privkey_t key;
438 struct charbuf keybuf;
439 struct charvbuf names;
444 if((fd = open(file, O_RDONLY)) < 0) {
445 flog(LOG_ERR, "ssl: %s: %s", file, strerror(errno));
449 sizebuf(keybuf, keybuf.d + 1024);
450 ret = read(fd, keybuf.b + keybuf.d, keybuf.s - keybuf.d);
452 flog(LOG_ERR, "ssl: reading from %s: %s", file, strerror(errno));
454 } else if(ret == 0) {
460 d.data = (unsigned char *)keybuf.b;
462 gnutls_x509_crt_init(&crt);
463 if((ret = gnutls_x509_crt_import(crt, &d, GNUTLS_X509_FMT_PEM)) != 0) {
464 flog(LOG_ERR, "ssl: could not load certificate from %s: %s", file, gnutls_strerror(ret));
467 cnl = sizeof(cn) - 1;
468 if((ret = gnutls_x509_crt_get_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, 0, cn, &cnl)) != 0) {
469 flog(LOG_ERR, "ssl: could not read common name from %s: %s", file, gnutls_strerror(ret));
473 bufadd(names, sstrdup(cn));
475 cnl = sizeof(cn) - 1;
476 if(gnutls_x509_crt_get_subject_alt_name2(crt, i, cn, &cnl, &type, NULL) < 0)
479 if(type == GNUTLS_SAN_DNSNAME)
480 bufadd(names, sstrdup(cn));
482 gnutls_x509_privkey_init(&key);
483 if((ret = gnutls_x509_privkey_import(key, &d, GNUTLS_X509_FMT_PEM)) != 0) {
484 flog(LOG_ERR, "ssl: could not load key from %s: %s", file, gnutls_strerror(ret));
491 gnutls_certificate_allocate_credentials(&nc->creds);
492 if((ret = gnutls_certificate_set_x509_key(nc->creds, &crt, 1, key)) != 0) {
493 flog(LOG_ERR, "ssl: could not use certificate from %s: %s", file, gnutls_strerror(ret));
496 gnutls_certificate_set_dh_params(nc->creds, dhparams());
500 static void readncdir(struct ncredbuf *buf, char *dir)
506 if((d = opendir(dir)) == NULL) {
507 flog(LOG_ERR, "ssl: could not read certificate directory %s: %s", dir, strerror(errno));
510 while((e = readdir(d)) != NULL) {
511 if(e->d_name[0] == '.')
513 if((es = strlen(e->d_name)) <= 4)
515 if(strcmp(e->d_name + es - 4, ".crt"))
517 bufadd(*buf, readncreds(sprintf3("%s/%s", dir, e->d_name)));
522 void handlegnussl(int argc, char **argp, char **argv)
524 int i, ret, port, fd;
525 gnutls_certificate_credentials_t creds;
526 gnutls_priority_t ciphers;
527 struct ncredbuf ncreds;
529 char *crtfile, *keyfile, *perr;
534 gnutls_certificate_allocate_credentials(&creds);
535 keyfile = crtfile = NULL;
537 for(i = 0; i < argc; i++) {
538 if(!strcmp(argp[i], "help")) {
539 printf("ssl handler parameters:\n");
540 printf("\tcert=CERT-FILE [mandatory]\n");
541 printf("\t\tThe name of the file to read the certificate from.\n");
542 printf("\tkey=KEY-FILE [same as CERT-FILE]\n");
543 printf("\t\tThe name of the file to read the private key from.\n");
544 printf("\tprio=PRIORITIES [NORMAL]\n");
545 printf("\t\tCiphersuite priorities, as a GnuTLS priority string.\n");
546 printf("\ttrust=CA-FILE [no default]\n");
547 printf("\t\tThe name of a file to read trusted certificates from.\n");
548 printf("\t\tMay be given multiple times.\n");
549 printf("\tcrl=CRL-FILE [no default]\n");
550 printf("\t\tThe name of a file to read revocation lists from.\n");
551 printf("\t\tMay be given multiple times.\n");
552 printf("\tncert=CERT-FILE [no default]\n");
553 printf("\t\tThe name of a file to read a named certificate from,\n");
554 printf("\t\tfor use with SNI-enabled clients.\n");
555 printf("\t\tMay be given multiple times.\n");
556 printf("\tncertdir=DIR [no default]\n");
557 printf("\t\tRead all *.crt files in the given directory as if they\n");
558 printf("\t\twere given with `ncert' options.\n");
559 printf("\t\tMay be given multiple times.\n");
560 printf("\tport=PORT [443]\n");
561 printf("\t\tThe TCP port to listen on.\n");
563 printf("\tAll X.509 data files must be PEM-encoded.\n");
564 printf("\tIf any certificates were given with `ncert' options, they will be\n");
565 printf("\tused if a client explicitly names one of them with a\n");
566 printf("\tserver-name indication. If a client indicates no server name,\n");
567 printf("\tor if a server-name indication does not match any given\n");
568 printf("\tcertificate, the certificate given with the `cert' option will\n");
569 printf("\tbe used instead.\n");
571 } else if(!strcmp(argp[i], "cert")) {
573 } else if(!strcmp(argp[i], "key")) {
575 } else if(!strcmp(argp[i], "prio")) {
577 gnutls_priority_deinit(ciphers);
578 ret = gnutls_priority_init(&ciphers, argv[i], (const char **)&perr);
579 if(ret == GNUTLS_E_INVALID_REQUEST) {
580 flog(LOG_ERR, "ssl: invalid cipher priority string, at `%s'", perr);
582 } else if(ret != 0) {
583 flog(LOG_ERR, "ssl: could not initialize cipher priorities: %s", gnutls_strerror(ret));
586 } else if(!strcmp(argp[i], "trust")) {
587 if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
588 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
591 for(i = 0; i < ncreds.d; i++) {
592 if((ret = gnutls_certificate_set_x509_trust_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
593 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
597 } else if(!strcmp(argp[i], "crl")) {
598 if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
599 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
602 for(i = 0; i < ncreds.d; i++) {
603 if((ret = gnutls_certificate_set_x509_crl_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
604 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
608 } else if(!strcmp(argp[i], "port")) {
609 port = atoi(argv[i]);
610 } else if(!strcmp(argp[i], "ncert")) {
611 bufadd(ncreds, readncreds(argv[i]));
612 } else if(!strcmp(argp[i], "ncertdir")) {
613 readncdir(&ncreds, argv[i]);
615 flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
619 if(crtfile == NULL) {
620 flog(LOG_ERR, "ssl: needs certificate file at the very least");
623 if((fd = listensock6(port)) < 0) {
624 flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
629 if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
630 flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
633 if((ciphers == NULL) && ((ret = gnutls_priority_init(&ciphers, "NORMAL", NULL)) != 0)) {
634 flog(LOG_ERR, "ssl: could not initialize cipher priorities: %s", gnutls_strerror(ret));
637 gnutls_certificate_set_dh_params(creds, dhparams());
638 bufadd(ncreds, NULL);
643 pd->ncreds = ncreds.b;
644 pd->ciphers = ciphers;
645 bufadd(listeners, mustart(listenloop, pd));
646 if((fd = listensock4(port)) < 0) {
647 if(errno != EADDRINUSE) {
648 flog(LOG_ERR, "could not listen on IPv4 port (port %i): %s", port, strerror(errno));
656 pd->ncreds = ncreds.b;
657 pd->ciphers = ciphers;
658 bufadd(listeners, mustart(listenloop, pd));