htparser: Pass the server's local IP address.
[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 <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>
42
43 struct sslport {
44     int fd;
45     int sport;
46     gnutls_certificate_credentials_t creds;
47 };
48
49 struct sslconn {
50     int fd;
51     struct sslport *port;
52     struct sockaddr_storage name;
53     gnutls_session_t sess;
54     struct charbuf in;
55 };
56
57 static gnutls_dh_params_t dhparams;
58
59 static int tlsblock(int fd, gnutls_session_t sess, time_t to)
60 {
61     if(gnutls_record_get_direction(sess))
62         return(block(fd, EV_WRITE, to));
63     else
64         return(block(fd, EV_READ, to));
65 }
66
67 static ssize_t sslread(void *cookie, char *buf, size_t len)
68 {
69     struct sslconn *ssl = cookie;
70     ssize_t xf;
71     int ret;
72
73     while(ssl->in.d == 0) {
74         sizebuf(ssl->in, ssl->in.d + 1024);
75         ret = gnutls_record_recv(ssl->sess, ssl->in.b + ssl->in.d, ssl->in.s - ssl->in.d);
76         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
77             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
78                 errno = ETIMEDOUT;
79                 return(-1);
80             }
81         } else if(ret < 0) {
82             errno = EIO;
83             return(-1);
84         } else if(ret == 0) {
85             return(0);
86         } else {
87             ssl->in.d += ret;
88         }
89     }
90     xf = min(ssl->in.d, len);
91     memcpy(buf, ssl->in.b, xf);
92     memmove(ssl->in.b, ssl->in.b + xf, ssl->in.d -= xf);
93     return(xf);
94 }
95
96 static ssize_t sslwrite(void *cookie, const char *buf, size_t len)
97 {
98     struct sslconn *ssl = cookie;
99     int ret;
100     size_t off;
101     
102     off = 0;
103     while(off < len) {
104         ret = gnutls_record_send(ssl->sess, buf + off, len - off);
105         if((ret == GNUTLS_E_INTERRUPTED) || (ret == GNUTLS_E_AGAIN)) {
106             if(tlsblock(ssl->fd, ssl->sess, 60) == 0) {
107                 if(off == 0) {
108                     errno = ETIMEDOUT;
109                     return(-1);
110                 }
111                 return(off);
112             }
113         } else if(ret < 0) {
114             if(off == 0) {
115                 errno = EIO;
116                 return(-1);
117             }
118             return(off);
119         } else {
120             off += ret;
121         }
122     }
123     return(off);
124 }
125
126 static int sslclose(void *cookie)
127 {
128     return(0);
129 }
130
131 static cookie_io_functions_t iofuns = {
132     .read = sslread,
133     .write = sslwrite,
134     .close = sslclose,
135 };
136
137 static int initreq(struct conn *conn, struct hthead *req)
138 {
139     struct sslconn *ssl = conn->pdata;
140     struct sockaddr_storage sa;
141     socklen_t salen;
142     char nmbuf[256];
143     
144     if(ssl->name.ss_family == AF_INET) {
145         headappheader(req, "X-Ash-Address", inet_ntop(AF_INET, &((struct sockaddr_in *)&ssl->name)->sin_addr, nmbuf, sizeof(nmbuf)));
146         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in *)&ssl->name)->sin_port)));
147     } else if(ssl->name.ss_family == AF_INET6) {
148         headappheader(req, "X-Ash-Address", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&ssl->name)->sin6_addr, nmbuf, sizeof(nmbuf)));
149         headappheader(req, "X-Ash-Port", sprintf3("%i", ntohs(((struct sockaddr_in6 *)&ssl->name)->sin6_port)));
150     }
151     salen = sizeof(sa);
152     if(!getsockname(ssl->fd, (struct sockaddr *)&sa, &salen)) {
153         if(sa.ss_family == AF_INET)
154             headappheader(req, "X-Ash-Server-Address", inet_ntop(AF_INET, &((struct sockaddr_in *)&sa)->sin_addr, nmbuf, sizeof(nmbuf)));
155         else if(sa.ss_family == AF_INET6)
156             headappheader(req, "X-Ash-Server-Address", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&sa)->sin6_addr, nmbuf, sizeof(nmbuf)));
157     }
158     headappheader(req, "X-Ash-Server-Port", sprintf3("%i", ssl->port->sport));
159     headappheader(req, "X-Ash-Protocol", "https");
160     return(0);
161 }
162
163 static void servessl(struct muth *muth, va_list args)
164 {
165     vavar(int, fd);
166     vavar(struct sockaddr_storage, name);
167     vavar(struct sslport *, pd);
168     struct conn conn;
169     struct sslconn ssl;
170     gnutls_session_t sess;
171     int ret;
172     FILE *in;
173     
174     fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
175     gnutls_init(&sess, GNUTLS_SERVER);
176     gnutls_set_default_priority(sess);
177     gnutls_credentials_set(sess, GNUTLS_CRD_CERTIFICATE, pd->creds);
178     gnutls_certificate_server_set_request(sess, GNUTLS_CERT_REQUEST);
179     gnutls_transport_set_ptr(sess, (gnutls_transport_ptr_t)(intptr_t)fd);
180     while((ret = gnutls_handshake(sess)) != 0) {
181         if((ret != GNUTLS_E_INTERRUPTED) && (ret != GNUTLS_E_AGAIN))
182             goto out;
183         if(tlsblock(fd, sess, 60) <= 0)
184             goto out;
185     }
186     memset(&conn, 0, sizeof(conn));
187     memset(&ssl, 0, sizeof(ssl));
188     conn.pdata = &ssl;
189     conn.initreq = initreq;
190     ssl.fd = fd;
191     ssl.port = pd;
192     ssl.name = name;
193     ssl.sess = sess;
194     bufinit(ssl.in);
195     in = fopencookie(&ssl, "r+", iofuns);
196     serve(in, &conn);
197     
198 out:
199     gnutls_deinit(sess);
200     close(fd);
201 }
202
203 static void listenloop(struct muth *muth, va_list args)
204 {
205     vavar(struct sslport *, pd);
206     int ns;
207     struct sockaddr_storage name;
208     socklen_t namelen;
209     
210     while(1) {
211         namelen = sizeof(name);
212         block(pd->fd, EV_READ, 0);
213         ns = accept(pd->fd, (struct sockaddr *)&name, &namelen);
214         if(ns < 0) {
215             flog(LOG_ERR, "accept: %s", strerror(errno));
216             goto out;
217         }
218         mustart(servessl, ns, name, pd);
219     }
220     
221 out:
222     close(pd->fd);
223     free(pd);
224 }
225
226 static void init(void)
227 {
228     static int inited = 0;
229     int ret;
230     
231     if(inited)
232         return;
233     inited = 1;
234     if((ret = gnutls_global_init()) != 0) {
235         flog(LOG_ERR, "could not initialize GnuTLS: %s", gnutls_strerror(ret));
236         exit(1);
237     }
238     if(((ret = gnutls_dh_params_init(&dhparams)) != 0) ||
239        ((ret = gnutls_dh_params_generate2(dhparams, 2048)) != 0)) {
240         flog(LOG_ERR, "GnuTLS could not generate Diffie-Hellman parameters: %s", gnutls_strerror(ret));
241         exit(1);
242     }
243 }
244
245 void handlegnussl(int argc, char **argp, char **argv)
246 {
247     int i, ret, port, fd;
248     gnutls_certificate_credentials_t creds;
249     struct sslport *pd;
250     char *crtfile, *keyfile;
251     
252     init();
253     port = 443;
254     gnutls_certificate_allocate_credentials(&creds);
255     keyfile = crtfile = NULL;
256     for(i = 0; i < argc; i++) {
257         if(!strcmp(argp[i], "help")) {
258             printf("ssl handler parameters:\n");
259             printf("\tcert=CERT-FILE  [mandatory]\n");
260             printf("\t\tThe name of the file to read the certificate from.\n");
261             printf("\tkey=KEY-FILE    [same as CERT-FILE]\n");
262             printf("\t\tThe name of the file to read the private key from.\n");
263             printf("\ttrust=CA-FILE   [no default]\n");
264             printf("\t\tThe name of a file to read trusted certificates from.\n");
265             printf("\t\tMay be given multiple times.\n");
266             printf("\tcrl=CRL-FILE    [no default]\n");
267             printf("\t\tThe name of a file to read revocation lists from.\n");
268             printf("\t\tMay be given multiple times.\n");
269             printf("\tport=PORT       [443]\n");
270             printf("\t\tThe TCP port to listen on.\n");
271             printf("\n");
272             printf("\tAll X.509 data files must be PEM-encoded.\n");
273             exit(0);
274         } else if(!strcmp(argp[i], "cert")) {
275             crtfile = argv[i];
276         } else if(!strcmp(argp[i], "key")) {
277             keyfile = argv[i];
278         } else if(!strcmp(argp[i], "trust")) {
279             if((ret = gnutls_certificate_set_x509_trust_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
280                 flog(LOG_ERR, "ssl: could not load trust file `%s': %s", argv[i], gnutls_strerror(ret));
281                 exit(1);
282             }
283         } else if(!strcmp(argp[i], "crl")) {
284             if((ret = gnutls_certificate_set_x509_crl_file(creds, argv[i], GNUTLS_X509_FMT_PEM)) != 0) {
285                 flog(LOG_ERR, "ssl: could not load CRL file `%s': %s", argv[i], gnutls_strerror(ret));
286                 exit(1);
287             }
288         } else if(!strcmp(argp[i], "port")) {
289             port = atoi(argv[i]);
290         } else {
291             flog(LOG_ERR, "unknown parameter `%s' to ssl handler", argp[i]);
292             exit(1);
293         }
294     }
295     if(crtfile == NULL) {
296         flog(LOG_ERR, "ssl: needs certificate file at the very least");
297         exit(1);
298     }
299     if(keyfile == NULL)
300         keyfile = crtfile;
301     if((ret = gnutls_certificate_set_x509_key_file(creds, crtfile, keyfile, GNUTLS_X509_FMT_PEM)) != 0) {
302         flog(LOG_ERR, "ssl: could not load certificate or key: %s", gnutls_strerror(ret));
303         exit(1);
304     }
305     gnutls_certificate_set_dh_params(creds, dhparams);
306     if((fd = listensock6(port)) < 0) {
307         flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
308         exit(1);
309     }
310     omalloc(pd);
311     pd->fd = fd;
312     pd->sport = port;
313     pd->creds = creds;
314     mustart(listenloop, pd);
315     if((fd = listensock6(port)) < 0) {
316         if(errno != EADDRINUSE) {
317             flog(LOG_ERR, "could not listen on IPv6 port (port %i): %s", port, strerror(errno));
318             exit(1);
319         }
320     } else {
321         omalloc(pd);
322         pd->fd = fd;
323         pd->sport = port;
324         pd->creds = creds;
325         mustart(listenloop, pd);
326     }
327 }
328
329 #endif