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