changing to use a separate client structure for each udp client
[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     BIO_dgram_set_peer(wbio, addr);
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 reply *reply;
217     
218     debug(DBG_DBG, "dtlsserverwr: starting for %s", client->conf->host);
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 reply *)list_shift(replyq->entries);
237         pthread_mutex_unlock(&replyq->mutex);
238         cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
239         if (cnt > 0)
240             debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d",
241                   cnt, RADLEN(reply->buf));
242         else
243             while ((error = ERR_get_error()))
244                 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
245         free(reply->buf);
246         free(reply);
247     }
248 }
249
250 void dtlsserverrd(struct client *client) {
251     struct request rq;
252     pthread_t dtlsserverwrth;
253     
254     debug(DBG_DBG, "dtlsserverrd: starting for %s", client->conf->host);
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         memset(&rq, 0, sizeof(struct request));
263         rq.buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
264         if (!rq.buf) {
265             debug(DBG_ERR, "dtlsserverrd: connection from %s lost", client->conf->host);
266             break;
267         }
268         debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", client->conf->host);
269         rq.from = client;
270         if (!radsrv(&rq)) {
271             debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
272             break;
273         }
274     }
275     
276     /* stop writer by setting ssl to NULL and give signal in case waiting for data */
277     client->ssl = NULL;
278
279     pthread_mutex_lock(&client->replyq->mutex);
280     pthread_cond_signal(&client->replyq->cond);
281     pthread_mutex_unlock(&client->replyq->mutex);
282     debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
283     pthread_join(dtlsserverwrth, NULL);
284     removeclientrqs(client);
285     debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", client->conf->host);
286 }
287
288 void *dtlsservernew(void *arg) {
289     struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
290     struct client *client;
291     struct clsrvconf *conf;
292     struct list_node *cur = NULL;
293     SSL *ssl = NULL;
294     X509 *cert = NULL;
295     uint8_t delay = 60;
296
297     debug(DBG_DBG, "dtlsservernew: starting");
298     conf = find_clconf(RAD_DTLS, (struct sockaddr *)&params->addr, NULL);
299     if (conf) {
300         ssl = dtlsacccon(1, conf->ssl_ctx, params->sock, (struct sockaddr *)&params->addr, params->sesscache->rbios);
301         if (!ssl)
302             goto exit;
303         cert = verifytlscert(ssl);
304         if (!cert)
305             goto exit;
306     }
307
308     while (conf) {
309         if (verifyconfcert(cert, conf)) {
310             X509_free(cert);
311             client = addclient(conf);
312             if (client) {
313                 client->sock = params->sock;
314                 client->rbios = params->sesscache->rbios;
315                 client->ssl = ssl;
316                 dtlsserverrd(client);
317                 removeclient(client);
318                 delay = 0;
319             } else {
320                 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
321             }
322             goto exit;
323         }
324         conf = find_clconf(RAD_DTLS, (struct sockaddr *)&params->addr, &cur);
325     }
326     debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
327
328     if (cert)
329         X509_free(cert);
330
331  exit:
332     if (ssl) {
333         SSL_shutdown(ssl);
334         SSL_free(ssl);
335     }
336     pthread_mutex_lock(&params->sesscache->mutex);
337     freebios(params->sesscache->rbios);
338     params->sesscache->rbios = NULL;
339     gettimeofday(&params->sesscache->expiry, NULL);
340     params->sesscache->expiry.tv_sec += delay;
341     pthread_mutex_unlock(&params->sesscache->mutex);
342     free(params);
343     ERR_remove_state(0);
344     pthread_exit(NULL);
345     debug(DBG_DBG, "dtlsservernew: exiting");
346 }
347
348 void cacheexpire(struct hash *cache, struct timeval *last) {
349     struct timeval now;
350     struct hash_entry *he;
351     struct sessioncacheentry *e;
352     
353     gettimeofday(&now, NULL);
354     if (now.tv_sec - last->tv_sec < 19)
355         return;
356
357     for (he = hash_first(cache); he; he = hash_next(he)) {
358         e = (struct sessioncacheentry *)he->data;
359         pthread_mutex_lock(&e->mutex);
360         if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
361             pthread_mutex_unlock(&e->mutex);
362             continue;
363         }
364         debug(DBG_DBG, "cacheexpire: freeing entry");
365         hash_extract(cache, he->key, he->keylen);
366         if (e->rbios) {
367             freebios(e->rbios);
368             e->rbios = NULL;
369         }
370         pthread_mutex_unlock(&e->mutex);
371         pthread_mutex_destroy(&e->mutex);
372     }
373     last->tv_sec = now.tv_sec;
374 }
375
376 void *udpdtlsserverrd(void *arg) {
377     int ndesc, cnt, s = *(int *)arg;
378     unsigned char buf[4];
379     struct sockaddr_storage from;
380     socklen_t fromlen = sizeof(from);
381     struct dtlsservernewparams *params;
382     fd_set readfds;
383     struct timeval timeout, lastexpiry;
384     pthread_t dtlsserverth;
385     struct hash *sessioncache;
386     struct sessioncacheentry *cacheentry;
387     
388     sessioncache = hash_create();
389     if (!sessioncache)
390         debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
391     gettimeofday(&lastexpiry, NULL);
392     
393     for (;;) {
394         FD_ZERO(&readfds);
395         FD_SET(s, &readfds);
396         memset(&timeout, 0, sizeof(struct timeval));
397         timeout.tv_sec = 60;
398         ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
399         if (ndesc < 1) {
400             cacheexpire(sessioncache, &lastexpiry);
401             continue;
402         }
403         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
404         if (cnt == -1) {
405             debug(DBG_WARN, "udpdtlsserverrd: recv failed");
406             cacheexpire(sessioncache, &lastexpiry);
407             continue;
408         }
409         cacheentry = hash_read(sessioncache, &from, fromlen);
410         if (cacheentry) {
411             debug(DBG_DBG, "udpdtlsserverrd: cache hit");
412             pthread_mutex_lock(&cacheentry->mutex);
413             if (cacheentry->rbios) {
414                 if (udp2bio(s, cacheentry->rbios, cnt))
415                     debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
416             } else
417                 recv(s, buf, 1, 0);
418             pthread_mutex_unlock(&cacheentry->mutex);
419             cacheexpire(sessioncache, &lastexpiry);
420             continue;
421         }
422
423         /* from new source */
424         debug(DBG_DBG, "udpdtlsserverrd: cache miss");
425         params = malloc(sizeof(struct dtlsservernewparams));
426         if (!params) {
427             cacheexpire(sessioncache, &lastexpiry);
428             recv(s, buf, 1, 0);
429             continue;
430         }
431         memset(params, 0, sizeof(struct dtlsservernewparams));
432         params->sesscache = malloc(sizeof(struct sessioncacheentry));
433         if (!params->sesscache) {
434             free(params);
435             cacheexpire(sessioncache, &lastexpiry);
436             recv(s, buf, 1, 0);
437             continue;
438         }
439         memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
440         pthread_mutex_init(&params->sesscache->mutex, NULL);
441         params->sesscache->rbios = newqueue();
442         if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
443             params->sock = s;
444             memcpy(&params->addr, &from, fromlen);
445
446             if (udp2bio(s, params->sesscache->rbios, cnt)) {
447                 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
448                 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
449                     pthread_detach(dtlsserverth);
450                     cacheexpire(sessioncache, &lastexpiry);
451                     continue;
452                 }
453                 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
454             }
455             hash_extract(sessioncache, &from, fromlen);
456         }
457         freebios(params->sesscache->rbios);
458         pthread_mutex_destroy(&params->sesscache->mutex);
459         free(params->sesscache);
460         free(params);
461         cacheexpire(sessioncache, &lastexpiry);
462     }
463 }
464
465 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
466     struct timeval now;
467     time_t elapsed;
468     X509 *cert;
469     
470     debug(DBG_DBG, "dtlsconnect: called from %s", text);
471     pthread_mutex_lock(&server->lock);
472     if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
473         /* already reconnected, nothing to do */
474         debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
475         pthread_mutex_unlock(&server->lock);
476         return 1;
477     }
478
479     for (;;) {
480         gettimeofday(&now, NULL);
481         elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
482
483         if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
484             debug(DBG_DBG, "dtlsconnect: timeout");
485             SSL_free(server->ssl);
486             server->ssl = NULL;
487             pthread_mutex_unlock(&server->lock);
488             return 0;
489         }
490
491         if (server->connectionok) {
492             server->connectionok = 0;
493             sleep(2);
494         } else if (elapsed < 1)
495             sleep(2);
496         else if (elapsed < 60) {
497             debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
498             sleep(elapsed);
499         } else if (elapsed < 100000) {
500             debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
501             sleep(60);
502         } else
503             server->lastconnecttry.tv_sec = now.tv_sec;  /* no sleep at startup */
504         debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
505
506         SSL_free(server->ssl);
507         server->ssl = dtlsacccon(0, server->conf->ssl_ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
508         if (!server->ssl)
509             continue;
510         debug(DBG_DBG, "dtlsconnect: DTLS: ok");
511         
512         cert = verifytlscert(server->ssl);
513         if (!cert)
514             continue;
515         
516         if (verifyconfcert(cert, server->conf))
517             break;
518         X509_free(cert);
519     }
520     X509_free(cert);
521     debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
522     gettimeofday(&server->lastconnecttry, NULL);
523     pthread_mutex_unlock(&server->lock);
524     return 1;
525 }
526
527 int clientradputdtls(struct server *server, unsigned char *rad) {
528     int cnt;
529     size_t len;
530     unsigned long error;
531     struct clsrvconf *conf = server->conf;
532
533     if (!server->ssl)
534         return 0;
535     len = RADLEN(rad);
536     while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
537         while ((error = ERR_get_error()))
538             debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
539     }
540     debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
541     return 1;
542 }
543
544 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
545 void *udpdtlsclientrd(void *arg) {
546     int cnt, s = *(int *)arg;
547     unsigned char buf[4];
548     struct sockaddr_storage from;
549     socklen_t fromlen = sizeof(from);
550     struct clsrvconf *conf;
551     fd_set readfds;
552     
553     for (;;) {
554         FD_ZERO(&readfds);
555         FD_SET(s, &readfds);
556         if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
557             continue;
558         cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
559         if (cnt == -1) {
560             debug(DBG_WARN, "udpdtlsclientrd: recv failed");
561             continue;
562         }
563         
564         conf = find_srvconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
565         if (!conf) {
566             debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
567             recv(s, buf, 4, 0);
568             continue;
569         }
570         if (udp2bio(s, conf->servers->rbios, cnt))
571             debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
572     }
573 }
574
575 void *dtlsclientrd(void *arg) {
576     struct server *server = (struct server *)arg;
577     unsigned char *buf;
578     struct timeval lastconnecttry;
579     int secs;
580     
581     for (;;) {
582         /* yes, lastconnecttry is really necessary */
583         lastconnecttry = server->lastconnecttry;
584         for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
585         if (!buf) {
586             dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
587             continue;
588         }
589         replyh(server, buf);
590     }
591     ERR_remove_state(0);
592     server->clientrdgone = 1;
593     return NULL;
594 }
595
596 void addserverextradtls(struct clsrvconf *conf) {
597     switch (conf->addrinfo->ai_family) {
598     case AF_INET:
599         if (client4_sock < 0) {
600             client4_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET, 0, 1);
601             if (client4_sock < 0)
602                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
603         }
604         conf->servers->sock = client4_sock;
605         break;
606     case AF_INET6:
607         if (client6_sock < 0) {
608             client6_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET6, 0, 1);
609             if (client6_sock < 0)
610                 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
611         }
612         conf->servers->sock = client6_sock;
613         break;
614     default:
615         debugx(1, DBG_ERR, "addserver: unsupported address family");
616     }
617 }
618
619 void initextradtls() {
620     pthread_t cl4th, cl6th;
621     
622     if (client4_sock >= 0)
623         if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
624             debugx(1, DBG_ERR, "pthread_create failed");
625     if (client6_sock >= 0)
626         if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
627             debugx(1, DBG_ERR, "pthread_create failed");
628 }