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 peer peers[MAX_PEERS];
57 static int peer_count = 0;
59 static struct replyq udp_server_replyq;
60 static int udp_server_sock = -1;
61 static char *udp_server_port = DEFAULT_UDP_PORT;
62 static pthread_mutex_t *ssl_locks;
63 static long *ssl_lock_count;
64 static SSL_CTX *ssl_ctx_cl;
68 /* callbacks for making OpenSSL thread safe */
69 unsigned long ssl_thread_id() {
70 return (unsigned long)pthread_self();
73 void ssl_locking_callback(int mode, int type, const char *file, int line) {
74 if (mode & CRYPTO_LOCK) {
75 pthread_mutex_lock(&ssl_locks[type]);
76 ssl_lock_count[type]++;
78 pthread_mutex_unlock(&ssl_locks[type]);
81 void ssl_locks_setup() {
84 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
85 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
86 for (i = 0; i < CRYPTO_num_locks(); i++) {
87 ssl_lock_count[i] = 0;
88 pthread_mutex_init(&ssl_locks[i], NULL);
91 CRYPTO_set_id_callback(ssl_thread_id);
92 CRYPTO_set_locking_callback(ssl_locking_callback);
95 int resolvepeer(struct peer *peer) {
96 struct addrinfo hints;
98 pthread_mutex_lock(&peer->lock);
100 /* assume we should re-resolve */
101 freeaddrinfo(peer->addrinfo);
102 peer->addrinfo = NULL;
105 memset(&hints, 0, sizeof(hints));
106 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
107 hints.ai_family = AF_UNSPEC;
108 if (getaddrinfo(peer->host, peer->port, &hints, &peer->addrinfo)) {
109 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
110 peer->addrinfo = NULL; /* probably don't need this */
111 pthread_mutex_unlock(&peer->lock);
114 pthread_mutex_unlock(&peer->lock);
118 int connecttopeer(struct peer *peer) {
120 struct addrinfo *res;
122 if (!peer->addrinfo) {
124 if (!peer->addrinfo) {
125 printf("connecttopeer: can't resolve %s into address to connect to\n", peer->host);
130 for (res = peer->addrinfo; res; res = res->ai_next) {
131 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
133 err("connecttopeer: socket failed");
136 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
138 err("connecttopeer: connect failed");
145 /* returns the peer with matching address, or NULL */
146 /* if peer argument is not NULL, we only check that one peer */
147 struct peer *find_peer(char type, struct sockaddr *addr, struct peer *peer) {
148 struct sockaddr_in6 *sa6;
149 struct in_addr *a4 = NULL;
152 struct addrinfo *res;
154 if (addr->sa_family == AF_INET6) {
155 sa6 = (struct sockaddr_in6 *)addr;
156 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
157 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
159 a4 = &((struct sockaddr_in *)addr)->sin_addr;
161 p = (peer ? peer : peers);
162 for (i = 0; i < peer_count; i++) {
164 for (res = p->addrinfo; res; res = res->ai_next)
165 if ((a4 && res->ai_family == AF_INET &&
166 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
167 (res->ai_family == AF_INET6 &&
168 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
177 /* if *peer == NULL we return who we received from, else require it to be from peer */
178 /* return from in sa if not NULL */
179 unsigned char *radudpget(int s, struct peer **peer, struct sockaddr_storage *sa) {
182 unsigned char buf[65536], *rad;
183 struct sockaddr_storage from;
184 socklen_t fromlen = sizeof(from);
187 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
189 err("radudpget: recv failed");
192 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
195 printf("radudpget: packet too small\n");
202 printf("radudpget: packet smaller than length field in radius header\n");
206 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
208 f = find_peer('U', (struct sockaddr *)&from, *peer);
210 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
217 err("radudpget: malloc failed");
219 memcpy(rad, buf, len);
220 *peer = f; /* only need this if *peer == NULL, but if not NULL *peer == f here */
226 void tlsconnect(struct peer *peer, struct timeval *when, char *text) {
231 pthread_mutex_lock(&peer->lock);
232 if (when && memcmp(&peer->lastconnecttry, when, sizeof(struct timeval))) {
233 /* already reconnected, nothing to do */
234 printf("tlsconnect: seems already reconnected\n");
235 pthread_mutex_unlock(&peer->lock);
239 printf("tlsconnect %s\n", text);
242 printf("tlsconnect: trying to open TLS connection to %s port %s\n", peer->host, peer->port);
243 gettimeofday(&now, NULL);
244 elapsed = now.tv_sec - peer->lastconnecttry.tv_sec;
245 memcpy(&peer->lastconnecttry, &now, sizeof(struct timeval));
246 if (peer->connectionok) {
247 peer->connectionok = 0;
249 } else if (elapsed < 5)
251 else if (elapsed < 600)
253 else if (elapsed < 10000) /* no sleep at startup */
255 if (peer->sockcl >= 0)
257 if ((peer->sockcl = connecttopeer(peer)) < 0)
259 SSL_free(peer->sslcl);
260 peer->sslcl = SSL_new(ssl_ctx_cl);
261 SSL_set_fd(peer->sslcl, peer->sockcl);
262 if (SSL_connect(peer->sslcl) > 0)
264 while ((error = ERR_get_error()))
265 err("tlsconnect: TLS: %s", ERR_error_string(error, NULL));
267 printf("tlsconnect: TLS connection to %s port %s up\n", peer->host, peer->port);
268 pthread_mutex_unlock(&peer->lock);
271 unsigned char *radtlsget(SSL *ssl) {
273 unsigned char buf[4], *rad;
276 for (total = 0; total < 4; total += cnt) {
277 cnt = SSL_read(ssl, buf + total, 4 - total);
279 printf("radtlsget: connection lost\n");
287 err("radtlsget: malloc failed");
292 for (; total < len; total += cnt) {
293 cnt = SSL_read(ssl, rad + total, len - total);
295 printf("radtlsget: connection lost\n");
305 printf("radtlsget: packet smaller than minimum radius size\n");
308 printf("radtlsget: got %d bytes\n", total);
312 int clientradput(struct peer *peer, unsigned char *rad) {
316 struct timeval lastconnecttry;
319 if (peer->type == 'U') {
320 if (send(peer->sockcl, rad, len, 0) >= 0) {
321 printf("clienradput: sent UDP of length %d to %s port %s\n", len, peer->host, peer->port);
324 err("clientradput: send failed");
328 lastconnecttry = peer->lastconnecttry;
329 while ((cnt = SSL_write(peer->sslcl, rad, len)) <= 0) {
330 while ((error = ERR_get_error()))
331 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
332 tlsconnect(peer, &lastconnecttry, "clientradput");
333 lastconnecttry = peer->lastconnecttry;
336 peer->connectionok = 1;
337 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
338 cnt, len, peer->host);
342 int radsign(unsigned char *rad, unsigned char *sec) {
343 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
344 static unsigned char first = 1;
345 static EVP_MD_CTX mdctx;
349 pthread_mutex_lock(&lock);
351 EVP_MD_CTX_init(&mdctx);
355 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
356 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
357 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
358 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
360 pthread_mutex_unlock(&lock);
364 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
365 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
366 static unsigned char first = 1;
367 static EVP_MD_CTX mdctx;
368 unsigned char hash[EVP_MAX_MD_SIZE];
372 pthread_mutex_lock(&lock);
374 EVP_MD_CTX_init(&mdctx);
380 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
381 EVP_DigestUpdate(&mdctx, rad, 4) &&
382 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
383 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
384 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
385 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
387 !memcmp(hash, rad + 4, 16));
388 pthread_mutex_unlock(&lock);
392 void sendrq(struct peer *to, struct peer *from, struct request *rq) {
395 pthread_mutex_lock(&to->newrq_mutex);
396 for (i = 0; i < MAX_REQUESTS; i++)
397 if (!to->requests[i].buf)
399 if (i == MAX_REQUESTS) {
400 printf("No room in queue, dropping request\n");
401 pthread_mutex_unlock(&to->newrq_mutex);
405 rq->buf[1] = (char)i;
406 to->requests[i] = *rq;
410 printf("signalling client writer\n");
411 pthread_cond_signal(&to->newrq_cond);
413 pthread_mutex_unlock(&to->newrq_mutex);
416 void sendreply(struct peer *to, struct peer *from, char *buf, struct sockaddr_storage *tosa) {
417 struct replyq *replyq = to->replyq;
419 pthread_mutex_lock(&replyq->count_mutex);
420 if (replyq->count == replyq->size) {
421 printf("No room in queue, dropping request\n");
422 pthread_mutex_unlock(&replyq->count_mutex);
426 replyq->replies[replyq->count].buf = buf;
428 replyq->replies[replyq->count].tosa = *tosa;
431 if (replyq->count == 1) {
432 printf("signalling client writer\n");
433 pthread_cond_signal(&replyq->count_cond);
435 pthread_mutex_unlock(&replyq->count_mutex);
438 int pwdcrypt(uint8_t *plain, uint8_t *enc, uint8_t enclen, uint8_t *shared, uint8_t sharedlen,
440 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
441 static unsigned char first = 1;
442 static EVP_MD_CTX mdctx;
443 unsigned char hash[EVP_MAX_MD_SIZE], *input;
445 uint8_t i, offset = 0;
447 pthread_mutex_lock(&lock);
449 EVP_MD_CTX_init(&mdctx);
455 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
456 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
457 !EVP_DigestUpdate(&mdctx, input, 16) ||
458 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
460 pthread_mutex_unlock(&lock);
463 for (i = 0; i < 16; i++)
464 plain[offset + i] = hash[i] ^ enc[offset + i];
466 if (offset == enclen)
468 input = enc + offset - 16;
470 pthread_mutex_unlock(&lock);
474 struct peer *id2peer(char *id, uint8_t len) {
478 for (i = 0; i < peer_count; i++) {
479 for (realm = peers[i].realms; *realm; realm++) {
480 /* assume test@domain */
481 printf("realmlength %d, usernamelength %d\n", strlen(*realm), len);
482 if (strlen(*realm) == len - 5) {
483 printf("lengths match\n");
484 if (!memcmp(id + 5, *realm, len - 5)) {
485 printf("found matching realm: %s, host %s\n", *realm, peers[i].host);
494 struct peer *radsrv(struct request *rq, char *buf, struct peer *from) {
495 uint8_t code, id, *auth, *attr, *usernameattr = NULL, *userpwdattr = NULL, pwd[128], pwdlen;
500 unsigned char newauth[16];
502 code = *(uint8_t *)buf;
503 id = *(uint8_t *)(buf + 1);
505 auth = (uint8_t *)(buf + 4);
507 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
509 if (code != RAD_Access_Request) {
510 printf("radsrv: server currently accepts only access-requests, ignoring\n");
518 left -= attr[RAD_Attr_Length];
520 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
523 switch (attr[RAD_Attr_Type]) {
524 case RAD_Attr_User_Name:
527 case RAD_Attr_User_Password:
531 attr += attr[RAD_Attr_Length];
534 printf("radsrv: malformed packet? remaining byte after last attribute\n");
537 printf("radsrv: Username: ");
538 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
539 printf("%c", usernameattr[RAD_Attr_Value + i]);
543 /* find out where to send the packet, for now we send to first connected
544 TLS peer if UDP, and first UDP peer if TLS */
546 to = id2peer(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
548 printf("radsrv: ignoring request, don't know where to send it\n");
555 switch (from->type) {
557 for (i = 0; i < peer_count; i++)
558 if (peers[i].type == 'T' && peers[i].sockcl >= 0)
562 for (i = 0; i < peer_count; i++)
563 if (peers[i].type == 'U')
567 if (i == peer_count) {
568 printf("radsrv: ignoring request, don't know where to send it\n");
576 if (!RAND_bytes(newauth, 16)) {
577 printf("radsrv: failed to generate random auth\n");
582 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
583 pwdlen = userpwdattr[RAD_Attr_Length] - 2;
584 if (pwdlen < 16 || pwdlen > 128 || pwdlen % 16) {
585 printf("radsrv: invalid user password length\n");
589 if (!pwdcrypt(pwd, &userpwdattr[RAD_Attr_Value], pwdlen, from->secret, strlen(from->secret), auth)) {
590 printf("radsrv: cannot decrypt password\n");
593 printf("radsrv: password: ");
594 for (i = 0; i < pwdlen; i++)
595 printf("%02x ", pwd[i]);
597 if (!pwdcrypt(&userpwdattr[RAD_Attr_Value], pwd, pwdlen, to->secret, strlen(to->secret), newauth)) {
598 printf("radsrv: cannot encrypt password\n");
606 memcpy(rq->origauth, auth, 16);
607 memcpy(rq->buf + 4, newauth, 16);
611 void *clientrd(void *arg) {
612 struct peer *from, *peer = (struct peer *)arg;
615 struct sockaddr_storage fromsa;
616 struct timeval lastconnecttry;
619 lastconnecttry = peer->lastconnecttry;
620 buf = (peer->type == 'U' ? radudpget(peer->sockcl, &peer, NULL) : radtlsget(peer->sslcl));
621 if (!buf && peer->type == 'T') {
622 tlsconnect(peer, &lastconnecttry, "clientrd");
626 peer->connectionok = 1;
628 i = buf[1]; /* i is the id */
630 pthread_mutex_lock(&peer->newrq_mutex);
631 if (!peer->requests[i].buf || !peer->requests[i].tries) {
632 pthread_mutex_unlock(&peer->newrq_mutex);
633 printf("clientrd: no matching request sent with this id, ignoring\n");
637 if (peer->requests[i].received) {
638 pthread_mutex_unlock(&peer->newrq_mutex);
639 printf("clientrd: already received, ignoring\n");
643 if (!validauth(buf, peer->requests[i].buf + 4, peer->secret)) {
644 pthread_mutex_unlock(&peer->newrq_mutex);
645 printf("clientrd: invalid auth, ignoring\n");
649 /* once we set received = 1, requests[i] may be reused */
650 buf[1] = (char)peer->requests[i].origid;
651 memcpy(buf + 4, peer->requests[i].origauth, 16);
652 from = peer->requests[i].from;
653 if (from->type == 'U')
654 fromsa = peer->requests[i].fromsa;
655 peer->requests[i].received = 1;
656 pthread_mutex_unlock(&peer->newrq_mutex);
658 if (!radsign(buf, from->secret)) {
659 printf("clientrd: failed to sign message\n");
663 printf("clientrd: giving packet back to where it came from\n");
664 sendreply(from, peer, buf, from->type == 'U' ? &fromsa : NULL);
668 void *clientwr(void *arg) {
669 struct peer *peer = (struct peer *)arg;
670 pthread_t clientrdth;
673 if (peer->type == 'U') {
674 if ((peer->sockcl = connecttopeer(peer)) < 0) {
675 printf("clientwr: connecttopeer failed\n");
679 tlsconnect(peer, NULL, "new client");
681 if (pthread_create(&clientrdth, NULL, clientrd, (void *)peer))
682 errx("clientwr: pthread_create failed");
685 pthread_mutex_lock(&peer->newrq_mutex);
686 while (!peer->newrq) {
687 printf("clientwr: waiting for signal\n");
688 pthread_cond_wait(&peer->newrq_cond, &peer->newrq_mutex);
689 printf("clientwr: got signal\n");
692 pthread_mutex_unlock(&peer->newrq_mutex);
694 for (i = 0; i < MAX_REQUESTS; i++) {
695 pthread_mutex_lock(&peer->newrq_mutex);
696 while (!peer->requests[i].buf && i < MAX_REQUESTS)
698 if (i == MAX_REQUESTS) {
699 pthread_mutex_unlock(&peer->newrq_mutex);
703 /* already received or too many tries */
704 if (peer->requests[i].received || peer->requests[i].tries > 2) {
705 free(peer->requests[i].buf);
706 /* setting this to NULL means that it can be reused */
707 peer->requests[i].buf = NULL;
708 pthread_mutex_unlock(&peer->newrq_mutex);
711 pthread_mutex_unlock(&peer->newrq_mutex);
713 peer->requests[i].tries++;
714 clientradput(peer, peer->requests[i].buf);
717 /* should do more work to maintain TLS connections, keepalives etc */
720 void *udpserverwr(void *arg) {
721 struct replyq *replyq = &udp_server_replyq;
722 struct reply *reply = replyq->replies;
724 pthread_mutex_lock(&replyq->count_mutex);
726 while (!replyq->count) {
727 printf("udp server writer, waiting for signal\n");
728 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
729 printf("udp server writer, got signal\n");
731 pthread_mutex_unlock(&replyq->count_mutex);
733 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
734 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
735 err("sendudp: send failed");
738 pthread_mutex_lock(&replyq->count_mutex);
740 memmove(replyq->replies, replyq->replies + 1,
741 replyq->count * sizeof(struct reply));
745 void *udpserverrd(void *arg) {
748 struct peer *to, *fr;
749 pthread_t udpserverwrth;
751 if ((udp_server_sock = bindport(SOCK_DGRAM, udp_server_port)) < 0) {
752 printf("udpserverrd: socket/bind failed\n");
755 printf("udpserverrd: listening on UDP port %s\n", udp_server_port);
757 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
758 errx("pthread_create failed");
762 memset(&rq, 0, sizeof(struct request));
763 buf = radudpget(udp_server_sock, &fr, &rq.fromsa);
764 to = radsrv(&rq, buf, fr);
766 printf("udpserverrd: ignoring request, no place to send it\n");
773 void *tlsserverwr(void *arg) {
776 struct peer *peer = (struct peer *)arg;
777 struct replyq *replyq;
779 pthread_mutex_lock(&peer->replycount_mutex);
781 replyq = peer->replyq;
782 while (!replyq->count) {
783 printf("tls server writer, waiting for signal\n");
784 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
785 printf("tls server writer, got signal\n");
787 pthread_mutex_unlock(&replyq->count_mutex);
788 cnt = SSL_write(peer->sslsrv, replyq->replies->buf, RADLEN(replyq->replies->buf));
790 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
791 cnt, RADLEN(replyq->replies->buf));
793 while ((error = ERR_get_error()))
794 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
795 free(replyq->replies->buf);
797 pthread_mutex_lock(&replyq->count_mutex);
799 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
803 void *tlsserverrd(void *arg) {
809 struct peer *peer = (struct peer *)arg;
810 pthread_t tlsserverwrth;
812 printf("tlsserverrd starting\n");
813 if (SSL_accept(peer->sslsrv) <= 0) {
814 while ((error = ERR_get_error()))
815 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
816 errx("accept failed, child exiting");
819 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)peer))
820 errx("pthread_create failed");
823 buf = radtlsget(peer->sslsrv);
825 printf("tlsserverrd: connection lost\n");
826 s = SSL_get_fd(peer->sslsrv);
827 SSL_free(peer->sslsrv);
833 printf("tlsserverrd: got Radius message from %s\n", peer->host);
834 memset(&rq, 0, sizeof(struct request));
835 to = radsrv(&rq, buf, peer);
837 printf("ignoring request, no place to send it\n");
840 sendrq(to, peer, &rq);
844 int tlslistener(SSL_CTX *ssl_ctx) {
845 pthread_t tlsserverth;
847 struct sockaddr_storage from;
848 size_t fromlen = sizeof(from);
851 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
852 printf("tlslistener: socket/bind failed\n");
857 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
860 snew = accept(s, (struct sockaddr *)&from, &fromlen);
862 errx("accept failed");
863 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
865 peer = find_peer('T', (struct sockaddr *)&from, NULL);
867 printf("ignoring request, not a known TLS peer\n");
873 printf("Ignoring incoming connection, already have one from this peer\n");
877 peer->sslsrv = SSL_new(ssl_ctx);
878 SSL_set_fd(peer->sslsrv, snew);
879 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)peer))
880 errx("pthread_create failed");
885 char *parsehostport(char *s, struct peer *peer) {
890 // allow literal addresses and port, e.g. [2001:db8::1]:1812
894 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
896 printf("no ] matching initial [\n");
902 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
905 printf("missing host/address\n");
908 peer->host = malloc(p - field + 1);
910 errx("malloc failed");
911 memcpy(peer->host, field, p - field);
912 peer->host[p - field] = '\0';
915 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
916 printf("unexpected character after ]\n");
921 /* port number or service name is specified */;
923 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
925 printf("syntax error, : but no following port\n");
928 peer->port = malloc(p - field + 1);
930 errx("malloc failed");
931 memcpy(peer->port, field, p - field);
932 peer->port[p - field] = '\0';
938 // * is default, else longest match ... ";" used for separator
939 char *parserealmlist(char *s, struct peer *peer) {
943 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
951 peer->realmdata = malloc(l + 1);
952 if (!peer->realmdata)
953 errx("malloc failed");
954 memcpy(peer->realmdata, s, l);
955 peer->realmdata[l] = '\0';
956 peer->realms = malloc((1+n) * sizeof(char *));
958 errx("malloc failed");
959 peer->realms[0] = peer->realmdata;
960 for (n = 1, i = 0; i < l; i++)
961 if (peer->realmdata[i] == ';') {
962 peer->realmdata[i] = '\0';
963 peer->realms[n++] = peer->realmdata + i + 1;
965 peer->realms[n] = NULL;
969 void getconfig(const char *filename) {
972 char *p, *field, **r;
977 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
978 if (!udp_server_replyq.replies)
979 errx("malloc failed");
980 udp_server_replyq.size = 4 * MAX_REQUESTS;
981 udp_server_replyq.count = 0;
982 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
983 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
985 f = fopen(filename, "r");
987 errx("getconfig failed to open %s for reading", filename);
989 while (fgets(line, 1024, f) && peer_count < MAX_PEERS) {
990 peer = &peers[peer_count];
991 memset(peer, 0, sizeof(struct peer));
993 for (p = line; *p == ' ' || *p == '\t'; p++);
994 if (*p == '#' || *p == '\n')
996 if (*p != 'U' && *p != 'T') {
997 printf("server type must be U or T, got %c\n", *p);
1001 for (p++; *p == ' ' || *p == '\t'; p++);
1002 p = parsehostport(p, peer);
1004 peer->port = (peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT);
1005 for (; *p == ' ' || *p == '\t'; p++);
1006 p = parserealmlist(p, peer);
1007 if (!peer->realms) {
1008 printf("realm list must be specified\n");
1011 for (; *p == ' ' || *p == '\t'; p++);
1013 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1015 /* no secret set and end of line, line is complete if TLS */
1016 if (peer->type == 'U') {
1017 printf("secret must be specified for UDP\n");
1020 peer->secret = DEFAULT_TLS_SECRET;
1022 peer->secret = malloc(p - field + 1);
1024 errx("malloc failed");
1025 memcpy(peer->secret, field, p - field);
1026 peer->secret[p - field] = '\0';
1027 /* check that rest of line only white space */
1028 for (; *p == ' ' || *p == '\t'; p++);
1029 if (*p && *p != '\n') {
1030 printf("max 4 fields per line, found a 5th\n");
1035 pthread_mutex_init(&peer->lock, NULL);
1036 if (!resolvepeer(peer)) {
1037 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1040 peer->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1041 if (!peer->requests)
1042 errx("malloc failed");
1043 memset(peer->requests, 0, MAX_REQUESTS * sizeof(struct request));
1045 pthread_mutex_init(&peer->newrq_mutex, NULL);
1046 pthread_cond_init(&peer->newrq_cond, NULL);
1048 if (peer->type == 'U')
1049 peer->replyq = &udp_server_replyq;
1051 peer->replyq = malloc(sizeof(struct replyq));
1053 errx("malloc failed");
1054 peer->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1055 if (!peer->replyq->replies)
1056 errx("malloc failed");
1057 peer->replyq->size = MAX_REQUESTS;
1058 peer->replyq->count = 0;
1059 pthread_mutex_init(&peer->replyq->count_mutex, NULL);
1060 pthread_cond_init(&peer->replyq->count_cond, NULL);
1062 printf("got type %c, host %s, port %s, secret %s\n", peers[peer_count].type,
1063 peers[peer_count].host, peers[peer_count].port, peers[peer_count].secret);
1064 printf(" with realms:");
1065 for (r = peer->realms; *r; r++)
1073 void parseargs(int argc, char **argv) {
1076 while ((c = getopt(argc, argv, "p:")) != -1) {
1079 udp_server_port = optarg;
1089 printf("radsecproxy [ -p UDP-port ]\n");
1093 int main(int argc, char **argv) {
1094 SSL_CTX *ssl_ctx_srv;
1095 unsigned long error;
1096 pthread_t udpserverth;
1097 pthread_attr_t joinable;
1100 parseargs(argc, argv);
1101 getconfig("radsecproxy.conf");
1105 pthread_attr_init(&joinable);
1106 pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1108 /* listen on UDP if at least one UDP peer */
1110 for (i = 0; i < peer_count; i++)
1111 if (peers[i].type == 'U') {
1112 if (pthread_create(&udpserverth, &joinable, udpserverrd, NULL))
1113 errx("pthread_create failed");
1117 for (i = 0; i < peer_count; i++)
1118 if (peers[i].type == 'T')
1121 if (i == peer_count) {
1122 printf("No TLS peers defined, just doing UDP proxying\n");
1123 /* just hang around doing nothing, anything to do here? */
1124 pthread_join(udpserverth, NULL);
1129 SSL_load_error_strings();
1132 while (!RAND_status()) {
1133 time_t t = time(NULL);
1134 pid_t pid = getpid();
1135 RAND_seed((unsigned char *)&t, sizeof(time_t));
1136 RAND_seed((unsigned char *)&pid, sizeof(pid));
1139 /* initialise client part and start clients */
1140 ssl_ctx_cl = SSL_CTX_new(TLSv1_client_method());
1144 for (i = 0; i < peer_count; i++) {
1145 if (pthread_create(&peers[i].clientth, NULL, clientwr, (void *)&peers[i]))
1146 errx("pthread_create failed");
1149 /* setting up server/daemon part */
1150 ssl_ctx_srv = SSL_CTX_new(TLSv1_server_method());
1153 if (!SSL_CTX_use_certificate_file(ssl_ctx_srv, "/tmp/server.pem", SSL_FILETYPE_PEM)) {
1154 while ((error = ERR_get_error()))
1155 err("SSL: %s", ERR_error_string(error, NULL));
1156 errx("Failed to load certificate");
1158 if (!SSL_CTX_use_PrivateKey_file(ssl_ctx_srv, "/tmp/server.key", SSL_FILETYPE_PEM)) {
1159 while ((error = ERR_get_error()))
1160 err("SSL: %s", ERR_error_string(error, NULL));
1161 errx("Failed to load private key");
1163 return tlslistener(ssl_ctx_srv);