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>
31 #include "radsecproxy.h"
38 static void setprotoopts(struct commonprotoopts *opts);
39 static char **getlistenerargs();
40 void *udpdtlsserverrd(void *arg);
41 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
42 void *dtlsclientrd(void *arg);
43 int clientradputdtls(struct server *server, unsigned char *rad);
44 void addserverextradtls(struct clsrvconf *conf);
48 static const struct protodefs protodefs = {
50 "mysecret", /* secretdefault */
51 SOCK_DGRAM, /* socktype */
52 "2083", /* portdefault */
53 REQUEST_RETRY_COUNT, /* retrycountdefault */
54 10, /* retrycountmax */
55 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
56 60, /* retryintervalmax */
57 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
58 setprotoopts, /* setprotoopts */
59 getlistenerargs, /* getlistenerargs */
60 udpdtlsserverrd, /* listener */
61 dtlsconnect, /* connecter */
62 dtlsclientrd, /* clientconnreader */
63 clientradputdtls, /* clientradput */
65 addserverextradtls, /* addserverextra */
66 dtlssetsrcres, /* setsrcres */
67 initextradtls /* initextra */
70 static int client4_sock = -1;
71 static int client6_sock = -1;
72 static struct addrinfo *srcres = NULL;
73 static uint8_t handle;
74 static struct commonprotoopts *protoopts = NULL;
76 const struct protodefs *dtlsinit(uint8_t h) {
81 static void setprotoopts(struct commonprotoopts *opts) {
85 static char **getlistenerargs() {
86 return protoopts ? protoopts->listenargs : NULL;
89 struct sessioncacheentry {
90 pthread_mutex_t mutex;
92 struct timeval expiry;
95 struct dtlsservernewparams {
96 struct sessioncacheentry *sesscache;
98 struct sockaddr_storage addr;
101 void dtlssetsrcres() {
103 srcres = resolvepassiveaddrinfo(protoopts ? protoopts->sourcearg : NULL, NULL, protodefs.socktype);
106 int udp2bio(int s, struct gqueue *q, int cnt) {
116 debug(DBG_ERR, "udp2bio: malloc failed");
121 cnt = recv(s, buf, cnt, 0);
123 debug(DBG_WARN, "udp2bio: recv failed");
128 rbio = BIO_new_mem_buf(buf, cnt);
129 BIO_set_mem_eof_return(rbio, -1);
131 pthread_mutex_lock(&q->mutex);
132 if (!list_push(q->entries, rbio)) {
134 pthread_mutex_unlock(&q->mutex);
137 pthread_cond_signal(&q->cond);
138 pthread_mutex_unlock(&q->mutex);
142 BIO *getrbio(SSL *ssl, struct gqueue *q, int timeout) {
147 pthread_mutex_lock(&q->mutex);
148 if (!(rbio = (BIO *)list_shift(q->entries))) {
150 gettimeofday(&now, NULL);
151 memset(&to, 0, sizeof(struct timespec));
152 to.tv_sec = now.tv_sec + timeout;
153 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
155 pthread_cond_wait(&q->cond, &q->mutex);
156 rbio = (BIO *)list_shift(q->entries);
158 pthread_mutex_unlock(&q->mutex);
162 int dtlsread(SSL *ssl, struct gqueue *q, unsigned char *buf, int num, int timeout) {
166 for (len = 0; len < num; len += cnt) {
167 cnt = SSL_read(ssl, buf + len, num - len);
169 switch (cnt = SSL_get_error(ssl, cnt)) {
170 case SSL_ERROR_WANT_READ:
171 rbio = getrbio(ssl, q, timeout);
178 case SSL_ERROR_WANT_WRITE:
181 case SSL_ERROR_ZERO_RETURN:
182 /* remote end sent close_notify, send one back */
192 /* accept if acc == 1, else connect */
193 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct gqueue *rbios) {
203 mem0bio = BIO_new(BIO_s_mem());
204 BIO_set_mem_eof_return(mem0bio, -1);
205 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
206 i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
207 SSL_set_bio(ssl, mem0bio, wbio);
209 for (i = 0; i < 5; i++) {
210 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
215 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
217 ssl->rbio = getrbio(ssl, rbios, 5);
221 while ((error = ERR_get_error()))
222 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
229 unsigned char *raddtlsget(SSL *ssl, struct gqueue *rbios, int timeout) {
231 unsigned char buf[4], *rad;
234 cnt = dtlsread(ssl, rbios, buf, 4, timeout);
236 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
243 debug(DBG_ERR, "raddtlsget: malloc failed");
248 cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
250 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
259 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
262 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
266 void *dtlsserverwr(void *arg) {
269 struct client *client = (struct client *)arg;
270 struct gqueue *replyq;
271 struct request *reply;
273 debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
274 replyq = client->replyq;
276 pthread_mutex_lock(&replyq->mutex);
277 while (!list_first(replyq->entries)) {
279 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
280 pthread_cond_wait(&replyq->cond, &replyq->mutex);
281 debug(DBG_DBG, "dtlsserverwr: got signal");
284 /* ssl might have changed while waiting */
285 pthread_mutex_unlock(&replyq->mutex);
286 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
291 reply = (struct request *)list_shift(replyq->entries);
292 pthread_mutex_unlock(&replyq->mutex);
293 cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
295 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
296 cnt, RADLEN(reply->replybuf), addr2string(client->addr));
298 while ((error = ERR_get_error()))
299 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
304 void dtlsserverrd(struct client *client) {
307 pthread_t dtlsserverwrth;
309 debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
311 if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
312 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
317 buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
319 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
322 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
331 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
336 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
339 pthread_mutex_lock(&client->replyq->mutex);
340 pthread_cond_signal(&client->replyq->cond);
341 pthread_mutex_unlock(&client->replyq->mutex);
342 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
343 pthread_join(dtlsserverwrth, NULL);
344 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
347 void *dtlsservernew(void *arg) {
348 struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
349 struct client *client;
350 struct clsrvconf *conf;
351 struct list_node *cur = NULL;
357 debug(DBG_DBG, "dtlsservernew: starting");
358 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, NULL);
360 ctx = tlsgetctx(handle, conf->tlsconf);
363 ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
366 cert = verifytlscert(ssl);
372 if (verifyconfcert(cert, conf)) {
374 client = addclient(conf, 1);
376 client->sock = params->sock;
377 client->addr = addr_copy((struct sockaddr *)¶ms->addr);
378 client->rbios = params->sesscache->rbios;
380 dtlsserverrd(client);
381 removeclient(client);
384 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
388 conf = find_clconf(handle, (struct sockaddr *)¶ms->addr, &cur);
390 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
400 pthread_mutex_lock(¶ms->sesscache->mutex);
401 freebios(params->sesscache->rbios);
402 params->sesscache->rbios = NULL;
403 gettimeofday(¶ms->sesscache->expiry, NULL);
404 params->sesscache->expiry.tv_sec += delay;
405 pthread_mutex_unlock(¶ms->sesscache->mutex);
409 debug(DBG_DBG, "dtlsservernew: exiting");
412 void cacheexpire(struct hash *cache, struct timeval *last) {
414 struct hash_entry *he;
415 struct sessioncacheentry *e;
417 gettimeofday(&now, NULL);
418 if (now.tv_sec - last->tv_sec < 19)
421 for (he = hash_first(cache); he; he = hash_next(he)) {
422 e = (struct sessioncacheentry *)he->data;
423 pthread_mutex_lock(&e->mutex);
424 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
425 pthread_mutex_unlock(&e->mutex);
428 debug(DBG_DBG, "cacheexpire: freeing entry");
429 hash_extract(cache, he->key, he->keylen);
434 pthread_mutex_unlock(&e->mutex);
435 pthread_mutex_destroy(&e->mutex);
437 last->tv_sec = now.tv_sec;
440 void *udpdtlsserverrd(void *arg) {
441 int ndesc, cnt, s = *(int *)arg;
442 unsigned char buf[4];
443 struct sockaddr_storage from;
444 socklen_t fromlen = sizeof(from);
445 struct dtlsservernewparams *params;
447 struct timeval timeout, lastexpiry;
448 pthread_t dtlsserverth;
449 struct hash *sessioncache;
450 struct sessioncacheentry *cacheentry;
452 sessioncache = hash_create();
454 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
455 gettimeofday(&lastexpiry, NULL);
460 memset(&timeout, 0, sizeof(struct timeval));
462 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
464 cacheexpire(sessioncache, &lastexpiry);
467 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
469 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
470 cacheexpire(sessioncache, &lastexpiry);
473 cacheentry = hash_read(sessioncache, &from, fromlen);
475 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
476 pthread_mutex_lock(&cacheentry->mutex);
477 if (cacheentry->rbios) {
478 if (udp2bio(s, cacheentry->rbios, cnt))
479 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
482 pthread_mutex_unlock(&cacheentry->mutex);
483 cacheexpire(sessioncache, &lastexpiry);
487 /* from new source */
488 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
489 params = malloc(sizeof(struct dtlsservernewparams));
491 cacheexpire(sessioncache, &lastexpiry);
495 memset(params, 0, sizeof(struct dtlsservernewparams));
496 params->sesscache = malloc(sizeof(struct sessioncacheentry));
497 if (!params->sesscache) {
499 cacheexpire(sessioncache, &lastexpiry);
503 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
504 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
505 params->sesscache->rbios = newqueue();
506 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
508 memcpy(¶ms->addr, &from, fromlen);
510 if (udp2bio(s, params->sesscache->rbios, cnt)) {
511 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
512 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
513 pthread_detach(dtlsserverth);
514 cacheexpire(sessioncache, &lastexpiry);
517 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
519 hash_extract(sessioncache, &from, fromlen);
521 freebios(params->sesscache->rbios);
522 pthread_mutex_destroy(¶ms->sesscache->mutex);
523 free(params->sesscache);
525 cacheexpire(sessioncache, &lastexpiry);
529 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
534 struct hostportres *hp;
536 debug(DBG_DBG, "dtlsconnect: called from %s", text);
537 pthread_mutex_lock(&server->lock);
538 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
539 /* already reconnected, nothing to do */
540 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
541 pthread_mutex_unlock(&server->lock);
545 hp = (struct hostportres *)list_first(server->conf->hostports)->data;
547 gettimeofday(&now, NULL);
548 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
550 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
551 debug(DBG_DBG, "dtlsconnect: timeout");
552 SSL_free(server->ssl);
554 pthread_mutex_unlock(&server->lock);
558 if (server->connectionok) {
559 server->connectionok = 0;
561 } else if (elapsed < 1)
563 else if (elapsed < 60) {
564 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
566 } else if (elapsed < 100000) {
567 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
570 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
571 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", hp->host, hp->port);
573 SSL_free(server->ssl);
575 ctx = tlsgetctx(handle, server->conf->tlsconf);
578 server->ssl = dtlsacccon(0, ctx, server->sock, hp->addrinfo->ai_addr, server->rbios);
581 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
583 cert = verifytlscert(server->ssl);
587 if (verifyconfcert(cert, server->conf))
592 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", hp->host, hp->port);
593 server->connectionok = 1;
594 gettimeofday(&server->lastconnecttry, NULL);
595 pthread_mutex_unlock(&server->lock);
599 int clientradputdtls(struct server *server, unsigned char *rad) {
603 struct clsrvconf *conf = server->conf;
605 if (!server->connectionok)
608 if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
609 while ((error = ERR_get_error()))
610 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
613 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->name);
617 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
618 void *udpdtlsclientrd(void *arg) {
619 int cnt, s = *(int *)arg;
620 unsigned char buf[4];
621 struct sockaddr_storage from;
622 socklen_t fromlen = sizeof(from);
623 struct clsrvconf *conf;
629 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
631 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
633 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
637 conf = find_srvconf(handle, (struct sockaddr *)&from, NULL);
639 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
643 if (udp2bio(s, conf->servers->rbios, cnt))
644 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
648 void *dtlsclientrd(void *arg) {
649 struct server *server = (struct server *)arg;
651 struct timeval lastconnecttry;
655 /* yes, lastconnecttry is really necessary */
656 lastconnecttry = server->lastconnecttry;
657 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
659 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
665 server->clientrdgone = 1;
669 void addserverextradtls(struct clsrvconf *conf) {
670 switch (((struct hostportres *)list_first(conf->hostports)->data)->addrinfo->ai_family) {
672 if (client4_sock < 0) {
673 client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
674 if (client4_sock < 0)
675 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
677 conf->servers->sock = client4_sock;
680 if (client6_sock < 0) {
681 client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
682 if (client6_sock < 0)
683 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->name);
685 conf->servers->sock = client6_sock;
688 debugx(1, DBG_ERR, "addserver: unsupported address family");
692 void initextradtls() {
693 pthread_t cl4th, cl6th;
696 freeaddrinfo(srcres);
700 if (client4_sock >= 0)
701 if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
702 debugx(1, DBG_ERR, "pthread_create failed");
703 if (client6_sock >= 0)
704 if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
705 debugx(1, DBG_ERR, "pthread_create failed");
708 const struct protodefs *dtlsinit(uint8_t h) {
713 /* Local Variables: */
714 /* c-file-style: "stroustrup" */