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