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 * make our server ignore client retrans and do its own instead?
12 * radius keep alives (server status)
13 * tls certificate validation, see below urls
14 * clean tls shutdown, see http://www.linuxjournal.com/article/4822
15 * and http://www.linuxjournal.com/article/5487
16 * SSL_shutdown() and shutdown()
17 * If shutdown() we may not need REUSEADDR
18 * when tls client goes away, ensure that all related threads and state
20 * setsockopt(keepalive...), check if openssl has some keepalive feature
23 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
24 * rd is responsible for init and launching wr
25 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
26 * each tlsserverrd launches tlsserverwr
27 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
28 * for init and launching rd
30 * serverrd will receive a request, processes it and puts it in the requestq of
31 * the appropriate clientwr
32 * clientwr monitors its requestq and sends requests
33 * clientrd looks for responses, processes them and puts them in the replyq of
34 * the peer the request came from
35 * serverwr monitors its reply and sends replies
37 * In addition to the main thread, we have:
38 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
39 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
40 * For each TLS peer connecting to us there will be 2 more TLS threads
41 * This is only for connected peers
42 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
43 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
50 #include <openssl/ssl.h>
51 #include <openssl/rand.h>
52 #include <openssl/err.h>
53 #include <openssl/md5.h>
54 #include <openssl/hmac.h>
55 #include "radsecproxy.h"
57 static struct options options;
58 static struct client clients[MAX_PEERS];
59 static struct server servers[MAX_PEERS];
61 static int client_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_cl = NULL;
69 static SSL_CTX *ssl_ctx_srv = NULL;
73 /* callbacks for making OpenSSL thread safe */
74 unsigned long ssl_thread_id() {
75 return (unsigned long)pthread_self();
78 void ssl_locking_callback(int mode, int type, const char *file, int line) {
79 if (mode & CRYPTO_LOCK) {
80 pthread_mutex_lock(&ssl_locks[type]);
81 ssl_lock_count[type]++;
83 pthread_mutex_unlock(&ssl_locks[type]);
86 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
91 err_cert = X509_STORE_CTX_get_current_cert(ctx);
92 err = X509_STORE_CTX_get_error(ctx);
93 depth = X509_STORE_CTX_get_error_depth(ctx);
95 if (depth > MAX_CERT_DEPTH) {
97 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
98 X509_STORE_CTX_set_error(ctx, err);
102 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
103 printf("verify error: num=%d:%s:depth=%d:%s\n", err, X509_verify_cert_error_string(err), depth, buf);
106 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
107 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
108 printf("issuer=%s\n", buf);
110 case X509_V_ERR_CERT_NOT_YET_VALID:
111 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
112 printf("Certificate not yet valid\n");
114 case X509_V_ERR_CERT_HAS_EXPIRED:
115 printf("Certificate has expired\n");
117 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
118 printf("Certificate no longer valid (after notAfter)\n");
122 printf("certificate verify returns %d\n", ok);
126 void ssl_init(SSL_CTX **ctx_srv, SSL_CTX **ctx_cl) {
129 STACK_OF(X509_NAME) *calist;
131 if (!options.tlscertificatefile || !options.tlscertificatekeyfile) {
132 printf("TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS\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));
157 *ctx_srv = SSL_CTX_new(TLSv1_server_method());
158 if (!SSL_CTX_use_certificate_chain_file(*ctx_srv, options.tlscertificatefile) ||
159 !SSL_CTX_use_PrivateKey_file(*ctx_srv, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
160 !SSL_CTX_check_private_key(*ctx_srv))
164 calist = (options.tlscacertificatefile
165 ? SSL_load_client_CA_file(options.tlscacertificatefile)
166 : sk_X509_NAME_new_null());
167 if (!calist || (options.tlscacertificatepath &&
168 !SSL_add_dir_cert_subjects_to_stack(calist, options.tlscacertificatepath)))
170 SSL_CTX_set_client_CA_list(*ctx_srv, calist);
172 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
173 printf("CA Certificate file/path need to be configured\n");
176 if (!SSL_CTX_load_verify_locations(*ctx_srv, options.tlscacertificatefile, options.tlscacertificatepath))
178 SSL_CTX_set_verify(*ctx_srv, SSL_VERIFY_PEER, verify_cb);
179 SSL_CTX_set_verify_depth(*ctx_srv, MAX_CERT_DEPTH + 1);
183 *ctx_cl = SSL_CTX_new(TLSv1_client_method());
184 if (!SSL_CTX_use_certificate_chain_file(*ctx_cl, options.tlscertificatefile) ||
185 !SSL_CTX_use_PrivateKey_file(*ctx_cl, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
186 !SSL_CTX_check_private_key(*ctx_cl))
188 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
189 printf("CA Certificate file/path need to be configured\n");
192 if (!SSL_CTX_load_verify_locations(*ctx_cl, options.tlscacertificatefile, options.tlscacertificatepath))
194 SSL_CTX_set_verify(*ctx_cl, SSL_VERIFY_PEER, verify_cb);
195 SSL_CTX_set_verify_depth(*ctx_cl, MAX_CERT_DEPTH + 1);
199 *ctx_srv = SSL_CTX_new(TLSv1_server_method());
200 if (!SSL_CTX_use_certificate_chain_file(*ctx_srv, options.tlscertificatefile) ||
201 !SSL_CTX_use_PrivateKey_file(*ctx_srv, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
202 !SSL_CTX_check_private_key(*ctx_srv))
205 calist = (SSL_load_client_CA_file(options.tlscacertificatefile));
206 SSL_CTX_set_client_CA_list(*ctx_srv, calist);
208 if (!SSL_CTX_load_verify_locations(*ctx_srv, options.tlscacertificatefile, NULL/*options.tlscacertificatepath*/))
211 SSL_CTX_set_verify(*ctx_srv, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
212 SSL_CTX_set_verify_depth(*ctx_srv, MAX_CERT_DEPTH + 1);
215 *ctx_cl = SSL_CTX_new(TLSv1_client_method());
216 if (!SSL_CTX_use_certificate_chain_file(*ctx_cl, options.tlscertificatefile) ||
217 !SSL_CTX_use_PrivateKey_file(*ctx_cl, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
218 !SSL_CTX_check_private_key(*ctx_cl))
220 if (!SSL_CTX_load_verify_locations(*ctx_cl,options.tlscacertificatefile, NULL/*options.tlscacertificatepath*/))
223 SSL_CTX_set_verify(*ctx_cl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
224 SSL_CTX_set_verify_depth(*ctx_cl, MAX_CERT_DEPTH + 1);
226 calist = (SSL_load_client_CA_file(options.tlscacertificatefile));
227 SSL_CTX_set_client_CA_list(*ctx_cl, calist);
234 while ((error = ERR_get_error()))
235 err("SSL: %s", ERR_error_string(error, NULL));
239 void printauth(char *s, unsigned char *t) {
242 for (i = 0; i < 16; i++)
243 printf("%02x ", t[i]);
247 int resolvepeer(struct peer *peer) {
248 struct addrinfo hints, *addrinfo;
250 memset(&hints, 0, sizeof(hints));
251 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
252 hints.ai_family = AF_UNSPEC;
253 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
254 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
259 freeaddrinfo(peer->addrinfo);
260 peer->addrinfo = addrinfo;
264 int connecttoserver(struct addrinfo *addrinfo) {
266 struct addrinfo *res;
268 for (res = addrinfo; res; res = res->ai_next) {
269 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
271 err("connecttoserver: socket failed");
274 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
276 err("connecttoserver: connect failed");
283 /* returns the client with matching address, or NULL */
284 /* if client argument is not NULL, we only check that one client */
285 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
286 struct sockaddr_in6 *sa6;
287 struct in_addr *a4 = NULL;
290 struct addrinfo *res;
292 if (addr->sa_family == AF_INET6) {
293 sa6 = (struct sockaddr_in6 *)addr;
294 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
295 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
297 a4 = &((struct sockaddr_in *)addr)->sin_addr;
299 c = (client ? client : clients);
300 for (i = 0; i < client_count; i++) {
301 if (c->peer.type == type)
302 for (res = c->peer.addrinfo; res; res = res->ai_next)
303 if ((a4 && res->ai_family == AF_INET &&
304 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
305 (res->ai_family == AF_INET6 &&
306 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
315 /* returns the server with matching address, or NULL */
316 /* if server argument is not NULL, we only check that one server */
317 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
318 struct sockaddr_in6 *sa6;
319 struct in_addr *a4 = NULL;
322 struct addrinfo *res;
324 if (addr->sa_family == AF_INET6) {
325 sa6 = (struct sockaddr_in6 *)addr;
326 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
327 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
329 a4 = &((struct sockaddr_in *)addr)->sin_addr;
331 s = (server ? server : servers);
332 for (i = 0; i < server_count; i++) {
333 if (s->peer.type == type)
334 for (res = s->peer.addrinfo; res; res = res->ai_next)
335 if ((a4 && res->ai_family == AF_INET &&
336 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
337 (res->ai_family == AF_INET6 &&
338 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
347 /* exactly one of client and server must be non-NULL */
348 /* if *peer == NULL we return who we received from, else require it to be from peer */
349 /* return from in sa if not NULL */
350 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
353 unsigned char buf[65536], *rad;
354 struct sockaddr_storage from;
355 socklen_t fromlen = sizeof(from);
358 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
360 err("radudpget: recv failed");
363 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
366 printf("radudpget: packet too small\n");
373 printf("radudpget: packet smaller than length field in radius header\n");
377 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
380 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
381 : (void *)find_server('U', (struct sockaddr *)&from, *server));
383 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
390 err("radudpget: malloc failed");
392 memcpy(rad, buf, len);
394 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
396 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
402 int tlsverifycert(struct peer *peer) {
411 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
412 printf("tlsverifycert: basic validation failed\n");
413 while ((error = ERR_get_error()))
414 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
418 cert = SSL_get_peer_certificate(peer->ssl);
420 printf("tlsverifycert: failed to obtain certificate\n");
423 nm = X509_get_subject_name(cert);
426 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
429 e = X509_NAME_get_entry(nm, loc);
430 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
434 for (i = 0; i < l; i++)
437 if (l == strlen(peer->host) && !strncasecmp(peer->host, v, l)) {
438 printf("tlsverifycert: Found cn matching host %s, All OK\n", peer->host);
441 printf("tlsverifycert: cn not matching host %s\n", peer->host);
447 void tlsconnect(struct server *server, struct timeval *when, char *text) {
451 printf("tlsconnect called from %s\n", text);
452 pthread_mutex_lock(&server->lock);
453 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
454 /* already reconnected, nothing to do */
455 printf("tlsconnect(%s): seems already reconnected\n", text);
456 pthread_mutex_unlock(&server->lock);
460 printf("tlsconnect %s\n", text);
463 gettimeofday(&now, NULL);
464 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
465 if (server->connectionok) {
466 server->connectionok = 0;
468 } else if (elapsed < 5)
470 else if (elapsed < 600)
472 else if (elapsed < 10000)
475 server->lastconnecttry.tv_sec = now.tv_sec; // no sleep at startup
476 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->peer.host, server->peer.port);
477 if (server->sock >= 0)
479 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
481 SSL_free(server->peer.ssl);
482 server->peer.ssl = SSL_new(ssl_ctx_cl);
483 SSL_set_fd(server->peer.ssl, server->sock);
484 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
487 printf("tlsconnect: TLS connection to %s port %s up\n", server->peer.host, server->peer.port);
488 gettimeofday(&server->lastconnecttry, NULL);
489 pthread_mutex_unlock(&server->lock);
492 unsigned char *radtlsget(SSL *ssl) {
494 unsigned char buf[4], *rad;
497 for (total = 0; total < 4; total += cnt) {
498 cnt = SSL_read(ssl, buf + total, 4 - total);
500 printf("radtlsget: connection lost\n");
501 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
502 //remote end sent close_notify, send one back
512 err("radtlsget: malloc failed");
517 for (; total < len; total += cnt) {
518 cnt = SSL_read(ssl, rad + total, len - total);
520 printf("radtlsget: connection lost\n");
521 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
522 //remote end sent close_notify, send one back
534 printf("radtlsget: packet smaller than minimum radius size\n");
537 printf("radtlsget: got %d bytes\n", total);
541 int clientradput(struct server *server, unsigned char *rad) {
545 struct timeval lastconnecttry;
548 if (server->peer.type == 'U') {
549 if (send(server->sock, rad, len, 0) >= 0) {
550 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->peer.host, server->peer.port);
553 err("clientradput: send failed");
557 lastconnecttry = server->lastconnecttry;
558 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
559 while ((error = ERR_get_error()))
560 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
561 tlsconnect(server, &lastconnecttry, "clientradput");
562 lastconnecttry = server->lastconnecttry;
565 server->connectionok = 1;
566 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
567 cnt, len, server->peer.host);
571 int radsign(unsigned char *rad, unsigned char *sec) {
572 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
573 static unsigned char first = 1;
574 static EVP_MD_CTX mdctx;
578 pthread_mutex_lock(&lock);
580 EVP_MD_CTX_init(&mdctx);
584 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
585 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
586 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
587 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
589 pthread_mutex_unlock(&lock);
593 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
594 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
595 static unsigned char first = 1;
596 static EVP_MD_CTX mdctx;
597 unsigned char hash[EVP_MAX_MD_SIZE];
601 pthread_mutex_lock(&lock);
603 EVP_MD_CTX_init(&mdctx);
609 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
610 EVP_DigestUpdate(&mdctx, rad, 4) &&
611 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
612 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
613 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
614 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
616 !memcmp(hash, rad + 4, 16));
617 pthread_mutex_unlock(&lock);
621 int checkmessageauth(char *rad, uint8_t *authattr, char *secret) {
622 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
623 static unsigned char first = 1;
624 static HMAC_CTX hmacctx;
626 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
628 pthread_mutex_lock(&lock);
630 HMAC_CTX_init(&hmacctx);
634 memcpy(auth, authattr, 16);
635 memset(authattr, 0, 16);
637 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
638 HMAC_Update(&hmacctx, rad, RADLEN(rad));
639 HMAC_Final(&hmacctx, hash, &md_len);
640 memcpy(authattr, auth, 16);
642 printf("message auth computation failed\n");
643 pthread_mutex_unlock(&lock);
647 if (memcmp(auth, hash, 16)) {
648 printf("message authenticator, wrong value\n");
649 pthread_mutex_unlock(&lock);
653 pthread_mutex_unlock(&lock);
657 int createmessageauth(char *rad, char *authattrval, char *secret) {
658 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
659 static unsigned char first = 1;
660 static HMAC_CTX hmacctx;
666 pthread_mutex_lock(&lock);
668 HMAC_CTX_init(&hmacctx);
672 memset(authattrval, 0, 16);
674 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
675 HMAC_Update(&hmacctx, rad, RADLEN(rad));
676 HMAC_Final(&hmacctx, authattrval, &md_len);
678 printf("message auth computation failed\n");
679 pthread_mutex_unlock(&lock);
683 pthread_mutex_unlock(&lock);
687 void sendrq(struct server *to, struct client *from, struct request *rq) {
690 pthread_mutex_lock(&to->newrq_mutex);
691 /* might simplify if only try nextid, might be ok */
692 for (i = to->nextid; i < MAX_REQUESTS; i++)
693 if (!to->requests[i].buf)
695 if (i == MAX_REQUESTS) {
696 for (i = 0; i < to->nextid; i++)
697 if (!to->requests[i].buf)
699 if (i == to->nextid) {
700 printf("No room in queue, dropping request\n");
701 pthread_mutex_unlock(&to->newrq_mutex);
707 rq->buf[1] = (char)i;
708 printf("sendrq: inserting packet with id %d in queue for %s\n", i, to->peer.host);
710 if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
713 gettimeofday(&rq->expiry, NULL);
714 rq->expiry.tv_sec += 30;
715 to->requests[i] = *rq;
719 printf("signalling client writer\n");
720 pthread_cond_signal(&to->newrq_cond);
722 pthread_mutex_unlock(&to->newrq_mutex);
725 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
726 struct replyq *replyq = to->replyq;
728 pthread_mutex_lock(&replyq->count_mutex);
729 if (replyq->count == replyq->size) {
730 printf("No room in queue, dropping request\n");
731 pthread_mutex_unlock(&replyq->count_mutex);
735 replyq->replies[replyq->count].buf = buf;
737 replyq->replies[replyq->count].tosa = *tosa;
740 if (replyq->count == 1) {
741 printf("signalling client writer\n");
742 pthread_cond_signal(&replyq->count_cond);
744 pthread_mutex_unlock(&replyq->count_mutex);
747 int pwdencrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
748 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
749 static unsigned char first = 1;
750 static EVP_MD_CTX mdctx;
751 unsigned char hash[EVP_MAX_MD_SIZE], *input;
753 uint8_t i, offset = 0, out[128];
755 pthread_mutex_lock(&lock);
757 EVP_MD_CTX_init(&mdctx);
763 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
764 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
765 !EVP_DigestUpdate(&mdctx, input, 16) ||
766 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
768 pthread_mutex_unlock(&lock);
771 for (i = 0; i < 16; i++)
772 out[offset + i] = hash[i] ^ in[offset + i];
773 input = out + offset - 16;
778 memcpy(in, out, len);
779 pthread_mutex_unlock(&lock);
783 int pwddecrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
784 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
785 static unsigned char first = 1;
786 static EVP_MD_CTX mdctx;
787 unsigned char hash[EVP_MAX_MD_SIZE], *input;
789 uint8_t i, offset = 0, out[128];
791 pthread_mutex_lock(&lock);
793 EVP_MD_CTX_init(&mdctx);
799 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
800 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
801 !EVP_DigestUpdate(&mdctx, input, 16) ||
802 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
804 pthread_mutex_unlock(&lock);
807 for (i = 0; i < 16; i++)
808 out[offset + i] = hash[i] ^ in[offset + i];
814 memcpy(in, out, len);
815 pthread_mutex_unlock(&lock);
819 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
820 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
821 static unsigned char first = 1;
822 static EVP_MD_CTX mdctx;
823 unsigned char hash[EVP_MAX_MD_SIZE];
827 pthread_mutex_lock(&lock);
829 EVP_MD_CTX_init(&mdctx);
834 printf("msppencrypt auth in: ");
835 for (i = 0; i < 16; i++)
836 printf("%02x ", auth[i]);
839 printf("msppencrypt salt in: ");
840 for (i = 0; i < 2; i++)
841 printf("%02x ", salt[i]);
844 printf("msppencrypt in: ");
845 for (i = 0; i < len; i++)
846 printf("%02x ", text[i]);
850 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
851 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
852 !EVP_DigestUpdate(&mdctx, auth, 16) ||
853 !EVP_DigestUpdate(&mdctx, salt, 2) ||
854 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
855 pthread_mutex_unlock(&lock);
860 printf("msppencrypt hash: ");
861 for (i = 0; i < 16; i++)
862 printf("%02x ", hash[i]);
866 for (i = 0; i < 16; i++)
869 for (offset = 16; offset < len; offset += 16) {
871 printf("text + offset - 16 c(%d): ", offset / 16);
872 for (i = 0; i < 16; i++)
873 printf("%02x ", (text + offset - 16)[i]);
876 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
877 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
878 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
879 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
881 pthread_mutex_unlock(&lock);
885 printf("msppencrypt hash: ");
886 for (i = 0; i < 16; i++)
887 printf("%02x ", hash[i]);
891 for (i = 0; i < 16; i++)
892 text[offset + i] ^= hash[i];
896 printf("msppencrypt out: ");
897 for (i = 0; i < len; i++)
898 printf("%02x ", text[i]);
902 pthread_mutex_unlock(&lock);
906 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
907 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
908 static unsigned char first = 1;
909 static EVP_MD_CTX mdctx;
910 unsigned char hash[EVP_MAX_MD_SIZE];
915 pthread_mutex_lock(&lock);
917 EVP_MD_CTX_init(&mdctx);
922 printf("msppdecrypt auth in: ");
923 for (i = 0; i < 16; i++)
924 printf("%02x ", auth[i]);
927 printf("msppedecrypt salt in: ");
928 for (i = 0; i < 2; i++)
929 printf("%02x ", salt[i]);
932 printf("msppedecrypt in: ");
933 for (i = 0; i < len; i++)
934 printf("%02x ", text[i]);
938 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
939 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
940 !EVP_DigestUpdate(&mdctx, auth, 16) ||
941 !EVP_DigestUpdate(&mdctx, salt, 2) ||
942 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
943 pthread_mutex_unlock(&lock);
948 printf("msppedecrypt hash: ");
949 for (i = 0; i < 16; i++)
950 printf("%02x ", hash[i]);
954 for (i = 0; i < 16; i++)
955 plain[i] = text[i] ^ hash[i];
957 for (offset = 16; offset < len; offset += 16) {
959 printf("text + offset - 16 c(%d): ", offset / 16);
960 for (i = 0; i < 16; i++)
961 printf("%02x ", (text + offset - 16)[i]);
964 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
965 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
966 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
967 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
969 pthread_mutex_unlock(&lock);
973 printf("msppedecrypt hash: ");
974 for (i = 0; i < 16; i++)
975 printf("%02x ", hash[i]);
979 for (i = 0; i < 16; i++)
980 plain[offset + i] = text[offset + i] ^ hash[i];
983 memcpy(text, plain, len);
985 printf("msppedecrypt out: ");
986 for (i = 0; i < len; i++)
987 printf("%02x ", text[i]);
991 pthread_mutex_unlock(&lock);
995 struct server *id2server(char *id, uint8_t len) {
997 char **realm, *idrealm;
999 idrealm = strchr(id, '@');
1002 len -= idrealm - id;
1007 for (i = 0; i < server_count; i++) {
1008 for (realm = servers[i].realms; *realm; realm++) {
1009 if ((strlen(*realm) == 1 && **realm == '*') ||
1010 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
1011 printf("found matching realm: %s, host %s\n", *realm, servers[i].peer.host);
1019 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
1020 uint8_t code, id, *auth, *attr, attrvallen;
1021 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
1026 unsigned char newauth[16];
1028 code = *(uint8_t *)buf;
1029 id = *(uint8_t *)(buf + 1);
1031 auth = (uint8_t *)(buf + 4);
1033 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
1035 if (code != RAD_Access_Request) {
1036 printf("radsrv: server currently accepts only access-requests, ignoring\n");
1044 left -= attr[RAD_Attr_Length];
1046 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
1049 switch (attr[RAD_Attr_Type]) {
1050 case RAD_Attr_User_Name:
1051 usernameattr = attr;
1053 case RAD_Attr_User_Password:
1056 case RAD_Attr_Tunnel_Password:
1057 tunnelpwdattr = attr;
1059 case RAD_Attr_Message_Authenticator:
1060 messageauthattr = attr;
1063 attr += attr[RAD_Attr_Length];
1066 printf("radsrv: malformed packet? remaining byte after last attribute\n");
1069 printf("radsrv: Username: ");
1070 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
1071 printf("%c", usernameattr[RAD_Attr_Value + i]);
1075 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1077 printf("radsrv: ignoring request, don't know where to send it\n");
1081 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1082 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1083 printf("radsrv: message authentication failed\n");
1087 if (!RAND_bytes(newauth, 16)) {
1088 printf("radsrv: failed to generate random auth\n");
1092 printauth("auth", auth);
1093 printauth("newauth", newauth);
1096 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
1097 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1098 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1099 printf("radsrv: invalid user password length\n");
1103 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1104 printf("radsrv: cannot decrypt password\n");
1107 printf("radsrv: password: ");
1108 for (i = 0; i < attrvallen; i++)
1109 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1111 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1112 printf("radsrv: cannot encrypt password\n");
1117 if (tunnelpwdattr) {
1118 printf("radsrv: found tunnelpwdattr of length %d\n", tunnelpwdattr[RAD_Attr_Length]);
1119 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1120 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1121 printf("radsrv: invalid user password length\n");
1125 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1126 printf("radsrv: cannot decrypt password\n");
1129 printf("radsrv: password: ");
1130 for (i = 0; i < attrvallen; i++)
1131 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1133 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1134 printf("radsrv: cannot encrypt password\n");
1142 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1143 memcpy(rq->origauth, auth, 16);
1144 memcpy(auth, newauth, 16);
1145 printauth("rq->origauth", rq->origauth);
1146 printauth("auth", auth);
1150 void *clientrd(void *arg) {
1151 struct server *server = (struct server *)arg;
1152 struct client *from;
1153 int i, left, subleft;
1154 unsigned char *buf, *messageauthattr, *subattr, *attr;
1155 struct sockaddr_storage fromsa;
1156 struct timeval lastconnecttry;
1161 lastconnecttry = server->lastconnecttry;
1162 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1163 if (!buf && server->peer.type == 'T') {
1164 tlsconnect(server, &lastconnecttry, "clientrd");
1168 server->connectionok = 1;
1170 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge) {
1171 printf("clientrd: discarding, only accept access accept, access reject and access challenge messages\n");
1175 i = buf[1]; /* i is the id */
1177 pthread_mutex_lock(&server->newrq_mutex);
1178 if (!server->requests[i].buf || !server->requests[i].tries) {
1179 pthread_mutex_unlock(&server->newrq_mutex);
1180 printf("clientrd: no matching request sent with this id, ignoring\n");
1184 if (server->requests[i].received) {
1185 pthread_mutex_unlock(&server->newrq_mutex);
1186 printf("clientrd: already received, ignoring\n");
1190 if (!validauth(buf, server->requests[i].buf + 4, server->peer.secret)) {
1191 pthread_mutex_unlock(&server->newrq_mutex);
1192 printf("clientrd: invalid auth, ignoring\n");
1196 from = server->requests[i].from;
1199 /* messageauthattr present? */
1200 messageauthattr = NULL;
1201 left = RADLEN(buf) - 20;
1204 left -= attr[RAD_Attr_Length];
1206 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1209 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1210 if (attr[RAD_Attr_Length] != 18) {
1211 printf("clientrd: illegal message auth attribute length, ignoring packet\n");
1214 memcpy(tmp, buf + 4, 16);
1215 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1216 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1217 printf("clientrd: message authentication failed\n");
1220 memcpy(buf + 4, tmp, 16);
1221 printf("clientrd: message auth ok\n");
1222 messageauthattr = attr;
1225 attr += attr[RAD_Attr_Length];
1228 /* handle MS MPPE */
1229 left = RADLEN(buf) - 20;
1232 left -= attr[RAD_Attr_Length];
1234 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1237 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1238 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { // 311 == MS
1239 subleft = attr[RAD_Attr_Length] - 6;
1241 while (subleft > 1) {
1242 subleft -= subattr[RAD_Attr_Length];
1245 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1246 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1248 printf("clientrd: Got MS MPPE\n");
1249 if (subattr[RAD_Attr_Length] < 20)
1252 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1253 server->peer.secret, strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1254 printf("clientrd: failed to decrypt msppe key\n");
1258 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1259 from->peer.secret, strlen(from->peer.secret), server->requests[i].origauth, subattr + 2)) {
1260 printf("clientrd: failed to encrypt msppe key\n");
1265 printf("clientrd: bad vendor specific attr or subattr length, ignoring packet\n");
1269 attr += attr[RAD_Attr_Length];
1272 /* once we set received = 1, requests[i] may be reused */
1273 buf[1] = (char)server->requests[i].origid;
1274 memcpy(buf + 4, server->requests[i].origauth, 16);
1275 printauth("origauth/buf+4", buf + 4);
1276 if (messageauthattr) {
1277 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1279 printf("clientrd: computed messageauthattr\n");
1282 if (from->peer.type == 'U')
1283 fromsa = server->requests[i].fromsa;
1284 server->requests[i].received = 1;
1285 pthread_mutex_unlock(&server->newrq_mutex);
1287 if (!radsign(buf, from->peer.secret)) {
1288 printf("clientrd: failed to sign message\n");
1291 printauth("signedorigauth/buf+4", buf + 4);
1292 printf("clientrd: giving packet back to where it came from\n");
1293 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1297 void *clientwr(void *arg) {
1298 struct server *server = (struct server *)arg;
1300 pthread_t clientrdth;
1304 if (server->peer.type == 'U') {
1305 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
1306 printf("clientwr: connecttoserver failed\n");
1310 tlsconnect(server, NULL, "new client");
1312 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1313 errx("clientwr: pthread_create failed");
1316 pthread_mutex_lock(&server->newrq_mutex);
1317 while (!server->newrq) {
1318 printf("clientwr: waiting for signal\n");
1319 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1320 printf("clientwr: got signal\n");
1323 pthread_mutex_unlock(&server->newrq_mutex);
1325 for (i = 0; i < MAX_REQUESTS; i++) {
1326 pthread_mutex_lock(&server->newrq_mutex);
1327 while (!server->requests[i].buf && i < MAX_REQUESTS)
1329 if (i == MAX_REQUESTS) {
1330 pthread_mutex_unlock(&server->newrq_mutex);
1334 gettimeofday(&now, NULL);
1335 rq = server->requests + i;
1338 printf("clientwr: removing received packet from queue\n");
1340 /* setting this to NULL means that it can be reused */
1342 pthread_mutex_unlock(&server->newrq_mutex);
1345 if (now.tv_sec > rq->expiry.tv_sec) {
1346 printf("clientwr: removing expired packet from queue\n");
1348 /* setting this to NULL means that it can be reused */
1350 pthread_mutex_unlock(&server->newrq_mutex);
1355 continue; // not re-sending (yet)
1358 pthread_mutex_unlock(&server->newrq_mutex);
1360 clientradput(server, server->requests[i].buf);
1363 /* should do more work to maintain TLS connections, keepalives etc */
1366 void *udpserverwr(void *arg) {
1367 struct replyq *replyq = &udp_server_replyq;
1368 struct reply *reply = replyq->replies;
1370 pthread_mutex_lock(&replyq->count_mutex);
1372 while (!replyq->count) {
1373 printf("udp server writer, waiting for signal\n");
1374 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1375 printf("udp server writer, got signal\n");
1377 pthread_mutex_unlock(&replyq->count_mutex);
1379 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1380 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1381 err("sendudp: send failed");
1384 pthread_mutex_lock(&replyq->count_mutex);
1386 memmove(replyq->replies, replyq->replies + 1,
1387 replyq->count * sizeof(struct reply));
1391 void *udpserverrd(void *arg) {
1396 pthread_t udpserverwrth;
1398 if ((udp_server_sock = bindport(SOCK_DGRAM, options.udpserverport)) < 0) {
1399 printf("udpserverrd: socket/bind failed\n");
1402 printf("udpserverrd: listening on UDP port %s\n", options.udpserverport);
1404 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1405 errx("pthread_create failed");
1409 memset(&rq, 0, sizeof(struct request));
1410 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1411 to = radsrv(&rq, buf, fr);
1413 printf("udpserverrd: ignoring request, no place to send it\n");
1416 sendrq(to, fr, &rq);
1420 void *tlsserverwr(void *arg) {
1422 unsigned long error;
1423 struct client *client = (struct client *)arg;
1424 struct replyq *replyq;
1426 printf("tlsserverwr starting for %s\n", client->peer.host);
1427 replyq = client->replyq;
1428 pthread_mutex_lock(&replyq->count_mutex);
1430 while (!replyq->count) {
1431 if (client->peer.ssl) {
1432 printf("tls server writer, waiting for signal\n");
1433 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1434 printf("tls server writer, got signal\n");
1436 if (!client->peer.ssl) {
1437 //ssl might have changed while waiting
1438 pthread_mutex_unlock(&replyq->count_mutex);
1439 printf("tlsserverwr: exiting as requested\n");
1443 pthread_mutex_unlock(&replyq->count_mutex);
1444 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1446 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
1447 cnt, RADLEN(replyq->replies->buf));
1449 while ((error = ERR_get_error()))
1450 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1451 free(replyq->replies->buf);
1453 pthread_mutex_lock(&replyq->count_mutex);
1455 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1459 void *tlsserverrd(void *arg) {
1462 unsigned long error;
1465 struct client *client = (struct client *)arg;
1466 pthread_t tlsserverwrth;
1469 printf("tlsserverrd starting for %s\n", client->peer.host);
1470 ssl = client->peer.ssl;
1472 if (SSL_accept(ssl) <= 0) {
1473 while ((error = ERR_get_error()))
1474 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1475 errx("accept failed, child exiting");
1478 if (1 /*tlsverifycert(&client->peer)*/) {
1479 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
1480 errx("pthread_create failed");
1483 buf = radtlsget(client->peer.ssl);
1486 printf("tlsserverrd: got Radius message from %s\n", client->peer.host);
1487 memset(&rq, 0, sizeof(struct request));
1488 to = radsrv(&rq, buf, client);
1490 printf("ignoring request, no place to send it\n");
1493 sendrq(to, client, &rq);
1495 printf("tlsserverrd: connection lost\n");
1496 // stop writer by setting peer.ssl to NULL and give signal in case waiting for data
1497 client->peer.ssl = NULL;
1498 pthread_mutex_lock(&client->replyq->count_mutex);
1499 pthread_cond_signal(&client->replyq->count_cond);
1500 pthread_mutex_unlock(&client->replyq->count_mutex);
1501 printf("tlsserverrd: waiting for writer to end\n");
1502 pthread_join(tlsserverwrth, NULL);
1504 s = SSL_get_fd(ssl);
1507 printf("tlsserverrd thread for %s exiting\n", client->peer.host);
1512 pthread_t tlsserverth;
1514 struct sockaddr_storage from;
1515 size_t fromlen = sizeof(from);
1516 struct client *client;
1518 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
1519 printf("tlslistener: socket/bind failed\n");
1524 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
1527 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1529 errx("accept failed");
1530 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
1532 client = find_client('T', (struct sockaddr *)&from, NULL);
1534 printf("ignoring request, not a known TLS client\n");
1535 shutdown(snew, SHUT_RDWR);
1540 if (client->peer.ssl) {
1541 printf("Ignoring incoming connection, already have one from this client\n");
1542 shutdown(snew, SHUT_RDWR);
1546 client->peer.ssl = SSL_new(ssl_ctx_srv);
1547 SSL_set_fd(client->peer.ssl, snew);
1548 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
1549 errx("pthread_create failed");
1550 pthread_detach(tlsserverth);
1555 char *parsehostport(char *s, struct peer *peer) {
1560 // allow literal addresses and port, e.g. [2001:db8::1]:1812
1564 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1566 printf("no ] matching initial [\n");
1572 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1575 printf("missing host/address\n");
1578 peer->host = stringcopy(field, p - field);
1581 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
1582 printf("unexpected character after ]\n");
1587 /* port number or service name is specified */;
1589 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1591 printf("syntax error, : but no following port\n");
1594 peer->port = stringcopy(field, p - field);
1596 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1600 // * is default, else longest match ... ";" used for separator
1601 char *parserealmlist(char *s, struct server *server) {
1605 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1610 printf("realm list must be specified\n");
1613 server->realmdata = stringcopy(s, l);
1614 server->realms = malloc((1+n) * sizeof(char *));
1615 if (!server->realms)
1616 errx("malloc failed");
1617 server->realms[0] = server->realmdata;
1618 for (n = 1, i = 0; i < l; i++)
1619 if (server->realmdata[i] == ';') {
1620 server->realmdata[i] = '\0';
1621 server->realms[n++] = server->realmdata + i + 1;
1623 server->realms[n] = NULL;
1627 /* exactly one argument must be non-NULL */
1628 void getconfig(const char *serverfile, const char *clientfile) {
1631 char *p, *field, **r;
1632 struct client *client;
1633 struct server *server;
1638 printf("opening file %s for reading\n", serverfile);
1639 f = fopen(serverfile, "r");
1641 errx("getconfig failed to open %s for reading", serverfile);
1642 count = &server_count;
1644 printf("opening file %s for reading\n", clientfile);
1645 f = fopen(clientfile, "r");
1647 errx("getconfig failed to open %s for reading", clientfile);
1648 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
1649 if (!udp_server_replyq.replies)
1650 errx("malloc failed");
1651 udp_server_replyq.size = 4 * MAX_REQUESTS;
1652 udp_server_replyq.count = 0;
1653 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1654 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1655 count = &client_count;
1659 while (fgets(line, 1024, f) && *count < MAX_PEERS) {
1661 server = &servers[*count];
1662 memset(server, 0, sizeof(struct server));
1663 peer = &server->peer;
1665 client = &clients[*count];
1666 memset(client, 0, sizeof(struct client));
1667 peer = &client->peer;
1669 for (p = line; *p == ' ' || *p == '\t'; p++);
1670 if (*p == '#' || *p == '\n')
1672 if (*p != 'U' && *p != 'T') {
1673 printf("server type must be U or T, got %c\n", *p);
1677 for (p++; *p == ' ' || *p == '\t'; p++);
1678 p = parsehostport(p, peer);
1679 for (; *p == ' ' || *p == '\t'; p++);
1681 p = parserealmlist(p, server);
1682 for (; *p == ' ' || *p == '\t'; p++);
1685 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1687 /* no secret set and end of line, line is complete if TLS */
1688 if (peer->type == 'U') {
1689 printf("secret must be specified for UDP\n");
1692 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1694 peer->secret = stringcopy(field, p - field);
1695 /* check that rest of line only white space */
1696 for (; *p == ' ' || *p == '\t'; p++);
1697 if (*p && *p != '\n') {
1698 printf("max 4 fields per line, found a 5th\n");
1703 if ((serverfile && !resolvepeer(&server->peer)) ||
1704 (clientfile && !resolvepeer(&client->peer))) {
1705 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1710 pthread_mutex_init(&server->lock, NULL);
1712 server->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1713 if (!server->requests)
1714 errx("malloc failed");
1715 memset(server->requests, 0, MAX_REQUESTS * sizeof(struct request));
1717 pthread_mutex_init(&server->newrq_mutex, NULL);
1718 pthread_cond_init(&server->newrq_cond, NULL);
1720 if (peer->type == 'U')
1721 client->replyq = &udp_server_replyq;
1723 client->replyq = malloc(sizeof(struct replyq));
1724 if (!client->replyq)
1725 errx("malloc failed");
1726 client->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1727 if (!client->replyq->replies)
1728 errx("malloc failed");
1729 client->replyq->size = MAX_REQUESTS;
1730 client->replyq->count = 0;
1731 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1732 pthread_cond_init(&client->replyq->count_cond, NULL);
1735 printf("got type %c, host %s, port %s, secret %s\n", peer->type, peer->host, peer->port, peer->secret);
1737 printf(" with realms:");
1738 for (r = server->realms; *r; r++)
1747 void getmainconfig(const char *configfile) {
1750 char *p, *opt, *endopt, *val, *endval;
1752 printf("opening file %s for reading\n", configfile);
1753 f = fopen(configfile, "r");
1755 errx("getmainconfig failed to open %s for reading", configfile);
1757 memset(&options, 0, sizeof(options));
1759 while (fgets(line, 1024, f)) {
1760 for (p = line; *p == ' ' || *p == '\t'; p++);
1761 if (!*p || *p == '#' || *p == '\n')
1764 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1766 for (; *p == ' ' || *p == '\t'; p++);
1767 if (!*p || *p == '\n') {
1769 printf("error in %s, option %s has no value\n", configfile, opt);
1773 for (; *p && *p != '\n'; p++)
1774 if (*p != ' ' && *p != '\t')
1778 printf("getmainconfig: %s = %s\n", opt, val);
1780 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1781 options.tlscacertificatefile = stringcopy(val, 0);
1784 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1785 options.tlscacertificatepath = stringcopy(val, 0);
1788 if (!strcasecmp(opt, "TLSCertificateFile")) {
1789 options.tlscertificatefile = stringcopy(val, 0);
1792 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1793 options.tlscertificatekeyfile = stringcopy(val, 0);
1796 if (!strcasecmp(opt, "UDPServerPort")) {
1797 options.udpserverport = stringcopy(val, 0);
1801 printf("error in %s, unknown option %s\n", configfile, opt);
1806 if (!options.udpserverport)
1807 options.udpserverport = stringcopy(DEFAULT_UDP_PORT, 0);
1811 void parseargs(int argc, char **argv) {
1814 while ((c = getopt(argc, argv, "p:")) != -1) {
1817 udp_server_port = optarg;
1827 printf("radsecproxy [ -p UDP-port ]\n");
1832 int main(int argc, char **argv) {
1833 pthread_t udpserverth;
1834 // pthread_attr_t joinable;
1835 int i, tlsclients = 0, tlsservers = 0;
1837 // parseargs(argc, argv);
1838 getmainconfig("radsecproxy.conf");
1839 getconfig("servers.conf", NULL);
1840 getconfig(NULL, "clients.conf");
1842 // pthread_attr_init(&joinable);
1843 // pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1845 /* listen on UDP if at least one UDP client */
1846 for (i = 0; i < client_count; i++)
1847 if (clients[i].peer.type == 'U') {
1848 if (pthread_create(&udpserverth, NULL /*&joinable*/, udpserverrd, NULL))
1849 errx("pthread_create failed");
1853 for (i = 0; i < client_count; i++)
1854 if (clients[i].peer.type == 'T') {
1858 for (i = 0; i < server_count; i++)
1859 if (servers[i].peer.type == 'T') {
1863 ssl_init(tlsclients ? &ssl_ctx_srv : NULL, tlsservers ? &ssl_ctx_cl : NULL);
1865 for (i = 0; i < server_count; i++)
1866 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1867 errx("pthread_create failed");
1870 return tlslistener();
1872 /* just hang around doing nothing, anything to do here? */