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 * tls certificate validation
22 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
23 * rd is responsible for init and launching wr
24 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
25 * each tlsserverrd launches tlsserverwr
26 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
27 * for init and launching rd
29 * serverrd will receive a request, processes it and puts it in the requestq of
30 * the appropriate clientwr
31 * clientwr monitors its requestq and sends requests
32 * clientrd looks for responses, processes them and puts them in the replyq of
33 * the peer the request came from
34 * serverwr monitors its reply and sends replies
36 * In addition to the main thread, we have:
37 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
38 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
39 * For each TLS peer connecting to us there will be 2 more TLS threads
40 * This is only for connected peers
41 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
42 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
48 #include <openssl/ssl.h>
49 #include <openssl/rand.h>
50 #include <openssl/err.h>
51 #include <openssl/md5.h>
52 #include "radsecproxy.h"
54 static struct peer peers[MAX_PEERS];
55 static int peer_count = 0;
57 static struct replyq udp_server_replyq;
58 static int udp_server_sock = -1;
59 static char *udp_server_port = DEFAULT_UDP_PORT;
60 static pthread_mutex_t *ssl_locks;
61 static long *ssl_lock_count;
62 static SSL_CTX *ssl_ctx_cl;
66 /* callbacks for making OpenSSL thread safe */
67 unsigned long ssl_thread_id() {
68 return (unsigned long)pthread_self();
71 void ssl_locking_callback(int mode, int type, const char *file, int line) {
72 if (mode & CRYPTO_LOCK) {
73 pthread_mutex_lock(&ssl_locks[type]);
74 ssl_lock_count[type]++;
76 pthread_mutex_unlock(&ssl_locks[type]);
79 void ssl_locks_setup() {
82 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
83 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
84 for (i = 0; i < CRYPTO_num_locks(); i++) {
85 ssl_lock_count[i] = 0;
86 pthread_mutex_init(&ssl_locks[i], NULL);
89 CRYPTO_set_id_callback(ssl_thread_id);
90 CRYPTO_set_locking_callback(ssl_locking_callback);
93 int resolvepeer(struct peer *peer) {
94 struct addrinfo hints;
96 pthread_mutex_lock(&peer->lock);
98 /* assume we should re-resolve */
99 freeaddrinfo(peer->addrinfo);
100 peer->addrinfo = NULL;
103 memset(&hints, 0, sizeof(hints));
104 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
105 hints.ai_family = AF_UNSPEC;
106 if (getaddrinfo(peer->host, peer->port, &hints, &peer->addrinfo)) {
107 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
108 peer->addrinfo = NULL; /* probably don't need this */
109 pthread_mutex_unlock(&peer->lock);
112 pthread_mutex_unlock(&peer->lock);
116 int connecttopeer(struct peer *peer) {
118 struct addrinfo *res;
120 if (!peer->addrinfo) {
122 if (!peer->addrinfo) {
123 printf("connecttopeer: can't resolve %s into address to connect to\n", peer->host);
128 for (res = peer->addrinfo; res; res = res->ai_next) {
129 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
131 err("connecttopeer: socket failed");
134 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
136 err("connecttopeer: connect failed");
143 /* returns the peer with matching address, or NULL */
144 /* if peer argument is not NULL, we only check that one peer */
145 struct peer *find_peer(char type, struct sockaddr *addr, struct peer *peer) {
146 struct sockaddr_in6 *sa6;
147 struct in_addr *a4 = NULL;
150 struct addrinfo *res;
152 if (addr->sa_family == AF_INET6) {
153 sa6 = (struct sockaddr_in6 *)addr;
154 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
155 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
157 a4 = &((struct sockaddr_in *)addr)->sin_addr;
159 p = (peer ? peer : peers);
160 for (i = 0; i < peer_count; i++) {
162 for (res = p->addrinfo; res; res = res->ai_next)
163 if ((a4 && res->ai_family == AF_INET &&
164 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
165 (res->ai_family == AF_INET6 &&
166 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
175 /* if *peer == NULL we return who we received from, else require it to be from peer */
176 /* return from in sa if not NULL */
177 unsigned char *radudpget(int s, struct peer **peer, struct sockaddr_storage *sa) {
180 unsigned char buf[65536], *rad;
181 struct sockaddr_storage from;
182 socklen_t fromlen = sizeof(from);
185 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
187 err("radudpget: recv failed");
190 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
193 printf("radudpget: packet too small\n");
200 printf("radudpget: packet smaller than length field in radius header\n");
204 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
206 f = find_peer('U', (struct sockaddr *)&from, *peer);
208 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
215 err("radudpget: malloc failed");
217 memcpy(rad, buf, len);
218 *peer = f; /* only need this if *peer == NULL, but if not NULL *peer == f here */
224 void tlsconnect(struct peer *peer, int oldsock, char *text) {
225 unsigned int sleeptime, try = 0;
227 pthread_mutex_lock(&peer->lock);
228 if (peer->sockcl != oldsock) {
229 /* already reconnected, nothing to do */
230 printf("reconnect: seems already reconnected\n");
231 pthread_mutex_unlock(&peer->lock);
235 printf("tlsconnect %d %s\n", oldsock, text);
238 printf("tlsconnect: trying to open TLS connection to %s port %s\n", peer->host, peer->port);
239 if ((peer->sockcl = connecttopeer(peer)) >= 0)
248 /* should possibly re-resolve host addresses at some point */
249 printf("tlsconnect: can't connect, retry #%d in %ds\n", try, sleeptime);
253 SSL_free(peer->sslcl);
254 peer->sslcl = SSL_new(ssl_ctx_cl);
255 SSL_set_fd(peer->sslcl, peer->sockcl);
256 /* must close oldsock after get new socket so that they are always different */
259 SSL_connect(peer->sslcl);
260 printf("tlsconnect: TLS connection to %s port %s up\n", peer->host, peer->port);
261 pthread_mutex_unlock(&peer->lock);
264 unsigned char *radtlsget(SSL *ssl) {
266 unsigned char buf[4], *rad;
269 for (total = 0; total < 4; total += cnt) {
270 cnt = SSL_read(ssl, buf + total, 4 - total);
272 printf("radtlsget: connection lost\n");
280 err("radtlsget: malloc failed");
285 for (; total < len; total += cnt) {
286 cnt = SSL_read(ssl, rad + total, len - total);
288 printf("radtlsget: connection lost\n");
298 printf("radtlsget: packet smaller than minimum radius size\n");
301 printf("radtlsget: got %d bytes\n", total);
305 int clientradput(struct peer *peer, unsigned char *rad) {
311 if (peer->type == 'U') {
312 if (send(peer->sockcl, rad, len, 0) >= 0) {
313 printf("clienradput: sent UDP of length %d to %s port %s\n", len, peer->host, peer->port);
316 err("clientradput: send failed");
321 while ((cnt = SSL_write(peer->sslcl, rad, len)) <= 0) {
322 while ((error = ERR_get_error()))
323 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
324 tlsconnect(peer, s, "clientradput");
328 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
329 cnt, len, peer->host);
333 int radsign(unsigned char *rad, unsigned char *sec) {
334 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
335 static unsigned char first = 1;
336 static EVP_MD_CTX mdctx;
340 pthread_mutex_lock(&lock);
342 EVP_MD_CTX_init(&mdctx);
346 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
347 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
348 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
349 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
351 pthread_mutex_unlock(&lock);
355 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
356 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
357 static unsigned char first = 1;
358 static EVP_MD_CTX mdctx;
359 unsigned char hash[EVP_MAX_MD_SIZE];
363 pthread_mutex_lock(&lock);
365 EVP_MD_CTX_init(&mdctx);
371 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
372 EVP_DigestUpdate(&mdctx, rad, 4) &&
373 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
374 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
375 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
376 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
378 !memcmp(hash, rad + 4, 16));
379 pthread_mutex_unlock(&lock);
383 void sendrq(struct peer *to, struct peer *from, struct request *rq) {
386 pthread_mutex_lock(&to->newrq_mutex);
387 for (i = 0; i < MAX_REQUESTS; i++)
388 if (!to->requests[i].buf)
390 if (i == MAX_REQUESTS) {
391 printf("No room in queue, dropping request\n");
392 pthread_mutex_unlock(&to->newrq_mutex);
396 rq->buf[1] = (char)i;
397 to->requests[i] = *rq;
401 printf("signalling client writer\n");
402 pthread_cond_signal(&to->newrq_cond);
404 pthread_mutex_unlock(&to->newrq_mutex);
407 void sendreply(struct peer *to, struct peer *from, char *buf, struct sockaddr_storage *tosa) {
408 struct replyq *replyq = to->replyq;
410 pthread_mutex_lock(&replyq->count_mutex);
411 if (replyq->count == replyq->size) {
412 printf("No room in queue, dropping request\n");
413 pthread_mutex_unlock(&replyq->count_mutex);
417 replyq->replies[replyq->count].buf = buf;
419 replyq->replies[replyq->count].tosa = *tosa;
422 if (replyq->count == 1) {
423 printf("signalling client writer\n");
424 pthread_cond_signal(&replyq->count_cond);
426 pthread_mutex_unlock(&replyq->count_mutex);
429 int pwdcrypt(uint8_t *plain, uint8_t *enc, uint8_t enclen, uint8_t *shared, uint8_t sharedlen,
431 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
432 static unsigned char first = 1;
433 static EVP_MD_CTX mdctx;
434 unsigned char hash[EVP_MAX_MD_SIZE], *input;
436 uint8_t i, offset = 0;
438 pthread_mutex_lock(&lock);
440 EVP_MD_CTX_init(&mdctx);
446 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
447 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
448 !EVP_DigestUpdate(&mdctx, input, 16) ||
449 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
451 pthread_mutex_unlock(&lock);
454 for (i = 0; i < 16; i++)
455 plain[offset + i] = hash[i] ^ enc[offset + i];
457 if (offset == enclen)
459 input = enc + offset - 16;
461 pthread_mutex_unlock(&lock);
465 struct peer *radsrv(struct request *rq, char *buf, struct peer *from) {
466 uint8_t code, id, *auth, *attr, *usernameattr = NULL, *userpwdattr = NULL, pwd[128], pwdlen;
471 unsigned char newauth[16];
473 code = *(uint8_t *)buf;
474 id = *(uint8_t *)(buf + 1);
476 auth = (uint8_t *)(buf + 4);
478 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
480 if (code != RAD_Access_Request) {
481 printf("radsrv: server currently accepts only access-requests, ignoring\n");
489 left -= attr[RAD_Attr_Length];
491 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
494 switch (attr[RAD_Attr_Type]) {
495 case RAD_Attr_User_Name:
498 case RAD_Attr_User_Password:
502 attr += attr[RAD_Attr_Length];
505 printf("radsrv: malformed packet? remaining byte after last attribute\n");
508 printf("radsrv: Username: ");
509 for (i = 0; i < usernameattr[RAD_Attr_Length]; i++)
510 printf("%c", usernameattr[RAD_Attr_Value + i]);
514 /* find out where to send the packet, for now we send to first connected
515 TLS peer if UDP, and first UDP peer if TLS */
518 switch (from->type) {
520 for (i = 0; i < peer_count; i++)
521 if (peers[i].type == 'T' && peers[i].sockcl >= 0)
525 for (i = 0; i < peer_count; i++)
526 if (peers[i].type == 'U')
531 if (i == peer_count) {
532 printf("radsrv: ignoring request, don't know where to send it\n");
538 if (!RAND_bytes(newauth, 16)) {
539 printf("radsrv: failed to generate random auth\n");
544 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
545 pwdlen = userpwdattr[RAD_Attr_Length] - 2;
546 if (pwdlen < 16 || pwdlen > 128 || pwdlen % 16) {
547 printf("radsrv: invalid user password length\n");
551 if (!pwdcrypt(pwd, &userpwdattr[RAD_Attr_Value], pwdlen, from->secret, strlen(from->secret), auth)) {
552 printf("radsrv: cannot decrypt password\n");
555 printf("radsrv: password: ");
556 for (i = 0; i < pwdlen; i++)
557 printf("%02x ", pwd[i]);
559 if (!pwdcrypt(&userpwdattr[RAD_Attr_Value], pwd, pwdlen, to->secret, strlen(to->secret), newauth)) {
560 printf("radsrv: cannot encrypt password\n");
568 memcpy(rq->origauth, auth, 16);
569 memcpy(rq->buf + 4, newauth, 16);
573 void *clientrd(void *arg) {
574 struct peer *from, *peer = (struct peer *)arg;
577 struct sockaddr_storage fromsa;
581 buf = (peer->type == 'U' ? radudpget(s, &peer, NULL) : radtlsget(peer->sslcl));
582 if (!buf && peer->type == 'T') {
583 printf("retry in 60s\n");
584 sleep(60); /* should have exponential backoff perhaps, better do it inside radtlsget */
585 tlsconnect(peer, s, "clientrd");
589 i = buf[1]; /* i is the id */
591 pthread_mutex_lock(&peer->newrq_mutex);
592 if (!peer->requests[i].buf || !peer->requests[i].tries) {
593 pthread_mutex_unlock(&peer->newrq_mutex);
594 printf("clientrd: no matching request sent with this id, ignoring\n");
598 if (peer->requests[i].received) {
599 pthread_mutex_unlock(&peer->newrq_mutex);
600 printf("clientrd: already received, ignoring\n");
604 if (!validauth(buf, peer->requests[i].buf + 4, peer->secret)) {
605 pthread_mutex_unlock(&peer->newrq_mutex);
606 printf("clientrd: invalid auth, ignoring\n");
610 /* once we set received = 1, requests[i] may be reused */
611 buf[1] = (char)peer->requests[i].origid;
612 memcpy(buf + 4, peer->requests[i].origauth, 16);
613 from = peer->requests[i].from;
614 if (from->type == 'U')
615 fromsa = peer->requests[i].fromsa;
616 peer->requests[i].received = 1;
617 pthread_mutex_unlock(&peer->newrq_mutex);
619 if (!radsign(buf, from->secret)) {
620 printf("clientrd: failed to sign message\n");
624 printf("clientrd: giving packet back to where it came from\n");
625 sendreply(from, peer, buf, from->type == 'U' ? &fromsa : NULL);
629 void *clientwr(void *arg) {
630 struct peer *peer = (struct peer *)arg;
631 pthread_t clientrdth;
634 if (peer->type == 'U') {
635 if ((peer->sockcl = connecttopeer(peer)) < 0) {
636 printf("clientwr: connecttopeer failed\n");
640 tlsconnect(peer, -1, "new client");
642 if (pthread_create(&clientrdth, NULL, clientrd, (void *)peer))
643 errx("clientwr: pthread_create failed");
646 pthread_mutex_lock(&peer->newrq_mutex);
647 while (!peer->newrq) {
648 printf("clientwr: waiting for signal\n");
649 pthread_cond_wait(&peer->newrq_cond, &peer->newrq_mutex);
650 printf("clientwr: got signal\n");
653 pthread_mutex_unlock(&peer->newrq_mutex);
655 for (i = 0; i < MAX_REQUESTS; i++) {
656 pthread_mutex_lock(&peer->newrq_mutex);
657 while (!peer->requests[i].buf && i < MAX_REQUESTS)
659 if (i == MAX_REQUESTS) {
660 pthread_mutex_unlock(&peer->newrq_mutex);
664 /* already received or too many tries */
665 if (peer->requests[i].received || peer->requests[i].tries > 2) {
666 free(peer->requests[i].buf);
667 /* setting this to NULL means that it can be reused */
668 peer->requests[i].buf = NULL;
669 pthread_mutex_unlock(&peer->newrq_mutex);
672 pthread_mutex_unlock(&peer->newrq_mutex);
674 peer->requests[i].tries++;
675 clientradput(peer, peer->requests[i].buf);
678 /* should do more work to maintain TLS connections, keepalives etc */
681 void *udpserverwr(void *arg) {
682 struct replyq *replyq = &udp_server_replyq;
683 struct reply *reply = replyq->replies;
685 pthread_mutex_lock(&replyq->count_mutex);
687 while (!replyq->count) {
688 printf("udp server writer, waiting for signal\n");
689 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
690 printf("udp server writer, got signal\n");
692 pthread_mutex_unlock(&replyq->count_mutex);
694 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
695 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
696 err("sendudp: send failed");
699 pthread_mutex_lock(&replyq->count_mutex);
701 memmove(replyq->replies, replyq->replies + 1,
702 replyq->count * sizeof(struct reply));
706 void *udpserverrd(void *arg) {
709 struct peer *to, *fr;
710 pthread_t udpserverwrth;
712 if ((udp_server_sock = bindport(SOCK_DGRAM, udp_server_port)) < 0) {
713 printf("udpserverrd: socket/bind failed\n");
716 printf("udpserverrd: listening on UDP port %s\n", udp_server_port);
718 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
719 errx("pthread_create failed");
723 memset(&rq, 0, sizeof(struct request));
724 buf = radudpget(udp_server_sock, &fr, &rq.fromsa);
725 to = radsrv(&rq, buf, fr);
727 printf("udpserverrd: ignoring request, no place to send it\n");
734 void *tlsserverwr(void *arg) {
737 struct peer *peer = (struct peer *)arg;
738 struct replyq *replyq;
740 pthread_mutex_lock(&peer->replycount_mutex);
742 replyq = peer->replyq;
743 while (!replyq->count) {
744 printf("tls server writer, waiting for signal\n");
745 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
746 printf("tls server writer, got signal\n");
748 pthread_mutex_unlock(&replyq->count_mutex);
749 cnt = SSL_write(peer->sslsrv, replyq->replies->buf, RADLEN(replyq->replies->buf));
751 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
752 cnt, RADLEN(replyq->replies->buf));
754 while ((error = ERR_get_error()))
755 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
756 free(replyq->replies->buf);
758 pthread_mutex_lock(&replyq->count_mutex);
760 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
764 void *tlsserverrd(void *arg) {
770 struct peer *peer = (struct peer *)arg;
771 pthread_t tlsserverwrth;
773 printf("tlsserverrd starting\n");
774 if (SSL_accept(peer->sslsrv) <= 0) {
775 while ((error = ERR_get_error()))
776 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
777 errx("accept failed, child exiting");
780 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)peer))
781 errx("pthread_create failed");
784 buf = radtlsget(peer->sslsrv);
786 printf("tlsserverrd: connection lost\n");
787 s = SSL_get_fd(peer->sslsrv);
788 SSL_free(peer->sslsrv);
794 printf("tlsserverrd: got Radius message from %s\n", peer->host);
795 memset(&rq, 0, sizeof(struct request));
796 to = radsrv(&rq, buf, peer);
798 printf("ignoring request, no place to send it\n");
801 sendrq(to, peer, &rq);
805 int tlslistener(SSL_CTX *ssl_ctx) {
806 pthread_t tlsserverth;
808 struct sockaddr_storage from;
809 size_t fromlen = sizeof(from);
812 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
813 printf("tlslistener: socket/bind failed\n");
818 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
821 snew = accept(s, (struct sockaddr *)&from, &fromlen);
823 errx("accept failed");
824 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
826 peer = find_peer('T', (struct sockaddr *)&from, NULL);
828 printf("ignoring request, not a known TLS peer\n");
834 printf("Ignoring incoming connection, already have one from this peer\n");
838 peer->sslsrv = SSL_new(ssl_ctx);
839 SSL_set_fd(peer->sslsrv, snew);
840 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)peer))
841 errx("pthread_create failed");
844 /* currently only one server thread, so just halt here */
851 char *parsehostport(char *s, char **host, char **port) {
856 // allow literal addresses and port, e.g. [2001:db8::1]:1812
860 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
862 printf("no ] matching initial [\n");
868 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
871 printf("missing host/address\n");
874 *host = malloc(p - field + 1);
876 errx("malloc failed");
877 memcpy(*host, field, p - field);
878 (*host)[p - field] = '\0';
881 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
882 printf("unexpected character after ]\n");
887 /* port number or service name is specified */;
889 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
891 printf("syntax error, : but no following port\n");
894 *port = malloc(p - field + 1);
896 errx("malloc failed");
897 memcpy(*port, field, p - field);
898 (*port)[p - field ] = '\0';
904 void getconfig(const char *filename) {
912 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
913 if (!udp_server_replyq.replies)
914 errx("malloc failed");
915 udp_server_replyq.size = 4 * MAX_REQUESTS;
916 udp_server_replyq.count = 0;
917 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
918 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
920 f = fopen(filename, "r");
922 errx("getconfig failed to open %s for reading", filename);
924 while (fgets(line, 1024, f) && peer_count < MAX_PEERS) {
925 peer = &peers[peer_count];
926 memset(peer, 0, sizeof(struct peer));
928 for (p = line; *p == ' ' || *p == '\t'; p++);
929 if (*p == '#' || *p == '\n')
931 if (*p != 'U' && *p != 'T') {
932 printf("server type must be U or T, got %c\n", *p);
936 for (p++; *p == ' ' || *p == '\t'; p++);
937 p = parsehostport(p, &peer->host, &peer->port);
939 peer->port = (peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT);
940 for (; *p == ' ' || *p == '\t'; p++);
942 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
944 /* no secret set and end of line, line is complete if TLS */
945 if (peer->type == 'U') {
946 printf("secret must be specified for UDP\n");
949 peer->secret = DEFAULT_TLS_SECRET;
951 peer->secret = malloc(p - field + 1);
953 errx("malloc failed");
954 memcpy(peer->secret, field, p - field);
955 peer->secret[p - field] = '\0';
956 /* check that rest of line only white space */
957 for (; *p == ' ' || *p == '\t'; p++);
958 if (*p && *p != '\n') {
959 printf("max 3 fields per line, found a 4th\n");
966 pthread_mutex_init(&peer->lock, NULL);
967 if (!resolvepeer(peer)) {
968 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
971 peer->requests = malloc(MAX_REQUESTS * sizeof(struct request));
973 errx("malloc failed");
974 memset(peer->requests, 0, MAX_REQUESTS * sizeof(struct request));
976 pthread_mutex_init(&peer->newrq_mutex, NULL);
977 pthread_cond_init(&peer->newrq_cond, NULL);
979 if (peer->type == 'U')
980 peer->replyq = &udp_server_replyq;
982 peer->replyq = malloc(sizeof(struct replyq));
984 errx("malloc failed");
985 peer->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
986 if (!peer->replyq->replies)
987 errx("malloc failed");
988 peer->replyq->size = MAX_REQUESTS;
989 peer->replyq->count = 0;
990 pthread_mutex_init(&peer->replyq->count_mutex, NULL);
991 pthread_cond_init(&peer->replyq->count_cond, NULL);
993 printf("got type %c, host %s, port %s, secret %s\n", peers[peer_count].type,
994 peers[peer_count].host, peers[peer_count].port, peers[peer_count].secret);
1000 void parseargs(int argc, char **argv) {
1003 while ((c = getopt(argc, argv, "p:")) != -1) {
1006 udp_server_port = optarg;
1016 printf("radsecproxy [ -p UDP-port ]\n");
1020 int main(int argc, char **argv) {
1021 SSL_CTX *ssl_ctx_srv;
1022 unsigned long error;
1023 pthread_t udpserverth;
1024 pthread_attr_t joinable;
1027 parseargs(argc, argv);
1028 getconfig("radsecproxy.conf");
1032 pthread_attr_init(&joinable);
1033 pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1035 /* listen on UDP if at least one UDP peer */
1037 for (i = 0; i < peer_count; i++)
1038 if (peers[i].type == 'U') {
1039 if (pthread_create(&udpserverth, &joinable, udpserverrd, NULL))
1040 errx("pthread_create failed");
1044 for (i = 0; i < peer_count; i++)
1045 if (peers[i].type == 'T')
1048 if (i == peer_count) {
1049 printf("No TLS peers defined, just doing UDP proxying\n");
1050 /* just hang around doing nothing, anything to do here? */
1051 pthread_join(udpserverth, NULL);
1056 SSL_load_error_strings();
1059 while (!RAND_status()) {
1060 time_t t = time(NULL);
1061 pid_t pid = getpid();
1062 RAND_seed((unsigned char *)&t, sizeof(time_t));
1063 RAND_seed((unsigned char *)&pid, sizeof(pid));
1066 /* initialise client part and start clients */
1067 ssl_ctx_cl = SSL_CTX_new(TLSv1_client_method());
1071 for (i = 0; i < peer_count; i++) {
1072 if (pthread_create(&peers[i].clientth, NULL, clientwr, (void *)&peers[i]))
1073 errx("pthread_create failed");
1076 /* setting up server/daemon part */
1077 ssl_ctx_srv = SSL_CTX_new(TLSv1_server_method());
1080 if (!SSL_CTX_use_certificate_file(ssl_ctx_srv, "/tmp/server.pem", SSL_FILETYPE_PEM)) {
1081 while ((error = ERR_get_error()))
1082 err("SSL: %s", ERR_error_string(error, NULL));
1083 errx("Failed to load certificate");
1085 if (!SSL_CTX_use_PrivateKey_file(ssl_ctx_srv, "/tmp/server.key", SSL_FILETYPE_PEM)) {
1086 while ((error = ERR_get_error()))
1087 err("SSL: %s", ERR_error_string(error, NULL));
1088 errx("Failed to load private key");
1090 return tlslistener(ssl_ctx_srv);