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