1 /* Copyright (c) 2006-2010, UNINETT AS
2 * Copyright (c) 2010-2012, NORDUnet A/S */
3 /* See LICENSE for licensing information. */
6 #include <sys/socket.h>
7 #include <netinet/in.h>
16 #include <sys/types.h>
17 #include <sys/select.h>
20 #include <arpa/inet.h>
23 #include <openssl/ssl.h>
24 #include <openssl/err.h>
26 #include "radsecproxy.h"
33 static void setprotoopts(struct commonprotoopts *opts);
34 static char **getlistenerargs();
35 void *udpdtlsserverrd(void *arg);
36 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
37 void *dtlsclientrd(void *arg);
38 int clientradputdtls(struct server *server, unsigned char *rad);
39 void addserverextradtls(struct clsrvconf *conf);
43 static const struct protodefs protodefs = {
45 "radsec", /* secretdefault */
46 SOCK_DGRAM, /* socktype */
47 "2083", /* portdefault */
48 REQUEST_RETRY_COUNT, /* retrycountdefault */
49 10, /* retrycountmax */
50 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
51 60, /* retryintervalmax */
52 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
53 setprotoopts, /* setprotoopts */
54 getlistenerargs, /* getlistenerargs */
55 udpdtlsserverrd, /* listener */
56 dtlsconnect, /* connecter */
57 dtlsclientrd, /* clientconnreader */
58 clientradputdtls, /* clientradput */
60 addserverextradtls, /* addserverextra */
61 dtlssetsrcres, /* setsrcres */
62 initextradtls /* initextra */
65 static int client4_sock = -1;
66 static int client6_sock = -1;
67 static struct addrinfo *srcres = NULL;
68 static uint8_t handle;
69 static struct commonprotoopts *protoopts = NULL;
71 const struct protodefs *dtlsinit(uint8_t h) {
76 static void setprotoopts(struct commonprotoopts *opts) {
80 static char **getlistenerargs() {
81 return protoopts ? protoopts->listenargs : NULL;
84 struct sessioncacheentry {
85 pthread_mutex_t mutex;
87 struct timeval expiry;
90 struct dtlsservernewparams {
91 struct sessioncacheentry *sesscache;
93 struct sockaddr_storage addr;
96 void dtlssetsrcres() {
99 resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL,
100 AF_UNSPEC, NULL, protodefs.socktype);
103 int udp2bio(int s, struct gqueue *q, int cnt) {
113 debug(DBG_ERR, "udp2bio: malloc failed");
118 cnt = recv(s, buf, cnt, 0);
120 debug(DBG_WARN, "udp2bio: recv failed");
125 rbio = BIO_new_mem_buf(buf, cnt);
126 BIO_set_mem_eof_return(rbio, -1);
128 pthread_mutex_lock(&q->mutex);
129 if (!list_push(q->entries, rbio)) {
131 pthread_mutex_unlock(&q->mutex);
134 pthread_cond_signal(&q->cond);
135 pthread_mutex_unlock(&q->mutex);
139 BIO *getrbio(SSL *ssl, struct gqueue *q, int timeout) {
144 pthread_mutex_lock(&q->mutex);
145 if (!(rbio = (BIO *)list_shift(q->entries))) {
147 gettimeofday(&now, NULL);
148 memset(&to, 0, sizeof(struct timespec));
149 to.tv_sec = now.tv_sec + timeout;
150 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
152 pthread_cond_wait(&q->cond, &q->mutex);
153 rbio = (BIO *)list_shift(q->entries);
155 pthread_mutex_unlock(&q->mutex);
159 int dtlsread(SSL *ssl, struct gqueue *q, unsigned char *buf, int num, int timeout) {
163 for (len = 0; len < num; len += cnt) {
164 cnt = SSL_read(ssl, buf + len, num - len);
166 switch (cnt = SSL_get_error(ssl, cnt)) {
167 case SSL_ERROR_WANT_READ:
168 rbio = getrbio(ssl, q, timeout);
175 case SSL_ERROR_WANT_WRITE:
178 case SSL_ERROR_ZERO_RETURN:
179 /* remote end sent close_notify, send one back */
189 /* accept if acc == 1, else connect */
190 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct gqueue *rbios) {
200 mem0bio = BIO_new(BIO_s_mem());
201 BIO_set_mem_eof_return(mem0bio, -1);
202 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
203 i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
204 SSL_set_bio(ssl, mem0bio, wbio);
206 for (i = 0; i < 5; i++) {
207 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
212 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
214 ssl->rbio = getrbio(ssl, rbios, 5);
218 while ((error = ERR_get_error()))
219 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
226 unsigned char *raddtlsget(SSL *ssl, struct gqueue *rbios, int timeout) {
228 unsigned char buf[4], *rad;
231 cnt = dtlsread(ssl, rbios, buf, 4, timeout);
233 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
240 debug(DBG_ERR, "raddtlsget: malloc failed");
245 cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
247 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
256 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
259 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
263 void *dtlsserverwr(void *arg) {
266 struct client *client = (struct client *)arg;
267 struct gqueue *replyq;
268 struct request *reply;
270 debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
271 replyq = client->replyq;
273 pthread_mutex_lock(&replyq->mutex);
274 while (!list_first(replyq->entries)) {
276 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
277 pthread_cond_wait(&replyq->cond, &replyq->mutex);
278 debug(DBG_DBG, "dtlsserverwr: got signal");
281 /* ssl might have changed while waiting */
282 pthread_mutex_unlock(&replyq->mutex);
283 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
288 reply = (struct request *)list_shift(replyq->entries);
289 pthread_mutex_unlock(&replyq->mutex);
290 cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
292 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
293 cnt, RADLEN(reply->replybuf), addr2string(client->addr));
295 while ((error = ERR_get_error()))
296 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
301 void dtlsserverrd(struct client *client) {
304 pthread_t dtlsserverwrth;
306 debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
308 if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
309 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
314 buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
316 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
319 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
328 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
333 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
336 pthread_mutex_lock(&client->replyq->mutex);
337 pthread_cond_signal(&client->replyq->cond);
338 pthread_mutex_unlock(&client->replyq->mutex);
339 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
340 pthread_join(dtlsserverwrth, NULL);
341 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
344 void *dtlsservernew(void *arg) {
345 struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
346 struct client *client;
347 struct clsrvconf *conf;
348 struct list_node *cur = NULL;
354 debug(DBG_DBG, "dtlsservernew: starting");
355 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, NULL);
357 ctx = tlsgetctx(handle, conf->tlsconf);
360 ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
363 cert = verifytlscert(ssl);
369 if (verifyconfcert(cert, conf)) {
371 client = addclient(conf, 1);
373 client->sock = params->sock;
374 client->addr = addr_copy((struct sockaddr *)¶ms->addr);
375 client->rbios = params->sesscache->rbios;
377 dtlsserverrd(client);
378 removeclient(client);
381 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
385 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, &cur);
387 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
397 pthread_mutex_lock(¶ms->sesscache->mutex);
398 freebios(params->sesscache->rbios);
399 params->sesscache->rbios = NULL;
400 gettimeofday(¶ms->sesscache->expiry, NULL);
401 params->sesscache->expiry.tv_sec += delay;
402 pthread_mutex_unlock(¶ms->sesscache->mutex);
406 debug(DBG_DBG, "dtlsservernew: exiting");
409 void cacheexpire(struct hash *cache, struct timeval *last) {
411 struct hash_entry *he;
412 struct sessioncacheentry *e;
414 gettimeofday(&now, NULL);
415 if (now.tv_sec - last->tv_sec < 19)
418 for (he = hash_first(cache); he; he = hash_next(he)) {
419 e = (struct sessioncacheentry *)he->data;
420 pthread_mutex_lock(&e->mutex);
421 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
422 pthread_mutex_unlock(&e->mutex);
425 debug(DBG_DBG, "cacheexpire: freeing entry");
426 hash_extract(cache, he->key, he->keylen);
431 pthread_mutex_unlock(&e->mutex);
432 pthread_mutex_destroy(&e->mutex);
434 last->tv_sec = now.tv_sec;
437 void *udpdtlsserverrd(void *arg) {
438 int ndesc, cnt, s = *(int *)arg;
439 unsigned char buf[4];
440 struct sockaddr_storage from;
441 socklen_t fromlen = sizeof(from);
442 struct dtlsservernewparams *params;
444 struct timeval timeout, lastexpiry;
445 pthread_t dtlsserverth;
446 struct hash *sessioncache;
447 struct sessioncacheentry *cacheentry;
449 sessioncache = hash_create();
451 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
452 gettimeofday(&lastexpiry, NULL);
457 memset(&timeout, 0, sizeof(struct timeval));
459 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
461 cacheexpire(sessioncache, &lastexpiry);
464 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
466 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
467 cacheexpire(sessioncache, &lastexpiry);
470 cacheentry = hash_read(sessioncache, &from, fromlen);
472 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
473 pthread_mutex_lock(&cacheentry->mutex);
474 if (cacheentry->rbios) {
475 if (udp2bio(s, cacheentry->rbios, cnt))
476 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
479 pthread_mutex_unlock(&cacheentry->mutex);
480 cacheexpire(sessioncache, &lastexpiry);
484 /* from new source */
485 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
486 params = malloc(sizeof(struct dtlsservernewparams));
488 cacheexpire(sessioncache, &lastexpiry);
492 memset(params, 0, sizeof(struct dtlsservernewparams));
493 params->sesscache = malloc(sizeof(struct sessioncacheentry));
494 if (!params->sesscache) {
496 cacheexpire(sessioncache, &lastexpiry);
500 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
501 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
502 params->sesscache->rbios = newqueue();
503 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
505 memcpy(¶ms->addr, &from, fromlen);
507 if (udp2bio(s, params->sesscache->rbios, cnt)) {
508 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
509 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
510 pthread_detach(dtlsserverth);
511 cacheexpire(sessioncache, &lastexpiry);
514 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
516 hash_extract(sessioncache, &from, fromlen);
518 freebios(params->sesscache->rbios);
519 pthread_mutex_destroy(¶ms->sesscache->mutex);
520 free(params->sesscache);
522 cacheexpire(sessioncache, &lastexpiry);
526 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
531 struct hostportres *hp;
533 debug(DBG_DBG, "dtlsconnect: called from %s", text);
534 pthread_mutex_lock(&server->lock);
535 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
536 /* already reconnected, nothing to do */
537 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
538 pthread_mutex_unlock(&server->lock);
542 hp = (struct hostportres *)list_first(server->conf->hostports)->data;
544 gettimeofday(&now, NULL);
545 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
547 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
548 debug(DBG_DBG, "dtlsconnect: timeout");
549 SSL_free(server->ssl);
551 pthread_mutex_unlock(&server->lock);
555 if (server->connectionok) {
556 server->connectionok = 0;
558 } else if (elapsed < 1)
560 else if (elapsed < 60) {
561 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
563 } else if (elapsed < 100000) {
564 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
567 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
568 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
570 SSL_free(server->ssl);
572 ctx = tlsgetctx(handle, server->conf->tlsconf);
575 server->ssl = dtlsacccon(0, ctx, server->sock, hp->addrinfo->ai_addr, server->rbios);
578 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
580 cert = verifytlscert(server->ssl);
584 if (verifyconfcert(cert, server->conf))
589 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", hp->host, hp->port);
590 server->connectionok = 1;
591 gettimeofday(&server->lastconnecttry, NULL);
592 pthread_mutex_unlock(&server->lock);
596 int clientradputdtls(struct server *server, unsigned char *rad) {
600 struct clsrvconf *conf = server->conf;
602 if (!server->connectionok)
605 if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
606 while ((error = ERR_get_error()))
607 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
610 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
614 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
615 void *udpdtlsclientrd(void *arg) {
616 int cnt, s = *(int *)arg;
617 unsigned char buf[4];
618 struct sockaddr_storage from;
619 socklen_t fromlen = sizeof(from);
620 struct clsrvconf *conf;
626 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
628 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
630 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
634 conf = find_srvconf(handle, (struct sockaddr *)&from, NULL);
636 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
640 if (udp2bio(s, conf->servers->rbios, cnt))
641 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
645 void *dtlsclientrd(void *arg) {
646 struct server *server = (struct server *)arg;
648 struct timeval lastconnecttry;
652 /* yes, lastconnecttry is really necessary */
653 lastconnecttry = server->lastconnecttry;
654 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
656 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
662 server->clientrdgone = 1;
666 void addserverextradtls(struct clsrvconf *conf) {
667 switch (((struct hostportres *)list_first(conf->hostports)->data)->addrinfo->ai_family) {
669 if (client4_sock < 0) {
670 client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
671 if (client4_sock < 0)
672 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
674 conf->servers->sock = client4_sock;
677 if (client6_sock < 0) {
678 client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
679 if (client6_sock < 0)
680 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
682 conf->servers->sock = client6_sock;
685 debugx(1, DBG_ERR, "addserver: unsupported address family");
689 void initextradtls() {
690 pthread_t cl4th, cl6th;
693 freeaddrinfo(srcres);
697 if (client4_sock >= 0)
698 if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
699 debugx(1, DBG_ERR, "pthread_create failed");
700 if (client6_sock >= 0)
701 if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
702 debugx(1, DBG_ERR, "pthread_create failed");
705 const struct protodefs *dtlsinit(uint8_t h) {
710 /* Local Variables: */
711 /* c-file-style: "stroustrup" */