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.
11 * radius keep alives (server status)
12 * setsockopt(keepalive...), check if openssl has some keepalive feature
15 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
16 * rd is responsible for init and launching wr
17 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
18 * each tlsserverrd launches tlsserverwr
19 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
20 * for init and launching rd
22 * serverrd will receive a request, processes it and puts it in the requestq of
23 * the appropriate clientwr
24 * clientwr monitors its requestq and sends requests
25 * clientrd looks for responses, processes them and puts them in the replyq of
26 * the peer the request came from
27 * serverwr monitors its reply and sends replies
29 * In addition to the main thread, we have:
30 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
31 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
32 * For each TLS peer connecting to us there will be 2 more TLS threads
33 * This is only for connected peers
34 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
35 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 #include <sys/socket.h>
39 #include <netinet/in.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
51 #include "radsecproxy.h"
53 static struct options options;
54 static struct client *clients;
55 static struct server *servers;
57 static int client_udp_count = 0;
58 static int client_tls_count = 0;
59 static int client_count = 0;
60 static int server_udp_count = 0;
61 static int server_tls_count = 0;
62 static int server_count = 0;
64 static struct replyq udp_server_replyq;
65 static int udp_server_sock = -1;
66 static pthread_mutex_t *ssl_locks;
67 static long *ssl_lock_count;
68 static SSL_CTX *ssl_ctx = NULL;
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 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
90 err_cert = X509_STORE_CTX_get_current_cert(ctx);
91 err = X509_STORE_CTX_get_error(ctx);
92 depth = X509_STORE_CTX_get_error_depth(ctx);
94 if (depth > MAX_CERT_DEPTH) {
96 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
97 X509_STORE_CTX_set_error(ctx, err);
101 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
102 printf("verify error: num=%d:%s:depth=%d:%s\n", err, X509_verify_cert_error_string(err), depth, buf);
105 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
106 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
107 printf("issuer=%s\n", buf);
109 case X509_V_ERR_CERT_NOT_YET_VALID:
110 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
111 printf("Certificate not yet valid\n");
113 case X509_V_ERR_CERT_HAS_EXPIRED:
114 printf("Certificate has expired\n");
116 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
117 printf("Certificate no longer valid (after notAfter)\n");
121 // printf("certificate verify returns %d\n", ok);
125 SSL_CTX *ssl_init() {
130 if (!options.tlscertificatefile || !options.tlscertificatekeyfile) {
131 printf("TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS\n");
134 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
135 printf("CA Certificate file/path need to be configured\n");
139 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
140 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
141 for (i = 0; i < CRYPTO_num_locks(); i++) {
142 ssl_lock_count[i] = 0;
143 pthread_mutex_init(&ssl_locks[i], NULL);
145 CRYPTO_set_id_callback(ssl_thread_id);
146 CRYPTO_set_locking_callback(ssl_locking_callback);
148 SSL_load_error_strings();
151 while (!RAND_status()) {
152 time_t t = time(NULL);
153 pid_t pid = getpid();
154 RAND_seed((unsigned char *)&t, sizeof(time_t));
155 RAND_seed((unsigned char *)&pid, sizeof(pid));
158 ctx = SSL_CTX_new(TLSv1_method());
159 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
160 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
161 SSL_CTX_check_private_key(ctx) &&
162 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
163 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
164 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
168 while ((error = ERR_get_error()))
169 err("SSL: %s", ERR_error_string(error, NULL));
173 void printauth(char *s, unsigned char *t) {
176 for (i = 0; i < 16; i++)
177 printf("%02x ", t[i]);
181 int resolvepeer(struct peer *peer) {
182 struct addrinfo hints, *addrinfo;
184 memset(&hints, 0, sizeof(hints));
185 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
186 hints.ai_family = AF_UNSPEC;
187 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
188 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
193 freeaddrinfo(peer->addrinfo);
194 peer->addrinfo = addrinfo;
198 int connecttoserver(struct addrinfo *addrinfo) {
200 struct addrinfo *res;
202 for (res = addrinfo; res; res = res->ai_next) {
203 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
205 err("connecttoserver: socket failed");
208 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
210 err("connecttoserver: connect failed");
217 /* returns the client with matching address, or NULL */
218 /* if client argument is not NULL, we only check that one client */
219 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
220 struct sockaddr_in6 *sa6;
221 struct in_addr *a4 = NULL;
224 struct addrinfo *res;
226 if (addr->sa_family == AF_INET6) {
227 sa6 = (struct sockaddr_in6 *)addr;
228 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
229 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
231 a4 = &((struct sockaddr_in *)addr)->sin_addr;
233 c = (client ? client : clients);
234 for (i = 0; i < client_count; i++) {
235 if (c->peer.type == type)
236 for (res = c->peer.addrinfo; res; res = res->ai_next)
237 if ((a4 && res->ai_family == AF_INET &&
238 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
239 (res->ai_family == AF_INET6 &&
240 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
249 /* returns the server with matching address, or NULL */
250 /* if server argument is not NULL, we only check that one server */
251 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
252 struct sockaddr_in6 *sa6;
253 struct in_addr *a4 = NULL;
256 struct addrinfo *res;
258 if (addr->sa_family == AF_INET6) {
259 sa6 = (struct sockaddr_in6 *)addr;
260 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
261 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
263 a4 = &((struct sockaddr_in *)addr)->sin_addr;
265 s = (server ? server : servers);
266 for (i = 0; i < server_count; i++) {
267 if (s->peer.type == type)
268 for (res = s->peer.addrinfo; res; res = res->ai_next)
269 if ((a4 && res->ai_family == AF_INET &&
270 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
271 (res->ai_family == AF_INET6 &&
272 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
281 /* exactly one of client and server must be non-NULL */
282 /* if *peer == NULL we return who we received from, else require it to be from peer */
283 /* return from in sa if not NULL */
284 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
287 unsigned char buf[65536], *rad;
288 struct sockaddr_storage from;
289 socklen_t fromlen = sizeof(from);
292 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
294 err("radudpget: recv failed");
297 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
300 printf("radudpget: packet too small\n");
307 printf("radudpget: packet smaller than length field in radius header\n");
311 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
314 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
315 : (void *)find_server('U', (struct sockaddr *)&from, *server));
317 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
324 err("radudpget: malloc failed");
326 memcpy(rad, buf, len);
328 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
330 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
336 int tlsverifycert(struct peer *peer) {
345 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
346 printf("tlsverifycert: basic validation failed\n");
347 while ((error = ERR_get_error()))
348 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
352 cert = SSL_get_peer_certificate(peer->ssl);
354 printf("tlsverifycert: failed to obtain certificate\n");
357 nm = X509_get_subject_name(cert);
360 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
363 e = X509_NAME_get_entry(nm, loc);
364 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
368 for (i = 0; i < l; i++)
371 if (l == strlen(peer->host) && !strncasecmp(peer->host, v, l)) {
372 printf("tlsverifycert: Found cn matching host %s, All OK\n", peer->host);
375 printf("tlsverifycert: cn not matching host %s\n", peer->host);
381 void tlsconnect(struct server *server, struct timeval *when, char *text) {
385 printf("tlsconnect called from %s\n", text);
386 pthread_mutex_lock(&server->lock);
387 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
388 /* already reconnected, nothing to do */
389 printf("tlsconnect(%s): seems already reconnected\n", text);
390 pthread_mutex_unlock(&server->lock);
394 printf("tlsconnect %s\n", text);
397 gettimeofday(&now, NULL);
398 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
399 if (server->connectionok) {
400 server->connectionok = 0;
402 } else if (elapsed < 5)
404 else if (elapsed < 600) {
405 printf("tlsconnect: sleeping %lds\n", elapsed);
407 } else if (elapsed < 1000) {
408 printf("tlsconnect: sleeping %ds\n", 900);
411 server->lastconnecttry.tv_sec = now.tv_sec; // no sleep at startup
412 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->peer.host, server->peer.port);
413 if (server->sock >= 0)
415 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
417 SSL_free(server->peer.ssl);
418 server->peer.ssl = SSL_new(ssl_ctx);
419 SSL_set_fd(server->peer.ssl, server->sock);
420 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
423 printf("tlsconnect: TLS connection to %s port %s up\n", server->peer.host, server->peer.port);
424 gettimeofday(&server->lastconnecttry, NULL);
425 pthread_mutex_unlock(&server->lock);
428 unsigned char *radtlsget(SSL *ssl) {
430 unsigned char buf[4], *rad;
433 for (total = 0; total < 4; total += cnt) {
434 cnt = SSL_read(ssl, buf + total, 4 - total);
436 printf("radtlsget: connection lost\n");
437 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
438 //remote end sent close_notify, send one back
448 err("radtlsget: malloc failed");
453 for (; total < len; total += cnt) {
454 cnt = SSL_read(ssl, rad + total, len - total);
456 printf("radtlsget: connection lost\n");
457 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
458 //remote end sent close_notify, send one back
470 printf("radtlsget: packet smaller than minimum radius size\n");
473 printf("radtlsget: got %d bytes\n", total);
477 int clientradput(struct server *server, unsigned char *rad) {
481 struct timeval lastconnecttry;
484 if (server->peer.type == 'U') {
485 if (send(server->sock, rad, len, 0) >= 0) {
486 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->peer.host, server->peer.port);
489 err("clientradput: send failed");
493 lastconnecttry = server->lastconnecttry;
494 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
495 while ((error = ERR_get_error()))
496 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
497 tlsconnect(server, &lastconnecttry, "clientradput");
498 lastconnecttry = server->lastconnecttry;
501 server->connectionok = 1;
502 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
503 cnt, len, server->peer.host);
507 int radsign(unsigned char *rad, unsigned char *sec) {
508 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
509 static unsigned char first = 1;
510 static EVP_MD_CTX mdctx;
514 pthread_mutex_lock(&lock);
516 EVP_MD_CTX_init(&mdctx);
520 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
521 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
522 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
523 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
525 pthread_mutex_unlock(&lock);
529 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
530 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
531 static unsigned char first = 1;
532 static EVP_MD_CTX mdctx;
533 unsigned char hash[EVP_MAX_MD_SIZE];
537 pthread_mutex_lock(&lock);
539 EVP_MD_CTX_init(&mdctx);
545 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
546 EVP_DigestUpdate(&mdctx, rad, 4) &&
547 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
548 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
549 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
550 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
552 !memcmp(hash, rad + 4, 16));
553 pthread_mutex_unlock(&lock);
557 int checkmessageauth(char *rad, uint8_t *authattr, char *secret) {
558 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
559 static unsigned char first = 1;
560 static HMAC_CTX hmacctx;
562 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
564 pthread_mutex_lock(&lock);
566 HMAC_CTX_init(&hmacctx);
570 memcpy(auth, authattr, 16);
571 memset(authattr, 0, 16);
573 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
574 HMAC_Update(&hmacctx, rad, RADLEN(rad));
575 HMAC_Final(&hmacctx, hash, &md_len);
576 memcpy(authattr, auth, 16);
578 printf("message auth computation failed\n");
579 pthread_mutex_unlock(&lock);
583 if (memcmp(auth, hash, 16)) {
584 printf("message authenticator, wrong value\n");
585 pthread_mutex_unlock(&lock);
589 pthread_mutex_unlock(&lock);
593 int createmessageauth(char *rad, char *authattrval, char *secret) {
594 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
595 static unsigned char first = 1;
596 static HMAC_CTX hmacctx;
602 pthread_mutex_lock(&lock);
604 HMAC_CTX_init(&hmacctx);
608 memset(authattrval, 0, 16);
610 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
611 HMAC_Update(&hmacctx, rad, RADLEN(rad));
612 HMAC_Final(&hmacctx, authattrval, &md_len);
614 printf("message auth computation failed\n");
615 pthread_mutex_unlock(&lock);
619 pthread_mutex_unlock(&lock);
623 void sendrq(struct server *to, struct client *from, struct request *rq) {
626 pthread_mutex_lock(&to->newrq_mutex);
627 /* might simplify if only try nextid, might be ok */
628 for (i = to->nextid; i < MAX_REQUESTS; i++)
629 if (!to->requests[i].buf)
631 if (i == MAX_REQUESTS) {
632 for (i = 0; i < to->nextid; i++)
633 if (!to->requests[i].buf)
635 if (i == to->nextid) {
636 printf("No room in queue, dropping request\n");
637 pthread_mutex_unlock(&to->newrq_mutex);
643 rq->buf[1] = (char)i;
644 printf("sendrq: inserting packet with id %d in queue for %s\n", i, to->peer.host);
646 if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
649 to->requests[i] = *rq;
653 printf("signalling client writer\n");
654 pthread_cond_signal(&to->newrq_cond);
656 pthread_mutex_unlock(&to->newrq_mutex);
659 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
660 struct replyq *replyq = to->replyq;
662 pthread_mutex_lock(&replyq->count_mutex);
663 if (replyq->count == replyq->size) {
664 printf("No room in queue, dropping request\n");
665 pthread_mutex_unlock(&replyq->count_mutex);
669 replyq->replies[replyq->count].buf = buf;
671 replyq->replies[replyq->count].tosa = *tosa;
674 if (replyq->count == 1) {
675 printf("signalling client writer\n");
676 pthread_cond_signal(&replyq->count_cond);
678 pthread_mutex_unlock(&replyq->count_mutex);
681 int pwdencrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
682 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
683 static unsigned char first = 1;
684 static EVP_MD_CTX mdctx;
685 unsigned char hash[EVP_MAX_MD_SIZE], *input;
687 uint8_t i, offset = 0, out[128];
689 pthread_mutex_lock(&lock);
691 EVP_MD_CTX_init(&mdctx);
697 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
698 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
699 !EVP_DigestUpdate(&mdctx, input, 16) ||
700 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
702 pthread_mutex_unlock(&lock);
705 for (i = 0; i < 16; i++)
706 out[offset + i] = hash[i] ^ in[offset + i];
707 input = out + offset - 16;
712 memcpy(in, out, len);
713 pthread_mutex_unlock(&lock);
717 int pwddecrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
718 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
719 static unsigned char first = 1;
720 static EVP_MD_CTX mdctx;
721 unsigned char hash[EVP_MAX_MD_SIZE], *input;
723 uint8_t i, offset = 0, out[128];
725 pthread_mutex_lock(&lock);
727 EVP_MD_CTX_init(&mdctx);
733 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
734 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
735 !EVP_DigestUpdate(&mdctx, input, 16) ||
736 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
738 pthread_mutex_unlock(&lock);
741 for (i = 0; i < 16; i++)
742 out[offset + i] = hash[i] ^ in[offset + i];
748 memcpy(in, out, len);
749 pthread_mutex_unlock(&lock);
753 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
754 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
755 static unsigned char first = 1;
756 static EVP_MD_CTX mdctx;
757 unsigned char hash[EVP_MAX_MD_SIZE];
761 pthread_mutex_lock(&lock);
763 EVP_MD_CTX_init(&mdctx);
768 printf("msppencrypt auth in: ");
769 for (i = 0; i < 16; i++)
770 printf("%02x ", auth[i]);
773 printf("msppencrypt salt in: ");
774 for (i = 0; i < 2; i++)
775 printf("%02x ", salt[i]);
778 printf("msppencrypt in: ");
779 for (i = 0; i < len; i++)
780 printf("%02x ", text[i]);
784 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
785 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
786 !EVP_DigestUpdate(&mdctx, auth, 16) ||
787 !EVP_DigestUpdate(&mdctx, salt, 2) ||
788 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
789 pthread_mutex_unlock(&lock);
794 printf("msppencrypt hash: ");
795 for (i = 0; i < 16; i++)
796 printf("%02x ", hash[i]);
800 for (i = 0; i < 16; i++)
803 for (offset = 16; offset < len; offset += 16) {
805 printf("text + offset - 16 c(%d): ", offset / 16);
806 for (i = 0; i < 16; i++)
807 printf("%02x ", (text + offset - 16)[i]);
810 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
811 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
812 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
813 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
815 pthread_mutex_unlock(&lock);
819 printf("msppencrypt hash: ");
820 for (i = 0; i < 16; i++)
821 printf("%02x ", hash[i]);
825 for (i = 0; i < 16; i++)
826 text[offset + i] ^= hash[i];
830 printf("msppencrypt out: ");
831 for (i = 0; i < len; i++)
832 printf("%02x ", text[i]);
836 pthread_mutex_unlock(&lock);
840 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
841 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
842 static unsigned char first = 1;
843 static EVP_MD_CTX mdctx;
844 unsigned char hash[EVP_MAX_MD_SIZE];
849 pthread_mutex_lock(&lock);
851 EVP_MD_CTX_init(&mdctx);
856 printf("msppdecrypt auth in: ");
857 for (i = 0; i < 16; i++)
858 printf("%02x ", auth[i]);
861 printf("msppedecrypt salt in: ");
862 for (i = 0; i < 2; i++)
863 printf("%02x ", salt[i]);
866 printf("msppedecrypt in: ");
867 for (i = 0; i < len; i++)
868 printf("%02x ", text[i]);
872 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
873 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
874 !EVP_DigestUpdate(&mdctx, auth, 16) ||
875 !EVP_DigestUpdate(&mdctx, salt, 2) ||
876 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
877 pthread_mutex_unlock(&lock);
882 printf("msppedecrypt hash: ");
883 for (i = 0; i < 16; i++)
884 printf("%02x ", hash[i]);
888 for (i = 0; i < 16; i++)
889 plain[i] = text[i] ^ hash[i];
891 for (offset = 16; offset < len; offset += 16) {
893 printf("text + offset - 16 c(%d): ", offset / 16);
894 for (i = 0; i < 16; i++)
895 printf("%02x ", (text + offset - 16)[i]);
898 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
899 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
900 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
901 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
903 pthread_mutex_unlock(&lock);
907 printf("msppedecrypt hash: ");
908 for (i = 0; i < 16; i++)
909 printf("%02x ", hash[i]);
913 for (i = 0; i < 16; i++)
914 plain[offset + i] = text[offset + i] ^ hash[i];
917 memcpy(text, plain, len);
919 printf("msppedecrypt out: ");
920 for (i = 0; i < len; i++)
921 printf("%02x ", text[i]);
925 pthread_mutex_unlock(&lock);
929 struct server *id2server(char *id, uint8_t len) {
931 char **realm, *idrealm;
933 idrealm = strchr(id, '@');
941 for (i = 0; i < server_count; i++) {
942 for (realm = servers[i].realms; *realm; realm++) {
943 if ((strlen(*realm) == 1 && **realm == '*') ||
944 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
945 printf("found matching realm: %s, host %s\n", *realm, servers[i].peer.host);
953 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
956 pthread_mutex_lock(&to->newrq_mutex);
957 for (i = 0; i < MAX_REQUESTS; i++)
958 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
960 pthread_mutex_unlock(&to->newrq_mutex);
962 return i < MAX_REQUESTS;
965 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
966 uint8_t code, id, *auth, *attr, attrvallen;
967 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
972 unsigned char newauth[16];
974 code = *(uint8_t *)buf;
975 id = *(uint8_t *)(buf + 1);
977 auth = (uint8_t *)(buf + 4);
979 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
981 if (code != RAD_Access_Request) {
982 printf("radsrv: server currently accepts only access-requests, ignoring\n");
990 left -= attr[RAD_Attr_Length];
992 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
995 switch (attr[RAD_Attr_Type]) {
996 case RAD_Attr_User_Name:
999 case RAD_Attr_User_Password:
1002 case RAD_Attr_Tunnel_Password:
1003 tunnelpwdattr = attr;
1005 case RAD_Attr_Message_Authenticator:
1006 messageauthattr = attr;
1009 attr += attr[RAD_Attr_Length];
1012 printf("radsrv: malformed packet? remaining byte after last attribute\n");
1015 printf("radsrv: Username: ");
1016 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
1017 printf("%c", usernameattr[RAD_Attr_Value + i]);
1021 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1023 printf("radsrv: ignoring request, don't know where to send it\n");
1027 if (rqinqueue(to, from, id)) {
1028 printf("radsrv: ignoring request from host %s with id %d, already got one\n", from->peer.host, id);
1032 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1033 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1034 printf("radsrv: message authentication failed\n");
1038 if (!RAND_bytes(newauth, 16)) {
1039 printf("radsrv: failed to generate random auth\n");
1043 printauth("auth", auth);
1044 printauth("newauth", newauth);
1047 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
1048 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1049 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1050 printf("radsrv: invalid user password length\n");
1054 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1055 printf("radsrv: cannot decrypt password\n");
1058 printf("radsrv: password: ");
1059 for (i = 0; i < attrvallen; i++)
1060 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1062 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1063 printf("radsrv: cannot encrypt password\n");
1068 if (tunnelpwdattr) {
1069 printf("radsrv: found tunnelpwdattr of length %d\n", tunnelpwdattr[RAD_Attr_Length]);
1070 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1071 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1072 printf("radsrv: invalid user password length\n");
1076 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1077 printf("radsrv: cannot decrypt password\n");
1080 printf("radsrv: password: ");
1081 for (i = 0; i < attrvallen; i++)
1082 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1084 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1085 printf("radsrv: cannot encrypt password\n");
1093 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1094 memcpy(rq->origauth, auth, 16);
1095 memcpy(auth, newauth, 16);
1096 printauth("rq->origauth", rq->origauth);
1097 printauth("auth", auth);
1101 void *clientrd(void *arg) {
1102 struct server *server = (struct server *)arg;
1103 struct client *from;
1104 int i, left, subleft;
1105 unsigned char *buf, *messageauthattr, *subattr, *attr;
1106 struct sockaddr_storage fromsa;
1107 struct timeval lastconnecttry;
1112 lastconnecttry = server->lastconnecttry;
1113 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1114 if (!buf && server->peer.type == 'T') {
1115 tlsconnect(server, &lastconnecttry, "clientrd");
1119 server->connectionok = 1;
1121 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge) {
1122 printf("clientrd: discarding, only accept access accept, access reject and access challenge messages\n");
1126 printf("got message type: %d, id: %d\n", buf[0], buf[1]);
1128 i = buf[1]; /* i is the id */
1130 pthread_mutex_lock(&server->newrq_mutex);
1131 if (!server->requests[i].buf || !server->requests[i].tries) {
1132 pthread_mutex_unlock(&server->newrq_mutex);
1133 printf("clientrd: no matching request sent with this id, ignoring\n");
1137 if (server->requests[i].received) {
1138 pthread_mutex_unlock(&server->newrq_mutex);
1139 printf("clientrd: already received, ignoring\n");
1143 if (!validauth(buf, server->requests[i].buf + 4, server->peer.secret)) {
1144 pthread_mutex_unlock(&server->newrq_mutex);
1145 printf("clientrd: invalid auth, ignoring\n");
1149 from = server->requests[i].from;
1151 /* messageauthattr present? */
1152 messageauthattr = NULL;
1153 left = RADLEN(buf) - 20;
1156 left -= attr[RAD_Attr_Length];
1158 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1161 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1162 if (attr[RAD_Attr_Length] != 18) {
1163 printf("clientrd: illegal message auth attribute length, ignoring packet\n");
1166 memcpy(tmp, buf + 4, 16);
1167 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1168 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1169 printf("clientrd: message authentication failed\n");
1172 memcpy(buf + 4, tmp, 16);
1173 printf("clientrd: message auth ok\n");
1174 messageauthattr = attr;
1177 attr += attr[RAD_Attr_Length];
1180 /* handle MS MPPE */
1181 left = RADLEN(buf) - 20;
1184 left -= attr[RAD_Attr_Length];
1186 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1189 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1190 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { // 311 == MS
1191 subleft = attr[RAD_Attr_Length] - 6;
1193 while (subleft > 1) {
1194 subleft -= subattr[RAD_Attr_Length];
1197 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1198 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1200 printf("clientrd: Got MS MPPE\n");
1201 if (subattr[RAD_Attr_Length] < 20)
1204 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1205 server->peer.secret, strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1206 printf("clientrd: failed to decrypt msppe key\n");
1210 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1211 from->peer.secret, strlen(from->peer.secret), server->requests[i].origauth, subattr + 2)) {
1212 printf("clientrd: failed to encrypt msppe key\n");
1217 printf("clientrd: bad vendor specific attr or subattr length, ignoring packet\n");
1221 attr += attr[RAD_Attr_Length];
1224 /* once we set received = 1, requests[i] may be reused */
1225 buf[1] = (char)server->requests[i].origid;
1226 memcpy(buf + 4, server->requests[i].origauth, 16);
1227 printauth("origauth/buf+4", buf + 4);
1228 if (messageauthattr) {
1229 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1231 printf("clientrd: computed messageauthattr\n");
1234 if (from->peer.type == 'U')
1235 fromsa = server->requests[i].fromsa;
1236 server->requests[i].received = 1;
1237 pthread_mutex_unlock(&server->newrq_mutex);
1239 if (!radsign(buf, from->peer.secret)) {
1240 printf("clientrd: failed to sign message\n");
1243 printauth("signedorigauth/buf+4", buf + 4);
1244 printf("clientrd: giving packet back to where it came from\n");
1245 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1249 void *clientwr(void *arg) {
1250 struct server *server = (struct server *)arg;
1252 pthread_t clientrdth;
1255 struct timespec timeout;
1257 memset(&timeout, 0, sizeof(struct timespec));
1259 if (server->peer.type == 'U') {
1260 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
1261 printf("clientwr: connecttoserver failed\n");
1265 tlsconnect(server, NULL, "new client");
1267 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1268 errx("clientwr: pthread_create failed");
1271 pthread_mutex_lock(&server->newrq_mutex);
1272 if (!server->newrq) {
1273 if (timeout.tv_nsec) {
1274 printf("clientwr: waiting up to %ld secs for new request\n", timeout.tv_nsec);
1275 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1276 timeout.tv_nsec = 0;
1278 printf("clientwr: waiting for new request\n");
1279 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1281 if (server->newrq) {
1282 printf("clientwr: got new request\n");
1286 pthread_mutex_unlock(&server->newrq_mutex);
1288 for (i = 0; i < MAX_REQUESTS; i++) {
1289 pthread_mutex_lock(&server->newrq_mutex);
1290 while (!server->requests[i].buf && i < MAX_REQUESTS)
1292 if (i == MAX_REQUESTS) {
1293 pthread_mutex_unlock(&server->newrq_mutex);
1296 rq = server->requests + i;
1299 printf("clientwr: removing received packet from queue\n");
1301 /* setting this to NULL means that it can be reused */
1303 pthread_mutex_unlock(&server->newrq_mutex);
1307 gettimeofday(&now, NULL);
1308 if (now.tv_sec <= rq->expiry.tv_sec) {
1309 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1310 timeout.tv_sec = rq->expiry.tv_sec;
1311 pthread_mutex_unlock(&server->newrq_mutex);
1315 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1316 printf("clientwr: removing expired packet from queue\n");
1318 /* setting this to NULL means that it can be reused */
1320 pthread_mutex_unlock(&server->newrq_mutex);
1323 pthread_mutex_unlock(&server->newrq_mutex);
1325 rq->expiry.tv_sec = now.tv_sec +
1326 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1327 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1328 timeout.tv_sec = rq->expiry.tv_sec;
1330 clientradput(server, server->requests[i].buf);
1334 /* should do more work to maintain TLS connections, keepalives etc */
1337 void *udpserverwr(void *arg) {
1338 struct replyq *replyq = &udp_server_replyq;
1339 struct reply *reply = replyq->replies;
1341 pthread_mutex_lock(&replyq->count_mutex);
1343 while (!replyq->count) {
1344 printf("udp server writer, waiting for signal\n");
1345 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1346 printf("udp server writer, got signal\n");
1348 pthread_mutex_unlock(&replyq->count_mutex);
1350 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1351 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1352 err("sendudp: send failed");
1355 pthread_mutex_lock(&replyq->count_mutex);
1357 memmove(replyq->replies, replyq->replies + 1,
1358 replyq->count * sizeof(struct reply));
1362 void *udpserverrd(void *arg) {
1367 pthread_t udpserverwrth;
1369 if ((udp_server_sock = bindport(SOCK_DGRAM, options.udpserverport)) < 0) {
1370 printf("udpserverrd: socket/bind failed\n");
1373 printf("udpserverrd: listening on UDP port %s\n", options.udpserverport);
1375 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1376 errx("pthread_create failed");
1380 memset(&rq, 0, sizeof(struct request));
1381 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1382 to = radsrv(&rq, buf, fr);
1384 printf("udpserverrd: ignoring request, no place to send it\n");
1387 sendrq(to, fr, &rq);
1391 void *tlsserverwr(void *arg) {
1393 unsigned long error;
1394 struct client *client = (struct client *)arg;
1395 struct replyq *replyq;
1397 printf("tlsserverwr starting for %s\n", client->peer.host);
1398 replyq = client->replyq;
1399 pthread_mutex_lock(&replyq->count_mutex);
1401 while (!replyq->count) {
1402 if (client->peer.ssl) {
1403 printf("tls server writer, waiting for signal\n");
1404 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1405 printf("tls server writer, got signal\n");
1407 if (!client->peer.ssl) {
1408 //ssl might have changed while waiting
1409 pthread_mutex_unlock(&replyq->count_mutex);
1410 printf("tlsserverwr: exiting as requested\n");
1414 pthread_mutex_unlock(&replyq->count_mutex);
1415 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1417 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
1418 cnt, RADLEN(replyq->replies->buf));
1420 while ((error = ERR_get_error()))
1421 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1422 free(replyq->replies->buf);
1424 pthread_mutex_lock(&replyq->count_mutex);
1426 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1430 void *tlsserverrd(void *arg) {
1433 unsigned long error;
1436 struct client *client = (struct client *)arg;
1437 pthread_t tlsserverwrth;
1440 printf("tlsserverrd starting for %s\n", client->peer.host);
1441 ssl = client->peer.ssl;
1443 if (SSL_accept(ssl) <= 0) {
1444 while ((error = ERR_get_error()))
1445 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1446 errx("accept failed, child exiting");
1449 if (tlsverifycert(&client->peer)) {
1450 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
1451 errx("pthread_create failed");
1454 buf = radtlsget(client->peer.ssl);
1457 printf("tlsserverrd: got Radius message from %s\n", client->peer.host);
1458 memset(&rq, 0, sizeof(struct request));
1459 to = radsrv(&rq, buf, client);
1461 printf("ignoring request, no place to send it\n");
1464 sendrq(to, client, &rq);
1466 printf("tlsserverrd: connection lost\n");
1467 // stop writer by setting peer.ssl to NULL and give signal in case waiting for data
1468 client->peer.ssl = NULL;
1469 pthread_mutex_lock(&client->replyq->count_mutex);
1470 pthread_cond_signal(&client->replyq->count_cond);
1471 pthread_mutex_unlock(&client->replyq->count_mutex);
1472 printf("tlsserverrd: waiting for writer to end\n");
1473 pthread_join(tlsserverwrth, NULL);
1475 s = SSL_get_fd(ssl);
1478 printf("tlsserverrd thread for %s exiting\n", client->peer.host);
1479 client->peer.ssl = NULL;
1484 pthread_t tlsserverth;
1486 struct sockaddr_storage from;
1487 size_t fromlen = sizeof(from);
1488 struct client *client;
1490 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
1491 printf("tlslistener: socket/bind failed\n");
1496 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
1499 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1501 errx("accept failed");
1502 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
1504 client = find_client('T', (struct sockaddr *)&from, NULL);
1506 printf("ignoring request, not a known TLS client\n");
1507 shutdown(snew, SHUT_RDWR);
1512 if (client->peer.ssl) {
1513 printf("Ignoring incoming connection, already have one from this client\n");
1514 shutdown(snew, SHUT_RDWR);
1518 client->peer.ssl = SSL_new(ssl_ctx);
1519 SSL_set_fd(client->peer.ssl, snew);
1520 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
1521 errx("pthread_create failed");
1522 pthread_detach(tlsserverth);
1527 char *parsehostport(char *s, struct peer *peer) {
1532 // allow literal addresses and port, e.g. [2001:db8::1]:1812
1536 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1538 printf("no ] matching initial [\n");
1544 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1547 printf("missing host/address\n");
1550 peer->host = stringcopy(field, p - field);
1553 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
1554 printf("unexpected character after ]\n");
1559 /* port number or service name is specified */;
1561 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1563 printf("syntax error, : but no following port\n");
1566 peer->port = stringcopy(field, p - field);
1568 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1572 // * is default, else longest match ... ";" used for separator
1573 char *parserealmlist(char *s, struct server *server) {
1577 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1582 printf("realm list must be specified\n");
1585 server->realmdata = stringcopy(s, l);
1586 server->realms = malloc((1+n) * sizeof(char *));
1587 if (!server->realms)
1588 errx("malloc failed");
1589 server->realms[0] = server->realmdata;
1590 for (n = 1, i = 0; i < l; i++)
1591 if (server->realmdata[i] == ';') {
1592 server->realmdata[i] = '\0';
1593 server->realms[n++] = server->realmdata + i + 1;
1595 server->realms[n] = NULL;
1599 FILE *openconfigfile(const char *filename) {
1601 char pathname[100], *base;
1603 f = fopen(filename, "r");
1605 printf("reading config file %s\n", filename);
1609 if (strlen(filename) + 1 <= sizeof(pathname)) {
1610 // basename() might modify the string
1611 strcpy(pathname, filename);
1612 base = basename(pathname);
1613 f = fopen(base, "r");
1617 err("could not read config file %s nor %s\n", filename, base);
1619 printf("reading config file %s\n", base);
1623 /* exactly one argument must be non-NULL */
1624 void getconfig(const char *serverfile, const char *clientfile) {
1627 char *p, *field, **r;
1628 struct client *client;
1629 struct server *server;
1631 int i, count, *ucount, *tcount;
1633 f = openconfigfile(serverfile ? serverfile : clientfile);
1635 ucount = &server_udp_count;
1636 tcount = &server_tls_count;
1638 ucount = &client_udp_count;
1639 tcount = &client_tls_count;
1641 while (fgets(line, 1024, f)) {
1642 for (p = line; *p == ' ' || *p == '\t'; p++);
1654 printf("type must be U or T, got %c\n", *p);
1660 count = server_count = server_udp_count + server_tls_count;
1661 servers = calloc(count, sizeof(struct server));
1663 errx("malloc failed");
1665 count = client_count = client_udp_count + client_tls_count;
1666 clients = calloc(count, sizeof(struct client));
1668 errx("malloc failed");
1671 if (client_udp_count) {
1672 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1673 if (!udp_server_replyq.replies)
1674 errx("malloc failed");
1675 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1676 udp_server_replyq.count = 0;
1677 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1678 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1682 for (i = 0; i < count && fgets(line, 1024, f);) {
1684 server = &servers[i];
1685 peer = &server->peer;
1687 client = &clients[i];
1688 peer = &client->peer;
1690 for (p = line; *p == ' ' || *p == '\t'; p++);
1691 if (*p == '#' || *p == '\n')
1693 peer->type = *p; // we already know it must be U or T
1694 for (p++; *p == ' ' || *p == '\t'; p++);
1695 p = parsehostport(p, peer);
1696 for (; *p == ' ' || *p == '\t'; p++);
1698 p = parserealmlist(p, server);
1699 for (; *p == ' ' || *p == '\t'; p++);
1702 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1704 /* no secret set and end of line, line is complete if TLS */
1705 if (peer->type == 'U') {
1706 printf("secret must be specified for UDP\n");
1709 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1711 peer->secret = stringcopy(field, p - field);
1712 /* check that rest of line only white space */
1713 for (; *p == ' ' || *p == '\t'; p++);
1714 if (*p && *p != '\n') {
1715 printf("max 4 fields per line, found a 5th\n");
1720 if ((serverfile && !resolvepeer(&server->peer)) ||
1721 (clientfile && !resolvepeer(&client->peer))) {
1722 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1727 pthread_mutex_init(&server->lock, NULL);
1729 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1730 if (!server->requests)
1731 errx("malloc failed");
1733 pthread_mutex_init(&server->newrq_mutex, NULL);
1734 pthread_cond_init(&server->newrq_cond, NULL);
1736 if (peer->type == 'U')
1737 client->replyq = &udp_server_replyq;
1739 client->replyq = malloc(sizeof(struct replyq));
1740 if (!client->replyq)
1741 errx("malloc failed");
1742 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1743 if (!client->replyq->replies)
1744 errx("malloc failed");
1745 client->replyq->size = MAX_REQUESTS;
1746 client->replyq->count = 0;
1747 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1748 pthread_cond_init(&client->replyq->count_cond, NULL);
1751 printf("got type %c, host %s, port %s, secret %s\n", peer->type, peer->host, peer->port, peer->secret);
1753 printf(" with realms:");
1754 for (r = server->realms; *r; r++)
1763 void getmainconfig(const char *configfile) {
1766 char *p, *opt, *endopt, *val, *endval;
1768 f = openconfigfile(configfile);
1769 memset(&options, 0, sizeof(options));
1771 while (fgets(line, 1024, f)) {
1772 for (p = line; *p == ' ' || *p == '\t'; p++);
1773 if (!*p || *p == '#' || *p == '\n')
1776 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1778 for (; *p == ' ' || *p == '\t'; p++);
1779 if (!*p || *p == '\n') {
1781 printf("error in %s, option %s has no value\n", configfile, opt);
1785 for (; *p && *p != '\n'; p++)
1786 if (*p != ' ' && *p != '\t')
1790 printf("getmainconfig: %s = %s\n", opt, val);
1792 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1793 options.tlscacertificatefile = stringcopy(val, 0);
1796 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1797 options.tlscacertificatepath = stringcopy(val, 0);
1800 if (!strcasecmp(opt, "TLSCertificateFile")) {
1801 options.tlscertificatefile = stringcopy(val, 0);
1804 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1805 options.tlscertificatekeyfile = stringcopy(val, 0);
1808 if (!strcasecmp(opt, "UDPServerPort")) {
1809 options.udpserverport = stringcopy(val, 0);
1813 printf("error in %s, unknown option %s\n", configfile, opt);
1818 if (!options.udpserverport)
1819 options.udpserverport = stringcopy(DEFAULT_UDP_PORT, 0);
1823 void parseargs(int argc, char **argv) {
1826 while ((c = getopt(argc, argv, "p:")) != -1) {
1829 udp_server_port = optarg;
1839 printf("radsecproxy [ -p UDP-port ]\n");
1844 int main(int argc, char **argv) {
1845 pthread_t udpserverth;
1846 // pthread_attr_t joinable;
1849 // parseargs(argc, argv);
1850 getmainconfig(CONFIG_MAIN);
1851 getconfig(CONFIG_SERVERS, NULL);
1852 getconfig(NULL, CONFIG_CLIENTS);
1854 // pthread_attr_init(&joinable);
1855 // pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1857 if (client_udp_count)
1858 if (pthread_create(&udpserverth, NULL /*&joinable*/, udpserverrd, NULL))
1859 errx("pthread_create failed");
1861 if (client_tls_count || server_tls_count)
1862 ssl_ctx = ssl_init();
1864 for (i = 0; i < server_count; i++)
1865 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1866 errx("pthread_create failed");
1868 if (client_tls_count)
1869 return tlslistener();
1871 /* just hang around doing nothing, anything to do here? */