sni: Documented SNI operation.
[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
70static gnutls_dh_params_t dhparams;
71
72static 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
80static 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
109static 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
139static int sslclose(void *cookie)
140{
141 return(0);
142}
143
144static cookie_io_functions_t iofuns = {
145 .read = sslread,
146 .write = sslwrite,
147 .close = sslclose,
148};
149
150static int initreq(struct conn *conn, struct hthead *req)
151{
152 struct sslconn *ssl = conn->pdata;
6b84641a
FT
153 struct sockaddr_storage sa;
154 socklen_t salen;
6ca53b2e
FT
155 char nmbuf[256];
156
7595e3a4 157 headappheader(req, "X-Ash-Address", formathaddress((struct sockaddr *)&ssl->name, sizeof(sa)));
6ca53b2e
FT
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 }
6b84641a 165 salen = sizeof(sa);
7595e3a4
FT
166 if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen))
167 headappheader(req, "X-Ash-Server-Address", formathaddress((struct sockaddr *)&sa, sizeof(sa)));
6ca53b2e
FT
168 headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
169 headappheader(req, "X-Ash-Protocol", "https");
170 return(0);
171}
172
173static 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
1b77e192
FT
184 int setcreds(gnutls_session_t sess)
185 {
28b2e619 186 int i, o, u;
1b77e192
FT
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;
28b2e619
FT
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 }
1b77e192
FT
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
6ca53b2e
FT
212 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
213 gnutls_init(&sess, GNUTLS_SERVER);
214 gnutls_set_default_priority(sess);
1b77e192 215 gnutls_handshake_set_post_client_hello_function(sess, setcreds);
6ca53b2e
FT
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
235out:
236 gnutls_deinit(sess);
237 close(fd);
238}
239
240static 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
258out:
259 close(pd->fd);
260 free(pd);
261}
262
263static 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
28b2e619
FT
282static 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
26902200
FT
353static 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
6ca53b2e
FT
375void handlegnussl(int argc, char **argp, char **argv)
376{
377 int i, ret, port, fd;
378 gnutls_certificate_credentials_t creds;
28b2e619 379 struct ncredbuf ncreds;
6ca53b2e
FT
380 struct sslport *pd;
381 char *crtfile, *keyfile;
382
383 init();
384 port = 443;
28b2e619 385 bufinit(ncreds);
6ca53b2e
FT
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");
4094af22
FT
401 printf("\tncert=CERT-FILE [no default]\n");
402 printf("\t\tThe name of a file to read a named certificate from,\n");
403 printf("\t\tfor use with SNI-enabled clients.\n");
404 printf("\t\tMay be given multiple times.\n");
405 printf("\tncertdir=DIR [no default]\n");
406 printf("\t\tRead all *.crt files in the given directory as if they\n");
407 printf("\t\twere given with `ncert' options.\n");
408 printf("\t\tMay be given multiple times.\n");
6ca53b2e
FT
409 printf("\tport=PORT [443]\n");
410 printf("\t\tThe TCP port to listen on.\n");
411 printf("\n");
412 printf("\tAll X.509 data files must be PEM-encoded.\n");
4094af22
FT
413 printf("\tIf any certificates were given with `ncert' options, they will be\n");
414 printf("\tused if a client explicitly names one of them with a\n");
415 printf("\tserver-name indication. If a client indicates no server name,\n");
416 printf("\tor if a server-name indication does not match any given\n");
417 printf("\tcertificate, the certificate given with the `cert' option will\n");
418 printf("\tbe used instead.\n");
6ca53b2e
FT
419 exit(0);
420 } else if(!strcmp(argp[i], "cert")) {
421 crtfile = argv[i];
422 } else if(!strcmp(argp[i], "key")) {
423 keyfile = argv[i];
424 } else if(!strcmp(argp[i], "trust")) {
425 if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
426 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
427 exit(1);
428 }
28b2e619
FT
429 for(i = 0; i < ncreds.d; i++) {
430 if((ret = gnutls_certificate_set_x509_trust_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
431 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
432 exit(1);
433 }
434 }
6ca53b2e
FT
435 } else if(!strcmp(argp[i], "crl")) {
436 if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
437 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
438 exit(1);
439 }
28b2e619
FT
440 for(i = 0; i < ncreds.d; i++) {
441 if((ret = gnutls_certificate_set_x509_crl_file(ncreds.b[i]->creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
442 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
443 exit(1);
444 }
445 }
6ca53b2e
FT
446 } else if(!strcmp(argp[i], "port")) {
447 port = atoi(argv[i]);
28b2e619
FT
448 } else if(!strcmp(argp[i], "ncert")) {
449 bufadd(ncreds, readncreds(argv[i]));
26902200
FT
450 } else if(!strcmp(argp[i], "ncertdir")) {
451 readncdir(&ncreds, argv[i]);
6ca53b2e
FT
452 } else {
453 flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
454 exit(1);
455 }
456 }
457 if(crtfile == NULL) {
458 flog(LOG_ERR, "ssl: needs certificate file at the very least");
459 exit(1);
460 }
461 if(keyfile == NULL)
462 keyfile = crtfile;
463 if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
464 flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
465 exit(1);
466 }
467 gnutls_certificate_set_dh_params(creds, dhparams);
468 if((fd = listensock6(port)) < 0) {
469 flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
470 exit(1);
471 }
28b2e619 472 bufadd(ncreds, NULL);
6ca53b2e
FT
473 omalloc(pd);
474 pd->fd = fd;
475 pd->sport = port;
476 pd->creds = creds;
28b2e619 477 pd->ncreds = ncreds.b;
6ca53b2e
FT
478 mustart(listenloop, pd);
479 if((fd = listensock6(port)) < 0) {
480 if(errno != EADDRINUSE) {
481 flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
482 exit(1);
483 }
484 } else {
485 omalloc(pd);
486 pd->fd = fd;
487 pd->sport = port;
488 pd->creds = creds;
489 mustart(listenloop, pd);
490 }
491}
492
493#endif