some code improvemetns, more efficiently removing outstanding requests when removing...
[radsecproxy.git] / dtls.c
1 /*
2  * Copyright (C) 2008 Stig Venaas <venaas@uninett.no>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  */
8
9 #include <signal.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <netdb.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <limits.h>
16 #ifdef SYS_SOLARIS9
17 #include <fcntl.h>
18 #endif
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #include <sys/select.h>
22 #include <ctype.h>
23 #include <sys/wait.h>
24 #include <arpa/inet.h>
25 #include <regex.h>
26 #include <pthread.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include "debug.h"
30 #include "list.h"
31 #include "hash.h"
32 #include "util.h"
33 #include "radsecproxy.h"
34 #include "dtls.h"
35
36 static int client4_sock = -1;
37 static int client6_sock = -1;
38
39 struct sessioncacheentry {
40     pthread_mutex_t mutex;
41     struct queue *rbios;
42     struct timeval expiry;
43 };
44
45 struct dtlsservernewparams {
46     struct sessioncacheentry *sesscache;
47     int sock;
48     struct sockaddr_storage addr;    
49 };
50
51 int udp2bio(int s, struct queue *q, int cnt) {
52     unsigned char *buf;
53     BIO *rbio;
54
55     if (cnt < 1)
56         return 0;
57     
58     buf = malloc(cnt);
59     if (!buf) {
60         unsigned char err;
61         debug(DBG_ERR, "udp2bio: malloc failed");
62         recv(s, &err, 1, 0);
63         return 0;
64     }
65
66     cnt = recv(s, buf, cnt, 0);
67     if (cnt < 1) {
68         debug(DBG_WARN, "udp2bio: recv failed");
69         free(buf);
70         return 0;
71     }
72
73     rbio = BIO_new_mem_buf(buf, cnt);
74     BIO_set_mem_eof_return(rbio, -1);
75
76     pthread_mutex_lock(&q->mutex);
77     if (!list_push(q->entries, rbio)) {
78         BIO_free(rbio);
79         pthread_mutex_unlock(&q->mutex);
80         return 0;
81     }
82     pthread_cond_signal(&q->cond);
83     pthread_mutex_unlock(&q->mutex);
84     return 1;
85 }
86
87 BIO *getrbio(SSL *ssl, struct queue *q, int timeout) {
88     BIO *rbio;
89     struct timeval now;
90     struct timespec to;
91
92     pthread_mutex_lock(&q->mutex);
93     if (!(rbio = (BIO *)list_shift(q->entries))) {
94         if (timeout) {
95             gettimeofday(&now, NULL);
96             memset(&to, 0, sizeof(struct timespec));
97             to.tv_sec = now.tv_sec + timeout;
98             pthread_cond_timedwait(&q->cond, &q->mutex, &to);
99         } else
100             pthread_cond_wait(&q->cond, &q->mutex);
101         rbio = (BIO *)list_shift(q->entries);
102     }
103     pthread_mutex_unlock(&q->mutex);
104     return rbio;
105 }
106
107 int dtlsread(SSL *ssl, struct queue *q, unsigned char *buf, int num, int timeout) {
108     int len, cnt;
109     BIO *rbio;
110     
111     for (len = 0; len < num; len += cnt) {
112         cnt = SSL_read(ssl, buf + len, num - len);
113         if (cnt <= 0)
114             switch (cnt = SSL_get_error(ssl, cnt)) {
115             case SSL_ERROR_WANT_READ:
116                 rbio = getrbio(ssl, q, timeout);
117                 if (!rbio)
118                     return 0;
119                 BIO_free(ssl->rbio);            
120                 ssl->rbio = rbio;
121                 cnt = 0;
122                 continue;
123             case SSL_ERROR_WANT_WRITE:
124                 cnt = 0;
125                 continue;
126             case SSL_ERROR_ZERO_RETURN:
127                 /* remote end sent close_notify, send one back */
128                 SSL_shutdown(ssl);
129                 return -1;
130             default:
131                 return -1;
132             }
133     }
134     return num;
135 }
136
137 /* accept if acc == 1, else connect */
138 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct queue *rbios) {
139     SSL *ssl;
140     int i, res;
141     unsigned long error;
142     BIO *mem0bio, *wbio;
143
144     ssl = SSL_new(ctx);
145     if (!ssl)
146         return NULL;
147     
148     mem0bio = BIO_new(BIO_s_mem());
149     BIO_set_mem_eof_return(mem0bio, -1);
150     wbio = BIO_new_dgram(s, BIO_NOCLOSE);
151     i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
152     SSL_set_bio(ssl, mem0bio, wbio);
153
154     for (i = 0; i < 5; i++) {
155         res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
156         if (res > 0)
157             return ssl;
158         if (res == 0)
159             break;
160         if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
161             BIO_free(ssl->rbio);
162             ssl->rbio = getrbio(ssl, rbios, 5);
163             if (!ssl->rbio)
164                 break;
165         }
166         while ((error = ERR_get_error()))
167             debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
168     }
169
170     SSL_free(ssl);
171     return NULL;
172 }
173
174 unsigned char *raddtlsget(SSL *ssl, struct queue *rbios, int timeout) {
175     int cnt, len;
176     unsigned char buf[4], *rad;
177
178     for (;;) {
179         cnt = dtlsread(ssl, rbios, buf, 4, timeout);
180         if (cnt < 1) {
181             debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
182             return NULL;
183         }
184
185         len = RADLEN(buf);
186         rad = malloc(len);
187         if (!rad) {
188             debug(DBG_ERR, "raddtlsget: malloc failed");
189             continue;
190         }
191         memcpy(rad, buf, 4);
192         
193         cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
194         if (cnt < 1) {
195             debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
196             free(rad);
197             return NULL;
198         }
199         
200         if (len >= 20)
201             break;
202         
203         free(rad);
204         debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
205     }
206     
207     debug(DBG_DBG, "raddtlsget: got %d bytes", len);
208     return rad;
209 }
210
211 void *dtlsserverwr(void *arg) {
212     int cnt;
213     unsigned long error;
214     struct client *client = (struct client *)arg;
215     struct queue *replyq;
216     struct request *reply;
217     
218     debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
219     replyq = client->replyq;
220     for (;;) {
221         pthread_mutex_lock(&replyq->mutex);
222         while (!list_first(replyq->entries)) {
223             if (client->ssl) {      
224                 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
225                 pthread_cond_wait(&replyq->cond, &replyq->mutex);
226                 debug(DBG_DBG, "dtlsserverwr: got signal");
227             }
228             if (!client->ssl) {
229                 /* ssl might have changed while waiting */
230                 pthread_mutex_unlock(&replyq->mutex);
231                 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
232                 ERR_remove_state(0);
233                 pthread_exit(NULL);
234             }
235         }
236         reply = (struct request *)list_shift(replyq->entries);
237         pthread_mutex_unlock(&replyq->mutex);
238         cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
239         if (cnt > 0)
240             debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
241                   cnt, RADLEN(reply->replybuf), addr2string(client->addr));
242         else
243             while ((error = ERR_get_error()))
244                 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
245         freerq(reply);
246     }
247 }
248
249 void dtlsserverrd(struct client *client) {
250     struct request *rq;
251     uint8_t *buf;
252     pthread_t dtlsserverwrth;
253     
254     debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
255
256     if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
257         debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
258         return;
259     }
260
261     for (;;) {
262         buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
263         if (!buf) {
264             debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
265             break;
266         }
267         debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
268         rq = newrequest();
269         if (!rq) {
270             free(buf);
271             continue;
272         }
273         rq->buf = buf;
274         rq->from = client;
275         if (!radsrv(rq)) {
276             debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
277             break;
278         }
279     }
280     
281     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
282     client->ssl = NULL;
283
284     pthread_mutex_lock(&client->replyq->mutex);
285     pthread_cond_signal(&client->replyq->cond);
286     pthread_mutex_unlock(&client->replyq->mutex);
287     debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
288     pthread_join(dtlsserverwrth, NULL);
289     debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
290 }
291
292 void *dtlsservernew(void *arg) {
293     struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
294     struct client *client;
295     struct clsrvconf *conf;
296     struct list_node *cur = NULL;
297     SSL *ssl = NULL;
298     X509 *cert = NULL;
299     SSL_CTX *ctx = NULL;
300     uint8_t delay = 60;
301
302     debug(DBG_DBG, "dtlsservernew: starting");
303     conf = find_clconf(RAD_DTLS, (struct sockaddr *)&params->addr, NULL);
304     if (conf) {
305         ctx = tlsgetctx(RAD_DTLS, conf->tlsconf);
306         if (!ctx)
307             goto exit;
308         ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)&params->addr, params->sesscache->rbios);
309         if (!ssl)
310             goto exit;
311         cert = verifytlscert(ssl);
312         if (!cert)
313             goto exit;
314     }
315
316     while (conf) {
317         if (verifyconfcert(cert, conf)) {
318             X509_free(cert);
319             client = addclient(conf, 1);
320             if (client) {
321                 client->sock = params->sock;
322                 client->addr = addr_copy((struct sockaddr *)&params->addr);
323                 client->rbios = params->sesscache->rbios;
324                 client->ssl = ssl;
325                 dtlsserverrd(client);
326                 removeclient(client);
327                 delay = 0;
328             } else {
329                 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
330             }
331             goto exit;
332         }
333         conf = find_clconf(RAD_DTLS, (struct sockaddr *)&params->addr, &cur);
334     }
335     debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
336
337     if (cert)
338         X509_free(cert);
339
340  exit:
341     if (ssl) {
342         SSL_shutdown(ssl);
343         SSL_free(ssl);
344     }
345     pthread_mutex_lock(&params->sesscache->mutex);
346     freebios(params->sesscache->rbios);
347     params->sesscache->rbios = NULL;
348     gettimeofday(&params->sesscache->expiry, NULL);
349     params->sesscache->expiry.tv_sec += delay;
350     pthread_mutex_unlock(&params->sesscache->mutex);
351     free(params);
352     ERR_remove_state(0);
353     pthread_exit(NULL);
354     debug(DBG_DBG, "dtlsservernew: exiting");
355 }
356
357 void cacheexpire(struct hash *cache, struct timeval *last) {
358     struct timeval now;
359     struct hash_entry *he;
360     struct sessioncacheentry *e;
361     
362     gettimeofday(&now, NULL);
363     if (now.tv_sec - last->tv_sec < 19)
364         return;
365
366     for (he = hash_first(cache); he; he = hash_next(he)) {
367         e = (struct sessioncacheentry *)he->data;
368         pthread_mutex_lock(&e->mutex);
369         if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
370             pthread_mutex_unlock(&e->mutex);
371             continue;
372         }
373         debug(DBG_DBG, "cacheexpire: freeing entry");
374         hash_extract(cache, he->key, he->keylen);
375         if (e->rbios) {
376             freebios(e->rbios);
377             e->rbios = NULL;
378         }
379         pthread_mutex_unlock(&e->mutex);
380         pthread_mutex_destroy(&e->mutex);
381     }
382     last->tv_sec = now.tv_sec;
383 }
384
385 void *udpdtlsserverrd(void *arg) {
386     int ndesc, cnt, s = *(int *)arg;
387     unsigned char buf[4];
388     struct sockaddr_storage from;
389     socklen_t fromlen = sizeof(from);
390     struct dtlsservernewparams *params;
391     fd_set readfds;
392     struct timeval timeout, lastexpiry;
393     pthread_t dtlsserverth;
394     struct hash *sessioncache;
395     struct sessioncacheentry *cacheentry;
396     
397     sessioncache = hash_create();
398     if (!sessioncache)
399         debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
400     gettimeofday(&lastexpiry, NULL);
401     
402     for (;;) {
403         FD_ZERO(&readfds);
404         FD_SET(s, &readfds);
405         memset(&timeout, 0, sizeof(struct timeval));
406         timeout.tv_sec = 60;
407         ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
408         if (ndesc < 1) {
409             cacheexpire(sessioncache, &lastexpiry);
410             continue;
411         }
412         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
413         if (cnt == -1) {
414             debug(DBG_WARN, "udpdtlsserverrd: recv failed");
415             cacheexpire(sessioncache, &lastexpiry);
416             continue;
417         }
418         cacheentry = hash_read(sessioncache, &from, fromlen);
419         if (cacheentry) {
420             debug(DBG_DBG, "udpdtlsserverrd: cache hit");
421             pthread_mutex_lock(&cacheentry->mutex);
422             if (cacheentry->rbios) {
423                 if (udp2bio(s, cacheentry->rbios, cnt))
424                     debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
425             } else
426                 recv(s, buf, 1, 0);
427             pthread_mutex_unlock(&cacheentry->mutex);
428             cacheexpire(sessioncache, &lastexpiry);
429             continue;
430         }
431
432         /* from new source */
433         debug(DBG_DBG, "udpdtlsserverrd: cache miss");
434         params = malloc(sizeof(struct dtlsservernewparams));
435         if (!params) {
436             cacheexpire(sessioncache, &lastexpiry);
437             recv(s, buf, 1, 0);
438             continue;
439         }
440         memset(params, 0, sizeof(struct dtlsservernewparams));
441         params->sesscache = malloc(sizeof(struct sessioncacheentry));
442         if (!params->sesscache) {
443             free(params);
444             cacheexpire(sessioncache, &lastexpiry);
445             recv(s, buf, 1, 0);
446             continue;
447         }
448         memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
449         pthread_mutex_init(&params->sesscache->mutex, NULL);
450         params->sesscache->rbios = newqueue();
451         if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
452             params->sock = s;
453             memcpy(&params->addr, &from, fromlen);
454
455             if (udp2bio(s, params->sesscache->rbios, cnt)) {
456                 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
457                 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
458                     pthread_detach(dtlsserverth);
459                     cacheexpire(sessioncache, &lastexpiry);
460                     continue;
461                 }
462                 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
463             }
464             hash_extract(sessioncache, &from, fromlen);
465         }
466         freebios(params->sesscache->rbios);
467         pthread_mutex_destroy(&params->sesscache->mutex);
468         free(params->sesscache);
469         free(params);
470         cacheexpire(sessioncache, &lastexpiry);
471     }
472 }
473
474 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
475     struct timeval now;
476     time_t elapsed;
477     X509 *cert;
478     SSL_CTX *ctx = NULL;
479
480     debug(DBG_DBG, "dtlsconnect: called from %s", text);
481     pthread_mutex_lock(&server->lock);
482     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
483         /* already reconnected, nothing to do */
484         debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
485         pthread_mutex_unlock(&server->lock);
486         return 1;
487     }
488
489     for (;;) {
490         gettimeofday(&now, NULL);
491         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
492
493         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
494             debug(DBG_DBG, "dtlsconnect: timeout");
495             SSL_free(server->ssl);
496             server->ssl = NULL;
497             pthread_mutex_unlock(&server->lock);
498             return 0;
499         }
500
501         if (server->connectionok) {
502             server->connectionok = 0;
503             sleep(2);
504         } else if (elapsed < 1)
505             sleep(2);
506         else if (elapsed < 60) {
507             debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
508             sleep(elapsed);
509         } else if (elapsed < 100000) {
510             debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
511             sleep(60);
512         } else
513             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
514         debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
515
516         SSL_free(server->ssl);
517         server->ssl = NULL;
518         ctx = tlsgetctx(RAD_DTLS, server->conf->tlsconf);
519         if (!ctx)
520             continue;
521         server->ssl = dtlsacccon(0, ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
522         if (!server->ssl)
523             continue;
524         debug(DBG_DBG, "dtlsconnect: DTLS: ok");
525         
526         cert = verifytlscert(server->ssl);
527         if (!cert)
528             continue;
529         
530         if (verifyconfcert(cert, server->conf))
531             break;
532         X509_free(cert);
533     }
534     X509_free(cert);
535     debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
536     server->connectionok = 1;
537     gettimeofday(&server->lastconnecttry, NULL);
538     pthread_mutex_unlock(&server->lock);
539     return 1;
540 }
541
542 int clientradputdtls(struct server *server, unsigned char *rad) {
543     int cnt;
544     size_t len;
545     unsigned long error;
546     struct clsrvconf *conf = server->conf;
547
548     if (!server->connectionok)
549         return 0;
550     len = RADLEN(rad);
551     if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
552         while ((error = ERR_get_error()))
553             debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
554         return 0;
555     }
556     debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
557     return 1;
558 }
559
560 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
561 void *udpdtlsclientrd(void *arg) {
562     int cnt, s = *(int *)arg;
563     unsigned char buf[4];
564     struct sockaddr_storage from;
565     socklen_t fromlen = sizeof(from);
566     struct clsrvconf *conf;
567     fd_set readfds;
568     
569     for (;;) {
570         FD_ZERO(&readfds);
571         FD_SET(s, &readfds);
572         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
573             continue;
574         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
575         if (cnt == -1) {
576             debug(DBG_WARN, "udpdtlsclientrd: recv failed");
577             continue;
578         }
579         
580         conf = find_srvconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
581         if (!conf) {
582             debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
583             recv(s, buf, 4, 0);
584             continue;
585         }
586         if (udp2bio(s, conf->servers->rbios, cnt))
587             debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
588     }
589 }
590
591 void *dtlsclientrd(void *arg) {
592     struct server *server = (struct server *)arg;
593     unsigned char *buf;
594     struct timeval lastconnecttry;
595     int secs;
596     
597     for (;;) {
598         /* yes, lastconnecttry is really necessary */
599         lastconnecttry = server->lastconnecttry;
600         for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
601         if (!buf) {
602             dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
603             continue;
604         }
605         replyh(server, buf);
606     }
607     ERR_remove_state(0);
608     server->clientrdgone = 1;
609     return NULL;
610 }
611
612 void addserverextradtls(struct clsrvconf *conf) {
613     switch (conf->addrinfo->ai_family) {
614     case AF_INET:
615         if (client4_sock < 0) {
616             client4_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET, 0, 1);
617             if (client4_sock < 0)
618                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
619         }
620         conf->servers->sock = client4_sock;
621         break;
622     case AF_INET6:
623         if (client6_sock < 0) {
624             client6_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET6, 0, 1);
625             if (client6_sock < 0)
626                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
627         }
628         conf->servers->sock = client6_sock;
629         break;
630     default:
631         debugx(1, DBG_ERR, "addserver: unsupported address family");
632     }
633 }
634
635 void initextradtls() {
636     pthread_t cl4th, cl6th;
637     
638     if (client4_sock >= 0)
639         if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
640             debugx(1, DBG_ERR, "pthread_create failed");
641     if (client6_sock >= 0)
642         if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
643             debugx(1, DBG_ERR, "pthread_create failed");
644 }