2 * Copyright (C) 2008-2009 Stig Venaas <venaas@uninett.no>
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.
10 #include <sys/socket.h>
11 #include <netinet/in.h>
20 #include <sys/types.h>
21 #include <sys/select.h>
24 #include <arpa/inet.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
30 #include "radsecproxy.h"
37 static void setprotoopts(struct commonprotoopts *opts);
38 static char **getlistenerargs();
39 void *udpdtlsserverrd(void *arg);
40 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
41 void *dtlsclientrd(void *arg);
42 int clientradputdtls(struct server *server, unsigned char *rad);
43 void addserverextradtls(struct clsrvconf *conf);
47 static const struct protodefs protodefs = {
49 "radsec", /* secretdefault */
50 SOCK_DGRAM, /* socktype */
51 "2083", /* portdefault */
52 REQUEST_RETRY_COUNT, /* retrycountdefault */
53 10, /* retrycountmax */
54 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
55 60, /* retryintervalmax */
56 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
57 setprotoopts, /* setprotoopts */
58 getlistenerargs, /* getlistenerargs */
59 udpdtlsserverrd, /* listener */
60 dtlsconnect, /* connecter */
61 dtlsclientrd, /* clientconnreader */
62 clientradputdtls, /* clientradput */
64 addserverextradtls, /* addserverextra */
65 dtlssetsrcres, /* setsrcres */
66 initextradtls /* initextra */
69 static int client4_sock = -1;
70 static int client6_sock = -1;
71 static struct addrinfo *srcres = NULL;
72 static uint8_t handle;
73 static struct commonprotoopts *protoopts = NULL;
75 const struct protodefs *dtlsinit(uint8_t h) {
80 static void setprotoopts(struct commonprotoopts *opts) {
84 static char **getlistenerargs() {
85 return protoopts ? protoopts->listenargs : NULL;
88 struct sessioncacheentry {
89 pthread_mutex_t mutex;
91 struct timeval expiry;
94 struct dtlsservernewparams {
95 struct sessioncacheentry *sesscache;
97 struct sockaddr_storage addr;
100 void dtlssetsrcres() {
103 resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
104 AF_UNSPEC, NULL, protodefs.socktype);
107 int udp2bio(int s, struct gqueue *q, int cnt) {
117 debug(DBG_ERR, "udp2bio: malloc failed");
122 cnt = recv(s, buf, cnt, 0);
124 debug(DBG_WARN, "udp2bio: recv failed");
129 rbio = BIO_new_mem_buf(buf, cnt);
130 BIO_set_mem_eof_return(rbio, -1);
132 pthread_mutex_lock(&q->mutex);
133 if (!list_push(q->entries, rbio)) {
135 pthread_mutex_unlock(&q->mutex);
138 pthread_cond_signal(&q->cond);
139 pthread_mutex_unlock(&q->mutex);
143 BIO *getrbio(SSL *ssl, struct gqueue *q, int timeout) {
148 pthread_mutex_lock(&q->mutex);
149 if (!(rbio = (BIO *)list_shift(q->entries))) {
151 gettimeofday(&now, NULL);
152 memset(&to, 0, sizeof(struct timespec));
153 to.tv_sec = now.tv_sec + timeout;
154 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
156 pthread_cond_wait(&q->cond, &q->mutex);
157 rbio = (BIO *)list_shift(q->entries);
159 pthread_mutex_unlock(&q->mutex);
163 int dtlsread(SSL *ssl, struct gqueue *q, unsigned char *buf, int num, int timeout) {
167 for (len = 0; len < num; len += cnt) {
168 cnt = SSL_read(ssl, buf + len, num - len);
170 switch (cnt = SSL_get_error(ssl, cnt)) {
171 case SSL_ERROR_WANT_READ:
172 rbio = getrbio(ssl, q, timeout);
179 case SSL_ERROR_WANT_WRITE:
182 case SSL_ERROR_ZERO_RETURN:
183 /* remote end sent close_notify, send one back */
193 /* accept if acc == 1, else connect */
194 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct gqueue *rbios) {
204 mem0bio = BIO_new(BIO_s_mem());
205 BIO_set_mem_eof_return(mem0bio, -1);
206 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
207 i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
208 SSL_set_bio(ssl, mem0bio, wbio);
210 for (i = 0; i < 5; i++) {
211 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
216 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
218 ssl->rbio = getrbio(ssl, rbios, 5);
222 while ((error = ERR_get_error()))
223 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
230 unsigned char *raddtlsget(SSL *ssl, struct gqueue *rbios, int timeout) {
232 unsigned char buf[4], *rad;
235 cnt = dtlsread(ssl, rbios, buf, 4, timeout);
237 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
244 debug(DBG_ERR, "raddtlsget: malloc failed");
249 cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
251 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
260 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
263 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
267 void *dtlsserverwr(void *arg) {
270 struct client *client = (struct client *)arg;
271 struct gqueue *replyq;
272 struct request *reply;
274 debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
275 replyq = client->replyq;
277 pthread_mutex_lock(&replyq->mutex);
278 while (!list_first(replyq->entries)) {
280 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
281 pthread_cond_wait(&replyq->cond, &replyq->mutex);
282 debug(DBG_DBG, "dtlsserverwr: got signal");
285 /* ssl might have changed while waiting */
286 pthread_mutex_unlock(&replyq->mutex);
287 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
292 reply = (struct request *)list_shift(replyq->entries);
293 pthread_mutex_unlock(&replyq->mutex);
294 cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
296 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
297 cnt, RADLEN(reply->replybuf), addr2string(client->addr));
299 while ((error = ERR_get_error()))
300 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
305 void dtlsserverrd(struct client *client) {
308 pthread_t dtlsserverwrth;
310 debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
312 if (pthread_create(&dtlsserverwrth, &pthread_attr, dtlsserverwr, (void *)client)) {
313 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
318 buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
320 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
323 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
332 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
337 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
340 pthread_mutex_lock(&client->replyq->mutex);
341 pthread_cond_signal(&client->replyq->cond);
342 pthread_mutex_unlock(&client->replyq->mutex);
343 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
344 pthread_join(dtlsserverwrth, NULL);
345 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
348 void *dtlsservernew(void *arg) {
349 struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
350 struct client *client;
351 struct clsrvconf *conf;
352 struct list_node *cur = NULL;
357 struct tls *accepted_tls = NULL;
359 debug(DBG_DBG, "dtlsservernew: starting");
360 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, NULL);
362 ctx = tlsgetctx(handle, conf->tlsconf);
365 ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
368 cert = verifytlscert(ssl);
371 accepted_tls = conf->tlsconf;
375 if (accepted_tls == conf->tlsconf && verifyconfcert(cert, conf)) {
377 client = addclient(conf, 1);
379 client->sock = params->sock;
380 client->addr = addr_copy((struct sockaddr *)¶ms->addr);
381 client->rbios = params->sesscache->rbios;
383 dtlsserverrd(client);
384 removeclient(client);
387 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
391 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, &cur);
393 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
403 pthread_mutex_lock(¶ms->sesscache->mutex);
404 freebios(params->sesscache->rbios);
405 params->sesscache->rbios = NULL;
406 gettimeofday(¶ms->sesscache->expiry, NULL);
407 params->sesscache->expiry.tv_sec += delay;
408 pthread_mutex_unlock(¶ms->sesscache->mutex);
412 debug(DBG_DBG, "dtlsservernew: exiting");
415 void cacheexpire(struct hash *cache, struct timeval *last) {
417 struct hash_entry *he;
418 struct sessioncacheentry *e;
420 gettimeofday(&now, NULL);
421 if (now.tv_sec - last->tv_sec < 19)
424 for (he = hash_first(cache); he; he = hash_next(he)) {
425 e = (struct sessioncacheentry *)he->data;
426 pthread_mutex_lock(&e->mutex);
427 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
428 pthread_mutex_unlock(&e->mutex);
431 debug(DBG_DBG, "cacheexpire: freeing entry");
432 hash_extract(cache, he->key, he->keylen);
437 pthread_mutex_unlock(&e->mutex);
438 pthread_mutex_destroy(&e->mutex);
440 last->tv_sec = now.tv_sec;
443 void *udpdtlsserverrd(void *arg) {
444 int ndesc, cnt, s = *(int *)arg;
445 unsigned char buf[4];
446 struct sockaddr_storage from;
447 socklen_t fromlen = sizeof(from);
448 struct dtlsservernewparams *params;
450 struct timeval timeout, lastexpiry;
451 pthread_t dtlsserverth;
452 struct hash *sessioncache;
453 struct sessioncacheentry *cacheentry;
455 sessioncache = hash_create();
457 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
458 gettimeofday(&lastexpiry, NULL);
463 memset(&timeout, 0, sizeof(struct timeval));
465 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
467 cacheexpire(sessioncache, &lastexpiry);
470 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
472 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
473 cacheexpire(sessioncache, &lastexpiry);
476 cacheentry = hash_read(sessioncache, &from, fromlen);
478 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
479 pthread_mutex_lock(&cacheentry->mutex);
480 if (cacheentry->rbios) {
481 if (udp2bio(s, cacheentry->rbios, cnt))
482 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
485 pthread_mutex_unlock(&cacheentry->mutex);
486 cacheexpire(sessioncache, &lastexpiry);
490 /* from new source */
491 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
492 params = malloc(sizeof(struct dtlsservernewparams));
494 cacheexpire(sessioncache, &lastexpiry);
498 memset(params, 0, sizeof(struct dtlsservernewparams));
499 params->sesscache = malloc(sizeof(struct sessioncacheentry));
500 if (!params->sesscache) {
502 cacheexpire(sessioncache, &lastexpiry);
506 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
507 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
508 params->sesscache->rbios = newqueue();
509 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
511 memcpy(¶ms->addr, &from, fromlen);
513 if (udp2bio(s, params->sesscache->rbios, cnt)) {
514 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
515 if (!pthread_create(&dtlsserverth, &pthread_attr, dtlsservernew, (void *)params)) {
516 pthread_detach(dtlsserverth);
517 cacheexpire(sessioncache, &lastexpiry);
520 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
522 hash_extract(sessioncache, &from, fromlen);
524 freebios(params->sesscache->rbios);
525 pthread_mutex_destroy(¶ms->sesscache->mutex);
526 free(params->sesscache);
528 cacheexpire(sessioncache, &lastexpiry);
532 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
537 struct hostportres *hp;
539 debug(DBG_DBG, "dtlsconnect: called from %s", text);
540 pthread_mutex_lock(&server->lock);
541 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
542 /* already reconnected, nothing to do */
543 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
544 pthread_mutex_unlock(&server->lock);
548 hp = (struct hostportres *)list_first(server->conf->hostports)->data;
550 gettimeofday(&now, NULL);
551 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
553 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
554 debug(DBG_DBG, "dtlsconnect: timeout");
555 SSL_free(server->ssl);
557 pthread_mutex_unlock(&server->lock);
561 if (server->connectionok) {
562 server->connectionok = 0;
564 } else if (elapsed < 1)
566 else if (elapsed < 60) {
567 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
569 } else if (elapsed < 100000) {
570 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
573 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
574 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
576 SSL_free(server->ssl);
578 ctx = tlsgetctx(handle, server->conf->tlsconf);
581 server->ssl = dtlsacccon(0, ctx, server->sock, hp->addrinfo->ai_addr, server->rbios);
584 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
586 cert = verifytlscert(server->ssl);
590 if (verifyconfcert(cert, server->conf))
595 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", hp->host, hp->port);
596 server->connectionok = 1;
597 gettimeofday(&server->lastconnecttry, NULL);
598 pthread_mutex_unlock(&server->lock);
602 int clientradputdtls(struct server *server, unsigned char *rad) {
606 struct clsrvconf *conf = server->conf;
608 if (!server->connectionok)
611 if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
612 while ((error = ERR_get_error()))
613 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
616 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
620 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
621 void *udpdtlsclientrd(void *arg) {
622 int cnt, s = *(int *)arg;
623 unsigned char buf[4];
624 struct sockaddr_storage from;
625 socklen_t fromlen = sizeof(from);
626 struct clsrvconf *conf;
632 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
634 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
636 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
640 conf = find_srvconf(handle, (struct sockaddr *)&from, NULL);
642 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
646 if (udp2bio(s, conf->servers->rbios, cnt))
647 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
651 void *dtlsclientrd(void *arg) {
652 struct server *server = (struct server *)arg;
654 struct timeval lastconnecttry;
658 /* yes, lastconnecttry is really necessary */
659 lastconnecttry = server->lastconnecttry;
660 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
662 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
668 server->clientrdgone = 1;
672 void addserverextradtls(struct clsrvconf *conf) {
673 switch (((struct hostportres *)list_first(conf->hostports)->data)->addrinfo->ai_family) {
675 if (client4_sock < 0) {
676 client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
677 if (client4_sock < 0)
678 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
680 conf->servers->sock = client4_sock;
683 if (client6_sock < 0) {
684 client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
685 if (client6_sock < 0)
686 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
688 conf->servers->sock = client6_sock;
691 debugx(1, DBG_ERR, "addserver: unsupported address family");
695 void initextradtls() {
696 pthread_t cl4th, cl6th;
699 freeaddrinfo(srcres);
703 if (client4_sock >= 0)
704 if (pthread_create(&cl4th, &pthread_attr, udpdtlsclientrd, (void *)&client4_sock))
705 debugx(1, DBG_ERR, "pthread_create failed");
706 if (client6_sock >= 0)
707 if (pthread_create(&cl6th, &pthread_attr, udpdtlsclientrd, (void *)&client6_sock))
708 debugx(1, DBG_ERR, "pthread_create failed");
711 const struct protodefs *dtlsinit(uint8_t h) {
716 /* Local Variables: */
717 /* c-file-style: "stroustrup" */