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 <openssl/hmac.h>
55 #include "radsecproxy.h"
57 static struct client clients[MAX_PEERS];
58 static struct server servers[MAX_PEERS];
60 static int client_count = 0;
61 static int server_count = 0;
63 static struct replyq udp_server_replyq;
64 static int udp_server_sock = -1;
65 static char *udp_server_port = DEFAULT_UDP_PORT;
66 static pthread_mutex_t *ssl_locks;
67 static long *ssl_lock_count;
68 static SSL_CTX *ssl_ctx_cl;
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74 return (unsigned long)pthread_self();
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78 if (mode & CRYPTO_LOCK) {
79 pthread_mutex_lock(&ssl_locks[type]);
80 ssl_lock_count[type]++;
82 pthread_mutex_unlock(&ssl_locks[type]);
85 void ssl_locks_setup() {
88 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
89 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
90 for (i = 0; i < CRYPTO_num_locks(); i++) {
91 ssl_lock_count[i] = 0;
92 pthread_mutex_init(&ssl_locks[i], NULL);
95 CRYPTO_set_id_callback(ssl_thread_id);
96 CRYPTO_set_locking_callback(ssl_locking_callback);
99 int resolvepeer(struct peer *peer) {
100 struct addrinfo hints, *addrinfo;
102 memset(&hints, 0, sizeof(hints));
103 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
104 hints.ai_family = AF_UNSPEC;
105 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
106 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
111 freeaddrinfo(peer->addrinfo);
112 peer->addrinfo = addrinfo;
116 int connecttoserver(struct addrinfo *addrinfo) {
118 struct addrinfo *res;
120 for (res = addrinfo; res; res = res->ai_next) {
121 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
123 err("connecttoserver: socket failed");
126 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
128 err("connecttoserver: connect failed");
135 /* returns the client with matching address, or NULL */
136 /* if client argument is not NULL, we only check that one client */
137 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
138 struct sockaddr_in6 *sa6;
139 struct in_addr *a4 = NULL;
142 struct addrinfo *res;
144 if (addr->sa_family == AF_INET6) {
145 sa6 = (struct sockaddr_in6 *)addr;
146 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
147 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
149 a4 = &((struct sockaddr_in *)addr)->sin_addr;
151 c = (client ? client : clients);
152 for (i = 0; i < client_count; i++) {
153 if (c->peer.type == type)
154 for (res = c->peer.addrinfo; res; res = res->ai_next)
155 if ((a4 && res->ai_family == AF_INET &&
156 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
157 (res->ai_family == AF_INET6 &&
158 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
167 /* returns the server with matching address, or NULL */
168 /* if server argument is not NULL, we only check that one server */
169 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
170 struct sockaddr_in6 *sa6;
171 struct in_addr *a4 = NULL;
174 struct addrinfo *res;
176 if (addr->sa_family == AF_INET6) {
177 sa6 = (struct sockaddr_in6 *)addr;
178 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
179 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
181 a4 = &((struct sockaddr_in *)addr)->sin_addr;
183 s = (server ? server : servers);
184 for (i = 0; i < server_count; i++) {
185 if (s->peer.type == type)
186 for (res = s->peer.addrinfo; res; res = res->ai_next)
187 if ((a4 && res->ai_family == AF_INET &&
188 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
189 (res->ai_family == AF_INET6 &&
190 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
199 /* exactly one of client and server must be non-NULL */
200 /* if *peer == NULL we return who we received from, else require it to be from peer */
201 /* return from in sa if not NULL */
202 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
205 unsigned char buf[65536], *rad;
206 struct sockaddr_storage from;
207 socklen_t fromlen = sizeof(from);
210 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
212 err("radudpget: recv failed");
215 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
218 printf("radudpget: packet too small\n");
225 printf("radudpget: packet smaller than length field in radius header\n");
229 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
232 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
233 : (void *)find_server('U', (struct sockaddr *)&from, *server));
235 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
242 err("radudpget: malloc failed");
244 memcpy(rad, buf, len);
246 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
248 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
254 void tlsconnect(struct server *server, struct timeval *when, char *text) {
259 printf("tlsconnect called from %s\n", text);
260 pthread_mutex_lock(&server->lock);
261 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
262 /* already reconnected, nothing to do */
263 printf("tlsconnect(%s): seems already reconnected\n", text);
264 pthread_mutex_unlock(&server->lock);
268 printf("tlsconnect %s\n", text);
271 gettimeofday(&now, NULL);
272 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
273 if (server->connectionok) {
274 server->connectionok = 0;
276 } else if (elapsed < 5)
278 else if (elapsed < 600)
280 else if (elapsed < 10000) /* no sleep at startup */
282 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->peer.host, server->peer.port);
283 if (server->sock >= 0)
285 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
287 SSL_free(server->peer.ssl);
288 server->peer.ssl = SSL_new(ssl_ctx_cl);
289 SSL_set_fd(server->peer.ssl, server->sock);
290 if (SSL_connect(server->peer.ssl) > 0)
292 while ((error = ERR_get_error()))
293 err("tlsconnect: TLS: %s", ERR_error_string(error, NULL));
295 printf("tlsconnect: TLS connection to %s port %s up\n", server->peer.host, server->peer.port);
296 gettimeofday(&server->lastconnecttry, NULL);
297 pthread_mutex_unlock(&server->lock);
300 unsigned char *radtlsget(SSL *ssl) {
302 unsigned char buf[4], *rad;
305 for (total = 0; total < 4; total += cnt) {
306 cnt = SSL_read(ssl, buf + total, 4 - total);
308 printf("radtlsget: connection lost\n");
316 err("radtlsget: malloc failed");
321 for (; total < len; total += cnt) {
322 cnt = SSL_read(ssl, rad + total, len - total);
324 printf("radtlsget: connection lost\n");
334 printf("radtlsget: packet smaller than minimum radius size\n");
337 printf("radtlsget: got %d bytes\n", total);
341 int clientradput(struct server *server, unsigned char *rad) {
345 struct timeval lastconnecttry;
348 if (server->peer.type == 'U') {
349 if (send(server->sock, rad, len, 0) >= 0) {
350 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->peer.host, server->peer.port);
353 err("clientradput: send failed");
357 lastconnecttry = server->lastconnecttry;
358 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
359 while ((error = ERR_get_error()))
360 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
361 tlsconnect(server, &lastconnecttry, "clientradput");
362 lastconnecttry = server->lastconnecttry;
365 server->connectionok = 1;
366 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
367 cnt, len, server->peer.host);
371 int radsign(unsigned char *rad, unsigned char *sec) {
372 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
373 static unsigned char first = 1;
374 static EVP_MD_CTX mdctx;
378 pthread_mutex_lock(&lock);
380 EVP_MD_CTX_init(&mdctx);
384 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
385 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
386 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
387 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
389 pthread_mutex_unlock(&lock);
393 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
394 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
395 static unsigned char first = 1;
396 static EVP_MD_CTX mdctx;
397 unsigned char hash[EVP_MAX_MD_SIZE];
401 pthread_mutex_lock(&lock);
403 EVP_MD_CTX_init(&mdctx);
409 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
410 EVP_DigestUpdate(&mdctx, rad, 4) &&
411 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
412 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
413 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
414 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
416 !memcmp(hash, rad + 4, 16));
417 pthread_mutex_unlock(&lock);
421 void sendrq(struct server *to, struct client *from, struct request *rq) {
424 pthread_mutex_lock(&to->newrq_mutex);
425 for (i = 0; i < MAX_REQUESTS; i++)
426 if (!to->requests[i].buf)
428 if (i == MAX_REQUESTS) {
429 printf("No room in queue, dropping request\n");
430 pthread_mutex_unlock(&to->newrq_mutex);
434 rq->buf[1] = (char)i;
435 to->requests[i] = *rq;
439 printf("signalling client writer\n");
440 pthread_cond_signal(&to->newrq_cond);
442 pthread_mutex_unlock(&to->newrq_mutex);
445 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
446 struct replyq *replyq = to->replyq;
448 pthread_mutex_lock(&replyq->count_mutex);
449 if (replyq->count == replyq->size) {
450 printf("No room in queue, dropping request\n");
451 pthread_mutex_unlock(&replyq->count_mutex);
455 replyq->replies[replyq->count].buf = buf;
457 replyq->replies[replyq->count].tosa = *tosa;
460 if (replyq->count == 1) {
461 printf("signalling client writer\n");
462 pthread_cond_signal(&replyq->count_cond);
464 pthread_mutex_unlock(&replyq->count_mutex);
467 int pwdcrypt(uint8_t *plain, uint8_t *enc, uint8_t enclen, uint8_t *shared, uint8_t sharedlen,
469 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
470 static unsigned char first = 1;
471 static EVP_MD_CTX mdctx;
472 unsigned char hash[EVP_MAX_MD_SIZE], *input;
474 uint8_t i, offset = 0;
476 pthread_mutex_lock(&lock);
478 EVP_MD_CTX_init(&mdctx);
484 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
485 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
486 !EVP_DigestUpdate(&mdctx, input, 16) ||
487 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
489 pthread_mutex_unlock(&lock);
492 for (i = 0; i < 16; i++)
493 plain[offset + i] = hash[i] ^ enc[offset + i];
495 if (offset == enclen)
497 input = enc + offset - 16;
499 pthread_mutex_unlock(&lock);
503 struct server *id2server(char *id, uint8_t len) {
505 char **realm, *idrealm;
507 idrealm = strchr(id, '@');
515 for (i = 0; i < server_count; i++) {
516 for (realm = servers[i].realms; *realm; realm++) {
517 if ((strlen(*realm) == 1 && **realm == '*') ||
518 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
519 printf("found matching realm: %s, host %s\n", *realm, servers[i].peer.host);
527 int messageauth(char *rad, uint8_t *authattr, uint8_t *newauth, struct peer *from, struct peer *to) {
528 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
529 static unsigned char first = 1;
530 static HMAC_CTX hmacctx;
532 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
534 pthread_mutex_lock(&lock);
536 HMAC_CTX_init(&hmacctx);
540 memcpy(auth, authattr, 16);
541 memset(authattr, 0, 16);
543 HMAC_Init_ex(&hmacctx, from->secret, strlen(from->secret), EVP_md5(), NULL);
544 HMAC_Update(&hmacctx, rad, RADLEN(rad));
545 HMAC_Final(&hmacctx, hash, &md_len);
547 printf("message auth computation failed\n");
548 pthread_mutex_unlock(&lock);
552 if (memcmp(auth, hash, 16)) {
553 printf("message authenticator, wrong value\n");
554 pthread_mutex_unlock(&lock);
559 HMAC_Init_ex(&hmacctx, to->secret, strlen(to->secret), EVP_md5(), NULL);
560 HMAC_Update(&hmacctx, rad, RADLEN(rad));
561 HMAC_Final(&hmacctx, authattr, &md_len);
563 printf("message auth re-computation failed\n");
564 pthread_mutex_unlock(&lock);
568 pthread_mutex_unlock(&lock);
572 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
573 uint8_t code, id, *auth, *attr, pwd[128], attrvallen;
574 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
579 unsigned char newauth[16];
581 code = *(uint8_t *)buf;
582 id = *(uint8_t *)(buf + 1);
584 auth = (uint8_t *)(buf + 4);
586 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
588 if (code != RAD_Access_Request) {
589 printf("radsrv: server currently accepts only access-requests, ignoring\n");
597 left -= attr[RAD_Attr_Length];
599 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
602 switch (attr[RAD_Attr_Type]) {
603 case RAD_Attr_User_Name:
606 case RAD_Attr_User_Password:
609 case RAD_Attr_Tunnel_Password:
610 tunnelpwdattr = attr;
612 case RAD_Attr_Message_Authenticator:
613 messageauthattr = attr;
616 attr += attr[RAD_Attr_Length];
619 printf("radsrv: malformed packet? remaining byte after last attribute\n");
622 printf("radsrv: Username: ");
623 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
624 printf("%c", usernameattr[RAD_Attr_Value + i]);
628 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
630 printf("radsrv: ignoring request, don't know where to send it\n");
634 if (!RAND_bytes(newauth, 16)) {
635 printf("radsrv: failed to generate random auth\n");
639 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
640 !messageauth(buf, &messageauthattr[RAD_Attr_Value], newauth, &from->peer, &to->peer))) {
641 printf("radsrv: message authentication failed\n");
646 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
647 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
648 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
649 printf("radsrv: invalid user password length\n");
653 if (!pwdcrypt(pwd, &userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
654 printf("radsrv: cannot decrypt password\n");
657 printf("radsrv: password: ");
658 for (i = 0; i < attrvallen; i++)
659 printf("%02x ", pwd[i]);
661 if (!pwdcrypt(&userpwdattr[RAD_Attr_Value], pwd, attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
662 printf("radsrv: cannot encrypt password\n");
668 printf("radsrv: found tunnelpwdattr of length %d\n", tunnelpwdattr[RAD_Attr_Length]);
669 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
670 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
671 printf("radsrv: invalid user password length\n");
675 if (!pwdcrypt(pwd, &tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
676 printf("radsrv: cannot decrypt password\n");
679 printf("radsrv: password: ");
680 for (i = 0; i < attrvallen; i++)
681 printf("%02x ", pwd[i]);
683 if (!pwdcrypt(&tunnelpwdattr[RAD_Attr_Value], pwd, attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
684 printf("radsrv: cannot encrypt password\n");
692 memcpy(rq->origauth, auth, 16);
693 memcpy(rq->buf + 4, newauth, 16);
697 void *clientrd(void *arg) {
698 struct server *server = (struct server *)arg;
702 struct sockaddr_storage fromsa;
703 struct timeval lastconnecttry;
706 lastconnecttry = server->lastconnecttry;
707 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
708 if (!buf && server->peer.type == 'T') {
709 tlsconnect(server, &lastconnecttry, "clientrd");
713 server->connectionok = 1;
715 i = buf[1]; /* i is the id */
717 pthread_mutex_lock(&server->newrq_mutex);
718 if (!server->requests[i].buf || !server->requests[i].tries) {
719 pthread_mutex_unlock(&server->newrq_mutex);
720 printf("clientrd: no matching request sent with this id, ignoring\n");
724 if (server->requests[i].received) {
725 pthread_mutex_unlock(&server->newrq_mutex);
726 printf("clientrd: already received, ignoring\n");
730 if (!validauth(buf, server->requests[i].buf + 4, server->peer.secret)) {
731 pthread_mutex_unlock(&server->newrq_mutex);
732 printf("clientrd: invalid auth, ignoring\n");
736 /* once we set received = 1, requests[i] may be reused */
737 buf[1] = (char)server->requests[i].origid;
738 memcpy(buf + 4, server->requests[i].origauth, 16);
739 from = server->requests[i].from;
740 if (from->peer.type == 'U')
741 fromsa = server->requests[i].fromsa;
742 server->requests[i].received = 1;
743 pthread_mutex_unlock(&server->newrq_mutex);
745 if (!radsign(buf, from->peer.secret)) {
746 printf("clientrd: failed to sign message\n");
750 printf("clientrd: giving packet back to where it came from\n");
751 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
755 void *clientwr(void *arg) {
756 struct server *server = (struct server *)arg;
757 pthread_t clientrdth;
760 if (server->peer.type == 'U') {
761 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
762 printf("clientwr: connecttoserver failed\n");
766 tlsconnect(server, NULL, "new client");
768 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
769 errx("clientwr: pthread_create failed");
772 pthread_mutex_lock(&server->newrq_mutex);
773 while (!server->newrq) {
774 printf("clientwr: waiting for signal\n");
775 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
776 printf("clientwr: got signal\n");
779 pthread_mutex_unlock(&server->newrq_mutex);
781 for (i = 0; i < MAX_REQUESTS; i++) {
782 pthread_mutex_lock(&server->newrq_mutex);
783 while (!server->requests[i].buf && i < MAX_REQUESTS)
785 if (i == MAX_REQUESTS) {
786 pthread_mutex_unlock(&server->newrq_mutex);
790 /* already received or too many tries */
791 if (server->requests[i].received || server->requests[i].tries > 2) {
792 free(server->requests[i].buf);
793 /* setting this to NULL means that it can be reused */
794 server->requests[i].buf = NULL;
795 pthread_mutex_unlock(&server->newrq_mutex);
798 pthread_mutex_unlock(&server->newrq_mutex);
800 server->requests[i].tries++;
801 clientradput(server, server->requests[i].buf);
804 /* should do more work to maintain TLS connections, keepalives etc */
807 void *udpserverwr(void *arg) {
808 struct replyq *replyq = &udp_server_replyq;
809 struct reply *reply = replyq->replies;
811 pthread_mutex_lock(&replyq->count_mutex);
813 while (!replyq->count) {
814 printf("udp server writer, waiting for signal\n");
815 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
816 printf("udp server writer, got signal\n");
818 pthread_mutex_unlock(&replyq->count_mutex);
820 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
821 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
822 err("sendudp: send failed");
825 pthread_mutex_lock(&replyq->count_mutex);
827 memmove(replyq->replies, replyq->replies + 1,
828 replyq->count * sizeof(struct reply));
832 void *udpserverrd(void *arg) {
837 pthread_t udpserverwrth;
839 if ((udp_server_sock = bindport(SOCK_DGRAM, udp_server_port)) < 0) {
840 printf("udpserverrd: socket/bind failed\n");
843 printf("udpserverrd: listening on UDP port %s\n", udp_server_port);
845 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
846 errx("pthread_create failed");
850 memset(&rq, 0, sizeof(struct request));
851 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
852 to = radsrv(&rq, buf, fr);
854 printf("udpserverrd: ignoring request, no place to send it\n");
861 void *tlsserverwr(void *arg) {
864 struct client *client = (struct client *)arg;
865 struct replyq *replyq;
867 pthread_mutex_lock(&client->replycount_mutex);
869 replyq = client->replyq;
870 while (!replyq->count) {
871 printf("tls server writer, waiting for signal\n");
872 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
873 printf("tls server writer, got signal\n");
875 pthread_mutex_unlock(&replyq->count_mutex);
876 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
878 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
879 cnt, RADLEN(replyq->replies->buf));
881 while ((error = ERR_get_error()))
882 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
883 free(replyq->replies->buf);
885 pthread_mutex_lock(&replyq->count_mutex);
887 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
891 void *tlsserverrd(void *arg) {
897 struct client *client = (struct client *)arg;
898 pthread_t tlsserverwrth;
900 printf("tlsserverrd starting\n");
901 if (SSL_accept(client->peer.ssl) <= 0) {
902 while ((error = ERR_get_error()))
903 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
904 errx("accept failed, child exiting");
907 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
908 errx("pthread_create failed");
911 buf = radtlsget(client->peer.ssl);
913 printf("tlsserverrd: connection lost\n");
914 s = SSL_get_fd(client->peer.ssl);
915 SSL_free(client->peer.ssl);
916 client->peer.ssl = NULL;
921 printf("tlsserverrd: got Radius message from %s\n", client->peer.host);
922 memset(&rq, 0, sizeof(struct request));
923 to = radsrv(&rq, buf, client);
925 printf("ignoring request, no place to send it\n");
928 sendrq(to, client, &rq);
932 int tlslistener(SSL_CTX *ssl_ctx) {
933 pthread_t tlsserverth;
935 struct sockaddr_storage from;
936 size_t fromlen = sizeof(from);
937 struct client *client;
939 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
940 printf("tlslistener: socket/bind failed\n");
945 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
948 snew = accept(s, (struct sockaddr *)&from, &fromlen);
950 errx("accept failed");
951 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
953 client = find_client('T', (struct sockaddr *)&from, NULL);
955 printf("ignoring request, not a known TLS client\n");
960 if (client->peer.ssl) {
961 printf("Ignoring incoming connection, already have one from this client\n");
965 client->peer.ssl = SSL_new(ssl_ctx);
966 SSL_set_fd(client->peer.ssl, snew);
967 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
968 errx("pthread_create failed");
973 char *parsehostport(char *s, struct peer *peer) {
978 // allow literal addresses and port, e.g. [2001:db8::1]:1812
982 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
984 printf("no ] matching initial [\n");
990 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
993 printf("missing host/address\n");
996 peer->host = malloc(p - field + 1);
998 errx("malloc failed");
999 memcpy(peer->host, field, p - field);
1000 peer->host[p - field] = '\0';
1003 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
1004 printf("unexpected character after ]\n");
1009 /* port number or service name is specified */;
1011 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1013 printf("syntax error, : but no following port\n");
1016 peer->port = malloc(p - field + 1);
1018 errx("malloc failed");
1019 memcpy(peer->port, field, p - field);
1020 peer->port[p - field] = '\0';
1026 // * is default, else longest match ... ";" used for separator
1027 char *parserealmlist(char *s, struct server *server) {
1031 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1036 server->realms = NULL;
1039 server->realmdata = malloc(l + 1);
1040 if (!server->realmdata)
1041 errx("malloc failed");
1042 memcpy(server->realmdata, s, l);
1043 server->realmdata[l] = '\0';
1044 server->realms = malloc((1+n) * sizeof(char *));
1045 if (!server->realms)
1046 errx("malloc failed");
1047 server->realms[0] = server->realmdata;
1048 for (n = 1, i = 0; i < l; i++)
1049 if (server->realmdata[i] == ';') {
1050 server->realmdata[i] = '\0';
1051 server->realms[n++] = server->realmdata + i + 1;
1053 server->realms[n] = NULL;
1057 /* exactly one argument must be non-NULL */
1058 void getconfig(const char *serverfile, const char *clientfile) {
1061 char *p, *field, **r;
1062 struct client *client;
1063 struct server *server;
1068 printf("opening file %s for reading\n", serverfile);
1069 f = fopen(serverfile, "r");
1071 errx("getconfig failed to open %s for reading", serverfile);
1072 count = &server_count;
1074 printf("opening file %s for reading\n", clientfile);
1075 f = fopen(clientfile, "r");
1077 errx("getconfig failed to open %s for reading", clientfile);
1078 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
1079 if (!udp_server_replyq.replies)
1080 errx("malloc failed");
1081 udp_server_replyq.size = 4 * MAX_REQUESTS;
1082 udp_server_replyq.count = 0;
1083 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1084 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1085 count = &client_count;
1089 while (fgets(line, 1024, f) && *count < MAX_PEERS) {
1091 server = &servers[*count];
1092 memset(server, 0, sizeof(struct server));
1093 peer = &server->peer;
1095 client = &clients[*count];
1096 memset(client, 0, sizeof(struct client));
1097 peer = &client->peer;
1099 for (p = line; *p == ' ' || *p == '\t'; p++);
1100 if (*p == '#' || *p == '\n')
1102 if (*p != 'U' && *p != 'T') {
1103 printf("server type must be U or T, got %c\n", *p);
1107 for (p++; *p == ' ' || *p == '\t'; p++);
1108 p = parsehostport(p, peer);
1110 peer->port = (peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT);
1111 for (; *p == ' ' || *p == '\t'; p++);
1113 p = parserealmlist(p, server);
1114 if (!server->realms) {
1115 printf("realm list must be specified\n");
1118 for (; *p == ' ' || *p == '\t'; p++);
1121 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1123 /* no secret set and end of line, line is complete if TLS */
1124 if (peer->type == 'U') {
1125 printf("secret must be specified for UDP\n");
1128 peer->secret = DEFAULT_TLS_SECRET;
1130 peer->secret = malloc(p - field + 1);
1132 errx("malloc failed");
1133 memcpy(peer->secret, field, p - field);
1134 peer->secret[p - field] = '\0';
1135 /* check that rest of line only white space */
1136 for (; *p == ' ' || *p == '\t'; p++);
1137 if (*p && *p != '\n') {
1138 printf("max 4 fields per line, found a 5th\n");
1143 if ((serverfile && !resolvepeer(&server->peer)) ||
1144 (clientfile && !resolvepeer(&client->peer))) {
1145 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1150 pthread_mutex_init(&server->lock, NULL);
1152 server->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1153 if (!server->requests)
1154 errx("malloc failed");
1155 memset(server->requests, 0, MAX_REQUESTS * sizeof(struct request));
1157 pthread_mutex_init(&server->newrq_mutex, NULL);
1158 pthread_cond_init(&server->newrq_cond, NULL);
1160 if (peer->type == 'U')
1161 client->replyq = &udp_server_replyq;
1163 client->replyq = malloc(sizeof(struct replyq));
1164 if (!client->replyq)
1165 errx("malloc failed");
1166 client->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1167 if (!client->replyq->replies)
1168 errx("malloc failed");
1169 client->replyq->size = MAX_REQUESTS;
1170 client->replyq->count = 0;
1171 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1172 pthread_cond_init(&client->replyq->count_cond, NULL);
1175 printf("got type %c, host %s, port %s, secret %s\n", peer->type, peer->host, peer->port, peer->secret);
1177 printf(" with realms:");
1178 for (r = server->realms; *r; r++)
1187 void parseargs(int argc, char **argv) {
1190 while ((c = getopt(argc, argv, "p:")) != -1) {
1193 udp_server_port = optarg;
1203 printf("radsecproxy [ -p UDP-port ]\n");
1207 int main(int argc, char **argv) {
1208 SSL_CTX *ssl_ctx_srv;
1209 unsigned long error;
1210 pthread_t udpserverth;
1211 pthread_attr_t joinable;
1214 parseargs(argc, argv);
1215 getconfig("servers.conf", NULL);
1216 getconfig(NULL, "clients.conf");
1220 pthread_attr_init(&joinable);
1221 pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1223 /* listen on UDP if at least one UDP client */
1225 for (i = 0; i < client_count; i++)
1226 if (clients[i].peer.type == 'U') {
1227 if (pthread_create(&udpserverth, &joinable, udpserverrd, NULL))
1228 errx("pthread_create failed");
1233 SSL_load_error_strings();
1236 while (!RAND_status()) {
1237 time_t t = time(NULL);
1238 pid_t pid = getpid();
1239 RAND_seed((unsigned char *)&t, sizeof(time_t));
1240 RAND_seed((unsigned char *)&pid, sizeof(pid));
1243 /* initialise client part and start clients */
1244 ssl_ctx_cl = SSL_CTX_new(TLSv1_client_method());
1248 for (i = 0; i < server_count; i++) {
1249 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1250 errx("pthread_create failed");
1253 for (i = 0; i < client_count; i++)
1254 if (clients[i].peer.type == 'T')
1257 if (i == client_count) {
1258 printf("No TLS clients defined, not starting TLS listener\n");
1259 /* just hang around doing nothing, anything to do here? */
1264 /* setting up server/daemon part */
1265 ssl_ctx_srv = SSL_CTX_new(TLSv1_server_method());
1268 if (!SSL_CTX_use_certificate_file(ssl_ctx_srv, "/tmp/server.pem", SSL_FILETYPE_PEM)) {
1269 while ((error = ERR_get_error()))
1270 err("SSL: %s", ERR_error_string(error, NULL));
1271 errx("Failed to load certificate");
1273 if (!SSL_CTX_use_PrivateKey_file(ssl_ctx_srv, "/tmp/server.key", SSL_FILETYPE_PEM)) {
1274 while ((error = ERR_get_error()))
1275 err("SSL: %s", ERR_error_string(error, NULL));
1276 errx("Failed to load private key");
1279 return tlslistener(ssl_ctx_srv);