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
43 #include <openssl/ssl.h>
44 #include <openssl/rand.h>
45 #include <openssl/err.h>
46 #include <openssl/md5.h>
47 #include <openssl/hmac.h>
48 #include "radsecproxy.h"
50 static struct options options;
51 static struct client *clients;
52 static struct server *servers;
54 static int client_udp_count = 0;
55 static int client_tls_count = 0;
56 static int client_count = 0;
57 static int server_udp_count = 0;
58 static int server_tls_count = 0;
59 static int server_count = 0;
61 static struct replyq udp_server_replyq;
62 static int udp_server_sock = -1;
63 static pthread_mutex_t *ssl_locks;
64 static long *ssl_lock_count;
65 static SSL_CTX *ssl_ctx = NULL;
69 /* callbacks for making OpenSSL thread safe */
70 unsigned long ssl_thread_id() {
71 return (unsigned long)pthread_self();
74 void ssl_locking_callback(int mode, int type, const char *file, int line) {
75 if (mode & CRYPTO_LOCK) {
76 pthread_mutex_lock(&ssl_locks[type]);
77 ssl_lock_count[type]++;
79 pthread_mutex_unlock(&ssl_locks[type]);
82 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
87 err_cert = X509_STORE_CTX_get_current_cert(ctx);
88 err = X509_STORE_CTX_get_error(ctx);
89 depth = X509_STORE_CTX_get_error_depth(ctx);
91 if (depth > MAX_CERT_DEPTH) {
93 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
94 X509_STORE_CTX_set_error(ctx, err);
98 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
99 printf("verify error: num=%d:%s:depth=%d:%s\n", err, X509_verify_cert_error_string(err), depth, buf);
102 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
103 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
104 printf("issuer=%s\n", buf);
106 case X509_V_ERR_CERT_NOT_YET_VALID:
107 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
108 printf("Certificate not yet valid\n");
110 case X509_V_ERR_CERT_HAS_EXPIRED:
111 printf("Certificate has expired\n");
113 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
114 printf("Certificate no longer valid (after notAfter)\n");
118 // printf("certificate verify returns %d\n", ok);
122 SSL_CTX *ssl_init() {
127 if (!options.tlscertificatefile || !options.tlscertificatekeyfile) {
128 printf("TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS\n");
131 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
132 printf("CA Certificate file/path need to be configured\n");
136 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
137 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
138 for (i = 0; i < CRYPTO_num_locks(); i++) {
139 ssl_lock_count[i] = 0;
140 pthread_mutex_init(&ssl_locks[i], NULL);
142 CRYPTO_set_id_callback(ssl_thread_id);
143 CRYPTO_set_locking_callback(ssl_locking_callback);
145 SSL_load_error_strings();
148 while (!RAND_status()) {
149 time_t t = time(NULL);
150 pid_t pid = getpid();
151 RAND_seed((unsigned char *)&t, sizeof(time_t));
152 RAND_seed((unsigned char *)&pid, sizeof(pid));
155 ctx = SSL_CTX_new(TLSv1_method());
156 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
157 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
158 SSL_CTX_check_private_key(ctx) &&
159 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
160 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
161 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
165 while ((error = ERR_get_error()))
166 err("SSL: %s", ERR_error_string(error, NULL));
170 void printauth(char *s, unsigned char *t) {
173 for (i = 0; i < 16; i++)
174 printf("%02x ", t[i]);
178 int resolvepeer(struct peer *peer) {
179 struct addrinfo hints, *addrinfo;
181 memset(&hints, 0, sizeof(hints));
182 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
183 hints.ai_family = AF_UNSPEC;
184 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
185 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
190 freeaddrinfo(peer->addrinfo);
191 peer->addrinfo = addrinfo;
195 int connecttoserver(struct addrinfo *addrinfo) {
197 struct addrinfo *res;
199 for (res = addrinfo; res; res = res->ai_next) {
200 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
202 err("connecttoserver: socket failed");
205 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
207 err("connecttoserver: connect failed");
214 /* returns the client with matching address, or NULL */
215 /* if client argument is not NULL, we only check that one client */
216 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
217 struct sockaddr_in6 *sa6;
218 struct in_addr *a4 = NULL;
221 struct addrinfo *res;
223 if (addr->sa_family == AF_INET6) {
224 sa6 = (struct sockaddr_in6 *)addr;
225 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
226 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
228 a4 = &((struct sockaddr_in *)addr)->sin_addr;
230 c = (client ? client : clients);
231 for (i = 0; i < client_count; i++) {
232 if (c->peer.type == type)
233 for (res = c->peer.addrinfo; res; res = res->ai_next)
234 if ((a4 && res->ai_family == AF_INET &&
235 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
236 (res->ai_family == AF_INET6 &&
237 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
246 /* returns the server with matching address, or NULL */
247 /* if server argument is not NULL, we only check that one server */
248 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
249 struct sockaddr_in6 *sa6;
250 struct in_addr *a4 = NULL;
253 struct addrinfo *res;
255 if (addr->sa_family == AF_INET6) {
256 sa6 = (struct sockaddr_in6 *)addr;
257 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
258 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
260 a4 = &((struct sockaddr_in *)addr)->sin_addr;
262 s = (server ? server : servers);
263 for (i = 0; i < server_count; i++) {
264 if (s->peer.type == type)
265 for (res = s->peer.addrinfo; res; res = res->ai_next)
266 if ((a4 && res->ai_family == AF_INET &&
267 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
268 (res->ai_family == AF_INET6 &&
269 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
278 /* exactly one of client and server must be non-NULL */
279 /* if *peer == NULL we return who we received from, else require it to be from peer */
280 /* return from in sa if not NULL */
281 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
284 unsigned char buf[65536], *rad;
285 struct sockaddr_storage from;
286 socklen_t fromlen = sizeof(from);
289 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
291 err("radudpget: recv failed");
294 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
297 printf("radudpget: packet too small\n");
304 printf("radudpget: packet smaller than length field in radius header\n");
308 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
311 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
312 : (void *)find_server('U', (struct sockaddr *)&from, *server));
314 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
321 err("radudpget: malloc failed");
323 memcpy(rad, buf, len);
325 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
327 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
333 int tlsverifycert(struct peer *peer) {
342 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
343 printf("tlsverifycert: basic validation failed\n");
344 while ((error = ERR_get_error()))
345 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
349 cert = SSL_get_peer_certificate(peer->ssl);
351 printf("tlsverifycert: failed to obtain certificate\n");
354 nm = X509_get_subject_name(cert);
357 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
360 e = X509_NAME_get_entry(nm, loc);
361 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
365 for (i = 0; i < l; i++)
368 if (l == strlen(peer->host) && !strncasecmp(peer->host, v, l)) {
369 printf("tlsverifycert: Found cn matching host %s, All OK\n", peer->host);
372 printf("tlsverifycert: cn not matching host %s\n", peer->host);
378 void tlsconnect(struct server *server, struct timeval *when, char *text) {
382 printf("tlsconnect called from %s\n", text);
383 pthread_mutex_lock(&server->lock);
384 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
385 /* already reconnected, nothing to do */
386 printf("tlsconnect(%s): seems already reconnected\n", text);
387 pthread_mutex_unlock(&server->lock);
391 printf("tlsconnect %s\n", text);
394 gettimeofday(&now, NULL);
395 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
396 if (server->connectionok) {
397 server->connectionok = 0;
399 } else if (elapsed < 5)
401 else if (elapsed < 600) {
402 printf("tlsconnect: sleeping %lds\n", elapsed);
404 } else if (elapsed < 1000) {
405 printf("tlsconnect: sleeping %ds\n", 900);
408 server->lastconnecttry.tv_sec = now.tv_sec; // no sleep at startup
409 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->peer.host, server->peer.port);
410 if (server->sock >= 0)
412 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
414 SSL_free(server->peer.ssl);
415 server->peer.ssl = SSL_new(ssl_ctx);
416 SSL_set_fd(server->peer.ssl, server->sock);
417 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
420 printf("tlsconnect: TLS connection to %s port %s up\n", server->peer.host, server->peer.port);
421 gettimeofday(&server->lastconnecttry, NULL);
422 pthread_mutex_unlock(&server->lock);
425 unsigned char *radtlsget(SSL *ssl) {
427 unsigned char buf[4], *rad;
430 for (total = 0; total < 4; total += cnt) {
431 cnt = SSL_read(ssl, buf + total, 4 - total);
433 printf("radtlsget: connection lost\n");
434 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
435 //remote end sent close_notify, send one back
445 err("radtlsget: malloc failed");
450 for (; total < len; total += cnt) {
451 cnt = SSL_read(ssl, rad + total, len - total);
453 printf("radtlsget: connection lost\n");
454 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
455 //remote end sent close_notify, send one back
467 printf("radtlsget: packet smaller than minimum radius size\n");
470 printf("radtlsget: got %d bytes\n", total);
474 int clientradput(struct server *server, unsigned char *rad) {
478 struct timeval lastconnecttry;
481 if (server->peer.type == 'U') {
482 if (send(server->sock, rad, len, 0) >= 0) {
483 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->peer.host, server->peer.port);
486 err("clientradput: send failed");
490 lastconnecttry = server->lastconnecttry;
491 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
492 while ((error = ERR_get_error()))
493 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
494 tlsconnect(server, &lastconnecttry, "clientradput");
495 lastconnecttry = server->lastconnecttry;
498 server->connectionok = 1;
499 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
500 cnt, len, server->peer.host);
504 int radsign(unsigned char *rad, unsigned char *sec) {
505 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
506 static unsigned char first = 1;
507 static EVP_MD_CTX mdctx;
511 pthread_mutex_lock(&lock);
513 EVP_MD_CTX_init(&mdctx);
517 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
518 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
519 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
520 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
522 pthread_mutex_unlock(&lock);
526 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
527 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
528 static unsigned char first = 1;
529 static EVP_MD_CTX mdctx;
530 unsigned char hash[EVP_MAX_MD_SIZE];
534 pthread_mutex_lock(&lock);
536 EVP_MD_CTX_init(&mdctx);
542 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
543 EVP_DigestUpdate(&mdctx, rad, 4) &&
544 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
545 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
546 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
547 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
549 !memcmp(hash, rad + 4, 16));
550 pthread_mutex_unlock(&lock);
554 int checkmessageauth(char *rad, uint8_t *authattr, char *secret) {
555 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
556 static unsigned char first = 1;
557 static HMAC_CTX hmacctx;
559 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
561 pthread_mutex_lock(&lock);
563 HMAC_CTX_init(&hmacctx);
567 memcpy(auth, authattr, 16);
568 memset(authattr, 0, 16);
570 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
571 HMAC_Update(&hmacctx, rad, RADLEN(rad));
572 HMAC_Final(&hmacctx, hash, &md_len);
573 memcpy(authattr, auth, 16);
575 printf("message auth computation failed\n");
576 pthread_mutex_unlock(&lock);
580 if (memcmp(auth, hash, 16)) {
581 printf("message authenticator, wrong value\n");
582 pthread_mutex_unlock(&lock);
586 pthread_mutex_unlock(&lock);
590 int createmessageauth(char *rad, char *authattrval, char *secret) {
591 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
592 static unsigned char first = 1;
593 static HMAC_CTX hmacctx;
599 pthread_mutex_lock(&lock);
601 HMAC_CTX_init(&hmacctx);
605 memset(authattrval, 0, 16);
607 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
608 HMAC_Update(&hmacctx, rad, RADLEN(rad));
609 HMAC_Final(&hmacctx, authattrval, &md_len);
611 printf("message auth computation failed\n");
612 pthread_mutex_unlock(&lock);
616 pthread_mutex_unlock(&lock);
620 void sendrq(struct server *to, struct client *from, struct request *rq) {
623 pthread_mutex_lock(&to->newrq_mutex);
624 /* might simplify if only try nextid, might be ok */
625 for (i = to->nextid; i < MAX_REQUESTS; i++)
626 if (!to->requests[i].buf)
628 if (i == MAX_REQUESTS) {
629 for (i = 0; i < to->nextid; i++)
630 if (!to->requests[i].buf)
632 if (i == to->nextid) {
633 printf("No room in queue, dropping request\n");
634 pthread_mutex_unlock(&to->newrq_mutex);
640 rq->buf[1] = (char)i;
641 printf("sendrq: inserting packet with id %d in queue for %s\n", i, to->peer.host);
643 if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
646 to->requests[i] = *rq;
650 printf("signalling client writer\n");
651 pthread_cond_signal(&to->newrq_cond);
653 pthread_mutex_unlock(&to->newrq_mutex);
656 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
657 struct replyq *replyq = to->replyq;
659 pthread_mutex_lock(&replyq->count_mutex);
660 if (replyq->count == replyq->size) {
661 printf("No room in queue, dropping request\n");
662 pthread_mutex_unlock(&replyq->count_mutex);
666 replyq->replies[replyq->count].buf = buf;
668 replyq->replies[replyq->count].tosa = *tosa;
671 if (replyq->count == 1) {
672 printf("signalling client writer\n");
673 pthread_cond_signal(&replyq->count_cond);
675 pthread_mutex_unlock(&replyq->count_mutex);
678 int pwdencrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
679 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
680 static unsigned char first = 1;
681 static EVP_MD_CTX mdctx;
682 unsigned char hash[EVP_MAX_MD_SIZE], *input;
684 uint8_t i, offset = 0, out[128];
686 pthread_mutex_lock(&lock);
688 EVP_MD_CTX_init(&mdctx);
694 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
695 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
696 !EVP_DigestUpdate(&mdctx, input, 16) ||
697 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
699 pthread_mutex_unlock(&lock);
702 for (i = 0; i < 16; i++)
703 out[offset + i] = hash[i] ^ in[offset + i];
704 input = out + offset - 16;
709 memcpy(in, out, len);
710 pthread_mutex_unlock(&lock);
714 int pwddecrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
715 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
716 static unsigned char first = 1;
717 static EVP_MD_CTX mdctx;
718 unsigned char hash[EVP_MAX_MD_SIZE], *input;
720 uint8_t i, offset = 0, out[128];
722 pthread_mutex_lock(&lock);
724 EVP_MD_CTX_init(&mdctx);
730 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
731 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
732 !EVP_DigestUpdate(&mdctx, input, 16) ||
733 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
735 pthread_mutex_unlock(&lock);
738 for (i = 0; i < 16; i++)
739 out[offset + i] = hash[i] ^ in[offset + i];
745 memcpy(in, out, len);
746 pthread_mutex_unlock(&lock);
750 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
751 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
752 static unsigned char first = 1;
753 static EVP_MD_CTX mdctx;
754 unsigned char hash[EVP_MAX_MD_SIZE];
758 pthread_mutex_lock(&lock);
760 EVP_MD_CTX_init(&mdctx);
765 printf("msppencrypt auth in: ");
766 for (i = 0; i < 16; i++)
767 printf("%02x ", auth[i]);
770 printf("msppencrypt salt in: ");
771 for (i = 0; i < 2; i++)
772 printf("%02x ", salt[i]);
775 printf("msppencrypt in: ");
776 for (i = 0; i < len; i++)
777 printf("%02x ", text[i]);
781 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
782 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
783 !EVP_DigestUpdate(&mdctx, auth, 16) ||
784 !EVP_DigestUpdate(&mdctx, salt, 2) ||
785 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
786 pthread_mutex_unlock(&lock);
791 printf("msppencrypt hash: ");
792 for (i = 0; i < 16; i++)
793 printf("%02x ", hash[i]);
797 for (i = 0; i < 16; i++)
800 for (offset = 16; offset < len; offset += 16) {
802 printf("text + offset - 16 c(%d): ", offset / 16);
803 for (i = 0; i < 16; i++)
804 printf("%02x ", (text + offset - 16)[i]);
807 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
808 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
809 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
810 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
812 pthread_mutex_unlock(&lock);
816 printf("msppencrypt hash: ");
817 for (i = 0; i < 16; i++)
818 printf("%02x ", hash[i]);
822 for (i = 0; i < 16; i++)
823 text[offset + i] ^= hash[i];
827 printf("msppencrypt out: ");
828 for (i = 0; i < len; i++)
829 printf("%02x ", text[i]);
833 pthread_mutex_unlock(&lock);
837 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
838 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
839 static unsigned char first = 1;
840 static EVP_MD_CTX mdctx;
841 unsigned char hash[EVP_MAX_MD_SIZE];
846 pthread_mutex_lock(&lock);
848 EVP_MD_CTX_init(&mdctx);
853 printf("msppdecrypt auth in: ");
854 for (i = 0; i < 16; i++)
855 printf("%02x ", auth[i]);
858 printf("msppedecrypt salt in: ");
859 for (i = 0; i < 2; i++)
860 printf("%02x ", salt[i]);
863 printf("msppedecrypt in: ");
864 for (i = 0; i < len; i++)
865 printf("%02x ", text[i]);
869 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
870 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
871 !EVP_DigestUpdate(&mdctx, auth, 16) ||
872 !EVP_DigestUpdate(&mdctx, salt, 2) ||
873 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
874 pthread_mutex_unlock(&lock);
879 printf("msppedecrypt hash: ");
880 for (i = 0; i < 16; i++)
881 printf("%02x ", hash[i]);
885 for (i = 0; i < 16; i++)
886 plain[i] = text[i] ^ hash[i];
888 for (offset = 16; offset < len; offset += 16) {
890 printf("text + offset - 16 c(%d): ", offset / 16);
891 for (i = 0; i < 16; i++)
892 printf("%02x ", (text + offset - 16)[i]);
895 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
896 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
897 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
898 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
900 pthread_mutex_unlock(&lock);
904 printf("msppedecrypt hash: ");
905 for (i = 0; i < 16; i++)
906 printf("%02x ", hash[i]);
910 for (i = 0; i < 16; i++)
911 plain[offset + i] = text[offset + i] ^ hash[i];
914 memcpy(text, plain, len);
916 printf("msppedecrypt out: ");
917 for (i = 0; i < len; i++)
918 printf("%02x ", text[i]);
922 pthread_mutex_unlock(&lock);
926 struct server *id2server(char *id, uint8_t len) {
928 char **realm, *idrealm;
930 idrealm = strchr(id, '@');
938 for (i = 0; i < server_count; i++) {
939 for (realm = servers[i].realms; *realm; realm++) {
940 if ((strlen(*realm) == 1 && **realm == '*') ||
941 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
942 printf("found matching realm: %s, host %s\n", *realm, servers[i].peer.host);
950 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
953 pthread_mutex_lock(&to->newrq_mutex);
954 for (i = 0; i < MAX_REQUESTS; i++)
955 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
957 pthread_mutex_unlock(&to->newrq_mutex);
959 return i < MAX_REQUESTS;
962 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
963 uint8_t code, id, *auth, *attr, attrvallen;
964 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
969 unsigned char newauth[16];
971 code = *(uint8_t *)buf;
972 id = *(uint8_t *)(buf + 1);
974 auth = (uint8_t *)(buf + 4);
976 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
978 if (code != RAD_Access_Request) {
979 printf("radsrv: server currently accepts only access-requests, ignoring\n");
987 left -= attr[RAD_Attr_Length];
989 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
992 switch (attr[RAD_Attr_Type]) {
993 case RAD_Attr_User_Name:
996 case RAD_Attr_User_Password:
999 case RAD_Attr_Tunnel_Password:
1000 tunnelpwdattr = attr;
1002 case RAD_Attr_Message_Authenticator:
1003 messageauthattr = attr;
1006 attr += attr[RAD_Attr_Length];
1009 printf("radsrv: malformed packet? remaining byte after last attribute\n");
1012 printf("radsrv: Username: ");
1013 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
1014 printf("%c", usernameattr[RAD_Attr_Value + i]);
1018 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1020 printf("radsrv: ignoring request, don't know where to send it\n");
1024 if (rqinqueue(to, from, id)) {
1025 printf("radsrv: ignoring request from host %s with id %d, already got one\n", from->peer.host, id);
1029 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1030 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1031 printf("radsrv: message authentication failed\n");
1035 if (!RAND_bytes(newauth, 16)) {
1036 printf("radsrv: failed to generate random auth\n");
1040 printauth("auth", auth);
1041 printauth("newauth", newauth);
1044 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
1045 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1046 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1047 printf("radsrv: invalid user password length\n");
1051 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1052 printf("radsrv: cannot decrypt password\n");
1055 printf("radsrv: password: ");
1056 for (i = 0; i < attrvallen; i++)
1057 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1059 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1060 printf("radsrv: cannot encrypt password\n");
1065 if (tunnelpwdattr) {
1066 printf("radsrv: found tunnelpwdattr of length %d\n", tunnelpwdattr[RAD_Attr_Length]);
1067 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1068 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1069 printf("radsrv: invalid user password length\n");
1073 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1074 printf("radsrv: cannot decrypt password\n");
1077 printf("radsrv: password: ");
1078 for (i = 0; i < attrvallen; i++)
1079 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1081 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1082 printf("radsrv: cannot encrypt password\n");
1090 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1091 memcpy(rq->origauth, auth, 16);
1092 memcpy(auth, newauth, 16);
1093 printauth("rq->origauth", rq->origauth);
1094 printauth("auth", auth);
1098 void *clientrd(void *arg) {
1099 struct server *server = (struct server *)arg;
1100 struct client *from;
1101 int i, left, subleft;
1102 unsigned char *buf, *messageauthattr, *subattr, *attr;
1103 struct sockaddr_storage fromsa;
1104 struct timeval lastconnecttry;
1109 lastconnecttry = server->lastconnecttry;
1110 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1111 if (!buf && server->peer.type == 'T') {
1112 tlsconnect(server, &lastconnecttry, "clientrd");
1116 server->connectionok = 1;
1118 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge) {
1119 printf("clientrd: discarding, only accept access accept, access reject and access challenge messages\n");
1123 printf("got message type: %d, id: %d\n", buf[0], buf[1]);
1125 i = buf[1]; /* i is the id */
1127 pthread_mutex_lock(&server->newrq_mutex);
1128 if (!server->requests[i].buf || !server->requests[i].tries) {
1129 pthread_mutex_unlock(&server->newrq_mutex);
1130 printf("clientrd: no matching request sent with this id, ignoring\n");
1134 if (server->requests[i].received) {
1135 pthread_mutex_unlock(&server->newrq_mutex);
1136 printf("clientrd: already received, ignoring\n");
1140 if (!validauth(buf, server->requests[i].buf + 4, server->peer.secret)) {
1141 pthread_mutex_unlock(&server->newrq_mutex);
1142 printf("clientrd: invalid auth, ignoring\n");
1146 from = server->requests[i].from;
1148 /* messageauthattr present? */
1149 messageauthattr = NULL;
1150 left = RADLEN(buf) - 20;
1153 left -= attr[RAD_Attr_Length];
1155 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1158 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1159 if (attr[RAD_Attr_Length] != 18) {
1160 printf("clientrd: illegal message auth attribute length, ignoring packet\n");
1163 memcpy(tmp, buf + 4, 16);
1164 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1165 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1166 printf("clientrd: message authentication failed\n");
1169 memcpy(buf + 4, tmp, 16);
1170 printf("clientrd: message auth ok\n");
1171 messageauthattr = attr;
1174 attr += attr[RAD_Attr_Length];
1177 /* handle MS MPPE */
1178 left = RADLEN(buf) - 20;
1181 left -= attr[RAD_Attr_Length];
1183 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1186 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1187 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { // 311 == MS
1188 subleft = attr[RAD_Attr_Length] - 6;
1190 while (subleft > 1) {
1191 subleft -= subattr[RAD_Attr_Length];
1194 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1195 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1197 printf("clientrd: Got MS MPPE\n");
1198 if (subattr[RAD_Attr_Length] < 20)
1201 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1202 server->peer.secret, strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1203 printf("clientrd: failed to decrypt msppe key\n");
1207 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1208 from->peer.secret, strlen(from->peer.secret), server->requests[i].origauth, subattr + 2)) {
1209 printf("clientrd: failed to encrypt msppe key\n");
1214 printf("clientrd: bad vendor specific attr or subattr length, ignoring packet\n");
1218 attr += attr[RAD_Attr_Length];
1221 /* once we set received = 1, requests[i] may be reused */
1222 buf[1] = (char)server->requests[i].origid;
1223 memcpy(buf + 4, server->requests[i].origauth, 16);
1224 printauth("origauth/buf+4", buf + 4);
1225 if (messageauthattr) {
1226 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1228 printf("clientrd: computed messageauthattr\n");
1231 if (from->peer.type == 'U')
1232 fromsa = server->requests[i].fromsa;
1233 server->requests[i].received = 1;
1234 pthread_mutex_unlock(&server->newrq_mutex);
1236 if (!radsign(buf, from->peer.secret)) {
1237 printf("clientrd: failed to sign message\n");
1240 printauth("signedorigauth/buf+4", buf + 4);
1241 printf("clientrd: giving packet back to where it came from\n");
1242 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1246 void *clientwr(void *arg) {
1247 struct server *server = (struct server *)arg;
1249 pthread_t clientrdth;
1252 struct timespec timeout;
1254 memset(&timeout, 0, sizeof(struct timespec));
1256 if (server->peer.type == 'U') {
1257 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
1258 printf("clientwr: connecttoserver failed\n");
1262 tlsconnect(server, NULL, "new client");
1264 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1265 errx("clientwr: pthread_create failed");
1268 pthread_mutex_lock(&server->newrq_mutex);
1269 if (!server->newrq) {
1270 if (timeout.tv_nsec) {
1271 printf("clientwr: waiting up to %ld secs for new request\n", timeout.tv_nsec);
1272 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1273 timeout.tv_nsec = 0;
1275 printf("clientwr: waiting for new request\n");
1276 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1278 if (server->newrq) {
1279 printf("clientwr: got new request\n");
1283 pthread_mutex_unlock(&server->newrq_mutex);
1285 for (i = 0; i < MAX_REQUESTS; i++) {
1286 pthread_mutex_lock(&server->newrq_mutex);
1287 while (!server->requests[i].buf && i < MAX_REQUESTS)
1289 if (i == MAX_REQUESTS) {
1290 pthread_mutex_unlock(&server->newrq_mutex);
1293 rq = server->requests + i;
1296 printf("clientwr: removing received packet from queue\n");
1298 /* setting this to NULL means that it can be reused */
1300 pthread_mutex_unlock(&server->newrq_mutex);
1304 gettimeofday(&now, NULL);
1305 if (now.tv_sec <= rq->expiry.tv_sec) {
1306 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1307 timeout.tv_sec = rq->expiry.tv_sec;
1308 pthread_mutex_unlock(&server->newrq_mutex);
1312 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1313 printf("clientwr: removing expired packet from queue\n");
1315 /* setting this to NULL means that it can be reused */
1317 pthread_mutex_unlock(&server->newrq_mutex);
1320 pthread_mutex_unlock(&server->newrq_mutex);
1322 rq->expiry.tv_sec = now.tv_sec +
1323 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1324 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1325 timeout.tv_sec = rq->expiry.tv_sec;
1327 clientradput(server, server->requests[i].buf);
1331 /* should do more work to maintain TLS connections, keepalives etc */
1334 void *udpserverwr(void *arg) {
1335 struct replyq *replyq = &udp_server_replyq;
1336 struct reply *reply = replyq->replies;
1338 pthread_mutex_lock(&replyq->count_mutex);
1340 while (!replyq->count) {
1341 printf("udp server writer, waiting for signal\n");
1342 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1343 printf("udp server writer, got signal\n");
1345 pthread_mutex_unlock(&replyq->count_mutex);
1347 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1348 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1349 err("sendudp: send failed");
1352 pthread_mutex_lock(&replyq->count_mutex);
1354 memmove(replyq->replies, replyq->replies + 1,
1355 replyq->count * sizeof(struct reply));
1359 void *udpserverrd(void *arg) {
1364 pthread_t udpserverwrth;
1366 if ((udp_server_sock = bindport(SOCK_DGRAM, options.udpserverport)) < 0) {
1367 printf("udpserverrd: socket/bind failed\n");
1370 printf("udpserverrd: listening on UDP port %s\n", options.udpserverport);
1372 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1373 errx("pthread_create failed");
1377 memset(&rq, 0, sizeof(struct request));
1378 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1379 to = radsrv(&rq, buf, fr);
1381 printf("udpserverrd: ignoring request, no place to send it\n");
1384 sendrq(to, fr, &rq);
1388 void *tlsserverwr(void *arg) {
1390 unsigned long error;
1391 struct client *client = (struct client *)arg;
1392 struct replyq *replyq;
1394 printf("tlsserverwr starting for %s\n", client->peer.host);
1395 replyq = client->replyq;
1396 pthread_mutex_lock(&replyq->count_mutex);
1398 while (!replyq->count) {
1399 if (client->peer.ssl) {
1400 printf("tls server writer, waiting for signal\n");
1401 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1402 printf("tls server writer, got signal\n");
1404 if (!client->peer.ssl) {
1405 //ssl might have changed while waiting
1406 pthread_mutex_unlock(&replyq->count_mutex);
1407 printf("tlsserverwr: exiting as requested\n");
1411 pthread_mutex_unlock(&replyq->count_mutex);
1412 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1414 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
1415 cnt, RADLEN(replyq->replies->buf));
1417 while ((error = ERR_get_error()))
1418 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1419 free(replyq->replies->buf);
1421 pthread_mutex_lock(&replyq->count_mutex);
1423 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1427 void *tlsserverrd(void *arg) {
1430 unsigned long error;
1433 struct client *client = (struct client *)arg;
1434 pthread_t tlsserverwrth;
1437 printf("tlsserverrd starting for %s\n", client->peer.host);
1438 ssl = client->peer.ssl;
1440 if (SSL_accept(ssl) <= 0) {
1441 while ((error = ERR_get_error()))
1442 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1443 errx("accept failed, child exiting");
1446 if (tlsverifycert(&client->peer)) {
1447 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
1448 errx("pthread_create failed");
1451 buf = radtlsget(client->peer.ssl);
1454 printf("tlsserverrd: got Radius message from %s\n", client->peer.host);
1455 memset(&rq, 0, sizeof(struct request));
1456 to = radsrv(&rq, buf, client);
1458 printf("ignoring request, no place to send it\n");
1461 sendrq(to, client, &rq);
1463 printf("tlsserverrd: connection lost\n");
1464 // stop writer by setting peer.ssl to NULL and give signal in case waiting for data
1465 client->peer.ssl = NULL;
1466 pthread_mutex_lock(&client->replyq->count_mutex);
1467 pthread_cond_signal(&client->replyq->count_cond);
1468 pthread_mutex_unlock(&client->replyq->count_mutex);
1469 printf("tlsserverrd: waiting for writer to end\n");
1470 pthread_join(tlsserverwrth, NULL);
1472 s = SSL_get_fd(ssl);
1475 printf("tlsserverrd thread for %s exiting\n", client->peer.host);
1476 client->peer.ssl = NULL;
1481 pthread_t tlsserverth;
1483 struct sockaddr_storage from;
1484 size_t fromlen = sizeof(from);
1485 struct client *client;
1487 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
1488 printf("tlslistener: socket/bind failed\n");
1493 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
1496 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1498 errx("accept failed");
1499 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
1501 client = find_client('T', (struct sockaddr *)&from, NULL);
1503 printf("ignoring request, not a known TLS client\n");
1504 shutdown(snew, SHUT_RDWR);
1509 if (client->peer.ssl) {
1510 printf("Ignoring incoming connection, already have one from this client\n");
1511 shutdown(snew, SHUT_RDWR);
1515 client->peer.ssl = SSL_new(ssl_ctx);
1516 SSL_set_fd(client->peer.ssl, snew);
1517 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
1518 errx("pthread_create failed");
1519 pthread_detach(tlsserverth);
1524 char *parsehostport(char *s, struct peer *peer) {
1529 // allow literal addresses and port, e.g. [2001:db8::1]:1812
1533 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1535 printf("no ] matching initial [\n");
1541 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1544 printf("missing host/address\n");
1547 peer->host = stringcopy(field, p - field);
1550 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
1551 printf("unexpected character after ]\n");
1556 /* port number or service name is specified */;
1558 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1560 printf("syntax error, : but no following port\n");
1563 peer->port = stringcopy(field, p - field);
1565 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1569 // * is default, else longest match ... ";" used for separator
1570 char *parserealmlist(char *s, struct server *server) {
1574 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1579 printf("realm list must be specified\n");
1582 server->realmdata = stringcopy(s, l);
1583 server->realms = malloc((1+n) * sizeof(char *));
1584 if (!server->realms)
1585 errx("malloc failed");
1586 server->realms[0] = server->realmdata;
1587 for (n = 1, i = 0; i < l; i++)
1588 if (server->realmdata[i] == ';') {
1589 server->realmdata[i] = '\0';
1590 server->realms[n++] = server->realmdata + i + 1;
1592 server->realms[n] = NULL;
1596 FILE *openconfigfile(const char *filename) {
1598 char pathname[100], *base;
1600 f = fopen(filename, "r");
1602 printf("reading config file %s\n", filename);
1606 if (strlen(filename) + 1 <= sizeof(pathname)) {
1607 // basename() might modify the string
1608 strcpy(pathname, filename);
1609 base = basename(pathname);
1610 f = fopen(base, "r");
1614 err("could not read config file %s nor %s\n", filename, base);
1616 printf("reading config file %s\n", base);
1620 /* exactly one argument must be non-NULL */
1621 void getconfig(const char *serverfile, const char *clientfile) {
1624 char *p, *field, **r;
1625 struct client *client;
1626 struct server *server;
1628 int i, count, *ucount, *tcount;
1630 f = openconfigfile(serverfile ? serverfile : clientfile);
1632 ucount = &server_udp_count;
1633 tcount = &server_tls_count;
1635 ucount = &client_udp_count;
1636 tcount = &client_tls_count;
1638 while (fgets(line, 1024, f)) {
1639 for (p = line; *p == ' ' || *p == '\t'; p++);
1651 printf("type must be U or T, got %c\n", *p);
1657 count = server_count = server_udp_count + server_tls_count;
1658 servers = calloc(count, sizeof(struct server));
1660 errx("malloc failed");
1662 count = client_count = client_udp_count + client_tls_count;
1663 clients = calloc(count, sizeof(struct client));
1665 errx("malloc failed");
1668 if (client_udp_count) {
1669 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1670 if (!udp_server_replyq.replies)
1671 errx("malloc failed");
1672 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1673 udp_server_replyq.count = 0;
1674 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1675 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1679 for (i = 0; i < count && fgets(line, 1024, f);) {
1681 server = &servers[i];
1682 peer = &server->peer;
1684 client = &clients[i];
1685 peer = &client->peer;
1687 for (p = line; *p == ' ' || *p == '\t'; p++);
1688 if (*p == '#' || *p == '\n')
1690 peer->type = *p; // we already know it must be U or T
1691 for (p++; *p == ' ' || *p == '\t'; p++);
1692 p = parsehostport(p, peer);
1693 for (; *p == ' ' || *p == '\t'; p++);
1695 p = parserealmlist(p, server);
1696 for (; *p == ' ' || *p == '\t'; p++);
1699 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1701 /* no secret set and end of line, line is complete if TLS */
1702 if (peer->type == 'U') {
1703 printf("secret must be specified for UDP\n");
1706 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1708 peer->secret = stringcopy(field, p - field);
1709 /* check that rest of line only white space */
1710 for (; *p == ' ' || *p == '\t'; p++);
1711 if (*p && *p != '\n') {
1712 printf("max 4 fields per line, found a 5th\n");
1717 if ((serverfile && !resolvepeer(&server->peer)) ||
1718 (clientfile && !resolvepeer(&client->peer))) {
1719 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1724 pthread_mutex_init(&server->lock, NULL);
1726 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1727 if (!server->requests)
1728 errx("malloc failed");
1730 pthread_mutex_init(&server->newrq_mutex, NULL);
1731 pthread_cond_init(&server->newrq_cond, NULL);
1733 if (peer->type == 'U')
1734 client->replyq = &udp_server_replyq;
1736 client->replyq = malloc(sizeof(struct replyq));
1737 if (!client->replyq)
1738 errx("malloc failed");
1739 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1740 if (!client->replyq->replies)
1741 errx("malloc failed");
1742 client->replyq->size = MAX_REQUESTS;
1743 client->replyq->count = 0;
1744 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1745 pthread_cond_init(&client->replyq->count_cond, NULL);
1748 printf("got type %c, host %s, port %s, secret %s\n", peer->type, peer->host, peer->port, peer->secret);
1750 printf(" with realms:");
1751 for (r = server->realms; *r; r++)
1760 void getmainconfig(const char *configfile) {
1763 char *p, *opt, *endopt, *val, *endval;
1765 f = openconfigfile(configfile);
1766 memset(&options, 0, sizeof(options));
1768 while (fgets(line, 1024, f)) {
1769 for (p = line; *p == ' ' || *p == '\t'; p++);
1770 if (!*p || *p == '#' || *p == '\n')
1773 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1775 for (; *p == ' ' || *p == '\t'; p++);
1776 if (!*p || *p == '\n') {
1778 printf("error in %s, option %s has no value\n", configfile, opt);
1782 for (; *p && *p != '\n'; p++)
1783 if (*p != ' ' && *p != '\t')
1787 printf("getmainconfig: %s = %s\n", opt, val);
1789 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1790 options.tlscacertificatefile = stringcopy(val, 0);
1793 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1794 options.tlscacertificatepath = stringcopy(val, 0);
1797 if (!strcasecmp(opt, "TLSCertificateFile")) {
1798 options.tlscertificatefile = stringcopy(val, 0);
1801 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1802 options.tlscertificatekeyfile = stringcopy(val, 0);
1805 if (!strcasecmp(opt, "UDPServerPort")) {
1806 options.udpserverport = stringcopy(val, 0);
1810 printf("error in %s, unknown option %s\n", configfile, opt);
1815 if (!options.udpserverport)
1816 options.udpserverport = stringcopy(DEFAULT_UDP_PORT, 0);
1820 void parseargs(int argc, char **argv) {
1823 while ((c = getopt(argc, argv, "p:")) != -1) {
1826 udp_server_port = optarg;
1836 printf("radsecproxy [ -p UDP-port ]\n");
1841 int main(int argc, char **argv) {
1842 pthread_t udpserverth;
1843 // pthread_attr_t joinable;
1846 // parseargs(argc, argv);
1847 getmainconfig(CONFIG_MAIN);
1848 getconfig(CONFIG_SERVERS, NULL);
1849 getconfig(NULL, CONFIG_CLIENTS);
1851 // pthread_attr_init(&joinable);
1852 // pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1854 if (client_udp_count)
1855 if (pthread_create(&udpserverth, NULL /*&joinable*/, udpserverrd, NULL))
1856 errx("pthread_create failed");
1858 if (client_tls_count || server_tls_count)
1859 ssl_ctx = ssl_init();
1861 for (i = 0; i < server_count; i++)
1862 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1863 errx("pthread_create failed");
1865 if (client_tls_count)
1866 return tlslistener();
1868 /* just hang around doing nothing, anything to do here? */