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;
39 struct sessioncacheentry {
40 pthread_mutex_t mutex;
42 struct timeval expiry;
45 struct dtlsservernewparams {
46 struct sessioncacheentry *sesscache;
48 struct sockaddr_storage addr;
51 int udp2bio(int s, struct queue *q, int cnt) {
61 debug(DBG_ERR, "udp2bio: malloc failed");
66 cnt = recv(s, buf, cnt, 0);
68 debug(DBG_WARN, "udp2bio: recv failed");
73 rbio = BIO_new_mem_buf(buf, cnt);
74 BIO_set_mem_eof_return(rbio, -1);
76 pthread_mutex_lock(&q->mutex);
77 if (!list_push(q->entries, rbio)) {
79 pthread_mutex_unlock(&q->mutex);
82 pthread_cond_signal(&q->cond);
83 pthread_mutex_unlock(&q->mutex);
87 BIO *getrbio(SSL *ssl, struct queue *q, int timeout) {
92 pthread_mutex_lock(&q->mutex);
93 if (!(rbio = (BIO *)list_shift(q->entries))) {
95 gettimeofday(&now, NULL);
96 memset(&to, 0, sizeof(struct timespec));
97 to.tv_sec = now.tv_sec + timeout;
98 pthread_cond_timedwait(&q->cond, &q->mutex, &to);
100 pthread_cond_wait(&q->cond, &q->mutex);
101 rbio = (BIO *)list_shift(q->entries);
103 pthread_mutex_unlock(&q->mutex);
107 int dtlsread(SSL *ssl, struct queue *q, unsigned char *buf, int num, int timeout) {
111 for (len = 0; len < num; len += cnt) {
112 cnt = SSL_read(ssl, buf + len, num - len);
114 switch (cnt = SSL_get_error(ssl, cnt)) {
115 case SSL_ERROR_WANT_READ:
116 rbio = getrbio(ssl, q, timeout);
123 case SSL_ERROR_WANT_WRITE:
126 case SSL_ERROR_ZERO_RETURN:
127 /* remote end sent close_notify, send one back */
137 /* accept if acc == 1, else connect */
138 SSL *dtlsacccon(uint8_t acc, SSL_CTX *ctx, int s, struct sockaddr *addr, struct queue *rbios) {
148 mem0bio = BIO_new(BIO_s_mem());
149 BIO_set_mem_eof_return(mem0bio, -1);
150 wbio = BIO_new_dgram(s, BIO_NOCLOSE);
151 BIO_dgram_set_peer(wbio, addr);
152 SSL_set_bio(ssl, mem0bio, wbio);
154 for (i = 0; i < 5; i++) {
155 res = acc ? SSL_accept(ssl) : SSL_connect(ssl);
160 if (SSL_get_error(ssl, res) == SSL_ERROR_WANT_READ) {
162 ssl->rbio = getrbio(ssl, rbios, 5);
166 while ((error = ERR_get_error()))
167 debug(DBG_ERR, "dtls%st: DTLS: %s", acc ? "accep" : "connec", ERR_error_string(error, NULL));
174 unsigned char *raddtlsget(SSL *ssl, struct queue *rbios, int timeout) {
176 unsigned char buf[4], *rad;
179 cnt = dtlsread(ssl, rbios, buf, 4, timeout);
181 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
188 debug(DBG_ERR, "raddtlsget: malloc failed");
193 cnt = dtlsread(ssl, rbios, rad + 4, len - 4, timeout);
195 debug(DBG_DBG, cnt ? "raddtlsget: connection lost" : "raddtlsget: timeout");
204 debug(DBG_WARN, "raddtlsget: packet smaller than minimum radius size");
207 debug(DBG_DBG, "raddtlsget: got %d bytes", len);
211 void *dtlsserverwr(void *arg) {
214 struct client *client = (struct client *)arg;
215 struct queue *replyq;
216 struct request *reply;
218 debug(DBG_DBG, "dtlsserverwr: starting for %s", client->conf->host);
219 replyq = client->replyq;
221 pthread_mutex_lock(&replyq->mutex);
222 while (!list_first(replyq->entries)) {
224 debug(DBG_DBG, "dtlsserverwr: waiting for signal");
225 pthread_cond_wait(&replyq->cond, &replyq->mutex);
226 debug(DBG_DBG, "dtlsserverwr: got signal");
229 /* ssl might have changed while waiting */
230 pthread_mutex_unlock(&replyq->mutex);
231 debug(DBG_DBG, "dtlsserverwr: exiting as requested");
236 reply = (struct request *)list_shift(replyq->entries);
237 pthread_mutex_unlock(&replyq->mutex);
238 cnt = SSL_write(client->ssl, reply->replybuf, RADLEN(reply->replybuf));
240 debug(DBG_DBG, "dtlsserverwr: sent %d bytes, Radius packet of length %d",
241 cnt, RADLEN(reply->replybuf));
243 while ((error = ERR_get_error()))
244 debug(DBG_ERR, "dtlsserverwr: SSL: %s", ERR_error_string(error, NULL));
249 void dtlsserverrd(struct client *client) {
252 pthread_t dtlsserverwrth;
254 debug(DBG_DBG, "dtlsserverrd: starting for %s", client->conf->host);
256 if (pthread_create(&dtlsserverwrth, NULL, dtlsserverwr, (void *)client)) {
257 debug(DBG_ERR, "dtlsserverrd: pthread_create failed");
262 buf = raddtlsget(client->ssl, client->rbios, IDLE_TIMEOUT);
264 debug(DBG_ERR, "dtlsserverrd: connection from %s lost", client->conf->host);
267 debug(DBG_DBG, "dtlsserverrd: got Radius message from %s", client->conf->host);
276 debug(DBG_ERR, "dtlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
281 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
284 pthread_mutex_lock(&client->replyq->mutex);
285 pthread_cond_signal(&client->replyq->cond);
286 pthread_mutex_unlock(&client->replyq->mutex);
287 debug(DBG_DBG, "dtlsserverrd: waiting for writer to end");
288 pthread_join(dtlsserverwrth, NULL);
289 removeclientrqs(client);
290 debug(DBG_DBG, "dtlsserverrd: reader for %s exiting", client->conf->host);
293 void *dtlsservernew(void *arg) {
294 struct dtlsservernewparams *params = (struct dtlsservernewparams *)arg;
295 struct client *client;
296 struct clsrvconf *conf;
297 struct list_node *cur = NULL;
302 debug(DBG_DBG, "dtlsservernew: starting");
303 conf = find_clconf(RAD_DTLS, (struct sockaddr *)¶ms->addr, NULL);
305 ssl = dtlsacccon(1, conf->ssl_ctx, params->sock, (struct sockaddr *)¶ms->addr, params->sesscache->rbios);
308 cert = verifytlscert(ssl);
314 if (verifyconfcert(cert, conf)) {
316 client = addclient(conf, 1);
318 client->sock = params->sock;
319 client->rbios = params->sesscache->rbios;
321 dtlsserverrd(client);
322 removeclient(client);
325 debug(DBG_WARN, "dtlsservernew: failed to create new client instance");
329 conf = find_clconf(RAD_DTLS, (struct sockaddr *)¶ms->addr, &cur);
331 debug(DBG_WARN, "dtlsservernew: ignoring request, no matching TLS client");
341 pthread_mutex_lock(¶ms->sesscache->mutex);
342 freebios(params->sesscache->rbios);
343 params->sesscache->rbios = NULL;
344 gettimeofday(¶ms->sesscache->expiry, NULL);
345 params->sesscache->expiry.tv_sec += delay;
346 pthread_mutex_unlock(¶ms->sesscache->mutex);
350 debug(DBG_DBG, "dtlsservernew: exiting");
353 void cacheexpire(struct hash *cache, struct timeval *last) {
355 struct hash_entry *he;
356 struct sessioncacheentry *e;
358 gettimeofday(&now, NULL);
359 if (now.tv_sec - last->tv_sec < 19)
362 for (he = hash_first(cache); he; he = hash_next(he)) {
363 e = (struct sessioncacheentry *)he->data;
364 pthread_mutex_lock(&e->mutex);
365 if (!e->expiry.tv_sec || e->expiry.tv_sec > now.tv_sec) {
366 pthread_mutex_unlock(&e->mutex);
369 debug(DBG_DBG, "cacheexpire: freeing entry");
370 hash_extract(cache, he->key, he->keylen);
375 pthread_mutex_unlock(&e->mutex);
376 pthread_mutex_destroy(&e->mutex);
378 last->tv_sec = now.tv_sec;
381 void *udpdtlsserverrd(void *arg) {
382 int ndesc, cnt, s = *(int *)arg;
383 unsigned char buf[4];
384 struct sockaddr_storage from;
385 socklen_t fromlen = sizeof(from);
386 struct dtlsservernewparams *params;
388 struct timeval timeout, lastexpiry;
389 pthread_t dtlsserverth;
390 struct hash *sessioncache;
391 struct sessioncacheentry *cacheentry;
393 sessioncache = hash_create();
395 debugx(1, DBG_ERR, "udpdtlsserverrd: malloc failed");
396 gettimeofday(&lastexpiry, NULL);
401 memset(&timeout, 0, sizeof(struct timeval));
403 ndesc = select(s + 1, &readfds, NULL, NULL, &timeout);
405 cacheexpire(sessioncache, &lastexpiry);
408 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
410 debug(DBG_WARN, "udpdtlsserverrd: recv failed");
411 cacheexpire(sessioncache, &lastexpiry);
414 cacheentry = hash_read(sessioncache, &from, fromlen);
416 debug(DBG_DBG, "udpdtlsserverrd: cache hit");
417 pthread_mutex_lock(&cacheentry->mutex);
418 if (cacheentry->rbios) {
419 if (udp2bio(s, cacheentry->rbios, cnt))
420 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
423 pthread_mutex_unlock(&cacheentry->mutex);
424 cacheexpire(sessioncache, &lastexpiry);
428 /* from new source */
429 debug(DBG_DBG, "udpdtlsserverrd: cache miss");
430 params = malloc(sizeof(struct dtlsservernewparams));
432 cacheexpire(sessioncache, &lastexpiry);
436 memset(params, 0, sizeof(struct dtlsservernewparams));
437 params->sesscache = malloc(sizeof(struct sessioncacheentry));
438 if (!params->sesscache) {
440 cacheexpire(sessioncache, &lastexpiry);
444 memset(params->sesscache, 0, sizeof(struct sessioncacheentry));
445 pthread_mutex_init(¶ms->sesscache->mutex, NULL);
446 params->sesscache->rbios = newqueue();
447 if (hash_insert(sessioncache, &from, fromlen, params->sesscache)) {
449 memcpy(¶ms->addr, &from, fromlen);
451 if (udp2bio(s, params->sesscache->rbios, cnt)) {
452 debug(DBG_DBG, "udpdtlsserverrd: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
453 if (!pthread_create(&dtlsserverth, NULL, dtlsservernew, (void *)params)) {
454 pthread_detach(dtlsserverth);
455 cacheexpire(sessioncache, &lastexpiry);
458 debug(DBG_ERR, "udpdtlsserverrd: pthread_create failed");
460 hash_extract(sessioncache, &from, fromlen);
462 freebios(params->sesscache->rbios);
463 pthread_mutex_destroy(¶ms->sesscache->mutex);
464 free(params->sesscache);
466 cacheexpire(sessioncache, &lastexpiry);
470 int dtlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
475 debug(DBG_DBG, "dtlsconnect: called from %s", text);
476 pthread_mutex_lock(&server->lock);
477 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
478 /* already reconnected, nothing to do */
479 debug(DBG_DBG, "dtlsconnect(%s): seems already reconnected", text);
480 pthread_mutex_unlock(&server->lock);
485 gettimeofday(&now, NULL);
486 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
488 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
489 debug(DBG_DBG, "dtlsconnect: timeout");
490 SSL_free(server->ssl);
492 pthread_mutex_unlock(&server->lock);
496 if (server->connectionok) {
497 server->connectionok = 0;
499 } else if (elapsed < 1)
501 else if (elapsed < 60) {
502 debug(DBG_INFO, "dtlsconnect: sleeping %lds", elapsed);
504 } else if (elapsed < 100000) {
505 debug(DBG_INFO, "dtlsconnect: sleeping %ds", 60);
508 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
509 debug(DBG_WARN, "dtlsconnect: trying to open DTLS connection to %s port %s", server->conf->host, server->conf->port);
511 SSL_free(server->ssl);
512 server->ssl = dtlsacccon(0, server->conf->ssl_ctx, server->sock, server->conf->addrinfo->ai_addr, server->rbios);
515 debug(DBG_DBG, "dtlsconnect: DTLS: ok");
517 cert = verifytlscert(server->ssl);
521 if (verifyconfcert(cert, server->conf))
526 debug(DBG_WARN, "dtlsconnect: DTLS connection to %s port %s up", server->conf->host, server->conf->port);
527 gettimeofday(&server->lastconnecttry, NULL);
528 pthread_mutex_unlock(&server->lock);
532 int clientradputdtls(struct server *server, unsigned char *rad) {
536 struct clsrvconf *conf = server->conf;
541 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
542 while ((error = ERR_get_error()))
543 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
545 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
549 /* reads UDP containing DTLS and passes it on to dtlsclientrd */
550 void *udpdtlsclientrd(void *arg) {
551 int cnt, s = *(int *)arg;
552 unsigned char buf[4];
553 struct sockaddr_storage from;
554 socklen_t fromlen = sizeof(from);
555 struct clsrvconf *conf;
561 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
563 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
565 debug(DBG_WARN, "udpdtlsclientrd: recv failed");
569 conf = find_srvconf(RAD_DTLS, (struct sockaddr *)&from, NULL);
571 debug(DBG_WARN, "udpdtlsclientrd: got packet from wrong or unknown DTLS peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
575 if (udp2bio(s, conf->servers->rbios, cnt))
576 debug(DBG_DBG, "radudpget: got DTLS in UDP from %s", addr2string((struct sockaddr *)&from, fromlen));
580 void *dtlsclientrd(void *arg) {
581 struct server *server = (struct server *)arg;
583 struct timeval lastconnecttry;
587 /* yes, lastconnecttry is really necessary */
588 lastconnecttry = server->lastconnecttry;
589 for (secs = 0; !(buf = raddtlsget(server->ssl, server->rbios, 10)) && !server->lostrqs && secs < IDLE_TIMEOUT; secs += 10);
591 dtlsconnect(server, &lastconnecttry, 0, "dtlsclientrd");
597 server->clientrdgone = 1;
601 void addserverextradtls(struct clsrvconf *conf) {
602 switch (conf->addrinfo->ai_family) {
604 if (client4_sock < 0) {
605 client4_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET, 0, 1);
606 if (client4_sock < 0)
607 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
609 conf->servers->sock = client4_sock;
612 if (client6_sock < 0) {
613 client6_sock = bindtoaddr(getsrcprotores(RAD_DTLS), AF_INET6, 0, 1);
614 if (client6_sock < 0)
615 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
617 conf->servers->sock = client6_sock;
620 debugx(1, DBG_ERR, "addserver: unsupported address family");
624 void initextradtls() {
625 pthread_t cl4th, cl6th;
627 if (client4_sock >= 0)
628 if (pthread_create(&cl4th, NULL, udpdtlsclientrd, (void *)&client4_sock))
629 debugx(1, DBG_ERR, "pthread_create failed");
630 if (client6_sock >= 0)
631 if (pthread_create(&cl6th, NULL, udpdtlsclientrd, (void *)&client6_sock))
632 debugx(1, DBG_ERR, "pthread_create failed");