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, NULL, 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;
358 debug(DBG_DBG, "dtlsservernew: starting");
359 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, NULL);
361 ctx = tlsgetctx(handle, conf->tlsconf);
364 ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
367 cert = verifytlscert(ssl);
373 if (verifyconfcert(cert, conf)) {
375 client = addclient(conf, 1);
377 client->sock = params->sock;
378 client->addr = addr_copy((struct sockaddr *)¶ms->addr);
379 client->rbios = params->sesscache->rbios;
381 dtlsserverrd(client);
382 removeclient(client);
385 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
389 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, &cur);
391 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
401 pthread_mutex_lock(¶ms->sesscache->mutex);
402 freebios(params->sesscache->rbios);
403 params->sesscache->rbios = NULL;
404 gettimeofday(¶ms->sesscache->expiry, NULL);
405 params->sesscache->expiry.tv_sec += delay;
406 pthread_mutex_unlock(¶ms->sesscache->mutex);
410 debug(DBG_DBG, "dtlsservernew: exiting");
413 void cacheexpire(struct hash *cache, struct timeval *last) {
415 struct hash_entry *he;
416 struct sessioncacheentry *e;
418 gettimeofday(&now, NULL);
419 if (now.tv_sec - last->tv_sec < 19)
422 for (he = hash_first(cache); he; he = hash_next(he)) {
423 e = (struct sessioncacheentry *)he->data;
424 pthread_mutex_lock(&e->mutex);
425 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
426 pthread_mutex_unlock(&e->mutex);
429 debug(DBG_DBG, "cacheexpire: freeing entry");
430 hash_extract(cache, he->key, he->keylen);
435 pthread_mutex_unlock(&e->mutex);
436 pthread_mutex_destroy(&e->mutex);
438 last->tv_sec = now.tv_sec;
441 void *udpdtlsserverrd(void *arg) {
442 int ndesc, cnt, s = *(int *)arg;
443 unsigned char buf[4];
444 struct sockaddr_storage from;
445 socklen_t fromlen = sizeof(from);
446 struct dtlsservernewparams *params;
448 struct timeval timeout, lastexpiry;
449 pthread_t dtlsserverth;
450 struct hash *sessioncache;
451 struct sessioncacheentry *cacheentry;
453 sessioncache = hash_create();
455 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
456 gettimeofday(&lastexpiry, NULL);
461 memset(&timeout, 0, sizeof(struct timeval));
463 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
465 cacheexpire(sessioncache, &lastexpiry);
468 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
470 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
471 cacheexpire(sessioncache, &lastexpiry);
474 cacheentry = hash_read(sessioncache, &from, fromlen);
476 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
477 pthread_mutex_lock(&cacheentry->mutex);
478 if (cacheentry->rbios) {
479 if (udp2bio(s, cacheentry->rbios, cnt))
480 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
483 pthread_mutex_unlock(&cacheentry->mutex);
484 cacheexpire(sessioncache, &lastexpiry);
488 /* from new source */
489 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
490 params = malloc(sizeof(struct dtlsservernewparams));
492 cacheexpire(sessioncache, &lastexpiry);
496 memset(params, 0, sizeof(struct dtlsservernewparams));
497 params->sesscache = malloc(sizeof(struct sessioncacheentry));
498 if (!params->sesscache) {
500 cacheexpire(sessioncache, &lastexpiry);
504 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
505 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
506 params->sesscache->rbios = newqueue();
507 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
509 memcpy(¶ms->addr, &from, fromlen);
511 if (udp2bio(s, params->sesscache->rbios, cnt)) {
512 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
513 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
514 pthread_detach(dtlsserverth);
515 cacheexpire(sessioncache, &lastexpiry);
518 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
520 hash_extract(sessioncache, &from, fromlen);
522 freebios(params->sesscache->rbios);
523 pthread_mutex_destroy(¶ms->sesscache->mutex);
524 free(params->sesscache);
526 cacheexpire(sessioncache, &lastexpiry);
530 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
535 struct hostportres *hp;
537 debug(DBG_DBG, "dtlsconnect: called from %s", text);
538 pthread_mutex_lock(&server->lock);
539 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
540 /* already reconnected, nothing to do */
541 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
542 pthread_mutex_unlock(&server->lock);
546 hp = (struct hostportres *)list_first(server->conf->hostports)->data;
548 gettimeofday(&now, NULL);
549 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
551 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
552 debug(DBG_DBG, "dtlsconnect: timeout");
553 SSL_free(server->ssl);
555 pthread_mutex_unlock(&server->lock);
559 if (server->connectionok) {
560 server->connectionok = 0;
562 } else if (elapsed < 1)
564 else if (elapsed < 60) {
565 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
567 } else if (elapsed < 100000) {
568 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
571 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
572 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
574 SSL_free(server->ssl);
576 ctx = tlsgetctx(handle, server->conf->tlsconf);
579 server->ssl = dtlsacccon(0, ctx, server->sock, hp->addrinfo->ai_addr, server->rbios);
582 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
584 cert = verifytlscert(server->ssl);
588 if (verifyconfcert(cert, server->conf))
593 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", hp->host, hp->port);
594 server->connectionok = 1;
595 gettimeofday(&server->lastconnecttry, NULL);
596 pthread_mutex_unlock(&server->lock);
600 int clientradputdtls(struct server *server, unsigned char *rad) {
604 struct clsrvconf *conf = server->conf;
606 if (!server->connectionok)
609 if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
610 while ((error = ERR_get_error()))
611 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
614 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
618 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
619 void *udpdtlsclientrd(void *arg) {
620 int cnt, s = *(int *)arg;
621 unsigned char buf[4];
622 struct sockaddr_storage from;
623 socklen_t fromlen = sizeof(from);
624 struct clsrvconf *conf;
630 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
632 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
634 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
638 conf = find_srvconf(handle, (struct sockaddr *)&from, NULL);
640 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
644 if (udp2bio(s, conf->servers->rbios, cnt))
645 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
649 void *dtlsclientrd(void *arg) {
650 struct server *server = (struct server *)arg;
652 struct timeval lastconnecttry;
656 /* yes, lastconnecttry is really necessary */
657 lastconnecttry = server->lastconnecttry;
658 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
660 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
666 server->clientrdgone = 1;
670 void addserverextradtls(struct clsrvconf *conf) {
671 switch (((struct hostportres *)list_first(conf->hostports)->data)->addrinfo->ai_family) {
673 if (client4_sock < 0) {
674 client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
675 if (client4_sock < 0)
676 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
678 conf->servers->sock = client4_sock;
681 if (client6_sock < 0) {
682 client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
683 if (client6_sock < 0)
684 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
686 conf->servers->sock = client6_sock;
689 debugx(1, DBG_ERR, "addserver: unsupported address family");
693 void initextradtls() {
694 pthread_t cl4th, cl6th;
697 freeaddrinfo(srcres);
701 if (client4_sock >= 0)
702 if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
703 debugx(1, DBG_ERR, "pthread_create failed");
704 if (client6_sock >= 0)
705 if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
706 debugx(1, DBG_ERR, "pthread_create failed");
709 const struct protodefs *dtlsinit(uint8_t h) {
714 /* Local Variables: */
715 /* c-file-style: "stroustrup" */