WIP: Fix the Proxy-State issue.
[libradsec.git] / tls.c
1 /* Copyright (c) 2007-2009, UNINETT AS
2  * Copyright (c) 2012, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
4
5 #include <signal.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netdb.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <limits.h>
12 #ifdef SYS_SOLARIS9
13 #include <fcntl.h>
14 #endif
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <sys/select.h>
18 #include <ctype.h>
19 #include <sys/wait.h>
20 #include <arpa/inet.h>
21 #include <regex.h>
22 #include <pthread.h>
23 #include <openssl/ssl.h>
24 #include <openssl/err.h>
25 #include "radsecproxy.h"
26 #include "hostport.h"
27
28 #ifdef RADPROT_TLS
29 #include "debug.h"
30 #include "util.h"
31
32 static void setprotoopts(struct commonprotoopts *opts);
33 static char **getlistenerargs();
34 void *tlslistener(void *arg);
35 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
36 void *tlsclientrd(void *arg);
37 int clientradputtls(struct server *server, unsigned char *rad);
38 void tlssetsrcres();
39
40 static const struct protodefs protodefs = {
41     "tls",
42     "radsec", /* secretdefault */
43     SOCK_STREAM, /* socktype */
44     "2083", /* portdefault */
45     0, /* retrycountdefault */
46     0, /* retrycountmax */
47     REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
48     60, /* retryintervalmax */
49     DUPLICATE_INTERVAL, /* duplicateintervaldefault */
50     setprotoopts, /* setprotoopts */
51     getlistenerargs, /* getlistenerargs */
52     tlslistener, /* listener */
53     tlsconnect, /* connecter */
54     tlsclientrd, /* clientconnreader */
55     clientradputtls, /* clientradput */
56     NULL, /* addclient */
57     NULL, /* addserverextra */
58     tlssetsrcres, /* setsrcres */
59     NULL /* initextra */
60 };
61
62 static struct addrinfo *srcres = NULL;
63 static uint8_t handle;
64 static struct commonprotoopts *protoopts = NULL;
65
66 const struct protodefs *tlsinit(uint8_t h) {
67     handle = h;
68     return &protodefs;
69 }
70
71 static void setprotoopts(struct commonprotoopts *opts) {
72     protoopts = opts;
73 }
74
75 static char **getlistenerargs() {
76     return protoopts ? protoopts->listenargs : NULL;
77 }
78
79 void tlssetsrcres() {
80     if (!srcres)
81         srcres =
82             resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
83                                    AF_UNSPEC, NULL, protodefs.socktype);
84 }
85
86 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
87     struct timeval now;
88     time_t elapsed;
89     X509 *cert;
90     SSL_CTX *ctx = NULL;
91     unsigned long error;
92
93     debug(DBG_DBG, "tlsconnect: called from %s", text);
94     pthread_mutex_lock(&server->lock);
95     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
96         /* already reconnected, nothing to do */
97         debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
98         pthread_mutex_unlock(&server->lock);
99         return 1;
100     }
101
102     for (;;) {
103         gettimeofday(&now, NULL);
104         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
105         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
106             debug(DBG_DBG, "tlsconnect: timeout");
107             if (server->sock >= 0)
108                 close(server->sock);
109             SSL_free(server->ssl);
110             server->ssl = NULL;
111             pthread_mutex_unlock(&server->lock);
112             return 0;
113         }
114         if (server->connectionok) {
115             server->connectionok = 0;
116             sleep(2);
117         } else if (elapsed < 1)
118             sleep(2);
119         else if (elapsed < 60) {
120             debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
121             sleep(elapsed);
122         } else if (elapsed < 100000) {
123             debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
124             sleep(60);
125         } else
126             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
127
128         if (server->sock >= 0)
129             close(server->sock);
130         if ((server->sock = connecttcphostlist(server->conf->hostports, srcres)) < 0)
131             continue;
132
133         SSL_free(server->ssl);
134         server->ssl = NULL;
135         ctx = tlsgetctx(handle, server->conf->tlsconf);
136         if (!ctx)
137             continue;
138         server->ssl = SSL_new(ctx);
139         if (!server->ssl)
140             continue;
141
142         SSL_set_fd(server->ssl, server->sock);
143         if (SSL_connect(server->ssl) <= 0) {
144             while ((error = ERR_get_error()))
145                 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
146             continue;
147         }
148         cert = verifytlscert(server->ssl);
149         if (!cert)
150             continue;
151         if (verifyconfcert(cert, server->conf)) {
152             X509_free(cert);
153             break;
154         }
155         X509_free(cert);
156     }
157     debug(DBG_WARN, "tlsconnect: TLS connection to %s up", server->conf->name);
158     server->connectionok = 1;
159     gettimeofday(&server->lastconnecttry, NULL);
160     pthread_mutex_unlock(&server->lock);
161     return 1;
162 }
163
164 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
165 /* returns 0 on timeout, -1 on error and num if ok */
166 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
167     int s, ndesc, cnt, len;
168     fd_set readfds;
169     struct timeval timer;
170
171     s = SSL_get_fd(ssl);
172     if (s < 0)
173         return -1;
174     /* make socket non-blocking? */
175     for (len = 0; len < num; len += cnt) {
176         if (SSL_pending(ssl) == 0) {
177             FD_ZERO(&readfds);
178             FD_SET(s, &readfds);
179             if (timeout) {
180                 timer.tv_sec = timeout;
181                 timer.tv_usec = 0;
182             }
183             ndesc = select(s + 1, &readfds, NULL, NULL, timeout ? &timer : NULL);
184             if (ndesc < 1)
185                 return ndesc;
186         }
187
188         cnt = SSL_read(ssl, buf + len, num - len);
189         if (cnt <= 0)
190             switch (SSL_get_error(ssl, cnt)) {
191             case SSL_ERROR_WANT_READ:
192             case SSL_ERROR_WANT_WRITE:
193                 cnt = 0;
194                 continue;
195             case SSL_ERROR_ZERO_RETURN:
196                 /* remote end sent close_notify, send one back */
197                 SSL_shutdown(ssl);
198                 return -1;
199             default:
200                 return -1;
201             }
202     }
203     return num;
204 }
205
206 /* timeout in seconds, 0 means no timeout (blocking) */
207 unsigned char *radtlsget(SSL *ssl, int timeout) {
208     int cnt, len;
209     unsigned char buf[4], *rad;
210
211     for (;;) {
212         cnt = sslreadtimeout(ssl, buf, 4, timeout);
213         if (cnt < 1) {
214             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
215             return NULL;
216         }
217
218         len = RADLEN(buf);
219         rad = malloc(len);
220         if (!rad) {
221             debug(DBG_ERR, "radtlsget: malloc failed");
222             continue;
223         }
224         memcpy(rad, buf, 4);
225
226         cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
227         if (cnt < 1) {
228             debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
229             free(rad);
230             return NULL;
231         }
232
233         if (len >= 20)
234             break;
235
236         free(rad);
237         debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
238     }
239
240     debug(DBG_DBG, "radtlsget: got %d bytes", len);
241     return rad;
242 }
243
244 int clientradputtls(struct server *server, unsigned char *rad) {
245     int cnt;
246     size_t len;
247     unsigned long error;
248     struct clsrvconf *conf = server->conf;
249
250     if (!server->connectionok)
251         return 0;
252     len = RADLEN(rad);
253     if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
254         while ((error = ERR_get_error()))
255             debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
256         return 0;
257     }
258
259     debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->name);
260     return 1;
261 }
262
263 void *tlsclientrd(void *arg) {
264     struct server *server = (struct server *)arg;
265     unsigned char *buf;
266     struct timeval now, lastconnecttry;
267
268     for (;;) {
269         /* yes, lastconnecttry is really necessary */
270         lastconnecttry = server->lastconnecttry;
271         buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
272         if (!buf) {
273             if (server->dynamiclookuparg)
274                 break;
275             tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
276             continue;
277         }
278
279         replyh(server, buf);
280
281         if (server->dynamiclookuparg) {
282             gettimeofday(&now, NULL);
283             if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
284                 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
285                 break;
286             }
287         }
288     }
289     debug(DBG_INFO, "tlsclientrd: exiting for %s", server->conf->name);
290     ERR_remove_state(0);
291     SSL_shutdown(server->ssl);
292     shutdown(server->sock, SHUT_RDWR);
293     close(server->sock);
294
295     /* Wake up clientwr(). */
296     server->clientrdgone = 1;
297     pthread_mutex_lock(&server->newrq_mutex);
298     pthread_cond_signal(&server->newrq_cond);
299     pthread_mutex_unlock(&server->newrq_mutex);
300     return NULL;
301 }
302
303 void *tlsserverwr(void *arg) {
304     int cnt;
305     unsigned long error;
306     struct client *client = (struct client *)arg;
307     struct gqueue *replyq;
308     struct request *reply;
309
310     debug(DBG_DBG, "tlsserverwr: starting for %s", addr2string(client->addr));
311     replyq = client->replyq;
312     for (;;) {
313         pthread_mutex_lock(&replyq->mutex);
314         while (!list_first(replyq->entries)) {
315             if (client->ssl) {
316                 debug(DBG_DBG, "tlsserverwr: waiting for signal");
317                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
318                 debug(DBG_DBG, "tlsserverwr: got signal");
319             }
320             if (!client->ssl) {
321                 /* ssl might have changed while waiting */
322                 pthread_mutex_unlock(&replyq->mutex);
323                 debug(DBG_DBG, "tlsserverwr: exiting as requested");
324                 ERR_remove_state(0);
325                 pthread_exit(NULL);
326             }
327         }
328         reply = (struct request *)list_shift(replyq->entries);
329         pthread_mutex_unlock(&replyq->mutex);
330         cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
331         if (cnt > 0)
332             debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d to %s",
333                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
334         else
335             while ((error = ERR_get_error()))
336                 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
337         freerq(reply);
338     }
339 }
340
341 void tlsserverrd(struct client *client) {
342     struct request *rq;
343     uint8_t *buf;
344     pthread_t tlsserverwrth;
345
346     debug(DBG_DBG, "tlsserverrd: starting for %s", addr2string(client->addr));
347
348     if (pthread_create(&tlsserverwrth, &pthread_attr, tlsserverwr, (void *)client)) {
349         debug(DBG_ERR, "tlsserverrd: pthread_create failed");
350         return;
351     }
352
353     for (;;) {
354         buf = radtlsget(client->ssl, IDLE_TIMEOUT * 3);
355         if (!buf) {
356             debug(DBG_ERR, "tlsserverrd: connection from %s lost", addr2string(client->addr));
357             break;
358         }
359         debug(DBG_DBG, "tlsserverrd: got Radius message from %s", addr2string(client->addr));
360         rq = newrequest();
361         if (!rq) {
362             free(buf);
363             continue;
364         }
365         rq->buf = buf;
366         rq->from = client;
367         if (!radsrv(rq)) {
368             debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
369             break;
370         }
371     }
372
373     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
374     client->ssl = NULL;
375     pthread_mutex_lock(&client->replyq->mutex);
376     pthread_cond_signal(&client->replyq->cond);
377     pthread_mutex_unlock(&client->replyq->mutex);
378     debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
379     pthread_join(tlsserverwrth, NULL);
380     debug(DBG_DBG, "tlsserverrd: reader for %s exiting", addr2string(client->addr));
381 }
382
383 void *tlsservernew(void *arg) {
384     int s;
385     struct sockaddr_storage from;
386     socklen_t fromlen = sizeof(from);
387     struct clsrvconf *conf;
388     struct list_node *cur = NULL;
389     SSL *ssl = NULL;
390     X509 *cert = NULL;
391     SSL_CTX *ctx = NULL;
392     unsigned long error;
393     struct client *client;
394     struct tls *accepted_tls = NULL;
395
396     s = *(int *)arg;
397     if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
398         debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
399         goto exit;
400     }
401     debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from));
402
403     conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
404     if (conf) {
405         ctx = tlsgetctx(handle, conf->tlsconf);
406         if (!ctx)
407             goto exit;
408         ssl = SSL_new(ctx);
409         if (!ssl)
410             goto exit;
411         SSL_set_fd(ssl, s);
412
413         if (SSL_accept(ssl) <= 0) {
414             while ((error = ERR_get_error()))
415                 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
416             debug(DBG_ERR, "tlsservernew: SSL_accept failed");
417             goto exit;
418         }
419         cert = verifytlscert(ssl);
420         if (!cert)
421             goto exit;
422         accepted_tls = conf->tlsconf;
423     }
424
425     while (conf) {
426         if (accepted_tls == conf->tlsconf && verifyconfcert(cert, conf)) {
427             X509_free(cert);
428             client = addclient(conf, 1);
429             if (client) {
430                 client->ssl = ssl;
431                 client->addr = addr_copy((struct sockaddr *)&from);
432                 tlsserverrd(client);
433                 removeclient(client);
434             } else
435                 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
436             goto exit;
437         }
438         conf = find_clconf(handle, (struct sockaddr *)&from, &cur);
439     }
440     debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
441     if (cert)
442         X509_free(cert);
443
444 exit:
445     if (ssl) {
446         SSL_shutdown(ssl);
447         SSL_free(ssl);
448     }
449     ERR_remove_state(0);
450     shutdown(s, SHUT_RDWR);
451     close(s);
452     pthread_exit(NULL);
453 }
454
455 void *tlslistener(void *arg) {
456     pthread_t tlsserverth;
457     int s, *sp = (int *)arg;
458     struct sockaddr_storage from;
459     socklen_t fromlen = sizeof(from);
460
461     listen(*sp, 0);
462
463     for (;;) {
464         s = accept(*sp, (struct sockaddr *)&from, &fromlen);
465         if (s < 0) {
466             debug(DBG_WARN, "accept failed");
467             continue;
468         }
469         if (pthread_create(&tlsserverth, &pthread_attr, tlsservernew, (void *)&s)) {
470             debug(DBG_ERR, "tlslistener: pthread_create failed");
471             shutdown(s, SHUT_RDWR);
472             close(s);
473             continue;
474         }
475         pthread_detach(tlsserverth);
476     }
477     free(sp);
478     return NULL;
479 }
480 #else
481 const struct protodefs *tlsinit(uint8_t h) {
482     return NULL;
483 }
484 #endif
485
486 /* Local Variables: */
487 /* c-file-style: "stroustrup" */
488 /* End: */