e27d31462e2b738836987379dd6e51d05737cfd8
[ashd.git] / src / ssl-gnutls.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
4
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.
9
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.
14
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/>.
17 */
18
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <string.h>
22 #include <fcntl.h>
23 #include <dirent.h>
24 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
27 #include <errno.h>
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32 #include <utils.h>
33 #include <mt.h>
34 #include <mtio.h>
35 #include <req.h>
36 #include <log.h>
37
38 #include "htparser.h"
39
40 #ifdef HAVE_GNUTLS
41
42 #include <gnutls/gnutls.h>
43 #include <gnutls/x509.h>
44
45 struct namedcreds {
46     char **names;
47     gnutls_certificate_credentials_t creds;
48 };
49
50 struct ncredbuf {
51     struct namedcreds **b;
52     size_t s, d;
53 };
54
55 struct sslport {
56     int fd;
57     int sport;
58     gnutls_certificate_credentials_t creds;
59     struct namedcreds **ncreds;
60 };
61
62 struct sslconn {
63     int fd;
64     struct sslport *port;
65     struct sockaddr_storage name;
66     gnutls_session_t sess;
67     struct charbuf in;
68 };
69
70 static gnutls_dh_params_t dhparams;
71
72 static int tlsblock(int fd, gnutls_session_t sess, time_t to)
73 {
74     if(gnutls_record_get_direction(sess))
75         return(block(fd, EV_WRITE, to));
76     else
77         return(block(fd, EV_READ, to));
78 }
79
80 static ssize_t sslread(void *cookie, char *buf, size_t len)
81 {
82     struct sslconn *ssl = cookie;
83     ssize_t xf;
84     int ret;
85
86     while(ssl->in.d == 0) {
87         sizebuf(ssl->in, ssl->in.d + 1024);
88         ret = gnutls_record_recv(ssl->sess, ssl->in.b + ssl->in.d, ssl->in.s - ssl->in.d);
89         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
90             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
91                 errno = ETIMEDOUT;
92                 return(-1);
93             }
94         } else if(ret < 0) {
95             errno = EIO;
96             return(-1);
97         } else if(ret == 0) {
98             return(0);
99         } else {
100             ssl->in.d += ret;
101         }
102     }
103     xf = min(ssl->in.d, len);
104     memcpy(buf, ssl->in.b, xf);
105     memmove(ssl->in.b, ssl->in.b + xf, ssl->in.d -= xf);
106     return(xf);
107 }
108
109 static ssize_t sslwrite(void *cookie, const char *buf, size_t len)
110 {
111     struct sslconn *ssl = cookie;
112     int ret;
113     size_t off;
114     
115     off = 0;
116     while(off < len) {
117         ret = gnutls_record_send(ssl->sess, buf + off, len - off);
118         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
119             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
120                 if(off == 0) {
121                     errno = ETIMEDOUT;
122                     return(-1);
123                 }
124                 return(off);
125             }
126         } else if(ret < 0) {
127             if(off == 0) {
128                 errno = EIO;
129                 return(-1);
130             }
131             return(off);
132         } else {
133             off += ret;
134         }
135     }
136     return(off);
137 }
138
139 static int sslclose(void *cookie)
140 {
141     return(0);
142 }
143
144 static cookie_io_functions_t iofuns = {
145     .read = sslread,
146     .write = sslwrite,
147     .close = sslclose,
148 };
149
150 static int initreq(struct conn *conn, struct hthead *req)
151 {
152     struct sslconn *ssl = conn->pdata;
153     struct sockaddr_storage sa;
154     socklen_t salen;
155     char nmbuf[256];
156     
157     headappheader(req, "X-Ash-Address", formathaddress((struct sockaddr *)&ssl->name, sizeof(sa)));
158     if(ssl->name.ss_family == AF_INET) {
159         headappheader(req, "X-Ash-Address", inet_ntop(AF_INET, &((struct sockaddr_in *)&ssl->name)->sin_addr, nmbuf, sizeof(nmbuf)));
160         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in *)&ssl->name)->sin_port)));
161     } else if(ssl->name.ss_family == AF_INET6) {
162         headappheader(req, "X-Ash-Address", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&ssl->name)->sin6_addr, nmbuf, sizeof(nmbuf)));
163         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in6 *)&ssl->name)->sin6_port)));
164     }
165     salen = sizeof(sa);
166     if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen))
167         headappheader(req, "X-Ash-Server-Address", formathaddress((struct sockaddr *)&sa, sizeof(sa)));
168     headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
169     headappheader(req, "X-Ash-Protocol", "https");
170     return(0);
171 }
172
173 static void servessl(struct muth *muth, va_list args)
174 {
175     vavar(int, fd);
176     vavar(struct sockaddr_storage, name);
177     vavar(struct sslport *, pd);
178     struct conn conn;
179     struct sslconn ssl;
180     gnutls_session_t sess;
181     int ret;
182     FILE *in;
183     
184     int setcreds(gnutls_session_t sess)
185     {
186         int i, o, u;
187         unsigned int ntype;
188         char nambuf[256];
189         size_t namlen;
190         
191         for(i = 0; 1; i++) {
192             namlen = sizeof(nambuf);
193             if(gnutls_server_name_get(sess, nambuf, &namlen, &ntype, i) != 0)
194                 break;
195             if(ntype != GNUTLS_NAME_DNS)
196                 continue;
197             for(o = 0; pd->ncreds[o] != NULL; o++) {
198                 for(u = 0; pd->ncreds[o]->names[u] != NULL; u++) {
199                     if(!strcmp(pd->ncreds[o]->names[u], nambuf)) {
200                         gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->ncreds[o]->creds);
201                         gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
202                         return(0);
203                     }
204                 }
205             }
206         }
207         gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->creds);
208         gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
209         return(0);
210     }
211
212     fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
213     gnutls_init(&sess, GNUTLS_SERVER);
214     gnutls_set_default_priority(sess);
215     gnutls_handshake_set_post_client_hello_function(sess, setcreds);
216     gnutls_transport_set_ptr(sess, (gnutls_transport_ptr_t)(intptr_t)fd);
217     while((ret = gnutls_handshake(sess)) != 0) {
218         if((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN))
219             goto out;
220         if(tlsblock(fd, sess, 60) <= 0)
221             goto out;
222     }
223     memset(&conn, 0, sizeof(conn));
224     memset(&ssl, 0, sizeof(ssl));
225     conn.pdata = &ssl;
226     conn.initreq = initreq;
227     ssl.fd = fd;
228     ssl.port = pd;
229     ssl.name = name;
230     ssl.sess = sess;
231     bufinit(ssl.in);
232     in = fopencookie(&ssl, "r+", iofuns);
233     serve(in, &conn);
234     
235 out:
236     gnutls_deinit(sess);
237     close(fd);
238 }
239
240 static void listenloop(struct muth *muth, va_list args)
241 {
242     vavar(struct sslport *, pd);
243     int ns;
244     struct sockaddr_storage name;
245     socklen_t namelen;
246     
247     while(1) {
248         namelen = sizeof(name);
249         block(pd->fd, EV_READ, 0);
250         ns = accept(pd->fd, (struct sockaddr *)&name, &namelen);
251         if(ns < 0) {
252             flog(LOG_ERR, "accept: %s", strerror(errno));
253             goto out;
254         }
255         mustart(servessl, ns, name, pd);
256     }
257     
258 out:
259     close(pd->fd);
260     free(pd);
261 }
262
263 static void init(void)
264 {
265     static int inited = 0;
266     int ret;
267     
268     if(inited)
269         return;
270     inited = 1;
271     if((ret = gnutls_global_init()) != 0) {
272         flog(LOG_ERR, "could not initialize GnuTLS: %s", gnutls_strerror(ret));
273         exit(1);
274     }
275     if(((ret = gnutls_dh_params_init(&dhparams)) != 0) ||
276        ((ret = gnutls_dh_params_generate2(dhparams, 2048)) != 0)) {
277         flog(LOG_ERR, "GnuTLS could not generate Diffie-Hellman parameters: %s", gnutls_strerror(ret));
278         exit(1);
279     }
280 }
281
282 static struct namedcreds *readncreds(char *file)
283 {
284     int i, fd, ret;
285     struct namedcreds *nc;
286     gnutls_x509_crt_t crt;
287     gnutls_x509_privkey_t key;
288     char cn[1024];
289     size_t cnl;
290     gnutls_datum_t d;
291     struct charbuf keybuf;
292     struct charvbuf names;
293     unsigned int type;
294     
295     bufinit(keybuf);
296     bufinit(names);
297     if((fd = open(file, O_RDONLY)) < 0) {
298         flog(LOG_ERR, "ssl: %s: %s", file, strerror(errno));
299         exit(1);
300     }
301     while(1) {
302         sizebuf(keybuf, keybuf.d + 1024);
303         ret = read(fd, keybuf.b + keybuf.d, keybuf.s - keybuf.d);
304         if(ret < 0) {
305             flog(LOG_ERR, "ssl: reading from %s: %s", file, strerror(errno));
306             exit(1);
307         } else if(ret == 0) {
308             break;
309         }
310         keybuf.d += ret;
311     }
312     close(fd);
313     d.data = (unsigned char *)keybuf.b;
314     d.size = keybuf.d;
315     gnutls_x509_crt_init(&crt);
316     if((ret = gnutls_x509_crt_import(crt, &d, GNUTLS_X509_FMT_PEM)) != 0) {
317         flog(LOG_ERR, "ssl: could not load certificate from %s: %s", file, gnutls_strerror(ret));
318         exit(1);
319     }
320     cnl = sizeof(cn) - 1;
321     if((ret = gnutls_x509_crt_get_dn_by_oid(crt, GNUTLS_OID_X520_COMMON_NAME, 0, 0, cn, &cnl)) != 0) {
322         flog(LOG_ERR, "ssl: could not read common name from %s: %s", file, gnutls_strerror(ret));
323         exit(1);
324     }
325     cn[cnl] = 0;
326     bufadd(names, sstrdup(cn));
327     for(i = 0; 1; i++) {
328         cnl = sizeof(cn) - 1;
329         if(gnutls_x509_crt_get_subject_alt_name2(crt, i, cn, &cnl, &type, NULL) < 0)
330             break;
331         cn[cnl] = 0;
332         if(type == GNUTLS_SAN_DNSNAME)
333             bufadd(names, sstrdup(cn));
334     }
335     gnutls_x509_privkey_init(&key);
336     if((ret = gnutls_x509_privkey_import(key, &d, GNUTLS_X509_FMT_PEM)) != 0) {
337         flog(LOG_ERR, "ssl: could not load key from %s: %s", file, gnutls_strerror(ret));
338         exit(1);
339     }
340     buffree(keybuf);
341     bufadd(names, NULL);
342     omalloc(nc);
343     nc->names = names.b;
344     gnutls_certificate_allocate_credentials(&nc->creds);
345     if((ret = gnutls_certificate_set_x509_key(nc->creds, &crt, 1, key)) != 0) {
346         flog(LOG_ERR, "ssl: could not use certificate from %s: %s", file, gnutls_strerror(ret));
347         exit(1);
348     }
349     gnutls_certificate_set_dh_params(nc->creds, dhparams);
350     return(nc);
351 }
352
353 static void readncdir(struct ncredbuf *buf, char *dir)
354 {
355     DIR *d;
356     struct dirent *e;
357     size_t es;
358     
359     if((d = opendir(dir)) == NULL) {
360         flog(LOG_ERR, "ssl: could not read certificate directory %s: %s", dir, strerror(errno));
361         exit(1);
362     }
363     while((e = readdir(d)) != NULL) {
364         if(e->d_name[0] == '.')
365             continue;
366         if((es = strlen(e->d_name)) <= 4)
367             continue;
368         if(strcmp(e->d_name + es - 4, ".crt"))
369             continue;
370         bufadd(*buf, readncreds(sprintf3("%s/%s", dir, e->d_name)));
371     }
372     closedir(d);
373 }
374
375 void handlegnussl(int argc, char **argp, char **argv)
376 {
377     int i, ret, port, fd;
378     gnutls_certificate_credentials_t creds;
379     struct ncredbuf ncreds;
380     struct sslport *pd;
381     char *crtfile, *keyfile;
382     
383     init();
384     port = 443;
385     bufinit(ncreds);
386     gnutls_certificate_allocate_credentials(&creds);
387     keyfile = crtfile = NULL;
388     for(i = 0; i < argc; i++) {
389         if(!strcmp(argp[i], "help")) {
390             printf("ssl handler parameters:\n");
391             printf("\tcert=CERT-FILE  [mandatory]\n");
392             printf("\t\tThe name of the file to read the certificate from.\n");
393             printf("\tkey=KEY-FILE    [same as CERT-FILE]\n");
394             printf("\t\tThe name of the file to read the private key from.\n");
395             printf("\ttrust=CA-FILE   [no default]\n");
396             printf("\t\tThe name of a file to read trusted certificates from.\n");
397             printf("\t\tMay be given multiple times.\n");
398             printf("\tcrl=CRL-FILE    [no default]\n");
399             printf("\t\tThe name of a file to read revocation lists from.\n");
400             printf("\t\tMay be given multiple times.\n");
401             printf("\tport=PORT       [443]\n");
402             printf("\t\tThe TCP port to listen on.\n");
403             printf("\n");
404             printf("\tAll X.509 data files must be PEM-encoded.\n");
405             printf("\tSee the manpage for information on specifying multiple\n\tcertificates to support SNI operation.\n");
406             exit(0);
407         } else if(!strcmp(argp[i], "cert")) {
408             crtfile = argv[i];
409         } else if(!strcmp(argp[i], "key")) {
410             keyfile = argv[i];
411         } else if(!strcmp(argp[i], "trust")) {
412             if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
413                 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
414                 exit(1);
415             }
416             for(i = 0; i < ncreds.d; i++) {
417                 if((ret = gnutls_certificate_set_x509_trust_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
418                     flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
419                     exit(1);
420                 }
421             }
422         } else if(!strcmp(argp[i], "crl")) {
423             if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
424                 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
425                 exit(1);
426             }
427             for(i = 0; i < ncreds.d; i++) {
428                 if((ret = gnutls_certificate_set_x509_crl_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
429                     flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
430                     exit(1);
431                 }
432             }
433         } else if(!strcmp(argp[i], "port")) {
434             port = atoi(argv[i]);
435         } else if(!strcmp(argp[i], "ncert")) {
436             bufadd(ncreds, readncreds(argv[i]));
437         } else if(!strcmp(argp[i], "ncertdir")) {
438             readncdir(&ncreds, argv[i]);
439         } else {
440             flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
441             exit(1);
442         }
443     }
444     if(crtfile == NULL) {
445         flog(LOG_ERR, "ssl: needs certificate file at the very least");
446         exit(1);
447     }
448     if(keyfile == NULL)
449         keyfile = crtfile;
450     if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
451         flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
452         exit(1);
453     }
454     gnutls_certificate_set_dh_params(creds, dhparams);
455     if((fd = listensock6(port)) < 0) {
456         flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
457         exit(1);
458     }
459     bufadd(ncreds, NULL);
460     omalloc(pd);
461     pd->fd = fd;
462     pd->sport = port;
463     pd->creds = creds;
464     pd->ncreds = ncreds.b;
465     mustart(listenloop, pd);
466     if((fd = listensock6(port)) < 0) {
467         if(errno != EADDRINUSE) {
468             flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
469             exit(1);
470         }
471     } else {
472         omalloc(pd);
473         pd->fd = fd;
474         pd->sport = port;
475         pd->creds = creds;
476         mustart(listenloop, pd);
477     }
478 }
479
480 #endif