2 * Copyright (C) 2008 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>
33 #include "radsecproxy.h"
36 static int client4_sock = -1;
37 static int client6_sock = -1;
38 static struct addrinfo *srcres = NULL;
40 struct sessioncacheentry {
41 pthread_mutex_t mutex;
43 struct timeval expiry;
46 struct dtlsservernewparams {
47 struct sessioncacheentry *sesscache;
49 struct sockaddr_storage addr;
52 void dtlssetsrcres(char *source) {
54 srcres = resolve_hostport_addrinfo(RAD_DTLS, source);
57 int udp2bio(int s, struct queue *q, int cnt) {
67 debug(DBG_ERR, "udp2bio: malloc failed");
72 cnt = recv(s, buf, cnt, 0);
74 debug(DBG_WARN, "udp2bio: recv failed");
79 rbio = BIO_new_mem_buf(buf, cnt);
80 BIO_set_mem_eof_return(rbio, -1);
82 pthread_mutex_lock(&q->mutex);
83 if (!list_push(q->entries, rbio)) {
85 pthread_mutex_unlock(&q->mutex);
88 pthread_cond_signal(&q->cond);
89 pthread_mutex_unlock(&q->mutex);
93 BIO *getrbio(SSL *ssl, struct queue *q, int timeout) {
98 pthread_mutex_lock(&q->mutex);
99 if (!(rbio = (BIO *)list_shift(q->entries))) {
101 gettimeofday(&now, NULL);
102 memset(&to, 0, sizeof(struct timespec));
103 to.tv_sec = now.tv_sec + timeout;
104 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
106 pthread_cond_wait(&q->cond, &q->mutex);
107 rbio = (BIO *)list_shift(q->entries);
109 pthread_mutex_unlock(&q->mutex);
113 int dtlsread(SSL *ssl, struct queue *q, unsigned char *buf, int num, int timeout) {
117 for (len = 0; len < num; len += cnt) {
118 cnt = SSL_read(ssl, buf + len, num - len);
120 switch (cnt = SSL_get_error(ssl, cnt)) {
121 case SSL_ERROR_WANT_READ:
122 rbio = getrbio(ssl, q, timeout);
129 case SSL_ERROR_WANT_WRITE:
132 case SSL_ERROR_ZERO_RETURN:
133 /* remote end sent close_notify, send one back */
143 /* accept if acc == 1, else connect */
144 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct queue *rbios) {
154 mem0bio = BIO_new(BIO_s_mem());
155 BIO_set_mem_eof_return(mem0bio, -1);
156 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
157 i = BIO_dgram_set_peer(wbio, addr); /* i just to avoid warning */
158 SSL_set_bio(ssl, mem0bio, wbio);
160 for (i = 0; i < 5; i++) {
161 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
166 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
168 ssl->rbio = getrbio(ssl, rbios, 5);
172 while ((error = ERR_get_error()))
173 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
180 unsigned char *raddtlsget(SSL *ssl, struct queue *rbios, int timeout) {
182 unsigned char buf[4], *rad;
185 cnt = dtlsread(ssl, rbios, buf, 4, timeout);
187 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
194 debug(DBG_ERR, "raddtlsget: malloc failed");
199 cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
201 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
210 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
213 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
217 void *dtlsserverwr(void *arg) {
220 struct client *client = (struct client *)arg;
221 struct queue *replyq;
222 struct request *reply;
224 debug(DBG_DBG, "dtlsserverwr: starting for %s", addr2string(client->addr));
225 replyq = client->replyq;
227 pthread_mutex_lock(&replyq->mutex);
228 while (!list_first(replyq->entries)) {
230 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
231 pthread_cond_wait(&replyq->cond, &replyq->mutex);
232 debug(DBG_DBG, "dtlsserverwr: got signal");
235 /* ssl might have changed while waiting */
236 pthread_mutex_unlock(&replyq->mutex);
237 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
242 reply = (struct request *)list_shift(replyq->entries);
243 pthread_mutex_unlock(&replyq->mutex);
244 cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
246 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d to %s",
247 cnt, RADLEN(reply->replybuf), addr2string(client->addr));
249 while ((error = ERR_get_error()))
250 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
255 void dtlsserverrd(struct client *client) {
258 pthread_t dtlsserverwrth;
260 debug(DBG_DBG, "dtlsserverrd: starting for %s", addr2string(client->addr));
262 if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
263 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
268 buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
270 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", addr2string(client->addr));
273 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", addr2string(client->addr));
282 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", addr2string(client->addr));
287 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
290 pthread_mutex_lock(&client->replyq->mutex);
291 pthread_cond_signal(&client->replyq->cond);
292 pthread_mutex_unlock(&client->replyq->mutex);
293 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
294 pthread_join(dtlsserverwrth, NULL);
295 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", addr2string(client->addr));
298 void *dtlsservernew(void *arg) {
299 struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
300 struct client *client;
301 struct clsrvconf *conf;
302 struct list_node *cur = NULL;
308 debug(DBG_DBG, "dtlsservernew: starting");
309 conf = find_clconf(RAD_DTLS, (struct sockaddr *)¶ms->addr, NULL);
311 ctx = tlsgetctx(RAD_DTLS, conf->tlsconf);
314 ssl = dtlsacccon(1, ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
317 cert = verifytlscert(ssl);
323 if (verifyconfcert(cert, conf)) {
325 client = addclient(conf, 1);
327 client->sock = params->sock;
328 client->addr = addr_copy((struct sockaddr *)¶ms->addr);
329 client->rbios = params->sesscache->rbios;
331 dtlsserverrd(client);
332 removeclient(client);
335 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
339 conf = find_clconf(RAD_DTLS, (struct sockaddr *)¶ms->addr, &cur);
341 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
351 pthread_mutex_lock(¶ms->sesscache->mutex);
352 freebios(params->sesscache->rbios);
353 params->sesscache->rbios = NULL;
354 gettimeofday(¶ms->sesscache->expiry, NULL);
355 params->sesscache->expiry.tv_sec += delay;
356 pthread_mutex_unlock(¶ms->sesscache->mutex);
360 debug(DBG_DBG, "dtlsservernew: exiting");
363 void cacheexpire(struct hash *cache, struct timeval *last) {
365 struct hash_entry *he;
366 struct sessioncacheentry *e;
368 gettimeofday(&now, NULL);
369 if (now.tv_sec - last->tv_sec < 19)
372 for (he = hash_first(cache); he; he = hash_next(he)) {
373 e = (struct sessioncacheentry *)he->data;
374 pthread_mutex_lock(&e->mutex);
375 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
376 pthread_mutex_unlock(&e->mutex);
379 debug(DBG_DBG, "cacheexpire: freeing entry");
380 hash_extract(cache, he->key, he->keylen);
385 pthread_mutex_unlock(&e->mutex);
386 pthread_mutex_destroy(&e->mutex);
388 last->tv_sec = now.tv_sec;
391 void *udpdtlsserverrd(void *arg) {
392 int ndesc, cnt, s = *(int *)arg;
393 unsigned char buf[4];
394 struct sockaddr_storage from;
395 socklen_t fromlen = sizeof(from);
396 struct dtlsservernewparams *params;
398 struct timeval timeout, lastexpiry;
399 pthread_t dtlsserverth;
400 struct hash *sessioncache;
401 struct sessioncacheentry *cacheentry;
403 sessioncache = hash_create();
405 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
406 gettimeofday(&lastexpiry, NULL);
411 memset(&timeout, 0, sizeof(struct timeval));
413 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
415 cacheexpire(sessioncache, &lastexpiry);
418 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
420 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
421 cacheexpire(sessioncache, &lastexpiry);
424 cacheentry = hash_read(sessioncache, &from, fromlen);
426 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
427 pthread_mutex_lock(&cacheentry->mutex);
428 if (cacheentry->rbios) {
429 if (udp2bio(s, cacheentry->rbios, cnt))
430 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
433 pthread_mutex_unlock(&cacheentry->mutex);
434 cacheexpire(sessioncache, &lastexpiry);
438 /* from new source */
439 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
440 params = malloc(sizeof(struct dtlsservernewparams));
442 cacheexpire(sessioncache, &lastexpiry);
446 memset(params, 0, sizeof(struct dtlsservernewparams));
447 params->sesscache = malloc(sizeof(struct sessioncacheentry));
448 if (!params->sesscache) {
450 cacheexpire(sessioncache, &lastexpiry);
454 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
455 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
456 params->sesscache->rbios = newqueue();
457 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
459 memcpy(¶ms->addr, &from, fromlen);
461 if (udp2bio(s, params->sesscache->rbios, cnt)) {
462 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
463 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
464 pthread_detach(dtlsserverth);
465 cacheexpire(sessioncache, &lastexpiry);
468 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
470 hash_extract(sessioncache, &from, fromlen);
472 freebios(params->sesscache->rbios);
473 pthread_mutex_destroy(¶ms->sesscache->mutex);
474 free(params->sesscache);
476 cacheexpire(sessioncache, &lastexpiry);
480 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
486 debug(DBG_DBG, "dtlsconnect: called from %s", text);
487 pthread_mutex_lock(&server->lock);
488 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
489 /* already reconnected, nothing to do */
490 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
491 pthread_mutex_unlock(&server->lock);
496 gettimeofday(&now, NULL);
497 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
499 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
500 debug(DBG_DBG, "dtlsconnect: timeout");
501 SSL_free(server->ssl);
503 pthread_mutex_unlock(&server->lock);
507 if (server->connectionok) {
508 server->connectionok = 0;
510 } else if (elapsed < 1)
512 else if (elapsed < 60) {
513 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
515 } else if (elapsed < 100000) {
516 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
519 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
520 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
522 SSL_free(server->ssl);
524 ctx = tlsgetctx(RAD_DTLS, server->conf->tlsconf);
527 server->ssl = dtlsacccon(0, ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
530 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
532 cert = verifytlscert(server->ssl);
536 if (verifyconfcert(cert, server->conf))
541 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
542 server->connectionok = 1;
543 gettimeofday(&server->lastconnecttry, NULL);
544 pthread_mutex_unlock(&server->lock);
548 int clientradputdtls(struct server *server, unsigned char *rad) {
552 struct clsrvconf *conf = server->conf;
554 if (!server->connectionok)
557 if ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
558 while ((error = ERR_get_error()))
559 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
562 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
566 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
567 void *udpdtlsclientrd(void *arg) {
568 int cnt, s = *(int *)arg;
569 unsigned char buf[4];
570 struct sockaddr_storage from;
571 socklen_t fromlen = sizeof(from);
572 struct clsrvconf *conf;
578 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
580 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
582 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
586 conf = find_srvconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
588 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from));
592 if (udp2bio(s, conf->servers->rbios, cnt))
593 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from));
597 void *dtlsclientrd(void *arg) {
598 struct server *server = (struct server *)arg;
600 struct timeval lastconnecttry;
604 /* yes, lastconnecttry is really necessary */
605 lastconnecttry = server->lastconnecttry;
606 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
608 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
614 server->clientrdgone = 1;
618 void addserverextradtls(struct clsrvconf *conf) {
619 switch (conf->addrinfo->ai_family) {
621 if (client4_sock < 0) {
622 client4_sock = bindtoaddr(srcres, AF_INET, 0, 1);
623 if (client4_sock < 0)
624 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
626 conf->servers->sock = client4_sock;
629 if (client6_sock < 0) {
630 client6_sock = bindtoaddr(srcres, AF_INET6, 0, 1);
631 if (client6_sock < 0)
632 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
634 conf->servers->sock = client6_sock;
637 debugx(1, DBG_ERR, "addserver: unsupported address family");
641 void initextradtls() {
642 pthread_t cl4th, cl6th;
645 freeaddrinfo(srcres);
649 if (client4_sock >= 0)
650 if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
651 debugx(1, DBG_ERR, "pthread_create failed");
652 if (client6_sock >= 0)
653 if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
654 debugx(1, DBG_ERR, "pthread_create failed");