2 * Copyright (C) 2006, 2007 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
11 * radius keep alives (server status)
12 * setsockopt(keepalive...), check if openssl has some keepalive feature
15 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
16 * rd is responsible for init and launching wr
17 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
18 * each tlsserverrd launches tlsserverwr
19 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
20 * for init and launching rd
22 * serverrd will receive a request, processes it and puts it in the requestq of
23 * the appropriate clientwr
24 * clientwr monitors its requestq and sends requests
25 * clientrd looks for responses, processes them and puts them in the replyq of
26 * the peer the request came from
27 * serverwr monitors its reply and sends replies
29 * In addition to the main thread, we have:
30 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
31 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
32 * For each TLS peer connecting to us there will be 2 more TLS threads
33 * This is only for connected peers
34 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
35 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 #include <sys/socket.h>
39 #include <netinet/in.h>
46 #include <openssl/ssl.h>
47 #include <openssl/rand.h>
48 #include <openssl/err.h>
49 #include <openssl/md5.h>
50 #include <openssl/hmac.h>
52 #include "radsecproxy.h"
54 static struct options options;
55 static struct client *clients;
56 static struct server *servers;
58 static int client_udp_count = 0;
59 static int client_tls_count = 0;
60 static int client_count = 0;
61 static int server_udp_count = 0;
62 static int server_tls_count = 0;
63 static int server_count = 0;
65 static struct peer *tcp_server_listen;
66 static struct peer *udp_server_listen;
67 static struct replyq udp_server_replyq;
68 static int udp_server_sock = -1;
69 static pthread_mutex_t *ssl_locks;
70 static long *ssl_lock_count;
71 static SSL_CTX *ssl_ctx = NULL;
75 /* callbacks for making OpenSSL thread safe */
76 unsigned long ssl_thread_id() {
77 return (unsigned long)pthread_self();
80 void ssl_locking_callback(int mode, int type, const char *file, int line) {
81 if (mode & CRYPTO_LOCK) {
82 pthread_mutex_lock(&ssl_locks[type]);
83 ssl_lock_count[type]++;
85 pthread_mutex_unlock(&ssl_locks[type]);
88 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
89 int pwdlen = strlen(userdata);
90 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
92 memcpy(buf, userdata, pwdlen);
96 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
101 err_cert = X509_STORE_CTX_get_current_cert(ctx);
102 err = X509_STORE_CTX_get_error(ctx);
103 depth = X509_STORE_CTX_get_error_depth(ctx);
105 if (depth > MAX_CERT_DEPTH) {
107 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
108 X509_STORE_CTX_set_error(ctx, err);
112 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
113 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
116 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
117 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
118 debug(DBG_WARN, "\tIssuer=%s", buf);
120 case X509_V_ERR_CERT_NOT_YET_VALID:
121 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
122 debug(DBG_WARN, "\tCertificate not yet valid");
124 case X509_V_ERR_CERT_HAS_EXPIRED:
125 debug(DBG_WARN, "Certificate has expired");
127 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
128 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
133 printf("certificate verify returns %d\n", ok);
138 SSL_CTX *ssl_init() {
143 if (!options.tlscertificatefile || !options.tlscertificatekeyfile)
144 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified for TLS");
146 if (!options.tlscacertificatefile && !options.tlscacertificatepath)
147 debugx(1, DBG_ERR, "CA Certificate file/path need to be configured");
149 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
150 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
151 for (i = 0; i < CRYPTO_num_locks(); i++) {
152 ssl_lock_count[i] = 0;
153 pthread_mutex_init(&ssl_locks[i], NULL);
155 CRYPTO_set_id_callback(ssl_thread_id);
156 CRYPTO_set_locking_callback(ssl_locking_callback);
158 SSL_load_error_strings();
161 while (!RAND_status()) {
162 time_t t = time(NULL);
163 pid_t pid = getpid();
164 RAND_seed((unsigned char *)&t, sizeof(time_t));
165 RAND_seed((unsigned char *)&pid, sizeof(pid));
168 ctx = SSL_CTX_new(TLSv1_method());
169 if (options.tlscertificatekeypassword) {
170 SSL_CTX_set_default_passwd_cb_userdata(ctx, options.tlscertificatekeypassword);
171 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
173 if (SSL_CTX_use_certificate_chain_file(ctx, options.tlscertificatefile) &&
174 SSL_CTX_use_PrivateKey_file(ctx, options.tlscertificatekeyfile, SSL_FILETYPE_PEM) &&
175 SSL_CTX_check_private_key(ctx) &&
176 SSL_CTX_load_verify_locations(ctx, options.tlscacertificatefile, options.tlscacertificatepath)) {
177 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
178 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
182 while ((error = ERR_get_error()))
183 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
184 debug(DBG_ERR, "Error initialising SSL/TLS");
189 void printauth(char *s, unsigned char *t) {
192 for (i = 0; i < 16; i++)
193 printf("%02x ", t[i]);
198 int resolvepeer(struct peer *peer, int ai_flags) {
199 struct addrinfo hints, *addrinfo;
201 memset(&hints, 0, sizeof(hints));
202 hints.ai_socktype = (peer->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
203 hints.ai_family = AF_UNSPEC;
204 hints.ai_flags = ai_flags;
205 if (getaddrinfo(peer->host, peer->port, &hints, &addrinfo)) {
206 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", peer->host, peer->port);
211 freeaddrinfo(peer->addrinfo);
212 peer->addrinfo = addrinfo;
216 int connecttoserver(struct addrinfo *addrinfo) {
218 struct addrinfo *res;
220 for (res = addrinfo; res; res = res->ai_next) {
221 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
223 debug(DBG_WARN, "connecttoserver: socket failed");
226 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
228 debug(DBG_WARN, "connecttoserver: connect failed");
235 int bindtoaddr(struct addrinfo *addrinfo) {
237 struct addrinfo *res;
239 for (res = addrinfo; res; res = res->ai_next) {
240 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
242 debug(DBG_WARN, "bindtoaddr: socket failed");
245 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
246 if (!bind(s, res->ai_addr, res->ai_addrlen))
248 debug(DBG_WARN, "bindtoaddr: bind failed");
254 /* returns the client with matching address, or NULL */
255 /* if client argument is not NULL, we only check that one client */
256 struct client *find_client(char type, struct sockaddr *addr, struct client *client) {
257 struct sockaddr_in6 *sa6;
258 struct in_addr *a4 = NULL;
261 struct addrinfo *res;
263 if (addr->sa_family == AF_INET6) {
264 sa6 = (struct sockaddr_in6 *)addr;
265 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
266 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
268 a4 = &((struct sockaddr_in *)addr)->sin_addr;
270 c = (client ? client : clients);
271 for (i = 0; i < client_count; i++) {
272 if (c->peer.type == type)
273 for (res = c->peer.addrinfo; res; res = res->ai_next)
274 if ((a4 && res->ai_family == AF_INET &&
275 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
276 (res->ai_family == AF_INET6 &&
277 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
286 /* returns the server with matching address, or NULL */
287 /* if server argument is not NULL, we only check that one server */
288 struct server *find_server(char type, struct sockaddr *addr, struct server *server) {
289 struct sockaddr_in6 *sa6;
290 struct in_addr *a4 = NULL;
293 struct addrinfo *res;
295 if (addr->sa_family == AF_INET6) {
296 sa6 = (struct sockaddr_in6 *)addr;
297 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
298 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
300 a4 = &((struct sockaddr_in *)addr)->sin_addr;
302 s = (server ? server : servers);
303 for (i = 0; i < server_count; i++) {
304 if (s->peer.type == type)
305 for (res = s->peer.addrinfo; res; res = res->ai_next)
306 if ((a4 && res->ai_family == AF_INET &&
307 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
308 (res->ai_family == AF_INET6 &&
309 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
318 /* exactly one of client and server must be non-NULL */
319 /* if *peer == NULL we return who we received from, else require it to be from peer */
320 /* return from in sa if not NULL */
321 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
324 unsigned char buf[65536], *rad;
325 struct sockaddr_storage from;
326 socklen_t fromlen = sizeof(from);
329 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
331 debug(DBG_WARN, "radudpget: recv failed");
334 debug(DBG_INFO, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
337 debug(DBG_WARN, "radudpget: packet too small");
344 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
348 debug(DBG_INFO, "radudpget: packet was padded with %d bytes", cnt - len);
351 ? (void *)find_client('U', (struct sockaddr *)&from, *client)
352 : (void *)find_server('U', (struct sockaddr *)&from, *server));
354 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
361 debug(DBG_ERR, "radudpget: malloc failed");
363 memcpy(rad, buf, len);
365 *client = (struct client *)f; /* only need this if *client == NULL, but if not NULL *client == f here */
367 *server = (struct server *)f; /* only need this if *server == NULL, but if not NULL *server == f here */
373 int tlsverifycert(struct peer *peer) {
381 if (SSL_get_verify_result(peer->ssl) != X509_V_OK) {
382 debug(DBG_ERR, "tlsverifycert: basic validation failed");
383 while ((error = ERR_get_error()))
384 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
388 cert = SSL_get_peer_certificate(peer->ssl);
390 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
393 nm = X509_get_subject_name(cert);
396 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
399 e = X509_NAME_get_entry(nm, loc);
400 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
407 for (i = 0; i < l; i++)
412 if (l == strlen(peer->host) && !strncasecmp(peer->host, (char *)v, l)) {
413 debug(DBG_INFO, "tlsverifycert: Found cn matching host %s, All OK", peer->host);
416 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", peer->host);
422 void tlsconnect(struct server *server, struct timeval *when, char *text) {
426 debug(DBG_INFO, "tlsconnect called from %s", text);
427 pthread_mutex_lock(&server->lock);
428 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
429 /* already reconnected, nothing to do */
430 debug(DBG_INFO, "tlsconnect(%s): seems already reconnected", text);
431 pthread_mutex_unlock(&server->lock);
435 debug(DBG_INFO, "tlsconnect %s", text);
438 gettimeofday(&now, NULL);
439 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
440 if (server->connectionok) {
441 server->connectionok = 0;
443 } else if (elapsed < 5)
445 else if (elapsed < 600) {
446 debug(DBG_WARN, "tlsconnect: sleeping %lds", elapsed);
448 } else if (elapsed < 1000) {
449 debug(DBG_WARN, "tlsconnect: sleeping %ds", 900);
452 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
453 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->peer.host, server->peer.port);
454 if (server->sock >= 0)
456 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0) {
457 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
461 SSL_free(server->peer.ssl);
462 server->peer.ssl = SSL_new(ssl_ctx);
463 SSL_set_fd(server->peer.ssl, server->sock);
464 if (SSL_connect(server->peer.ssl) > 0 && tlsverifycert(&server->peer))
467 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->peer.host, server->peer.port);
468 gettimeofday(&server->lastconnecttry, NULL);
469 pthread_mutex_unlock(&server->lock);
472 unsigned char *radtlsget(SSL *ssl) {
474 unsigned char buf[4], *rad;
477 for (total = 0; total < 4; total += cnt) {
478 cnt = SSL_read(ssl, buf + total, 4 - total);
480 debug(DBG_ERR, "radtlsget: connection lost");
481 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
482 /* remote end sent close_notify, send one back */
492 debug(DBG_ERR, "radtlsget: malloc failed");
497 for (; total < len; total += cnt) {
498 cnt = SSL_read(ssl, rad + total, len - total);
500 debug(DBG_ERR, "radtlsget: connection lost");
501 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
502 /* remote end sent close_notify, send one back */
514 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
517 debug(DBG_INFO, "radtlsget: got %d bytes", total);
521 int clientradput(struct server *server, unsigned char *rad) {
525 struct timeval lastconnecttry;
528 if (server->peer.type == 'U') {
529 if (send(server->sock, rad, len, 0) >= 0) {
530 debug(DBG_INFO, "clienradput: sent UDP of length %d to %s port %s", len, server->peer.host, server->peer.port);
533 debug(DBG_WARN, "clientradput: send failed");
537 lastconnecttry = server->lastconnecttry;
538 while ((cnt = SSL_write(server->peer.ssl, rad, len)) <= 0) {
539 while ((error = ERR_get_error()))
540 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
541 tlsconnect(server, &lastconnecttry, "clientradput");
542 lastconnecttry = server->lastconnecttry;
545 server->connectionok = 1;
546 debug(DBG_INFO, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
547 cnt, len, server->peer.host);
551 int radsign(unsigned char *rad, unsigned char *sec) {
552 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
553 static unsigned char first = 1;
554 static EVP_MD_CTX mdctx;
558 pthread_mutex_lock(&lock);
560 EVP_MD_CTX_init(&mdctx);
564 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
565 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
566 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
567 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
569 pthread_mutex_unlock(&lock);
573 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
574 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
575 static unsigned char first = 1;
576 static EVP_MD_CTX mdctx;
577 unsigned char hash[EVP_MAX_MD_SIZE];
581 pthread_mutex_lock(&lock);
583 EVP_MD_CTX_init(&mdctx);
589 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
590 EVP_DigestUpdate(&mdctx, rad, 4) &&
591 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
592 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
593 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
594 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
596 !memcmp(hash, rad + 4, 16));
597 pthread_mutex_unlock(&lock);
601 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
602 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
603 static unsigned char first = 1;
604 static HMAC_CTX hmacctx;
606 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
608 pthread_mutex_lock(&lock);
610 HMAC_CTX_init(&hmacctx);
614 memcpy(auth, authattr, 16);
615 memset(authattr, 0, 16);
617 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
618 HMAC_Update(&hmacctx, rad, RADLEN(rad));
619 HMAC_Final(&hmacctx, hash, &md_len);
620 memcpy(authattr, auth, 16);
622 debug(DBG_WARN, "message auth computation failed");
623 pthread_mutex_unlock(&lock);
627 if (memcmp(auth, hash, 16)) {
628 debug(DBG_WARN, "message authenticator, wrong value");
629 pthread_mutex_unlock(&lock);
633 pthread_mutex_unlock(&lock);
637 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
638 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
639 static unsigned char first = 1;
640 static HMAC_CTX hmacctx;
646 pthread_mutex_lock(&lock);
648 HMAC_CTX_init(&hmacctx);
652 memset(authattrval, 0, 16);
654 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
655 HMAC_Update(&hmacctx, rad, RADLEN(rad));
656 HMAC_Final(&hmacctx, authattrval, &md_len);
658 debug(DBG_WARN, "message auth computation failed");
659 pthread_mutex_unlock(&lock);
663 pthread_mutex_unlock(&lock);
667 void sendrq(struct server *to, struct client *from, struct request *rq) {
670 pthread_mutex_lock(&to->newrq_mutex);
671 /* might simplify if only try nextid, might be ok */
672 for (i = to->nextid; i < MAX_REQUESTS; i++)
673 if (!to->requests[i].buf)
675 if (i == MAX_REQUESTS) {
676 for (i = 0; i < to->nextid; i++)
677 if (!to->requests[i].buf)
679 if (i == to->nextid) {
680 debug(DBG_WARN, "No room in queue, dropping request");
681 pthread_mutex_unlock(&to->newrq_mutex);
687 rq->buf[1] = (char)i;
688 debug(DBG_INFO, "sendrq: inserting packet with id %d in queue for %s", i, to->peer.host);
690 if (!createmessageauth(rq->buf, rq->messageauthattrval, to->peer.secret))
693 to->requests[i] = *rq;
697 debug(DBG_INFO, "signalling client writer");
698 pthread_cond_signal(&to->newrq_cond);
700 pthread_mutex_unlock(&to->newrq_mutex);
703 void sendreply(struct client *to, struct server *from, unsigned char *buf, struct sockaddr_storage *tosa) {
704 struct replyq *replyq = to->replyq;
706 pthread_mutex_lock(&replyq->count_mutex);
707 if (replyq->count == replyq->size) {
708 debug(DBG_WARN, "No room in queue, dropping request");
709 pthread_mutex_unlock(&replyq->count_mutex);
713 replyq->replies[replyq->count].buf = buf;
715 replyq->replies[replyq->count].tosa = *tosa;
718 if (replyq->count == 1) {
719 debug(DBG_INFO, "signalling client writer");
720 pthread_cond_signal(&replyq->count_cond);
722 pthread_mutex_unlock(&replyq->count_mutex);
725 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
726 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
727 static unsigned char first = 1;
728 static EVP_MD_CTX mdctx;
729 unsigned char hash[EVP_MAX_MD_SIZE], *input;
731 uint8_t i, offset = 0, out[128];
733 pthread_mutex_lock(&lock);
735 EVP_MD_CTX_init(&mdctx);
741 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
742 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
743 !EVP_DigestUpdate(&mdctx, input, 16) ||
744 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
746 pthread_mutex_unlock(&lock);
749 for (i = 0; i < 16; i++)
750 out[offset + i] = hash[i] ^ in[offset + i];
751 input = out + offset - 16;
756 memcpy(in, out, len);
757 pthread_mutex_unlock(&lock);
761 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
762 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
763 static unsigned char first = 1;
764 static EVP_MD_CTX mdctx;
765 unsigned char hash[EVP_MAX_MD_SIZE], *input;
767 uint8_t i, offset = 0, out[128];
769 pthread_mutex_lock(&lock);
771 EVP_MD_CTX_init(&mdctx);
777 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
778 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
779 !EVP_DigestUpdate(&mdctx, input, 16) ||
780 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
782 pthread_mutex_unlock(&lock);
785 for (i = 0; i < 16; i++)
786 out[offset + i] = hash[i] ^ in[offset + i];
792 memcpy(in, out, len);
793 pthread_mutex_unlock(&lock);
797 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
798 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
799 static unsigned char first = 1;
800 static EVP_MD_CTX mdctx;
801 unsigned char hash[EVP_MAX_MD_SIZE];
805 pthread_mutex_lock(&lock);
807 EVP_MD_CTX_init(&mdctx);
812 printf("msppencrypt auth in: ");
813 for (i = 0; i < 16; i++)
814 printf("%02x ", auth[i]);
817 printf("msppencrypt salt in: ");
818 for (i = 0; i < 2; i++)
819 printf("%02x ", salt[i]);
822 printf("msppencrypt in: ");
823 for (i = 0; i < len; i++)
824 printf("%02x ", text[i]);
828 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
829 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
830 !EVP_DigestUpdate(&mdctx, auth, 16) ||
831 !EVP_DigestUpdate(&mdctx, salt, 2) ||
832 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
833 pthread_mutex_unlock(&lock);
838 printf("msppencrypt hash: ");
839 for (i = 0; i < 16; i++)
840 printf("%02x ", hash[i]);
844 for (i = 0; i < 16; i++)
847 for (offset = 16; offset < len; offset += 16) {
849 printf("text + offset - 16 c(%d): ", offset / 16);
850 for (i = 0; i < 16; i++)
851 printf("%02x ", (text + offset - 16)[i]);
854 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
855 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
856 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
857 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
859 pthread_mutex_unlock(&lock);
863 printf("msppencrypt hash: ");
864 for (i = 0; i < 16; i++)
865 printf("%02x ", hash[i]);
869 for (i = 0; i < 16; i++)
870 text[offset + i] ^= hash[i];
874 printf("msppencrypt out: ");
875 for (i = 0; i < len; i++)
876 printf("%02x ", text[i]);
880 pthread_mutex_unlock(&lock);
884 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
885 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
886 static unsigned char first = 1;
887 static EVP_MD_CTX mdctx;
888 unsigned char hash[EVP_MAX_MD_SIZE];
893 pthread_mutex_lock(&lock);
895 EVP_MD_CTX_init(&mdctx);
900 printf("msppdecrypt auth in: ");
901 for (i = 0; i < 16; i++)
902 printf("%02x ", auth[i]);
905 printf("msppedecrypt salt in: ");
906 for (i = 0; i < 2; i++)
907 printf("%02x ", salt[i]);
910 printf("msppedecrypt in: ");
911 for (i = 0; i < len; i++)
912 printf("%02x ", text[i]);
916 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
917 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
918 !EVP_DigestUpdate(&mdctx, auth, 16) ||
919 !EVP_DigestUpdate(&mdctx, salt, 2) ||
920 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
921 pthread_mutex_unlock(&lock);
926 printf("msppedecrypt hash: ");
927 for (i = 0; i < 16; i++)
928 printf("%02x ", hash[i]);
932 for (i = 0; i < 16; i++)
933 plain[i] = text[i] ^ hash[i];
935 for (offset = 16; offset < len; offset += 16) {
937 printf("text + offset - 16 c(%d): ", offset / 16);
938 for (i = 0; i < 16; i++)
939 printf("%02x ", (text + offset - 16)[i]);
942 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
943 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
944 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
945 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
947 pthread_mutex_unlock(&lock);
951 printf("msppedecrypt hash: ");
952 for (i = 0; i < 16; i++)
953 printf("%02x ", hash[i]);
957 for (i = 0; i < 16; i++)
958 plain[offset + i] = text[offset + i] ^ hash[i];
961 memcpy(text, plain, len);
963 printf("msppedecrypt out: ");
964 for (i = 0; i < len; i++)
965 printf("%02x ", text[i]);
969 pthread_mutex_unlock(&lock);
973 struct server *id2server(char *id, uint8_t len) {
975 char **realm, *idrealm;
977 idrealm = strchr(id, '@');
985 for (i = 0; i < server_count; i++) {
986 for (realm = servers[i].realms; *realm; realm++) {
987 if ((strlen(*realm) == 1 && **realm == '*') ||
988 (strlen(*realm) == len && !memcmp(idrealm, *realm, len))) {
989 debug(DBG_INFO, "found matching realm: %s, host %s", *realm, servers[i].peer.host);
997 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1000 pthread_mutex_lock(&to->newrq_mutex);
1001 for (i = 0; i < MAX_REQUESTS; i++)
1002 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1004 pthread_mutex_unlock(&to->newrq_mutex);
1006 return i < MAX_REQUESTS;
1009 struct server *radsrv(struct request *rq, unsigned char *buf, struct client *from) {
1010 uint8_t code, id, *auth, *attr, attrvallen;
1011 uint8_t *usernameattr = NULL, *userpwdattr = NULL, *tunnelpwdattr = NULL, *messageauthattr = NULL;
1015 unsigned char newauth[16];
1020 code = *(uint8_t *)buf;
1021 id = *(uint8_t *)(buf + 1);
1023 auth = (uint8_t *)(buf + 4);
1025 debug(DBG_INFO, "radsrv: code %d, id %d, length %d", code, id, len);
1027 if (code != RAD_Access_Request) {
1028 debug(DBG_WARN, "radsrv: server currently accepts only access-requests, ignoring");
1036 left -= attr[RAD_Attr_Length];
1038 debug(DBG_WARN, "radsrv: attribute length exceeds packet length, ignoring packet");
1041 switch (attr[RAD_Attr_Type]) {
1042 case RAD_Attr_User_Name:
1043 usernameattr = attr;
1045 case RAD_Attr_User_Password:
1048 case RAD_Attr_Tunnel_Password:
1049 tunnelpwdattr = attr;
1051 case RAD_Attr_Message_Authenticator:
1052 messageauthattr = attr;
1055 attr += attr[RAD_Attr_Length];
1058 debug(DBG_WARN, "radsrv: malformed packet? remaining byte after last attribute");
1062 printf("radsrv: Username: ");
1063 for (i = 0; i < usernameattr[RAD_Attr_Length] - 2; i++)
1064 printf("%c", usernameattr[RAD_Attr_Value + i]);
1069 to = id2server((char *)&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1071 debug(DBG_WARN, "radsrv: ignoring request, don't know where to send it");
1075 if (rqinqueue(to, from, id)) {
1076 debug(DBG_WARN, "radsrv: ignoring request from host %s with id %d, already got one", from->peer.host, id);
1080 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1081 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1082 debug(DBG_WARN, "radsrv: message authentication failed");
1086 if (!RAND_bytes(newauth, 16)) {
1087 debug(DBG_WARN, "radsrv: failed to generate random auth");
1092 printauth("auth", auth);
1093 printauth("newauth", newauth);
1097 debug(DBG_INFO, "radsrv: found userpwdattr of length %d", userpwdattr[RAD_Attr_Length]);
1098 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1099 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1100 debug(DBG_WARN, "radsrv: invalid user password length");
1104 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1105 debug(DBG_WARN, "radsrv: cannot decrypt password");
1109 printf("radsrv: password: ");
1110 for (i = 0; i < attrvallen; i++)
1111 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1114 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1115 debug(DBG_WARN, "radsrv: cannot encrypt password");
1120 if (tunnelpwdattr) {
1121 debug(DBG_INFO, "radsrv: found tunnelpwdattr of length %d", tunnelpwdattr[RAD_Attr_Length]);
1122 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1123 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1124 debug(DBG_WARN, "radsrv: invalid user password length");
1128 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1129 debug(DBG_WARN, "radsrv: cannot decrypt password");
1133 printf("radsrv: password: ");
1134 for (i = 0; i < attrvallen; i++)
1135 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1138 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1139 debug(DBG_WARN, "radsrv: cannot encrypt password");
1147 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1148 memcpy(rq->origauth, auth, 16);
1149 memcpy(auth, newauth, 16);
1151 printauth("rq->origauth", (unsigned char *)rq->origauth);
1152 printauth("auth", auth);
1157 void *clientrd(void *arg) {
1158 struct server *server = (struct server *)arg;
1159 struct client *from;
1160 int i, left, subleft;
1161 unsigned char *buf, *messageauthattr, *subattr, *attr;
1162 struct sockaddr_storage fromsa;
1163 struct timeval lastconnecttry;
1168 lastconnecttry = server->lastconnecttry;
1169 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1170 if (!buf && server->peer.type == 'T') {
1171 tlsconnect(server, &lastconnecttry, "clientrd");
1175 server->connectionok = 1;
1177 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge) {
1178 debug(DBG_WARN, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1182 debug(DBG_INFO, "got message type: %d, id: %d", buf[0], buf[1]);
1184 i = buf[1]; /* i is the id */
1186 pthread_mutex_lock(&server->newrq_mutex);
1187 if (!server->requests[i].buf || !server->requests[i].tries) {
1188 pthread_mutex_unlock(&server->newrq_mutex);
1189 debug(DBG_WARN, "clientrd: no matching request sent with this id, ignoring");
1193 if (server->requests[i].received) {
1194 pthread_mutex_unlock(&server->newrq_mutex);
1195 debug(DBG_WARN, "clientrd: already received, ignoring");
1199 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1200 pthread_mutex_unlock(&server->newrq_mutex);
1201 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1205 from = server->requests[i].from;
1207 /* messageauthattr present? */
1208 messageauthattr = NULL;
1209 left = RADLEN(buf) - 20;
1212 left -= attr[RAD_Attr_Length];
1214 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1217 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1218 if (attr[RAD_Attr_Length] != 18) {
1219 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1222 memcpy(tmp, buf + 4, 16);
1223 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1224 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1225 debug(DBG_WARN, "clientrd: message authentication failed");
1228 memcpy(buf + 4, tmp, 16);
1229 debug(DBG_INFO, "clientrd: message auth ok");
1230 messageauthattr = attr;
1233 attr += attr[RAD_Attr_Length];
1236 /* handle MS MPPE */
1237 left = RADLEN(buf) - 20;
1240 left -= attr[RAD_Attr_Length];
1242 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1245 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1246 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { /* 311 == MS */
1247 subleft = attr[RAD_Attr_Length] - 6;
1249 while (subleft > 1) {
1250 subleft -= subattr[RAD_Attr_Length];
1253 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1254 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1256 debug(DBG_INFO, "clientrd: Got MS MPPE");
1257 if (subattr[RAD_Attr_Length] < 20)
1260 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)server->peer.secret,
1261 strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1262 debug(DBG_WARN, "clientrd: failed to decrypt msppe key");
1266 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)from->peer.secret,
1267 strlen(from->peer.secret), (unsigned char *)server->requests[i].origauth, subattr + 2)) {
1268 debug(DBG_WARN, "clientrd: failed to encrypt msppe key");
1273 debug(DBG_WARN, "clientrd: bad vendor specific attr or subattr length, ignoring packet");
1277 attr += attr[RAD_Attr_Length];
1280 /* once we set received = 1, requests[i] may be reused */
1281 buf[1] = (char)server->requests[i].origid;
1282 memcpy(buf + 4, server->requests[i].origauth, 16);
1284 printauth("origauth/buf+4", buf + 4);
1286 if (messageauthattr) {
1287 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1289 debug(DBG_INFO, "clientrd: computed messageauthattr");
1292 if (from->peer.type == 'U')
1293 fromsa = server->requests[i].fromsa;
1294 server->requests[i].received = 1;
1295 pthread_mutex_unlock(&server->newrq_mutex);
1297 if (!radsign(buf, (unsigned char *)from->peer.secret)) {
1298 debug(DBG_WARN, "clientrd: failed to sign message");
1302 printauth("signedorigauth/buf+4", buf + 4);
1304 debug(DBG_INFO, "clientrd: giving packet back to where it came from");
1305 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1309 void *clientwr(void *arg) {
1310 struct server *server = (struct server *)arg;
1312 pthread_t clientrdth;
1315 struct timeval now, lastsend;
1316 struct timespec timeout;
1318 memset(&lastsend, 0, sizeof(struct timeval));
1319 memset(&timeout, 0, sizeof(struct timespec));
1321 if (server->peer.type == 'U') {
1322 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1323 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1325 tlsconnect(server, NULL, "new client");
1327 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1328 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1331 pthread_mutex_lock(&server->newrq_mutex);
1332 if (!server->newrq) {
1333 gettimeofday(&now, NULL);
1334 if (timeout.tv_sec) {
1335 debug(DBG_INFO, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1336 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1338 } else if (options.statusserver) {
1339 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD;
1340 /* add random 0-7 seconds to timeout */
1341 RAND_bytes(&rnd, 1);
1342 timeout.tv_sec += rnd / 32;
1343 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1346 debug(DBG_INFO, "clientwr: waiting for new request");
1347 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1350 if (server->newrq) {
1351 debug(DBG_INFO, "clientwr: got new request");
1354 debug(DBG_INFO, "clientwr: request timer expired, processing request queue");
1355 pthread_mutex_unlock(&server->newrq_mutex);
1357 for (i = 0; i < MAX_REQUESTS; i++) {
1358 pthread_mutex_lock(&server->newrq_mutex);
1359 while (!server->requests[i].buf && i < MAX_REQUESTS)
1361 if (i == MAX_REQUESTS) {
1362 pthread_mutex_unlock(&server->newrq_mutex);
1365 rq = server->requests + i;
1368 debug(DBG_INFO, "clientwr: removing received packet from queue");
1370 /* setting this to NULL means that it can be reused */
1372 pthread_mutex_unlock(&server->newrq_mutex);
1376 gettimeofday(&now, NULL);
1377 if (now.tv_sec <= rq->expiry.tv_sec) {
1378 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1379 timeout.tv_sec = rq->expiry.tv_sec;
1380 pthread_mutex_unlock(&server->newrq_mutex);
1384 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1385 debug(DBG_INFO, "clientwr: removing expired packet from queue");
1387 /* setting this to NULL means that it can be reused */
1389 pthread_mutex_unlock(&server->newrq_mutex);
1392 pthread_mutex_unlock(&server->newrq_mutex);
1394 rq->expiry.tv_sec = now.tv_sec +
1395 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1396 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1397 timeout.tv_sec = rq->expiry.tv_sec;
1399 clientradput(server, server->requests[i].buf);
1400 gettimeofday(&lastsend, NULL);
1403 if (options.statusserver) {
1404 gettimeofday(&now, NULL);
1405 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1406 lastsend.tv_sec = now.tv_sec;
1407 debug(DBG_INFO, "clientwr: should send status to %s here", server->peer.host);
1413 void *udpserverwr(void *arg) {
1414 struct replyq *replyq = &udp_server_replyq;
1415 struct reply *reply = replyq->replies;
1417 pthread_mutex_lock(&replyq->count_mutex);
1419 while (!replyq->count) {
1420 debug(DBG_INFO, "udp server writer, waiting for signal");
1421 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1422 debug(DBG_INFO, "udp server writer, got signal");
1424 pthread_mutex_unlock(&replyq->count_mutex);
1426 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1427 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1428 debug(DBG_WARN, "sendudp: send failed");
1431 pthread_mutex_lock(&replyq->count_mutex);
1433 memmove(replyq->replies, replyq->replies + 1,
1434 replyq->count * sizeof(struct reply));
1438 void *udpserverrd(void *arg) {
1443 pthread_t udpserverwrth;
1445 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1446 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1448 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1449 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1451 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1452 debugx(1, DBG_ERR, "pthread_create failed");
1456 memset(&rq, 0, sizeof(struct request));
1457 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1458 to = radsrv(&rq, buf, fr);
1460 debug(DBG_WARN, "udpserverrd: ignoring request, no place to send it");
1463 sendrq(to, fr, &rq);
1467 void *tlsserverwr(void *arg) {
1469 unsigned long error;
1470 struct client *client = (struct client *)arg;
1471 struct replyq *replyq;
1473 debug(DBG_INFO, "tlsserverwr starting for %s", client->peer.host);
1474 replyq = client->replyq;
1475 pthread_mutex_lock(&replyq->count_mutex);
1477 while (!replyq->count) {
1478 if (client->peer.ssl) {
1479 debug(DBG_INFO, "tls server writer, waiting for signal");
1480 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1481 debug(DBG_INFO, "tls server writer, got signal");
1483 if (!client->peer.ssl) {
1484 /* ssl might have changed while waiting */
1485 pthread_mutex_unlock(&replyq->count_mutex);
1486 debug(DBG_INFO, "tlsserverwr: exiting as requested");
1490 pthread_mutex_unlock(&replyq->count_mutex);
1491 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1493 debug(DBG_INFO, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1494 cnt, RADLEN(replyq->replies->buf));
1496 while ((error = ERR_get_error()))
1497 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1498 free(replyq->replies->buf);
1500 pthread_mutex_lock(&replyq->count_mutex);
1502 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1506 void *tlsserverrd(void *arg) {
1509 unsigned long error;
1512 struct client *client = (struct client *)arg;
1513 pthread_t tlsserverwrth;
1516 debug(DBG_INFO, "tlsserverrd starting for %s", client->peer.host);
1517 ssl = client->peer.ssl;
1519 if (SSL_accept(ssl) <= 0) {
1520 while ((error = ERR_get_error()))
1521 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1522 debug(DBG_ERR, "SSL_accept failed");
1525 if (tlsverifycert(&client->peer)) {
1526 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1527 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1531 buf = radtlsget(client->peer.ssl);
1534 debug(DBG_INFO, "tlsserverrd: got Radius message from %s", client->peer.host);
1535 memset(&rq, 0, sizeof(struct request));
1536 to = radsrv(&rq, buf, client);
1538 debug(DBG_WARN, "tlsserverrd: ignoring request, no place to send it");
1541 sendrq(to, client, &rq);
1543 debug(DBG_ERR, "tlsserverrd: connection lost");
1544 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1545 client->peer.ssl = NULL;
1546 pthread_mutex_lock(&client->replyq->count_mutex);
1547 pthread_cond_signal(&client->replyq->count_cond);
1548 pthread_mutex_unlock(&client->replyq->count_mutex);
1549 debug(DBG_INFO, "tlsserverrd: waiting for writer to end");
1550 pthread_join(tlsserverwrth, NULL);
1554 s = SSL_get_fd(ssl);
1556 shutdown(s, SHUT_RDWR);
1558 debug(DBG_INFO, "tlsserverrd thread for %s exiting", client->peer.host);
1559 client->peer.ssl = NULL;
1564 pthread_t tlsserverth;
1566 struct sockaddr_storage from;
1567 size_t fromlen = sizeof(from);
1568 struct client *client;
1570 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1571 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1574 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1575 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1578 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1580 debug(DBG_WARN, "accept failed");
1583 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1585 client = find_client('T', (struct sockaddr *)&from, NULL);
1587 debug(DBG_WARN, "ignoring request, not a known TLS client");
1588 shutdown(snew, SHUT_RDWR);
1593 if (client->peer.ssl) {
1594 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1595 shutdown(snew, SHUT_RDWR);
1599 client->peer.ssl = SSL_new(ssl_ctx);
1600 SSL_set_fd(client->peer.ssl, snew);
1601 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1602 debug(DBG_ERR, "tlslistener: pthread_create failed");
1603 SSL_free(client->peer.ssl);
1604 shutdown(snew, SHUT_RDWR);
1606 client->peer.ssl = NULL;
1609 pthread_detach(tlsserverth);
1614 char *parsehostport(char *s, struct peer *peer) {
1619 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1623 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1625 debugx(1, DBG_ERR, "no ] matching initial [");
1629 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1632 debugx(1, DBG_ERR, "missing host/address");
1634 peer->host = stringcopy(field, p - field);
1637 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1638 debugx(1, DBG_ERR, "unexpected character after ]");
1641 /* port number or service name is specified */;
1643 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1645 debugx(1, DBG_ERR, "syntax error, : but no following port");
1646 peer->port = stringcopy(field, p - field);
1648 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1652 /* * is default, else longest match ... ";" used for separator */
1653 char *parserealmlist(char *s, struct server *server) {
1657 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1662 debugx(1, DBG_ERR, "realm list must be specified");
1664 server->realmdata = stringcopy(s, l);
1665 server->realms = malloc((1+n) * sizeof(char *));
1666 if (!server->realms)
1667 debugx(1, DBG_ERR, "malloc failed");
1668 server->realms[0] = server->realmdata;
1669 for (n = 1, i = 0; i < l; i++)
1670 if (server->realmdata[i] == ';') {
1671 server->realmdata[i] = '\0';
1672 server->realms[n++] = server->realmdata + i + 1;
1674 server->realms[n] = NULL;
1678 FILE *openconfigfile(const char *filename) {
1680 char pathname[100], *base;
1682 f = fopen(filename, "r");
1684 debug(DBG_INFO, "reading config file %s", filename);
1688 if (strlen(filename) + 1 <= sizeof(pathname)) {
1689 /* basename() might modify the string */
1690 strcpy(pathname, filename);
1691 base = basename(pathname);
1692 f = fopen(base, "r");
1696 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1698 debug(DBG_INFO, "reading config file %s", base);
1702 /* exactly one argument must be non-NULL */
1703 void getconfig(const char *serverfile, const char *clientfile) {
1706 char *p, *field, **r;
1707 struct client *client;
1708 struct server *server;
1710 int i, count, *ucount, *tcount;
1712 f = openconfigfile(serverfile ? serverfile : clientfile);
1714 ucount = &server_udp_count;
1715 tcount = &server_tls_count;
1717 ucount = &client_udp_count;
1718 tcount = &client_tls_count;
1720 while (fgets(line, 1024, f)) {
1721 for (p = line; *p == ' ' || *p == '\t'; p++);
1733 debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1738 count = server_count = server_udp_count + server_tls_count;
1739 servers = calloc(count, sizeof(struct server));
1741 debugx(1, DBG_ERR, "malloc failed");
1743 count = client_count = client_udp_count + client_tls_count;
1744 clients = calloc(count, sizeof(struct client));
1746 debugx(1, DBG_ERR, "malloc failed");
1749 if (client_udp_count) {
1750 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1751 if (!udp_server_replyq.replies)
1752 debugx(1, DBG_ERR, "malloc failed");
1753 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1754 udp_server_replyq.count = 0;
1755 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1756 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1760 for (i = 0; i < count && fgets(line, 1024, f);) {
1762 server = &servers[i];
1763 peer = &server->peer;
1765 client = &clients[i];
1766 peer = &client->peer;
1768 for (p = line; *p == ' ' || *p == '\t'; p++);
1769 if (*p == '#' || *p == '\n')
1771 peer->type = *p; /* we already know it must be U or T */
1772 for (p++; *p == ' ' || *p == '\t'; p++);
1773 p = parsehostport(p, peer);
1774 for (; *p == ' ' || *p == '\t'; p++);
1776 p = parserealmlist(p, server);
1777 for (; *p == ' ' || *p == '\t'; p++);
1780 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1782 /* no secret set and end of line, line is complete if TLS */
1783 if (peer->type == 'U')
1784 debugx(1, DBG_ERR, "secret must be specified for UDP");
1785 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1787 peer->secret = stringcopy(field, p - field);
1788 /* check that rest of line only white space */
1789 for (; *p == ' ' || *p == '\t'; p++);
1790 if (*p && *p != '\n')
1791 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1794 if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1795 (clientfile && !resolvepeer(&client->peer, 0)))
1796 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1799 pthread_mutex_init(&server->lock, NULL);
1801 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1802 if (!server->requests)
1803 debugx(1, DBG_ERR, "malloc failed");
1805 pthread_mutex_init(&server->newrq_mutex, NULL);
1806 pthread_cond_init(&server->newrq_cond, NULL);
1808 if (peer->type == 'U')
1809 client->replyq = &udp_server_replyq;
1811 client->replyq = malloc(sizeof(struct replyq));
1812 if (!client->replyq)
1813 debugx(1, DBG_ERR, "malloc failed");
1814 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1815 if (!client->replyq->replies)
1816 debugx(1, DBG_ERR, "malloc failed");
1817 client->replyq->size = MAX_REQUESTS;
1818 client->replyq->count = 0;
1819 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1820 pthread_cond_init(&client->replyq->count_cond, NULL);
1823 debug(DBG_INFO, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1825 debug(DBG_INFO, " with realms:");
1826 for (r = server->realms; *r; r++)
1827 debug(DBG_INFO, "\t%s", *r);
1834 struct peer *server_create(char type) {
1835 struct peer *server;
1838 server = malloc(sizeof(struct peer));
1840 debugx(1, DBG_ERR, "malloc failed");
1841 memset(server, 0, sizeof(struct peer));
1842 server->type = type;
1843 conf = (type == 'T' ? options.listentcp : options.listenudp);
1845 parsehostport(conf, server);
1846 if (!strcmp(server->host, "*")) {
1848 server->host = NULL;
1851 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1852 if (!resolvepeer(server, AI_PASSIVE))
1853 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1857 void getmainconfig(const char *configfile) {
1860 char *p, *opt, *endopt, *val, *endval;
1862 f = openconfigfile(configfile);
1863 memset(&options, 0, sizeof(options));
1865 while (fgets(line, 1024, f)) {
1866 for (p = line; *p == ' ' || *p == '\t'; p++);
1867 if (!*p || *p == '#' || *p == '\n')
1870 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1872 for (; *p == ' ' || *p == '\t'; p++);
1873 if (!*p || *p == '\n') {
1875 debugx(1, DBG_ERR, "error in %s, option %s has no value", configfile, opt);
1878 for (; *p && *p != '\n'; p++)
1879 if (*p != ' ' && *p != '\t')
1883 debug(DBG_INFO, "getmainconfig: %s = %s", opt, val);
1885 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1886 options.tlscacertificatefile = stringcopy(val, 0);
1889 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1890 options.tlscacertificatepath = stringcopy(val, 0);
1893 if (!strcasecmp(opt, "TLSCertificateFile")) {
1894 options.tlscertificatefile = stringcopy(val, 0);
1897 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1898 options.tlscertificatekeyfile = stringcopy(val, 0);
1901 if (!strcasecmp(opt, "TLSCertificateKeyPassword")) {
1902 options.tlscertificatekeypassword = stringcopy(val, 0);
1905 if (!strcasecmp(opt, "ListenUDP")) {
1906 options.listenudp = stringcopy(val, 0);
1909 if (!strcasecmp(opt, "ListenTCP")) {
1910 options.listentcp = stringcopy(val, 0);
1913 if (!strcasecmp(opt, "StatusServer")) {
1914 if (!strcasecmp(val, "on"))
1915 options.statusserver = 1;
1916 else if (strcasecmp(val, "off")) {
1917 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be on or off", configfile, opt, val);
1921 if (!strcasecmp(opt, "LogLevel")) {
1922 if (!strcasecmp(val, "1"))
1923 options.loglevel = DBG_ERR;
1924 else if (!strcasecmp(val, "2"))
1925 options.loglevel = DBG_WARN;
1926 else if (!strcasecmp(val, "3"))
1927 options.loglevel = DBG_INFO;
1929 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be 1, 2 or 3", configfile, opt, val);
1932 if (!strcasecmp(opt, "LogDestination")) {
1933 options.logdestination = stringcopy(val, 0);
1936 debugx(1, DBG_ERR, "error in %s, unknown option %s", configfile, opt);
1941 int main(int argc, char **argv) {
1942 pthread_t udpserverth;
1945 debug_set_level(DEBUG_LEVEL);
1946 getmainconfig(CONFIG_MAIN);
1947 debug_init("radsecproxy");
1948 if (options.loglevel)
1949 debug_set_level(options.loglevel);
1950 if (options.logdestination)
1951 debug_set_destination(options.logdestination);
1952 getconfig(CONFIG_SERVERS, NULL);
1953 getconfig(NULL, CONFIG_CLIENTS);
1955 if (client_udp_count) {
1956 udp_server_listen = server_create('U');
1957 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
1958 debugx(1, DBG_ERR, "pthread_create failed");
1961 if (client_tls_count || server_tls_count)
1962 ssl_ctx = ssl_init();
1964 for (i = 0; i < server_count; i++)
1965 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
1966 debugx(1, DBG_ERR, "pthread_create failed");
1968 if (client_tls_count) {
1969 tcp_server_listen = server_create('T');
1970 return tlslistener();
1973 /* just hang around doing nothing, anything to do here? */