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 struct namedcreds **ncreds;
65 struct sockaddr_storage name;
66 gnutls_session_t sess;
71 struct savedsess *next, *prev;
72 gnutls_datum_t key, value;
75 static int numconn = 0, numsess = 0;
76 static struct btree *sessidx = NULL;
77 static struct savedsess *sesslistf = NULL, *sesslistl = NULL;
79 static int sesscmp(void *ap, void *bp)
81 struct savedsess *a = ap, *b = bp;
83 if(a->key.size != b->key.size)
84 return(a->key.size - b->key.size);
85 return(memcmp(a->key.data, b->key.data, a->key.size));
88 static gnutls_datum_t sessdbfetch(void *uudata, gnutls_datum_t key)
90 struct savedsess *sess, lkey;
93 memset(&ret, 0, sizeof(ret));
95 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
97 ret.data = memcpy(gnutls_malloc(ret.size = sess->value.size), sess->value.data, sess->value.size);
101 static void freesess(struct savedsess *sess)
103 bbtreedel(&sessidx, sess, sesscmp);
105 sess->next->prev = sess->prev;
107 sess->prev->next = sess->next;
108 if(sess == sesslistf)
109 sesslistf = sess->next;
110 if(sess == sesslistl)
111 sesslistl = sess->prev;
112 free(sess->key.data);
113 free(sess->value.data);
118 static int sessdbdel(void *uudata, gnutls_datum_t key)
120 struct savedsess *sess, lkey;
123 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL)
129 static void cleansess(void)
131 while(numsess > (max(numconn, 1) * 100))
135 static int sessdbstore(void *uudata, gnutls_datum_t key, gnutls_datum_t value)
138 struct savedsess *sess, lkey;
140 if((value.data == NULL) || (value.size == 0)) {
141 sessdbdel(NULL, key);
145 if((sess = btreeget(sessidx, &lkey, sesscmp)) == NULL) {
147 sess->key.data = memcpy(smalloc(sess->key.size = key.size), key.data, key.size);
148 sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
149 bbtreeput(&sessidx, sess, sesscmp);
151 sess->next = sesslistf;
153 sesslistf->prev = sess;
155 if(sesslistl == NULL)
159 free(sess->value.data);
160 sess->value.data = memcpy(smalloc(sess->value.size = value.size), value.data, value.size);
161 if(sess != sesslistf) {
163 sess->next->prev = sess->prev;
165 sess->prev->next = sess->next;
166 if(sess == sesslistl)
167 sesslistl = sess->prev;
169 sess->next = sesslistf;
171 sesslistf->prev = sess;
182 static int tlsblock(int fd, gnutls_session_t sess, time_t to)
184 if(gnutls_record_get_direction(sess))
185 return(block(fd, EV_WRITE, to));
187 return(block(fd, EV_READ, to));
190 static ssize_t sslread(void *cookie, char *buf, size_t len)
192 struct sslconn *ssl = cookie;
196 while(ssl->in.d == 0) {
197 sizebuf(ssl->in, ssl->in.d + 1024);
198 ret = gnutls_record_recv(ssl->sess, ssl->in.b + ssl->in.d, ssl->in.s - ssl->in.d);
199 if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
200 if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
207 } else if(ret == 0) {
213 xf = min(ssl->in.d, len);
214 memcpy(buf, ssl->in.b, xf);
215 memmove(ssl->in.b, ssl->in.b + xf, ssl->in.d -= xf);
219 static ssize_t sslwrite(void *cookie, const char *buf, size_t len)
221 struct sslconn *ssl = cookie;
227 ret = gnutls_record_send(ssl->sess, buf + off, len - off);
228 if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
229 if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
249 static int sslclose(void *cookie)
251 struct sslconn *ssl = cookie;
257 static cookie_io_functions_t iofuns = {
263 static int initreq(struct conn *conn, struct hthead *req)
265 struct sslconn *ssl = conn->pdata;
266 struct sockaddr_storage sa;
270 headappheader(req, "X-Ash-Address", formathaddress((struct sockaddr *)&ssl->name, sizeof(sa)));
271 if(ssl->name.ss_family == AF_INET) {
272 headappheader(req, "X-Ash-Address", inet_ntop(AF_INET, &((struct sockaddr_in *)&ssl->name)->sin_addr, nmbuf, sizeof(nmbuf)));
273 headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in *)&ssl->name)->sin_port)));
274 } else if(ssl->name.ss_family == AF_INET6) {
275 headappheader(req, "X-Ash-Address", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&ssl->name)->sin6_addr, nmbuf, sizeof(nmbuf)));
276 headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in6 *)&ssl->name)->sin6_port)));
279 if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen))
280 headappheader(req, "X-Ash-Server-Address", formathaddress((struct sockaddr *)&sa, sizeof(sa)));
281 headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
282 headappheader(req, "X-Ash-Protocol", "https");
286 static void servessl(struct muth *muth, va_list args)
289 vavar(struct sockaddr_storage, name);
290 vavar(struct sslport *, pd);
293 gnutls_session_t sess;
297 int setcreds(gnutls_session_t sess)
305 namlen = sizeof(nambuf);
306 if(gnutls_server_name_get(sess, nambuf, &namlen, &ntype, i) != 0)
308 if(ntype != GNUTLS_NAME_DNS)
310 for(o = 0; pd->ncreds[o] != NULL; o++) {
311 for(u = 0; pd->ncreds[o]->names[u] != NULL; u++) {
312 if(!strcmp(pd->ncreds[o]->names[u], nambuf)) {
313 gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->ncreds[o]->creds);
314 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
320 gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->creds);
321 gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
326 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
327 gnutls_init(&sess, GNUTLS_SERVER);
328 gnutls_set_default_priority(sess);
329 gnutls_db_set_retrieve_function(sess, sessdbfetch);
330 gnutls_db_set_store_function(sess, sessdbstore);
331 gnutls_db_set_remove_function(sess, sessdbdel);
332 gnutls_db_set_ptr(sess, NULL);
333 gnutls_handshake_set_post_client_hello_function(sess, setcreds);
334 gnutls_transport_set_ptr(sess, (gnutls_transport_ptr_t)(intptr_t)fd);
335 while((ret = gnutls_handshake(sess)) != 0) {
336 if((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN))
338 if(tlsblock(fd, sess, 60) <= 0)
341 memset(&conn, 0, sizeof(conn));
342 memset(&ssl, 0, sizeof(ssl));
344 conn.initreq = initreq;
350 in = fopencookie(&ssl, "r+", iofuns);
359 static void listenloop(struct muth *muth, va_list args)
361 vavar(struct sslport *, pd);
363 struct sockaddr_storage name;
367 namelen = sizeof(name);
368 if(block(pd->fd, EV_READ, 0) == 0)
370 ns = accept(pd->fd, (struct sockaddr *)&name, &namelen);
372 flog(LOG_ERR, "accept: %s", strerror(errno));
375 mustart(servessl, ns, name, pd);
381 for(i = 0; i < listeners.d; i++) {
382 if(listeners.b[i] == muth)
383 bufdel(listeners, i);
387 static gnutls_dh_params_t dhparams(void)
389 static int inited = 0;
390 static gnutls_dh_params_t pars;
394 if(((ret = gnutls_dh_params_init(&pars)) != 0) ||
395 ((ret = gnutls_dh_params_generate2(pars, 2048)) != 0)) {
396 flog(LOG_ERR, "GnuTLS could not generate Diffie-Hellman parameters: %s", gnutls_strerror(ret));
404 static void init(void)
406 static int inited = 0;
412 if((ret = gnutls_global_init()) != 0) {
413 flog(LOG_ERR, "could not initialize GnuTLS: %s", gnutls_strerror(ret));
418 static struct namedcreds *readncreds(char *file)
421 struct namedcreds *nc;
422 gnutls_x509_crt_t crt;
423 gnutls_x509_privkey_t key;
427 struct charbuf keybuf;
428 struct charvbuf names;
433 if((fd = open(file, O_RDONLY)) < 0) {
434 flog(LOG_ERR, "ssl: %s: %s", file, strerror(errno));
438 sizebuf(keybuf, keybuf.d + 1024);
439 ret = read(fd, keybuf.b + keybuf.d, keybuf.s - keybuf.d);
441 flog(LOG_ERR, "ssl: reading from %s: %s", file, strerror(errno));
443 } else if(ret == 0) {
449 d.data = (unsigned char *)keybuf.b;
451 gnutls_x509_crt_init(&crt);
452 if((ret = gnutls_x509_crt_import(crt, &d, GNUTLS_X509_FMT_PEM)) != 0) {
453 flog(LOG_ERR, "ssl: could not load certificate from %s: %s", file, gnutls_strerror(ret));
456 cnl = sizeof(cn) - 1;
457 if((ret = gnutls_x509_crt_get_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, 0, cn, &cnl)) != 0) {
458 flog(LOG_ERR, "ssl: could not read common name from %s: %s", file, gnutls_strerror(ret));
462 bufadd(names, sstrdup(cn));
464 cnl = sizeof(cn) - 1;
465 if(gnutls_x509_crt_get_subject_alt_name2(crt, i, cn, &cnl, &type, NULL) < 0)
468 if(type == GNUTLS_SAN_DNSNAME)
469 bufadd(names, sstrdup(cn));
471 gnutls_x509_privkey_init(&key);
472 if((ret = gnutls_x509_privkey_import(key, &d, GNUTLS_X509_FMT_PEM)) != 0) {
473 flog(LOG_ERR, "ssl: could not load key from %s: %s", file, gnutls_strerror(ret));
480 gnutls_certificate_allocate_credentials(&nc->creds);
481 if((ret = gnutls_certificate_set_x509_key(nc->creds, &crt, 1, key)) != 0) {
482 flog(LOG_ERR, "ssl: could not use certificate from %s: %s", file, gnutls_strerror(ret));
485 gnutls_certificate_set_dh_params(nc->creds, dhparams());
489 static void readncdir(struct ncredbuf *buf, char *dir)
495 if((d = opendir(dir)) == NULL) {
496 flog(LOG_ERR, "ssl: could not read certificate directory %s: %s", dir, strerror(errno));
499 while((e = readdir(d)) != NULL) {
500 if(e->d_name[0] == '.')
502 if((es = strlen(e->d_name)) <= 4)
504 if(strcmp(e->d_name + es - 4, ".crt"))
506 bufadd(*buf, readncreds(sprintf3("%s/%s", dir, e->d_name)));
511 void handlegnussl(int argc, char **argp, char **argv)
513 int i, ret, port, fd;
514 gnutls_certificate_credentials_t creds;
515 struct ncredbuf ncreds;
517 char *crtfile, *keyfile;
522 gnutls_certificate_allocate_credentials(&creds);
523 keyfile = crtfile = NULL;
524 for(i = 0; i < argc; i++) {
525 if(!strcmp(argp[i], "help")) {
526 printf("ssl handler parameters:\n");
527 printf("\tcert=CERT-FILE [mandatory]\n");
528 printf("\t\tThe name of the file to read the certificate from.\n");
529 printf("\tkey=KEY-FILE [same as CERT-FILE]\n");
530 printf("\t\tThe name of the file to read the private key from.\n");
531 printf("\ttrust=CA-FILE [no default]\n");
532 printf("\t\tThe name of a file to read trusted certificates from.\n");
533 printf("\t\tMay be given multiple times.\n");
534 printf("\tcrl=CRL-FILE [no default]\n");
535 printf("\t\tThe name of a file to read revocation lists from.\n");
536 printf("\t\tMay be given multiple times.\n");
537 printf("\tncert=CERT-FILE [no default]\n");
538 printf("\t\tThe name of a file to read a named certificate from,\n");
539 printf("\t\tfor use with SNI-enabled clients.\n");
540 printf("\t\tMay be given multiple times.\n");
541 printf("\tncertdir=DIR [no default]\n");
542 printf("\t\tRead all *.crt files in the given directory as if they\n");
543 printf("\t\twere given with `ncert' options.\n");
544 printf("\t\tMay be given multiple times.\n");
545 printf("\tport=PORT [443]\n");
546 printf("\t\tThe TCP port to listen on.\n");
548 printf("\tAll X.509 data files must be PEM-encoded.\n");
549 printf("\tIf any certificates were given with `ncert' options, they will be\n");
550 printf("\tused if a client explicitly names one of them with a\n");
551 printf("\tserver-name indication. If a client indicates no server name,\n");
552 printf("\tor if a server-name indication does not match any given\n");
553 printf("\tcertificate, the certificate given with the `cert' option will\n");
554 printf("\tbe used instead.\n");
556 } else if(!strcmp(argp[i], "cert")) {
558 } else if(!strcmp(argp[i], "key")) {
560 } else if(!strcmp(argp[i], "trust")) {
561 if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
562 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
565 for(i = 0; i < ncreds.d; i++) {
566 if((ret = gnutls_certificate_set_x509_trust_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
567 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
571 } else if(!strcmp(argp[i], "crl")) {
572 if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
573 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
576 for(i = 0; i < ncreds.d; i++) {
577 if((ret = gnutls_certificate_set_x509_crl_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
578 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
582 } else if(!strcmp(argp[i], "port")) {
583 port = atoi(argv[i]);
584 } else if(!strcmp(argp[i], "ncert")) {
585 bufadd(ncreds, readncreds(argv[i]));
586 } else if(!strcmp(argp[i], "ncertdir")) {
587 readncdir(&ncreds, argv[i]);
589 flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
593 if(crtfile == NULL) {
594 flog(LOG_ERR, "ssl: needs certificate file at the very least");
597 if((fd = listensock6(port)) < 0) {
598 flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
603 if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
604 flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
607 gnutls_certificate_set_dh_params(creds, dhparams());
608 bufadd(ncreds, NULL);
613 pd->ncreds = ncreds.b;
614 bufadd(listeners, mustart(listenloop, pd));
615 if((fd = listensock4(port)) < 0) {
616 if(errno != EADDRINUSE) {
617 flog(LOG_ERR, "could not listen on IPv4 port (port %i): %s", port, strerror(errno));
625 bufadd(listeners, mustart(listenloop, pd));