2 * Copyright (C) 2006 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 * peers can not yet be specified with literal IPv6 addresses due to port syntax
15 * timer based client retrans or maybe no retrans and just a timer...
16 * make our server ignore client retrans?
18 * routing based on id....
19 * need to also encrypt Tunnel-Password and Message-Authenticator attrs
20 * tls certificate validation
23 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
24 * rd is responsible for init and launching wr
25 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
26 * each tlsserverrd launches tlsserverwr
27 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
28 * for init and launching rd
30 * serverrd will receive a request, processes it and puts it in the requestq of
31 * the appropriate clientwr
32 * clientwr monitors its requestq and sends requests
33 * clientrd looks for responses, processes them and puts them in the replyq of
34 * the peer the request came from
35 * serverwr monitors its reply and sends replies
37 * In addition to the main thread, we have:
38 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
39 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
40 * For each TLS peer connecting to us there will be 2 more TLS threads
41 * This is only for connected peers
42 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
43 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
50 #include <openssl/ssl.h>
51 #include <openssl/rand.h>
52 #include <openssl/err.h>
53 #include <openssl/md5.h>
54 #include "radsecproxy.h"
56 static struct client clients[MAX_PEERS];
57 static struct server servers[MAX_PEERS];
59 static int client_count = 0;
60 static int server_count = 0;
62 static struct replyq udp_server_replyq;
63 static int udp_server_sock = -1;
64 static char *udp_server_port = DEFAULT_UDP_PORT;
65 static pthread_mutex_t *ssl_locks;
66 static long *ssl_lock_count;
67 static SSL_CTX *ssl_ctx_cl;
71 /* callbacks for making OpenSSL thread safe */
72 unsigned long ssl_thread_id() {
73 return (unsigned long)pthread_self();
76 void ssl_locking_callback(int mode, int type, const char *file, int line) {
77 if (mode & CRYPTO_LOCK) {
78 pthread_mutex_lock(&ssl_locks[type]);
79 ssl_lock_count[type]++;
81 pthread_mutex_unlock(&ssl_locks[type]);
84 void ssl_locks_setup() {
87 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
88 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
89 for (i = 0; i < CRYPTO_num_locks(); i++) {
90 ssl_lock_count[i] = 0;
91 pthread_mutex_init(&ssl_locks[i], NULL);
94 CRYPTO_set_id_callback(ssl_thread_id);
95 CRYPTO_set_locking_callback(ssl_locking_callback);
98 /* exactly one of the args must be non-NULL */
99 int resolvepeer(struct server *server, struct client *client) {
102 struct addrinfo hints, **addrinfo, *newaddrinfo;
108 addrinfo = &server->addrinfo;
113 addrinfo = &client->addrinfo;
116 memset(&hints, 0, sizeof(hints));
117 hints.ai_socktype = (type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
118 hints.ai_family = AF_UNSPEC;
119 if (getaddrinfo(host, port, &hints, &newaddrinfo)) {
120 err("resolvepeer: can't resolve %s port %s", host, port);
125 freeaddrinfo(*addrinfo);
126 *addrinfo = newaddrinfo;
130 int connecttoserver(struct addrinfo *addrinfo) {
132 struct addrinfo *res;
134 for (res = addrinfo; res; res = res->ai_next) {
135 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
137 err("connecttoserver: socket failed");
140 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
142 err("connecttoserver: connect failed");
149 /* returns the client with matching address, or NULL */
150 /* if client argument is not NULL, we only check that one client */
151 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
152 struct sockaddr_in6 *sa6;
153 struct in_addr *a4 = NULL;
156 struct addrinfo *res;
158 if (addr->sa_family == AF_INET6) {
159 sa6 = (struct sockaddr_in6 *)addr;
160 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
161 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
163 a4 = &((struct sockaddr_in *)addr)->sin_addr;
165 c = (client ? client : clients);
166 for (i = 0; i < client_count; i++) {
168 for (res = c->addrinfo; res; res = res->ai_next)
169 if ((a4 && res->ai_family == AF_INET &&
170 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
171 (res->ai_family == AF_INET6 &&
172 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
181 /* returns the server with matching address, or NULL */
182 /* if server argument is not NULL, we only check that one server */
183 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
184 struct sockaddr_in6 *sa6;
185 struct in_addr *a4 = NULL;
188 struct addrinfo *res;
190 if (addr->sa_family == AF_INET6) {
191 sa6 = (struct sockaddr_in6 *)addr;
192 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
193 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
195 a4 = &((struct sockaddr_in *)addr)->sin_addr;
197 s = (server ? server : servers);
198 for (i = 0; i < server_count; i++) {
200 for (res = s->addrinfo; res; res = res->ai_next)
201 if ((a4 && res->ai_family == AF_INET &&
202 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
203 (res->ai_family == AF_INET6 &&
204 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
213 /* exactly one of client and server must be non-NULL */
214 /* if *peer == NULL we return who we received from, else require it to be from peer */
215 /* return from in sa if not NULL */
216 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
219 unsigned char buf[65536], *rad;
220 struct sockaddr_storage from;
221 socklen_t fromlen = sizeof(from);
224 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
226 err("radudpget: recv failed");
229 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
232 printf("radudpget: packet too small\n");
239 printf("radudpget: packet smaller than length field in radius header\n");
243 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
246 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
247 : (void *)find_server('U', (struct sockaddr *)&from, *server));
249 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
256 err("radudpget: malloc failed");
258 memcpy(rad, buf, len);
260 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
262 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
268 void tlsconnect(struct server *server, struct timeval *when, char *text) {
273 printf("tlsconnect called from %s\n", text);
274 pthread_mutex_lock(&server->lock);
275 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
276 /* already reconnected, nothing to do */
277 printf("tlsconnect: seems already reconnected\n");
278 pthread_mutex_unlock(&server->lock);
282 printf("tlsconnect %s\n", text);
285 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->host, server->port);
286 gettimeofday(&now, NULL);
287 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
288 memcpy(&server->lastconnecttry, &now, sizeof(struct timeval));
289 if (server->connectionok) {
290 server->connectionok = 0;
292 } else if (elapsed < 5)
294 else if (elapsed < 600)
296 else if (elapsed < 10000) /* no sleep at startup */
298 if (server->sock >= 0)
300 if ((server->sock = connecttoserver(server->addrinfo)) < 0)
302 SSL_free(server->ssl);
303 server->ssl = SSL_new(ssl_ctx_cl);
304 SSL_set_fd(server->ssl, server->sock);
305 if (SSL_connect(server->ssl) > 0)
307 while ((error = ERR_get_error()))
308 err("tlsconnect: TLS: %s", ERR_error_string(error, NULL));
310 printf("tlsconnect: TLS connection to %s port %s up\n", server->host, server->port);
311 pthread_mutex_unlock(&server->lock);
314 unsigned char *radtlsget(SSL *ssl) {
316 unsigned char buf[4], *rad;
319 for (total = 0; total < 4; total += cnt) {
320 cnt = SSL_read(ssl, buf + total, 4 - total);
322 printf("radtlsget: connection lost\n");
330 err("radtlsget: malloc failed");
335 for (; total < len; total += cnt) {
336 cnt = SSL_read(ssl, rad + total, len - total);
338 printf("radtlsget: connection lost\n");
348 printf("radtlsget: packet smaller than minimum radius size\n");
351 printf("radtlsget: got %d bytes\n", total);
355 int clientradput(struct server *server, unsigned char *rad) {
359 struct timeval lastconnecttry;
362 if (server->type == 'U') {
363 if (send(server->sock, rad, len, 0) >= 0) {
364 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->host, server->port);
367 err("clientradput: send failed");
371 lastconnecttry = server->lastconnecttry;
372 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
373 while ((error = ERR_get_error()))
374 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
375 tlsconnect(server, &lastconnecttry, "clientradput");
376 lastconnecttry = server->lastconnecttry;
379 server->connectionok = 1;
380 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
381 cnt, len, server->host);
385 int radsign(unsigned char *rad, unsigned char *sec) {
386 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
387 static unsigned char first = 1;
388 static EVP_MD_CTX mdctx;
392 pthread_mutex_lock(&lock);
394 EVP_MD_CTX_init(&mdctx);
398 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
399 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
400 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
401 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
403 pthread_mutex_unlock(&lock);
407 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
408 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
409 static unsigned char first = 1;
410 static EVP_MD_CTX mdctx;
411 unsigned char hash[EVP_MAX_MD_SIZE];
415 pthread_mutex_lock(&lock);
417 EVP_MD_CTX_init(&mdctx);
423 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
424 EVP_DigestUpdate(&mdctx, rad, 4) &&
425 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
426 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
427 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
428 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
430 !memcmp(hash, rad + 4, 16));
431 pthread_mutex_unlock(&lock);
435 void sendrq(struct server *to, struct client *from, struct request *rq) {
438 pthread_mutex_lock(&to->newrq_mutex);
439 for (i = 0; i < MAX_REQUESTS; i++)
440 if (!to->requests[i].buf)
442 if (i == MAX_REQUESTS) {
443 printf("No room in queue, dropping request\n");
444 pthread_mutex_unlock(&to->newrq_mutex);
448 rq->buf[1] = (char)i;
449 to->requests[i] = *rq;
453 printf("signalling client writer\n");
454 pthread_cond_signal(&to->newrq_cond);
456 pthread_mutex_unlock(&to->newrq_mutex);
459 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
460 struct replyq *replyq = to->replyq;
462 pthread_mutex_lock(&replyq->count_mutex);
463 if (replyq->count == replyq->size) {
464 printf("No room in queue, dropping request\n");
465 pthread_mutex_unlock(&replyq->count_mutex);
469 replyq->replies[replyq->count].buf = buf;
471 replyq->replies[replyq->count].tosa = *tosa;
474 if (replyq->count == 1) {
475 printf("signalling client writer\n");
476 pthread_cond_signal(&replyq->count_cond);
478 pthread_mutex_unlock(&replyq->count_mutex);
481 int pwdcrypt(uint8_t *plain, uint8_t *enc, uint8_t enclen, uint8_t *shared, uint8_t sharedlen,
483 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
484 static unsigned char first = 1;
485 static EVP_MD_CTX mdctx;
486 unsigned char hash[EVP_MAX_MD_SIZE], *input;
488 uint8_t i, offset = 0;
490 pthread_mutex_lock(&lock);
492 EVP_MD_CTX_init(&mdctx);
498 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
499 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
500 !EVP_DigestUpdate(&mdctx, input, 16) ||
501 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
503 pthread_mutex_unlock(&lock);
506 for (i = 0; i < 16; i++)
507 plain[offset + i] = hash[i] ^ enc[offset + i];
509 if (offset == enclen)
511 input = enc + offset - 16;
513 pthread_mutex_unlock(&lock);
517 struct server *id2server(char *id, uint8_t len) {
519 char **realm, *idrealm;
521 idrealm = strchr(id, '@');
529 for (i = 0; i < server_count; i++) {
530 for (realm = servers[i].realms; *realm; realm++) {
531 if ((strlen(*realm) == 1 && **realm == '*') ||
532 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
533 printf("found matching realm: %s, host %s\n", *realm, servers[i].host);
541 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
542 uint8_t code, id, *auth, *attr, *usernameattr = NULL, *userpwdattr = NULL, pwd[128], pwdlen;
547 unsigned char newauth[16];
549 code = *(uint8_t *)buf;
550 id = *(uint8_t *)(buf + 1);
552 auth = (uint8_t *)(buf + 4);
554 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
556 if (code != RAD_Access_Request) {
557 printf("radsrv: server currently accepts only access-requests, ignoring\n");
565 left -= attr[RAD_Attr_Length];
567 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
570 switch (attr[RAD_Attr_Type]) {
571 case RAD_Attr_User_Name:
574 case RAD_Attr_User_Password:
578 attr += attr[RAD_Attr_Length];
581 printf("radsrv: malformed packet? remaining byte after last attribute\n");
584 printf("radsrv: Username: ");
585 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
586 printf("%c", usernameattr[RAD_Attr_Value + i]);
590 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
592 printf("radsrv: ignoring request, don't know where to send it\n");
596 if (!RAND_bytes(newauth, 16)) {
597 printf("radsrv: failed to generate random auth\n");
602 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
603 pwdlen = userpwdattr[RAD_Attr_Length] - 2;
604 if (pwdlen < 16 || pwdlen > 128 || pwdlen % 16) {
605 printf("radsrv: invalid user password length\n");
609 if (!pwdcrypt(pwd, &userpwdattr[RAD_Attr_Value], pwdlen, from->secret, strlen(from->secret), auth)) {
610 printf("radsrv: cannot decrypt password\n");
613 printf("radsrv: password: ");
614 for (i = 0; i < pwdlen; i++)
615 printf("%02x ", pwd[i]);
617 if (!pwdcrypt(&userpwdattr[RAD_Attr_Value], pwd, pwdlen, to->secret, strlen(to->secret), newauth)) {
618 printf("radsrv: cannot encrypt password\n");
626 memcpy(rq->origauth, auth, 16);
627 memcpy(rq->buf + 4, newauth, 16);
631 void *clientrd(void *arg) {
632 struct server *server = (struct server *)arg;
636 struct sockaddr_storage fromsa;
637 struct timeval lastconnecttry;
640 lastconnecttry = server->lastconnecttry;
641 buf = (server->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
642 if (!buf && server->type == 'T') {
643 tlsconnect(server, &lastconnecttry, "clientrd");
647 server->connectionok = 1;
649 i = buf[1]; /* i is the id */
651 pthread_mutex_lock(&server->newrq_mutex);
652 if (!server->requests[i].buf || !server->requests[i].tries) {
653 pthread_mutex_unlock(&server->newrq_mutex);
654 printf("clientrd: no matching request sent with this id, ignoring\n");
658 if (server->requests[i].received) {
659 pthread_mutex_unlock(&server->newrq_mutex);
660 printf("clientrd: already received, ignoring\n");
664 if (!validauth(buf, server->requests[i].buf + 4, server->secret)) {
665 pthread_mutex_unlock(&server->newrq_mutex);
666 printf("clientrd: invalid auth, ignoring\n");
670 /* once we set received = 1, requests[i] may be reused */
671 buf[1] = (char)server->requests[i].origid;
672 memcpy(buf + 4, server->requests[i].origauth, 16);
673 from = server->requests[i].from;
674 if (from->type == 'U')
675 fromsa = server->requests[i].fromsa;
676 server->requests[i].received = 1;
677 pthread_mutex_unlock(&server->newrq_mutex);
679 if (!radsign(buf, from->secret)) {
680 printf("clientrd: failed to sign message\n");
684 printf("clientrd: giving packet back to where it came from\n");
685 sendreply(from, server, buf, from->type == 'U' ? &fromsa : NULL);
689 void *clientwr(void *arg) {
690 struct server *server = (struct server *)arg;
691 pthread_t clientrdth;
694 if (server->type == 'U') {
695 if ((server->sock = connecttoserver(server->addrinfo)) < 0) {
696 printf("clientwr: connecttoserver failed\n");
700 tlsconnect(server, NULL, "new client");
702 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
703 errx("clientwr: pthread_create failed");
706 pthread_mutex_lock(&server->newrq_mutex);
707 while (!server->newrq) {
708 printf("clientwr: waiting for signal\n");
709 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
710 printf("clientwr: got signal\n");
713 pthread_mutex_unlock(&server->newrq_mutex);
715 for (i = 0; i < MAX_REQUESTS; i++) {
716 pthread_mutex_lock(&server->newrq_mutex);
717 while (!server->requests[i].buf && i < MAX_REQUESTS)
719 if (i == MAX_REQUESTS) {
720 pthread_mutex_unlock(&server->newrq_mutex);
724 /* already received or too many tries */
725 if (server->requests[i].received || server->requests[i].tries > 2) {
726 free(server->requests[i].buf);
727 /* setting this to NULL means that it can be reused */
728 server->requests[i].buf = NULL;
729 pthread_mutex_unlock(&server->newrq_mutex);
732 pthread_mutex_unlock(&server->newrq_mutex);
734 server->requests[i].tries++;
735 clientradput(server, server->requests[i].buf);
738 /* should do more work to maintain TLS connections, keepalives etc */
741 void *udpserverwr(void *arg) {
742 struct replyq *replyq = &udp_server_replyq;
743 struct reply *reply = replyq->replies;
745 pthread_mutex_lock(&replyq->count_mutex);
747 while (!replyq->count) {
748 printf("udp server writer, waiting for signal\n");
749 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
750 printf("udp server writer, got signal\n");
752 pthread_mutex_unlock(&replyq->count_mutex);
754 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
755 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
756 err("sendudp: send failed");
759 pthread_mutex_lock(&replyq->count_mutex);
761 memmove(replyq->replies, replyq->replies + 1,
762 replyq->count * sizeof(struct reply));
766 void *udpserverrd(void *arg) {
771 pthread_t udpserverwrth;
773 if ((udp_server_sock = bindport(SOCK_DGRAM, udp_server_port)) < 0) {
774 printf("udpserverrd: socket/bind failed\n");
777 printf("udpserverrd: listening on UDP port %s\n", udp_server_port);
779 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
780 errx("pthread_create failed");
784 memset(&rq, 0, sizeof(struct request));
785 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
786 to = radsrv(&rq, buf, fr);
788 printf("udpserverrd: ignoring request, no place to send it\n");
795 void *tlsserverwr(void *arg) {
798 struct client *client = (struct client *)arg;
799 struct replyq *replyq;
801 pthread_mutex_lock(&client->replycount_mutex);
803 replyq = client->replyq;
804 while (!replyq->count) {
805 printf("tls server writer, waiting for signal\n");
806 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
807 printf("tls server writer, got signal\n");
809 pthread_mutex_unlock(&replyq->count_mutex);
810 cnt = SSL_write(client->ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
812 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
813 cnt, RADLEN(replyq->replies->buf));
815 while ((error = ERR_get_error()))
816 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
817 free(replyq->replies->buf);
819 pthread_mutex_lock(&replyq->count_mutex);
821 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
825 void *tlsserverrd(void *arg) {
831 struct client *client = (struct client *)arg;
832 pthread_t tlsserverwrth;
834 printf("tlsserverrd starting\n");
835 if (SSL_accept(client->ssl) <= 0) {
836 while ((error = ERR_get_error()))
837 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
838 errx("accept failed, child exiting");
841 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
842 errx("pthread_create failed");
845 buf = radtlsget(client->ssl);
847 printf("tlsserverrd: connection lost\n");
848 s = SSL_get_fd(client->ssl);
849 SSL_free(client->ssl);
855 printf("tlsserverrd: got Radius message from %s\n", client->host);
856 memset(&rq, 0, sizeof(struct request));
857 to = radsrv(&rq, buf, client);
859 printf("ignoring request, no place to send it\n");
862 sendrq(to, client, &rq);
866 int tlslistener(SSL_CTX *ssl_ctx) {
867 pthread_t tlsserverth;
869 struct sockaddr_storage from;
870 size_t fromlen = sizeof(from);
871 struct client *client;
873 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
874 printf("tlslistener: socket/bind failed\n");
879 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
882 snew = accept(s, (struct sockaddr *)&from, &fromlen);
884 errx("accept failed");
885 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
887 client = find_client('T', (struct sockaddr *)&from, NULL);
889 printf("ignoring request, not a known TLS client\n");
895 printf("Ignoring incoming connection, already have one from this client\n");
899 client->ssl = SSL_new(ssl_ctx);
900 SSL_set_fd(client->ssl, snew);
901 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
902 errx("pthread_create failed");
907 char *parsehostport(char *s, char **host, char **port) {
912 // allow literal addresses and port, e.g. [2001:db8::1]:1812
916 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
918 printf("no ] matching initial [\n");
924 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
927 printf("missing host/address\n");
930 *host = malloc(p - field + 1);
932 errx("malloc failed");
933 memcpy(*host, field, p - field);
934 (*host)[p - field] = '\0';
937 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
938 printf("unexpected character after ]\n");
943 /* port number or service name is specified */;
945 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
947 printf("syntax error, : but no following port\n");
950 *port = malloc(p - field + 1);
952 errx("malloc failed");
953 memcpy(*port, field, p - field);
954 (*port)[p - field] = '\0';
960 // * is default, else longest match ... ";" used for separator
961 char *parserealmlist(char *s, struct server *server) {
965 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
970 server->realms = NULL;
973 server->realmdata = malloc(l + 1);
974 if (!server->realmdata)
975 errx("malloc failed");
976 memcpy(server->realmdata, s, l);
977 server->realmdata[l] = '\0';
978 server->realms = malloc((1+n) * sizeof(char *));
980 errx("malloc failed");
981 server->realms[0] = server->realmdata;
982 for (n = 1, i = 0; i < l; i++)
983 if (server->realmdata[i] == ';') {
984 server->realmdata[i] = '\0';
985 server->realms[n++] = server->realmdata + i + 1;
987 server->realms[n] = NULL;
991 /* exactly one argument must be non-NULL */
992 void getconfig(const char *serverfile, const char *clientfile) {
995 char *p, *field, **r;
996 struct client *client;
997 struct server *server;
998 char *type, **host, **port, **secret;
1002 printf("opening file %s for reading\n", serverfile);
1003 f = fopen(serverfile, "r");
1005 errx("getconfig failed to open %s for reading", serverfile);
1006 count = &server_count;
1008 printf("opening file %s for reading\n", clientfile);
1009 f = fopen(clientfile, "r");
1011 errx("getconfig failed to open %s for reading", clientfile);
1012 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
1013 if (!udp_server_replyq.replies)
1014 errx("malloc failed");
1015 udp_server_replyq.size = 4 * MAX_REQUESTS;
1016 udp_server_replyq.count = 0;
1017 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1018 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1019 count = &client_count;
1023 while (fgets(line, 1024, f) && *count < MAX_PEERS) {
1025 server = &servers[*count];
1026 memset(server, 0, sizeof(struct server));
1027 type = &server->type;
1028 host = &server->host;
1029 port = &server->port;
1030 secret = &server->secret;
1032 client = &clients[*count];
1033 memset(client, 0, sizeof(struct client));
1034 type = &client->type;
1035 host = &client->host;
1036 port = &client->port;
1037 secret = &client->secret;
1039 for (p = line; *p == ' ' || *p == '\t'; p++);
1040 if (*p == '#' || *p == '\n')
1042 if (*p != 'U' && *p != 'T') {
1043 printf("server type must be U or T, got %c\n", *p);
1047 for (p++; *p == ' ' || *p == '\t'; p++);
1048 p = parsehostport(p, host, port);
1050 *port = (*type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT);
1051 for (; *p == ' ' || *p == '\t'; p++);
1053 p = parserealmlist(p, server);
1054 if (!server->realms) {
1055 printf("realm list must be specified\n");
1058 for (; *p == ' ' || *p == '\t'; p++);
1061 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1063 /* no secret set and end of line, line is complete if TLS */
1065 printf("secret must be specified for UDP\n");
1068 *secret = DEFAULT_TLS_SECRET;
1070 *secret = malloc(p - field + 1);
1072 errx("malloc failed");
1073 memcpy(*secret, field, p - field);
1074 (*secret)[p - field] = '\0';
1075 /* check that rest of line only white space */
1076 for (; *p == ' ' || *p == '\t'; p++);
1077 if (*p && *p != '\n') {
1078 printf("max 4 fields per line, found a 5th\n");
1083 if ((serverfile && !resolvepeer(server, NULL)) ||
1084 (clientfile && !resolvepeer(NULL, client))) {
1085 printf("failed to resolve host %s port %s, exiting\n", *host, *port);
1090 pthread_mutex_init(&server->lock, NULL);
1092 server->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1093 if (!server->requests)
1094 errx("malloc failed");
1095 memset(server->requests, 0, MAX_REQUESTS * sizeof(struct request));
1097 pthread_mutex_init(&server->newrq_mutex, NULL);
1098 pthread_cond_init(&server->newrq_cond, NULL);
1101 client->replyq = &udp_server_replyq;
1103 client->replyq = malloc(sizeof(struct replyq));
1104 if (!client->replyq)
1105 errx("malloc failed");
1106 client->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1107 if (!client->replyq->replies)
1108 errx("malloc failed");
1109 client->replyq->size = MAX_REQUESTS;
1110 client->replyq->count = 0;
1111 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1112 pthread_cond_init(&client->replyq->count_cond, NULL);
1115 printf("got type %c, host %s, port %s, secret %s\n", *type, *host, *port, *secret);
1117 printf(" with realms:");
1118 for (r = server->realms; *r; r++)
1127 void parseargs(int argc, char **argv) {
1130 while ((c = getopt(argc, argv, "p:")) != -1) {
1133 udp_server_port = optarg;
1143 printf("radsecproxy [ -p UDP-port ]\n");
1147 int main(int argc, char **argv) {
1148 SSL_CTX *ssl_ctx_srv;
1149 unsigned long error;
1150 pthread_t udpserverth;
1151 pthread_attr_t joinable;
1154 parseargs(argc, argv);
1155 getconfig("servers.conf", NULL);
1156 getconfig(NULL, "clients.conf");
1160 pthread_attr_init(&joinable);
1161 pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1163 /* listen on UDP if at least one UDP client */
1165 for (i = 0; i < client_count; i++)
1166 if (clients[i].type == 'U') {
1167 if (pthread_create(&udpserverth, &joinable, udpserverrd, NULL))
1168 errx("pthread_create failed");
1173 SSL_load_error_strings();
1176 while (!RAND_status()) {
1177 time_t t = time(NULL);
1178 pid_t pid = getpid();
1179 RAND_seed((unsigned char *)&t, sizeof(time_t));
1180 RAND_seed((unsigned char *)&pid, sizeof(pid));
1183 /* initialise client part and start clients */
1184 ssl_ctx_cl = SSL_CTX_new(TLSv1_client_method());
1188 for (i = 0; i < server_count; i++) {
1189 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1190 errx("pthread_create failed");
1193 for (i = 0; i < client_count; i++)
1194 if (clients[i].type == 'T')
1197 if (i == client_count) {
1198 printf("No TLS clients defined, not starting TLS listener\n");
1199 /* just hang around doing nothing, anything to do here? */
1204 /* setting up server/daemon part */
1205 ssl_ctx_srv = SSL_CTX_new(TLSv1_server_method());
1208 if (!SSL_CTX_use_certificate_file(ssl_ctx_srv, "/tmp/server.pem", SSL_FILETYPE_PEM)) {
1209 while ((error = ERR_get_error()))
1210 err("SSL: %s", ERR_error_string(error, NULL));
1211 errx("Failed to load certificate");
1213 if (!SSL_CTX_use_PrivateKey_file(ssl_ctx_srv, "/tmp/server.key", SSL_FILETYPE_PEM)) {
1214 while ((error = ERR_get_error()))
1215 err("SSL: %s", ERR_error_string(error, NULL));
1216 errx("Failed to load private key");
1219 return tlslistener(ssl_ctx_srv);