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 * tls certificate validation, see below urls
13 * clean tls shutdown, see http://www.linuxjournal.com/article/4822
14 * and http://www.linuxjournal.com/article/5487
15 * SSL_shutdown() and shutdown()
16 * If shutdown() we may not need REUSEADDR
17 * when tls client goes away, ensure that all related threads and state
19 * setsockopt(keepalive...), check if openssl has some keepalive feature
22 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
23 * rd is responsible for init and launching wr
24 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
25 * each tlsserverrd launches tlsserverwr
26 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
27 * for init and launching rd
29 * serverrd will receive a request, processes it and puts it in the requestq of
30 * the appropriate clientwr
31 * clientwr monitors its requestq and sends requests
32 * clientrd looks for responses, processes them and puts them in the replyq of
33 * the peer the request came from
34 * serverwr monitors its reply and sends replies
36 * In addition to the main thread, we have:
37 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
38 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
39 * For each TLS peer connecting to us there will be 2 more TLS threads
40 * This is only for connected peers
41 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
42 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
49 #include <openssl/ssl.h>
50 #include <openssl/rand.h>
51 #include <openssl/err.h>
52 #include <openssl/md5.h>
53 #include <openssl/hmac.h>
54 #include "radsecproxy.h"
56 static struct options options;
57 static struct client clients[MAX_PEERS];
58 static struct server servers[MAX_PEERS];
60 static int client_count = 0;
61 static int server_count = 0;
63 static struct replyq udp_server_replyq;
64 static int udp_server_sock = -1;
65 static pthread_mutex_t *ssl_locks;
66 static long *ssl_lock_count;
67 static SSL_CTX *ssl_ctx_cl = NULL;
68 static SSL_CTX *ssl_ctx_srv = NULL;
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74 return (unsigned long)pthread_self();
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78 if (mode & CRYPTO_LOCK) {
79 pthread_mutex_lock(&ssl_locks[type]);
80 ssl_lock_count[type]++;
82 pthread_mutex_unlock(&ssl_locks[type]);
85 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
90 err_cert = X509_STORE_CTX_get_current_cert(ctx);
91 err = X509_STORE_CTX_get_error(ctx);
92 depth = X509_STORE_CTX_get_error_depth(ctx);
94 if (depth > MAX_CERT_DEPTH) {
96 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
97 X509_STORE_CTX_set_error(ctx, err);
101 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
102 printf("verify error: num=%d:%s:depth=%d:%s\n", err, X509_verify_cert_error_string(err), depth, buf);
105 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
106 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
107 printf("issuer=%s\n", buf);
109 case X509_V_ERR_CERT_NOT_YET_VALID:
110 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
111 printf("Certificate not yet valid\n");
113 case X509_V_ERR_CERT_HAS_EXPIRED:
114 printf("Certificate has expired\n");
116 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
117 printf("Certificate no longer valid (after notAfter)\n");
121 printf("certificate verify returns %d\n", ok);
125 void ssl_init(SSL_CTX **ctx_srv, SSL_CTX **ctx_cl) {
128 STACK_OF(X509_NAME) *calist;
130 if (!options.tlscertificatefile || !options.tlscertificatekeyfile) {
131 printf("TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS\n");
135 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
136 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
137 for (i = 0; i < CRYPTO_num_locks(); i++) {
138 ssl_lock_count[i] = 0;
139 pthread_mutex_init(&ssl_locks[i], NULL);
141 CRYPTO_set_id_callback(ssl_thread_id);
142 CRYPTO_set_locking_callback(ssl_locking_callback);
144 SSL_load_error_strings();
147 while (!RAND_status()) {
148 time_t t = time(NULL);
149 pid_t pid = getpid();
150 RAND_seed((unsigned char *)&t, sizeof(time_t));
151 RAND_seed((unsigned char *)&pid, sizeof(pid));
156 *ctx_srv = SSL_CTX_new(TLSv1_server_method());
157 if (!SSL_CTX_use_certificate_chain_file(*ctx_srv, options.tlscertificatefile) ||
158 !SSL_CTX_use_PrivateKey_file(*ctx_srv, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
159 !SSL_CTX_check_private_key(*ctx_srv))
163 calist = (options.tlscacertificatefile
164 ? SSL_load_client_CA_file(options.tlscacertificatefile)
165 : sk_X509_NAME_new_null());
166 if (!calist || (options.tlscacertificatepath &&
167 !SSL_add_dir_cert_subjects_to_stack(calist, options.tlscacertificatepath)))
169 SSL_CTX_set_client_CA_list(*ctx_srv, calist);
171 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
172 printf("CA Certificate file/path need to be configured\n");
175 if (!SSL_CTX_load_verify_locations(*ctx_srv, options.tlscacertificatefile, options.tlscacertificatepath))
177 SSL_CTX_set_verify(*ctx_srv, SSL_VERIFY_PEER, verify_cb);
178 SSL_CTX_set_verify_depth(*ctx_srv, MAX_CERT_DEPTH + 1);
182 *ctx_cl = SSL_CTX_new(TLSv1_client_method());
183 if (!SSL_CTX_use_certificate_chain_file(*ctx_cl, options.tlscertificatefile) ||
184 !SSL_CTX_use_PrivateKey_file(*ctx_cl, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
185 !SSL_CTX_check_private_key(*ctx_cl))
187 if (!options.tlscacertificatefile && !options.tlscacertificatepath) {
188 printf("CA Certificate file/path need to be configured\n");
191 if (!SSL_CTX_load_verify_locations(*ctx_cl, options.tlscacertificatefile, options.tlscacertificatepath))
193 SSL_CTX_set_verify(*ctx_cl, SSL_VERIFY_PEER, verify_cb);
194 SSL_CTX_set_verify_depth(*ctx_cl, MAX_CERT_DEPTH + 1);
198 *ctx_srv = SSL_CTX_new(TLSv1_server_method());
199 if (!SSL_CTX_use_certificate_chain_file(*ctx_srv, options.tlscertificatefile) ||
200 !SSL_CTX_use_PrivateKey_file(*ctx_srv, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
201 !SSL_CTX_check_private_key(*ctx_srv))
204 calist = (SSL_load_client_CA_file(options.tlscacertificatefile));
205 SSL_CTX_set_client_CA_list(*ctx_srv, calist);
207 if (!SSL_CTX_load_verify_locations(*ctx_srv, options.tlscacertificatefile, NULL/*options.tlscacertificatepath*/))
210 SSL_CTX_set_verify(*ctx_srv, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
211 SSL_CTX_set_verify_depth(*ctx_srv, MAX_CERT_DEPTH + 1);
214 *ctx_cl = SSL_CTX_new(TLSv1_client_method());
215 if (!SSL_CTX_use_certificate_chain_file(*ctx_cl, options.tlscertificatefile) ||
216 !SSL_CTX_use_PrivateKey_file(*ctx_cl, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) ||
217 !SSL_CTX_check_private_key(*ctx_cl))
219 if (!SSL_CTX_load_verify_locations(*ctx_cl,options.tlscacertificatefile, NULL/*options.tlscacertificatepath*/))
222 SSL_CTX_set_verify(*ctx_cl, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
223 SSL_CTX_set_verify_depth(*ctx_cl, MAX_CERT_DEPTH + 1);
225 calist = (SSL_load_client_CA_file(options.tlscacertificatefile));
226 SSL_CTX_set_client_CA_list(*ctx_cl, calist);
233 while ((error = ERR_get_error()))
234 err("SSL: %s", ERR_error_string(error, NULL));
238 void printauth(char *s, unsigned char *t) {
241 for (i = 0; i < 16; i++)
242 printf("%02x ", t[i]);
246 int resolvepeer(struct peer *peer) {
247 struct addrinfo hints, *addrinfo;
249 memset(&hints, 0, sizeof(hints));
250 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
251 hints.ai_family = AF_UNSPEC;
252 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
253 err("resolvepeer: can't resolve %s port %s", peer->host, peer->port);
258 freeaddrinfo(peer->addrinfo);
259 peer->addrinfo = addrinfo;
263 int connecttoserver(struct addrinfo *addrinfo) {
265 struct addrinfo *res;
267 for (res = addrinfo; res; res = res->ai_next) {
268 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
270 err("connecttoserver: socket failed");
273 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
275 err("connecttoserver: connect failed");
282 /* returns the client with matching address, or NULL */
283 /* if client argument is not NULL, we only check that one client */
284 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
285 struct sockaddr_in6 *sa6;
286 struct in_addr *a4 = NULL;
289 struct addrinfo *res;
291 if (addr->sa_family == AF_INET6) {
292 sa6 = (struct sockaddr_in6 *)addr;
293 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
294 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
296 a4 = &((struct sockaddr_in *)addr)->sin_addr;
298 c = (client ? client : clients);
299 for (i = 0; i < client_count; i++) {
300 if (c->peer.type == type)
301 for (res = c->peer.addrinfo; res; res = res->ai_next)
302 if ((a4 && res->ai_family == AF_INET &&
303 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
304 (res->ai_family == AF_INET6 &&
305 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
314 /* returns the server with matching address, or NULL */
315 /* if server argument is not NULL, we only check that one server */
316 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
317 struct sockaddr_in6 *sa6;
318 struct in_addr *a4 = NULL;
321 struct addrinfo *res;
323 if (addr->sa_family == AF_INET6) {
324 sa6 = (struct sockaddr_in6 *)addr;
325 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
326 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
328 a4 = &((struct sockaddr_in *)addr)->sin_addr;
330 s = (server ? server : servers);
331 for (i = 0; i < server_count; i++) {
332 if (s->peer.type == type)
333 for (res = s->peer.addrinfo; res; res = res->ai_next)
334 if ((a4 && res->ai_family == AF_INET &&
335 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
336 (res->ai_family == AF_INET6 &&
337 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
346 /* exactly one of client and server must be non-NULL */
347 /* if *peer == NULL we return who we received from, else require it to be from peer */
348 /* return from in sa if not NULL */
349 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
352 unsigned char buf[65536], *rad;
353 struct sockaddr_storage from;
354 socklen_t fromlen = sizeof(from);
357 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
359 err("radudpget: recv failed");
362 printf("radudpget: got %d bytes from %s\n", cnt, addr2string((struct sockaddr *)&from, fromlen));
365 printf("radudpget: packet too small\n");
372 printf("radudpget: packet smaller than length field in radius header\n");
376 printf("radudpget: packet was padded with %d bytes\n", cnt - len);
379 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
380 : (void *)find_server('U', (struct sockaddr *)&from, *server));
382 printf("radudpget: got packet from wrong or unknown UDP peer, ignoring\n");
389 err("radudpget: malloc failed");
391 memcpy(rad, buf, len);
393 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
395 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
401 int tlsverifycert(struct peer *peer) {
410 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
411 printf("tlsverifycert: basic validation failed\n");
412 while ((error = ERR_get_error()))
413 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
417 cert = SSL_get_peer_certificate(peer->ssl);
419 printf("tlsverifycert: failed to obtain certificate\n");
422 nm = X509_get_subject_name(cert);
425 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
428 e = X509_NAME_get_entry(nm, loc);
429 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
433 for (i = 0; i < l; i++)
436 if (l == strlen(peer->host) && !strncasecmp(peer->host, v, l)) {
437 printf("tlsverifycert: Found cn matching host %s, All OK\n", peer->host);
440 printf("tlsverifycert: cn not matching host %s\n", peer->host);
446 void tlsconnect(struct server *server, struct timeval *when, char *text) {
450 printf("tlsconnect called from %s\n", text);
451 pthread_mutex_lock(&server->lock);
452 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
453 /* already reconnected, nothing to do */
454 printf("tlsconnect(%s): seems already reconnected\n", text);
455 pthread_mutex_unlock(&server->lock);
459 printf("tlsconnect %s\n", text);
462 gettimeofday(&now, NULL);
463 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
464 if (server->connectionok) {
465 server->connectionok = 0;
467 } else if (elapsed < 5)
469 else if (elapsed < 600)
471 else if (elapsed < 10000)
474 server->lastconnecttry.tv_sec = now.tv_sec; // no sleep at startup
475 printf("tlsconnect: trying to open TLS connection to %s port %s\n", server->peer.host, server->peer.port);
476 if (server->sock >= 0)
478 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
480 SSL_free(server->peer.ssl);
481 server->peer.ssl = SSL_new(ssl_ctx_cl);
482 SSL_set_fd(server->peer.ssl, server->sock);
483 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
486 printf("tlsconnect: TLS connection to %s port %s up\n", server->peer.host, server->peer.port);
487 gettimeofday(&server->lastconnecttry, NULL);
488 pthread_mutex_unlock(&server->lock);
491 unsigned char *radtlsget(SSL *ssl) {
493 unsigned char buf[4], *rad;
496 for (total = 0; total < 4; total += cnt) {
497 cnt = SSL_read(ssl, buf + total, 4 - total);
499 printf("radtlsget: connection lost\n");
500 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
501 //remote end sent close_notify, send one back
511 err("radtlsget: malloc failed");
516 for (; total < len; total += cnt) {
517 cnt = SSL_read(ssl, rad + total, len - total);
519 printf("radtlsget: connection lost\n");
520 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
521 //remote end sent close_notify, send one back
533 printf("radtlsget: packet smaller than minimum radius size\n");
536 printf("radtlsget: got %d bytes\n", total);
540 int clientradput(struct server *server, unsigned char *rad) {
544 struct timeval lastconnecttry;
547 if (server->peer.type == 'U') {
548 if (send(server->sock, rad, len, 0) >= 0) {
549 printf("clienradput: sent UDP of length %d to %s port %s\n", len, server->peer.host, server->peer.port);
552 err("clientradput: send failed");
556 lastconnecttry = server->lastconnecttry;
557 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
558 while ((error = ERR_get_error()))
559 err("clientwr: TLS: %s", ERR_error_string(error, NULL));
560 tlsconnect(server, &lastconnecttry, "clientradput");
561 lastconnecttry = server->lastconnecttry;
564 server->connectionok = 1;
565 printf("clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s\n",
566 cnt, len, server->peer.host);
570 int radsign(unsigned char *rad, unsigned char *sec) {
571 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
572 static unsigned char first = 1;
573 static EVP_MD_CTX mdctx;
577 pthread_mutex_lock(&lock);
579 EVP_MD_CTX_init(&mdctx);
583 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
584 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
585 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
586 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
588 pthread_mutex_unlock(&lock);
592 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
593 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
594 static unsigned char first = 1;
595 static EVP_MD_CTX mdctx;
596 unsigned char hash[EVP_MAX_MD_SIZE];
600 pthread_mutex_lock(&lock);
602 EVP_MD_CTX_init(&mdctx);
608 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
609 EVP_DigestUpdate(&mdctx, rad, 4) &&
610 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
611 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
612 EVP_DigestUpdate(&mdctx, sec, strlen(sec)) &&
613 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
615 !memcmp(hash, rad + 4, 16));
616 pthread_mutex_unlock(&lock);
620 int checkmessageauth(char *rad, uint8_t *authattr, char *secret) {
621 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
622 static unsigned char first = 1;
623 static HMAC_CTX hmacctx;
625 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
627 pthread_mutex_lock(&lock);
629 HMAC_CTX_init(&hmacctx);
633 memcpy(auth, authattr, 16);
634 memset(authattr, 0, 16);
636 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
637 HMAC_Update(&hmacctx, rad, RADLEN(rad));
638 HMAC_Final(&hmacctx, hash, &md_len);
639 memcpy(authattr, auth, 16);
641 printf("message auth computation failed\n");
642 pthread_mutex_unlock(&lock);
646 if (memcmp(auth, hash, 16)) {
647 printf("message authenticator, wrong value\n");
648 pthread_mutex_unlock(&lock);
652 pthread_mutex_unlock(&lock);
656 int createmessageauth(char *rad, char *authattrval, char *secret) {
657 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
658 static unsigned char first = 1;
659 static HMAC_CTX hmacctx;
665 pthread_mutex_lock(&lock);
667 HMAC_CTX_init(&hmacctx);
671 memset(authattrval, 0, 16);
673 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
674 HMAC_Update(&hmacctx, rad, RADLEN(rad));
675 HMAC_Final(&hmacctx, authattrval, &md_len);
677 printf("message auth computation failed\n");
678 pthread_mutex_unlock(&lock);
682 pthread_mutex_unlock(&lock);
686 void sendrq(struct server *to, struct client *from, struct request *rq) {
689 pthread_mutex_lock(&to->newrq_mutex);
690 /* might simplify if only try nextid, might be ok */
691 for (i = to->nextid; i < MAX_REQUESTS; i++)
692 if (!to->requests[i].buf)
694 if (i == MAX_REQUESTS) {
695 for (i = 0; i < to->nextid; i++)
696 if (!to->requests[i].buf)
698 if (i == to->nextid) {
699 printf("No room in queue, dropping request\n");
700 pthread_mutex_unlock(&to->newrq_mutex);
706 rq->buf[1] = (char)i;
707 printf("sendrq: inserting packet with id %d in queue for %s\n", i, to->peer.host);
709 if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
712 to->requests[i] = *rq;
716 printf("signalling client writer\n");
717 pthread_cond_signal(&to->newrq_cond);
719 pthread_mutex_unlock(&to->newrq_mutex);
722 void sendreply(struct client *to, struct server *from, char *buf, struct sockaddr_storage *tosa) {
723 struct replyq *replyq = to->replyq;
725 pthread_mutex_lock(&replyq->count_mutex);
726 if (replyq->count == replyq->size) {
727 printf("No room in queue, dropping request\n");
728 pthread_mutex_unlock(&replyq->count_mutex);
732 replyq->replies[replyq->count].buf = buf;
734 replyq->replies[replyq->count].tosa = *tosa;
737 if (replyq->count == 1) {
738 printf("signalling client writer\n");
739 pthread_cond_signal(&replyq->count_cond);
741 pthread_mutex_unlock(&replyq->count_mutex);
744 int pwdencrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
745 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
746 static unsigned char first = 1;
747 static EVP_MD_CTX mdctx;
748 unsigned char hash[EVP_MAX_MD_SIZE], *input;
750 uint8_t i, offset = 0, out[128];
752 pthread_mutex_lock(&lock);
754 EVP_MD_CTX_init(&mdctx);
760 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
761 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
762 !EVP_DigestUpdate(&mdctx, input, 16) ||
763 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
765 pthread_mutex_unlock(&lock);
768 for (i = 0; i < 16; i++)
769 out[offset + i] = hash[i] ^ in[offset + i];
770 input = out + offset - 16;
775 memcpy(in, out, len);
776 pthread_mutex_unlock(&lock);
780 int pwddecrypt(uint8_t *in, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth) {
781 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
782 static unsigned char first = 1;
783 static EVP_MD_CTX mdctx;
784 unsigned char hash[EVP_MAX_MD_SIZE], *input;
786 uint8_t i, offset = 0, out[128];
788 pthread_mutex_lock(&lock);
790 EVP_MD_CTX_init(&mdctx);
796 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
797 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
798 !EVP_DigestUpdate(&mdctx, input, 16) ||
799 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
801 pthread_mutex_unlock(&lock);
804 for (i = 0; i < 16; i++)
805 out[offset + i] = hash[i] ^ in[offset + i];
811 memcpy(in, out, len);
812 pthread_mutex_unlock(&lock);
816 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
817 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
818 static unsigned char first = 1;
819 static EVP_MD_CTX mdctx;
820 unsigned char hash[EVP_MAX_MD_SIZE];
824 pthread_mutex_lock(&lock);
826 EVP_MD_CTX_init(&mdctx);
831 printf("msppencrypt auth in: ");
832 for (i = 0; i < 16; i++)
833 printf("%02x ", auth[i]);
836 printf("msppencrypt salt in: ");
837 for (i = 0; i < 2; i++)
838 printf("%02x ", salt[i]);
841 printf("msppencrypt in: ");
842 for (i = 0; i < len; i++)
843 printf("%02x ", text[i]);
847 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
848 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
849 !EVP_DigestUpdate(&mdctx, auth, 16) ||
850 !EVP_DigestUpdate(&mdctx, salt, 2) ||
851 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
852 pthread_mutex_unlock(&lock);
857 printf("msppencrypt hash: ");
858 for (i = 0; i < 16; i++)
859 printf("%02x ", hash[i]);
863 for (i = 0; i < 16; i++)
866 for (offset = 16; offset < len; offset += 16) {
868 printf("text + offset - 16 c(%d): ", offset / 16);
869 for (i = 0; i < 16; i++)
870 printf("%02x ", (text + offset - 16)[i]);
873 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
874 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
875 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
876 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
878 pthread_mutex_unlock(&lock);
882 printf("msppencrypt hash: ");
883 for (i = 0; i < 16; i++)
884 printf("%02x ", hash[i]);
888 for (i = 0; i < 16; i++)
889 text[offset + i] ^= hash[i];
893 printf("msppencrypt out: ");
894 for (i = 0; i < len; i++)
895 printf("%02x ", text[i]);
899 pthread_mutex_unlock(&lock);
903 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
904 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
905 static unsigned char first = 1;
906 static EVP_MD_CTX mdctx;
907 unsigned char hash[EVP_MAX_MD_SIZE];
912 pthread_mutex_lock(&lock);
914 EVP_MD_CTX_init(&mdctx);
919 printf("msppdecrypt auth in: ");
920 for (i = 0; i < 16; i++)
921 printf("%02x ", auth[i]);
924 printf("msppedecrypt salt in: ");
925 for (i = 0; i < 2; i++)
926 printf("%02x ", salt[i]);
929 printf("msppedecrypt in: ");
930 for (i = 0; i < len; i++)
931 printf("%02x ", text[i]);
935 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
936 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
937 !EVP_DigestUpdate(&mdctx, auth, 16) ||
938 !EVP_DigestUpdate(&mdctx, salt, 2) ||
939 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
940 pthread_mutex_unlock(&lock);
945 printf("msppedecrypt hash: ");
946 for (i = 0; i < 16; i++)
947 printf("%02x ", hash[i]);
951 for (i = 0; i < 16; i++)
952 plain[i] = text[i] ^ hash[i];
954 for (offset = 16; offset < len; offset += 16) {
956 printf("text + offset - 16 c(%d): ", offset / 16);
957 for (i = 0; i < 16; i++)
958 printf("%02x ", (text + offset - 16)[i]);
961 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
962 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
963 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
964 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
966 pthread_mutex_unlock(&lock);
970 printf("msppedecrypt hash: ");
971 for (i = 0; i < 16; i++)
972 printf("%02x ", hash[i]);
976 for (i = 0; i < 16; i++)
977 plain[offset + i] = text[offset + i] ^ hash[i];
980 memcpy(text, plain, len);
982 printf("msppedecrypt out: ");
983 for (i = 0; i < len; i++)
984 printf("%02x ", text[i]);
988 pthread_mutex_unlock(&lock);
992 struct server *id2server(char *id, uint8_t len) {
994 char **realm, *idrealm;
996 idrealm = strchr(id, '@');
1004 for (i = 0; i < server_count; i++) {
1005 for (realm = servers[i].realms; *realm; realm++) {
1006 if ((strlen(*realm) == 1 && **realm == '*') ||
1007 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
1008 printf("found matching realm: %s, host %s\n", *realm, servers[i].peer.host);
1016 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1019 pthread_mutex_lock(&to->newrq_mutex);
1020 for (i = 0; i < MAX_REQUESTS; i++)
1021 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1023 pthread_mutex_unlock(&to->newrq_mutex);
1025 return i < MAX_REQUESTS;
1028 struct server *radsrv(struct request *rq, char *buf, struct client *from) {
1029 uint8_t code, id, *auth, *attr, attrvallen;
1030 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
1035 unsigned char newauth[16];
1037 code = *(uint8_t *)buf;
1038 id = *(uint8_t *)(buf + 1);
1040 auth = (uint8_t *)(buf + 4);
1042 printf("radsrv: code %d, id %d, length %d\n", code, id, len);
1044 if (code != RAD_Access_Request) {
1045 printf("radsrv: server currently accepts only access-requests, ignoring\n");
1053 left -= attr[RAD_Attr_Length];
1055 printf("radsrv: attribute length exceeds packet length, ignoring packet\n");
1058 switch (attr[RAD_Attr_Type]) {
1059 case RAD_Attr_User_Name:
1060 usernameattr = attr;
1062 case RAD_Attr_User_Password:
1065 case RAD_Attr_Tunnel_Password:
1066 tunnelpwdattr = attr;
1068 case RAD_Attr_Message_Authenticator:
1069 messageauthattr = attr;
1072 attr += attr[RAD_Attr_Length];
1075 printf("radsrv: malformed packet? remaining byte after last attribute\n");
1078 printf("radsrv: Username: ");
1079 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
1080 printf("%c", usernameattr[RAD_Attr_Value + i]);
1084 to = id2server(&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1086 printf("radsrv: ignoring request, don't know where to send it\n");
1090 if (rqinqueue(to, from, id)) {
1091 printf("radsrv: ignoring request from host %s with id %d, already got one\n", from->peer.host, id);
1095 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1096 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1097 printf("radsrv: message authentication failed\n");
1101 if (!RAND_bytes(newauth, 16)) {
1102 printf("radsrv: failed to generate random auth\n");
1106 printauth("auth", auth);
1107 printauth("newauth", newauth);
1110 printf("radsrv: found userpwdattr of length %d\n", userpwdattr[RAD_Attr_Length]);
1111 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1112 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1113 printf("radsrv: invalid user password length\n");
1117 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1118 printf("radsrv: cannot decrypt password\n");
1121 printf("radsrv: password: ");
1122 for (i = 0; i < attrvallen; i++)
1123 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1125 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1126 printf("radsrv: cannot encrypt password\n");
1131 if (tunnelpwdattr) {
1132 printf("radsrv: found tunnelpwdattr of length %d\n", tunnelpwdattr[RAD_Attr_Length]);
1133 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1134 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1135 printf("radsrv: invalid user password length\n");
1139 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1140 printf("radsrv: cannot decrypt password\n");
1143 printf("radsrv: password: ");
1144 for (i = 0; i < attrvallen; i++)
1145 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1147 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1148 printf("radsrv: cannot encrypt password\n");
1156 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1157 memcpy(rq->origauth, auth, 16);
1158 memcpy(auth, newauth, 16);
1159 printauth("rq->origauth", rq->origauth);
1160 printauth("auth", auth);
1164 void *clientrd(void *arg) {
1165 struct server *server = (struct server *)arg;
1166 struct client *from;
1167 int i, left, subleft;
1168 unsigned char *buf, *messageauthattr, *subattr, *attr;
1169 struct sockaddr_storage fromsa;
1170 struct timeval lastconnecttry;
1175 lastconnecttry = server->lastconnecttry;
1176 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1177 if (!buf && server->peer.type == 'T') {
1178 tlsconnect(server, &lastconnecttry, "clientrd");
1182 server->connectionok = 1;
1184 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge) {
1185 printf("clientrd: discarding, only accept access accept, access reject and access challenge messages\n");
1189 i = buf[1]; /* i is the id */
1191 pthread_mutex_lock(&server->newrq_mutex);
1192 if (!server->requests[i].buf || !server->requests[i].tries) {
1193 pthread_mutex_unlock(&server->newrq_mutex);
1194 printf("clientrd: no matching request sent with this id, ignoring\n");
1198 if (server->requests[i].received) {
1199 pthread_mutex_unlock(&server->newrq_mutex);
1200 printf("clientrd: already received, ignoring\n");
1204 if (!validauth(buf, server->requests[i].buf + 4, server->peer.secret)) {
1205 pthread_mutex_unlock(&server->newrq_mutex);
1206 printf("clientrd: invalid auth, ignoring\n");
1210 from = server->requests[i].from;
1213 /* messageauthattr present? */
1214 messageauthattr = NULL;
1215 left = RADLEN(buf) - 20;
1218 left -= attr[RAD_Attr_Length];
1220 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1223 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1224 if (attr[RAD_Attr_Length] != 18) {
1225 printf("clientrd: illegal message auth attribute length, ignoring packet\n");
1228 memcpy(tmp, buf + 4, 16);
1229 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1230 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1231 printf("clientrd: message authentication failed\n");
1234 memcpy(buf + 4, tmp, 16);
1235 printf("clientrd: message auth ok\n");
1236 messageauthattr = attr;
1239 attr += attr[RAD_Attr_Length];
1242 /* handle MS MPPE */
1243 left = RADLEN(buf) - 20;
1246 left -= attr[RAD_Attr_Length];
1248 printf("clientrd: attribute length exceeds packet length, ignoring packet\n");
1251 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1252 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { // 311 == MS
1253 subleft = attr[RAD_Attr_Length] - 6;
1255 while (subleft > 1) {
1256 subleft -= subattr[RAD_Attr_Length];
1259 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1260 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1262 printf("clientrd: Got MS MPPE\n");
1263 if (subattr[RAD_Attr_Length] < 20)
1266 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1267 server->peer.secret, strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1268 printf("clientrd: failed to decrypt msppe key\n");
1272 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4,
1273 from->peer.secret, strlen(from->peer.secret), server->requests[i].origauth, subattr + 2)) {
1274 printf("clientrd: failed to encrypt msppe key\n");
1279 printf("clientrd: bad vendor specific attr or subattr length, ignoring packet\n");
1283 attr += attr[RAD_Attr_Length];
1286 /* once we set received = 1, requests[i] may be reused */
1287 buf[1] = (char)server->requests[i].origid;
1288 memcpy(buf + 4, server->requests[i].origauth, 16);
1289 printauth("origauth/buf+4", buf + 4);
1290 if (messageauthattr) {
1291 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1293 printf("clientrd: computed messageauthattr\n");
1296 if (from->peer.type == 'U')
1297 fromsa = server->requests[i].fromsa;
1298 server->requests[i].received = 1;
1299 pthread_mutex_unlock(&server->newrq_mutex);
1301 if (!radsign(buf, from->peer.secret)) {
1302 printf("clientrd: failed to sign message\n");
1305 printauth("signedorigauth/buf+4", buf + 4);
1306 printf("clientrd: giving packet back to where it came from\n");
1307 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1311 void *clientwr(void *arg) {
1312 struct server *server = (struct server *)arg;
1314 pthread_t clientrdth;
1317 struct timespec timeout;
1319 memset(&timeout, 0, sizeof(struct timespec));
1321 if (server->peer.type == 'U') {
1322 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
1323 printf("clientwr: connecttoserver failed\n");
1327 tlsconnect(server, NULL, "new client");
1329 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1330 errx("clientwr: pthread_create failed");
1333 pthread_mutex_lock(&server->newrq_mutex);
1334 if (!server->newrq) {
1335 if (timeout.tv_nsec) {
1336 printf("clientwr: waiting up to %ld secs for new request\n", timeout.tv_nsec);
1337 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1338 timeout.tv_nsec = 0;
1340 printf("clientwr: waiting for new request\n");
1341 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1343 if (server->newrq) {
1344 printf("clientwr: got new request\n");
1348 pthread_mutex_unlock(&server->newrq_mutex);
1350 for (i = 0; i < MAX_REQUESTS; i++) {
1351 pthread_mutex_lock(&server->newrq_mutex);
1352 while (!server->requests[i].buf && i < MAX_REQUESTS)
1354 if (i == MAX_REQUESTS) {
1355 pthread_mutex_unlock(&server->newrq_mutex);
1358 rq = server->requests + i;
1361 printf("clientwr: removing received packet from queue\n");
1363 /* setting this to NULL means that it can be reused */
1365 pthread_mutex_unlock(&server->newrq_mutex);
1369 gettimeofday(&now, NULL);
1370 if (now.tv_sec <= rq->expiry.tv_sec) {
1371 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1372 timeout.tv_sec = rq->expiry.tv_sec;
1373 pthread_mutex_unlock(&server->newrq_mutex);
1377 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1378 printf("clientwr: removing expired packet from queue\n");
1380 /* setting this to NULL means that it can be reused */
1382 pthread_mutex_unlock(&server->newrq_mutex);
1385 pthread_mutex_unlock(&server->newrq_mutex);
1387 rq->expiry.tv_sec = now.tv_sec +
1388 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1389 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1390 timeout.tv_sec = rq->expiry.tv_sec;
1392 clientradput(server, server->requests[i].buf);
1396 /* should do more work to maintain TLS connections, keepalives etc */
1399 void *udpserverwr(void *arg) {
1400 struct replyq *replyq = &udp_server_replyq;
1401 struct reply *reply = replyq->replies;
1403 pthread_mutex_lock(&replyq->count_mutex);
1405 while (!replyq->count) {
1406 printf("udp server writer, waiting for signal\n");
1407 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1408 printf("udp server writer, got signal\n");
1410 pthread_mutex_unlock(&replyq->count_mutex);
1412 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1413 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1414 err("sendudp: send failed");
1417 pthread_mutex_lock(&replyq->count_mutex);
1419 memmove(replyq->replies, replyq->replies + 1,
1420 replyq->count * sizeof(struct reply));
1424 void *udpserverrd(void *arg) {
1429 pthread_t udpserverwrth;
1431 if ((udp_server_sock = bindport(SOCK_DGRAM, options.udpserverport)) < 0) {
1432 printf("udpserverrd: socket/bind failed\n");
1435 printf("udpserverrd: listening on UDP port %s\n", options.udpserverport);
1437 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1438 errx("pthread_create failed");
1442 memset(&rq, 0, sizeof(struct request));
1443 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1444 to = radsrv(&rq, buf, fr);
1446 printf("udpserverrd: ignoring request, no place to send it\n");
1449 sendrq(to, fr, &rq);
1453 void *tlsserverwr(void *arg) {
1455 unsigned long error;
1456 struct client *client = (struct client *)arg;
1457 struct replyq *replyq;
1459 printf("tlsserverwr starting for %s\n", client->peer.host);
1460 replyq = client->replyq;
1461 pthread_mutex_lock(&replyq->count_mutex);
1463 while (!replyq->count) {
1464 if (client->peer.ssl) {
1465 printf("tls server writer, waiting for signal\n");
1466 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1467 printf("tls server writer, got signal\n");
1469 if (!client->peer.ssl) {
1470 //ssl might have changed while waiting
1471 pthread_mutex_unlock(&replyq->count_mutex);
1472 printf("tlsserverwr: exiting as requested\n");
1476 pthread_mutex_unlock(&replyq->count_mutex);
1477 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1479 printf("tlsserverwr: Sent %d bytes, Radius packet of length %d\n",
1480 cnt, RADLEN(replyq->replies->buf));
1482 while ((error = ERR_get_error()))
1483 err("tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1484 free(replyq->replies->buf);
1486 pthread_mutex_lock(&replyq->count_mutex);
1488 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1492 void *tlsserverrd(void *arg) {
1495 unsigned long error;
1498 struct client *client = (struct client *)arg;
1499 pthread_t tlsserverwrth;
1502 printf("tlsserverrd starting for %s\n", client->peer.host);
1503 ssl = client->peer.ssl;
1505 if (SSL_accept(ssl) <= 0) {
1506 while ((error = ERR_get_error()))
1507 err("tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1508 errx("accept failed, child exiting");
1511 if (1 /*tlsverifycert(&client->peer)*/) {
1512 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client))
1513 errx("pthread_create failed");
1516 buf = radtlsget(client->peer.ssl);
1519 printf("tlsserverrd: got Radius message from %s\n", client->peer.host);
1520 memset(&rq, 0, sizeof(struct request));
1521 to = radsrv(&rq, buf, client);
1523 printf("ignoring request, no place to send it\n");
1526 sendrq(to, client, &rq);
1528 printf("tlsserverrd: connection lost\n");
1529 // stop writer by setting peer.ssl to NULL and give signal in case waiting for data
1530 client->peer.ssl = NULL;
1531 pthread_mutex_lock(&client->replyq->count_mutex);
1532 pthread_cond_signal(&client->replyq->count_cond);
1533 pthread_mutex_unlock(&client->replyq->count_mutex);
1534 printf("tlsserverrd: waiting for writer to end\n");
1535 pthread_join(tlsserverwrth, NULL);
1537 s = SSL_get_fd(ssl);
1540 printf("tlsserverrd thread for %s exiting\n", client->peer.host);
1545 pthread_t tlsserverth;
1547 struct sockaddr_storage from;
1548 size_t fromlen = sizeof(from);
1549 struct client *client;
1551 if ((s = bindport(SOCK_STREAM, DEFAULT_TLS_PORT)) < 0) {
1552 printf("tlslistener: socket/bind failed\n");
1557 printf("listening for incoming TLS on port %s\n", DEFAULT_TLS_PORT);
1560 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1562 errx("accept failed");
1563 printf("incoming TLS connection from %s\n", addr2string((struct sockaddr *)&from, fromlen));
1565 client = find_client('T', (struct sockaddr *)&from, NULL);
1567 printf("ignoring request, not a known TLS client\n");
1568 shutdown(snew, SHUT_RDWR);
1573 if (client->peer.ssl) {
1574 printf("Ignoring incoming connection, already have one from this client\n");
1575 shutdown(snew, SHUT_RDWR);
1579 client->peer.ssl = SSL_new(ssl_ctx_srv);
1580 SSL_set_fd(client->peer.ssl, snew);
1581 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client))
1582 errx("pthread_create failed");
1583 pthread_detach(tlsserverth);
1588 char *parsehostport(char *s, struct peer *peer) {
1593 // allow literal addresses and port, e.g. [2001:db8::1]:1812
1597 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1599 printf("no ] matching initial [\n");
1605 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1608 printf("missing host/address\n");
1611 peer->host = stringcopy(field, p - field);
1614 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n') {
1615 printf("unexpected character after ]\n");
1620 /* port number or service name is specified */;
1622 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1624 printf("syntax error, : but no following port\n");
1627 peer->port = stringcopy(field, p - field);
1629 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1633 // * is default, else longest match ... ";" used for separator
1634 char *parserealmlist(char *s, struct server *server) {
1638 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1643 printf("realm list must be specified\n");
1646 server->realmdata = stringcopy(s, l);
1647 server->realms = malloc((1+n) * sizeof(char *));
1648 if (!server->realms)
1649 errx("malloc failed");
1650 server->realms[0] = server->realmdata;
1651 for (n = 1, i = 0; i < l; i++)
1652 if (server->realmdata[i] == ';') {
1653 server->realmdata[i] = '\0';
1654 server->realms[n++] = server->realmdata + i + 1;
1656 server->realms[n] = NULL;
1660 /* exactly one argument must be non-NULL */
1661 void getconfig(const char *serverfile, const char *clientfile) {
1664 char *p, *field, **r;
1665 struct client *client;
1666 struct server *server;
1671 printf("opening file %s for reading\n", serverfile);
1672 f = fopen(serverfile, "r");
1674 errx("getconfig failed to open %s for reading", serverfile);
1675 count = &server_count;
1677 printf("opening file %s for reading\n", clientfile);
1678 f = fopen(clientfile, "r");
1680 errx("getconfig failed to open %s for reading", clientfile);
1681 udp_server_replyq.replies = malloc(4 * MAX_REQUESTS * sizeof(struct reply));
1682 if (!udp_server_replyq.replies)
1683 errx("malloc failed");
1684 udp_server_replyq.size = 4 * MAX_REQUESTS;
1685 udp_server_replyq.count = 0;
1686 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1687 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1688 count = &client_count;
1692 while (fgets(line, 1024, f) && *count < MAX_PEERS) {
1694 server = &servers[*count];
1695 memset(server, 0, sizeof(struct server));
1696 peer = &server->peer;
1698 client = &clients[*count];
1699 memset(client, 0, sizeof(struct client));
1700 peer = &client->peer;
1702 for (p = line; *p == ' ' || *p == '\t'; p++);
1703 if (*p == '#' || *p == '\n')
1705 if (*p != 'U' && *p != 'T') {
1706 printf("server type must be U or T, got %c\n", *p);
1710 for (p++; *p == ' ' || *p == '\t'; p++);
1711 p = parsehostport(p, peer);
1712 for (; *p == ' ' || *p == '\t'; p++);
1714 p = parserealmlist(p, server);
1715 for (; *p == ' ' || *p == '\t'; p++);
1718 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1720 /* no secret set and end of line, line is complete if TLS */
1721 if (peer->type == 'U') {
1722 printf("secret must be specified for UDP\n");
1725 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1727 peer->secret = stringcopy(field, p - field);
1728 /* check that rest of line only white space */
1729 for (; *p == ' ' || *p == '\t'; p++);
1730 if (*p && *p != '\n') {
1731 printf("max 4 fields per line, found a 5th\n");
1736 if ((serverfile && !resolvepeer(&server->peer)) ||
1737 (clientfile && !resolvepeer(&client->peer))) {
1738 printf("failed to resolve host %s port %s, exiting\n", peer->host, peer->port);
1743 pthread_mutex_init(&server->lock, NULL);
1745 server->requests = malloc(MAX_REQUESTS * sizeof(struct request));
1746 if (!server->requests)
1747 errx("malloc failed");
1748 memset(server->requests, 0, MAX_REQUESTS * sizeof(struct request));
1750 pthread_mutex_init(&server->newrq_mutex, NULL);
1751 pthread_cond_init(&server->newrq_cond, NULL);
1753 if (peer->type == 'U')
1754 client->replyq = &udp_server_replyq;
1756 client->replyq = malloc(sizeof(struct replyq));
1757 if (!client->replyq)
1758 errx("malloc failed");
1759 client->replyq->replies = malloc(MAX_REQUESTS * sizeof(struct reply));
1760 if (!client->replyq->replies)
1761 errx("malloc failed");
1762 client->replyq->size = MAX_REQUESTS;
1763 client->replyq->count = 0;
1764 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1765 pthread_cond_init(&client->replyq->count_cond, NULL);
1768 printf("got type %c, host %s, port %s, secret %s\n", peer->type, peer->host, peer->port, peer->secret);
1770 printf(" with realms:");
1771 for (r = server->realms; *r; r++)
1780 void getmainconfig(const char *configfile) {
1783 char *p, *opt, *endopt, *val, *endval;
1785 printf("opening file %s for reading\n", configfile);
1786 f = fopen(configfile, "r");
1788 errx("getmainconfig failed to open %s for reading", configfile);
1790 memset(&options, 0, sizeof(options));
1792 while (fgets(line, 1024, f)) {
1793 for (p = line; *p == ' ' || *p == '\t'; p++);
1794 if (!*p || *p == '#' || *p == '\n')
1797 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1799 for (; *p == ' ' || *p == '\t'; p++);
1800 if (!*p || *p == '\n') {
1802 printf("error in %s, option %s has no value\n", configfile, opt);
1806 for (; *p && *p != '\n'; p++)
1807 if (*p != ' ' && *p != '\t')
1811 printf("getmainconfig: %s = %s\n", opt, val);
1813 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1814 options.tlscacertificatefile = stringcopy(val, 0);
1817 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1818 options.tlscacertificatepath = stringcopy(val, 0);
1821 if (!strcasecmp(opt, "TLSCertificateFile")) {
1822 options.tlscertificatefile = stringcopy(val, 0);
1825 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1826 options.tlscertificatekeyfile = stringcopy(val, 0);
1829 if (!strcasecmp(opt, "UDPServerPort")) {
1830 options.udpserverport = stringcopy(val, 0);
1834 printf("error in %s, unknown option %s\n", configfile, opt);
1839 if (!options.udpserverport)
1840 options.udpserverport = stringcopy(DEFAULT_UDP_PORT, 0);
1844 void parseargs(int argc, char **argv) {
1847 while ((c = getopt(argc, argv, "p:")) != -1) {
1850 udp_server_port = optarg;
1860 printf("radsecproxy [ -p UDP-port ]\n");
1865 int main(int argc, char **argv) {
1866 pthread_t udpserverth;
1867 // pthread_attr_t joinable;
1868 int i, tlsclients = 0, tlsservers = 0;
1870 // parseargs(argc, argv);
1871 getmainconfig("radsecproxy.conf");
1872 getconfig("servers.conf", NULL);
1873 getconfig(NULL, "clients.conf");
1875 // pthread_attr_init(&joinable);
1876 // pthread_attr_setdetachstate(&joinable, PTHREAD_CREATE_JOINABLE);
1878 /* listen on UDP if at least one UDP client */
1879 for (i = 0; i < client_count; i++)
1880 if (clients[i].peer.type == 'U') {
1881 if (pthread_create(&udpserverth, NULL /*&joinable*/, udpserverrd, NULL))
1882 errx("pthread_create failed");
1886 for (i = 0; i < client_count; i++)
1887 if (clients[i].peer.type == 'T') {
1891 for (i = 0; i < server_count; i++)
1892 if (servers[i].peer.type == 'T') {
1896 ssl_init(tlsclients ? &ssl_ctx_srv : NULL, tlsservers ? &ssl_ctx_cl : NULL);
1898 for (i = 0; i < server_count; i++)
1899 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1900 errx("pthread_create failed");
1903 return tlslistener();
1905 /* just hang around doing nothing, anything to do here? */