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_DBG, "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_DBG, "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_DBG, "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_DBG, "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_DBG, "tlsconnect(%s): seems already reconnected", text);
431 pthread_mutex_unlock(&server->lock);
435 debug(DBG_DBG, "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_INFO, "tlsconnect: sleeping %lds", elapsed);
448 } else if (elapsed < 1000) {
449 debug(DBG_INFO, "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_DBG, "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_DBG, "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_DBG, "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_DBG, "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_DBG, "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_DBG, "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_DBG, "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];
1016 char attrstring[256];
1021 code = *(uint8_t *)buf;
1022 id = *(uint8_t *)(buf + 1);
1024 auth = (uint8_t *)(buf + 4);
1026 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1028 if (code != RAD_Access_Request) {
1029 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, ignoring");
1037 if (attr[RAD_Attr_Length] < 2) {
1038 debug(DBG_WARN, "radsrv: invalid attribute length, ignoring packet");
1041 left -= attr[RAD_Attr_Length];
1043 debug(DBG_WARN, "radsrv: attribute length exceeds packet length, ignoring packet");
1046 switch (attr[RAD_Attr_Type]) {
1047 case RAD_Attr_User_Name:
1048 usernameattr = attr;
1050 case RAD_Attr_User_Password:
1053 case RAD_Attr_Tunnel_Password:
1054 tunnelpwdattr = attr;
1056 case RAD_Attr_Message_Authenticator:
1057 messageauthattr = attr;
1060 attr += attr[RAD_Attr_Length];
1063 debug(DBG_WARN, "radsrv: malformed packet? remaining byte after last attribute");
1065 if (!usernameattr) {
1066 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1070 memcpy(attrstring, &usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1071 attrstring[usernameattr[RAD_Attr_Length] - 2] = '\0';
1072 debug(DBG_DBG, "Access Request with username: %s", attrstring);
1074 to = id2server((char *)&usernameattr[RAD_Attr_Value], usernameattr[RAD_Attr_Length] - 2);
1076 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1080 if (rqinqueue(to, from, id)) {
1081 debug(DBG_INFO, "radsrv: ignoring request from host %s with id %d, already got one", from->peer.host, id);
1085 if (messageauthattr && (messageauthattr[RAD_Attr_Length] != 18 ||
1086 !checkmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))) {
1087 debug(DBG_WARN, "radsrv: message authentication failed");
1091 if (!RAND_bytes(newauth, 16)) {
1092 debug(DBG_WARN, "radsrv: failed to generate random auth");
1097 printauth("auth", auth);
1098 printauth("newauth", newauth);
1102 debug(DBG_DBG, "radsrv: found userpwdattr of length %d", userpwdattr[RAD_Attr_Length]);
1103 attrvallen = userpwdattr[RAD_Attr_Length] - 2;
1104 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1105 debug(DBG_WARN, "radsrv: invalid user password length");
1109 if (!pwddecrypt(&userpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1110 debug(DBG_WARN, "radsrv: cannot decrypt password");
1114 printf("radsrv: password: ");
1115 for (i = 0; i < attrvallen; i++)
1116 printf("%02x ", userpwdattr[RAD_Attr_Value + i]);
1119 if (!pwdencrypt(&userpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1120 debug(DBG_WARN, "radsrv: cannot encrypt password");
1125 if (tunnelpwdattr) {
1126 debug(DBG_DBG, "radsrv: found tunnelpwdattr of length %d", tunnelpwdattr[RAD_Attr_Length]);
1127 attrvallen = tunnelpwdattr[RAD_Attr_Length] - 2;
1128 if (attrvallen < 16 || attrvallen > 128 || attrvallen % 16) {
1129 debug(DBG_WARN, "radsrv: invalid user password length");
1133 if (!pwddecrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, from->peer.secret, strlen(from->peer.secret), auth)) {
1134 debug(DBG_WARN, "radsrv: cannot decrypt password");
1138 printf("radsrv: password: ");
1139 for (i = 0; i < attrvallen; i++)
1140 printf("%02x ", tunnelpwdattr[RAD_Attr_Value + i]);
1143 if (!pwdencrypt(&tunnelpwdattr[RAD_Attr_Value], attrvallen, to->peer.secret, strlen(to->peer.secret), newauth)) {
1144 debug(DBG_WARN, "radsrv: cannot encrypt password");
1152 rq->messageauthattrval = (messageauthattr ? &messageauthattr[RAD_Attr_Value] : NULL);
1153 memcpy(rq->origauth, auth, 16);
1154 memcpy(auth, newauth, 16);
1156 printauth("rq->origauth", (unsigned char *)rq->origauth);
1157 printauth("auth", auth);
1162 void *clientrd(void *arg) {
1163 struct server *server = (struct server *)arg;
1164 struct client *from;
1165 int i, left, subleft;
1166 unsigned char *buf, *messageauthattr, *subattr, *attr;
1167 struct sockaddr_storage fromsa;
1168 struct timeval lastconnecttry;
1173 lastconnecttry = server->lastconnecttry;
1174 buf = (server->peer.type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->peer.ssl));
1175 if (!buf && server->peer.type == 'T') {
1176 tlsconnect(server, &lastconnecttry, "clientrd");
1180 server->connectionok = 1;
1182 i = buf[1]; /* i is the id */
1185 case RAD_Access_Accept:
1186 debug(DBG_DBG, "got Access Accept with id %d", i);
1188 case RAD_Access_Reject:
1189 debug(DBG_DBG, "got Access Reject with id %d", i);
1191 case RAD_Access_Challenge:
1192 debug(DBG_DBG, "got Access Challenge with id %d", i);
1195 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1199 pthread_mutex_lock(&server->newrq_mutex);
1200 if (!server->requests[i].buf || !server->requests[i].tries) {
1201 pthread_mutex_unlock(&server->newrq_mutex);
1202 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1206 if (server->requests[i].received) {
1207 pthread_mutex_unlock(&server->newrq_mutex);
1208 debug(DBG_INFO, "clientrd: already received, ignoring");
1212 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->peer.secret)) {
1213 pthread_mutex_unlock(&server->newrq_mutex);
1214 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1218 from = server->requests[i].from;
1220 /* messageauthattr present? */
1221 messageauthattr = NULL;
1222 left = RADLEN(buf) - 20;
1225 left -= attr[RAD_Attr_Length];
1227 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1230 if (attr[RAD_Attr_Type] == RAD_Attr_Message_Authenticator) {
1231 if (attr[RAD_Attr_Length] != 18) {
1232 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1235 memcpy(tmp, buf + 4, 16);
1236 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1237 if (!checkmessageauth(buf, &attr[RAD_Attr_Value], server->peer.secret)) {
1238 debug(DBG_WARN, "clientrd: message authentication failed");
1241 memcpy(buf + 4, tmp, 16);
1242 debug(DBG_DBG, "clientrd: message auth ok");
1243 messageauthattr = attr;
1246 attr += attr[RAD_Attr_Length];
1249 /* handle MS MPPE */
1250 left = RADLEN(buf) - 20;
1253 left -= attr[RAD_Attr_Length];
1255 debug(DBG_WARN, "clientrd: attribute length exceeds packet length, ignoring packet");
1258 if (attr[RAD_Attr_Type] == RAD_Attr_Vendor_Specific &&
1259 ((uint16_t *)attr)[1] == 0 && ntohs(((uint16_t *)attr)[2]) == 311) { /* 311 == MS */
1260 subleft = attr[RAD_Attr_Length] - 6;
1262 while (subleft > 1) {
1263 subleft -= subattr[RAD_Attr_Length];
1266 if (subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Send_Key &&
1267 subattr[RAD_Attr_Type] != RAD_VS_ATTR_MS_MPPE_Recv_Key)
1269 debug(DBG_DBG, "clientrd: Got MS MPPE");
1270 if (subattr[RAD_Attr_Length] < 20)
1273 if (!msmppdecrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)server->peer.secret,
1274 strlen(server->peer.secret), server->requests[i].buf + 4, subattr + 2)) {
1275 debug(DBG_WARN, "clientrd: failed to decrypt msppe key");
1279 if (!msmppencrypt(subattr + 4, subattr[RAD_Attr_Length] - 4, (unsigned char *)from->peer.secret,
1280 strlen(from->peer.secret), (unsigned char *)server->requests[i].origauth, subattr + 2)) {
1281 debug(DBG_WARN, "clientrd: failed to encrypt msppe key");
1286 debug(DBG_WARN, "clientrd: bad vendor specific attr or subattr length, ignoring packet");
1290 attr += attr[RAD_Attr_Length];
1293 /* log DBG_INFO that received access accept/reject and username attr from original request */
1295 /* once we set received = 1, requests[i] may be reused */
1296 buf[1] = (char)server->requests[i].origid;
1297 memcpy(buf + 4, server->requests[i].origauth, 16);
1299 printauth("origauth/buf+4", buf + 4);
1301 if (messageauthattr) {
1302 if (!createmessageauth(buf, &messageauthattr[RAD_Attr_Value], from->peer.secret))
1304 debug(DBG_DBG, "clientrd: computed messageauthattr");
1307 if (from->peer.type == 'U')
1308 fromsa = server->requests[i].fromsa;
1309 server->requests[i].received = 1;
1310 pthread_mutex_unlock(&server->newrq_mutex);
1312 if (!radsign(buf, (unsigned char *)from->peer.secret)) {
1313 debug(DBG_WARN, "clientrd: failed to sign message");
1317 printauth("signedorigauth/buf+4", buf + 4);
1319 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1320 sendreply(from, server, buf, from->peer.type == 'U' ? &fromsa : NULL);
1324 void *clientwr(void *arg) {
1325 struct server *server = (struct server *)arg;
1327 pthread_t clientrdth;
1330 struct timeval now, lastsend;
1331 struct timespec timeout;
1333 memset(&lastsend, 0, sizeof(struct timeval));
1334 memset(&timeout, 0, sizeof(struct timespec));
1336 if (server->peer.type == 'U') {
1337 if ((server->sock = connecttoserver(server->peer.addrinfo)) < 0)
1338 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1340 tlsconnect(server, NULL, "new client");
1342 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1343 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1346 pthread_mutex_lock(&server->newrq_mutex);
1347 if (!server->newrq) {
1348 gettimeofday(&now, NULL);
1349 if (timeout.tv_sec) {
1350 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1351 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1353 } else if (options.statusserver) {
1354 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD;
1355 /* add random 0-7 seconds to timeout */
1356 RAND_bytes(&rnd, 1);
1357 timeout.tv_sec += rnd / 32;
1358 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1361 debug(DBG_DBG, "clientwr: waiting for new request");
1362 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1365 if (server->newrq) {
1366 debug(DBG_DBG, "clientwr: got new request");
1369 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1370 pthread_mutex_unlock(&server->newrq_mutex);
1372 for (i = 0; i < MAX_REQUESTS; i++) {
1373 pthread_mutex_lock(&server->newrq_mutex);
1374 while (!server->requests[i].buf && i < MAX_REQUESTS)
1376 if (i == MAX_REQUESTS) {
1377 pthread_mutex_unlock(&server->newrq_mutex);
1380 rq = server->requests + i;
1383 debug(DBG_DBG, "clientwr: removing received packet from queue");
1385 /* setting this to NULL means that it can be reused */
1387 pthread_mutex_unlock(&server->newrq_mutex);
1391 gettimeofday(&now, NULL);
1392 if (now.tv_sec <= rq->expiry.tv_sec) {
1393 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1394 timeout.tv_sec = rq->expiry.tv_sec;
1395 pthread_mutex_unlock(&server->newrq_mutex);
1399 if (rq->tries == (server->peer.type == 'T' ? 1 : REQUEST_RETRIES)) {
1400 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1402 /* setting this to NULL means that it can be reused */
1404 pthread_mutex_unlock(&server->newrq_mutex);
1407 pthread_mutex_unlock(&server->newrq_mutex);
1409 rq->expiry.tv_sec = now.tv_sec +
1410 (server->peer.type == 'T' ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1411 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1412 timeout.tv_sec = rq->expiry.tv_sec;
1414 clientradput(server, server->requests[i].buf);
1415 gettimeofday(&lastsend, NULL);
1418 if (options.statusserver) {
1419 gettimeofday(&now, NULL);
1420 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1421 lastsend.tv_sec = now.tv_sec;
1422 debug(DBG_DBG, "clientwr: should send status to %s here", server->peer.host);
1428 void *udpserverwr(void *arg) {
1429 struct replyq *replyq = &udp_server_replyq;
1430 struct reply *reply = replyq->replies;
1432 pthread_mutex_lock(&replyq->count_mutex);
1434 while (!replyq->count) {
1435 debug(DBG_DBG, "udp server writer, waiting for signal");
1436 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1437 debug(DBG_DBG, "udp server writer, got signal");
1439 pthread_mutex_unlock(&replyq->count_mutex);
1441 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1442 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1443 debug(DBG_WARN, "sendudp: send failed");
1446 pthread_mutex_lock(&replyq->count_mutex);
1448 memmove(replyq->replies, replyq->replies + 1,
1449 replyq->count * sizeof(struct reply));
1453 void *udpserverrd(void *arg) {
1458 pthread_t udpserverwrth;
1460 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1461 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1463 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1464 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1466 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1467 debugx(1, DBG_ERR, "pthread_create failed");
1471 memset(&rq, 0, sizeof(struct request));
1472 buf = radudpget(udp_server_sock, &fr, NULL, &rq.fromsa);
1473 to = radsrv(&rq, buf, fr);
1475 debug(DBG_INFO, "udpserverrd: ignoring request, no place to send it");
1478 sendrq(to, fr, &rq);
1482 void *tlsserverwr(void *arg) {
1484 unsigned long error;
1485 struct client *client = (struct client *)arg;
1486 struct replyq *replyq;
1488 debug(DBG_DBG, "tlsserverwr starting for %s", client->peer.host);
1489 replyq = client->replyq;
1490 pthread_mutex_lock(&replyq->count_mutex);
1492 while (!replyq->count) {
1493 if (client->peer.ssl) {
1494 debug(DBG_DBG, "tls server writer, waiting for signal");
1495 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1496 debug(DBG_DBG, "tls server writer, got signal");
1498 if (!client->peer.ssl) {
1499 /* ssl might have changed while waiting */
1500 pthread_mutex_unlock(&replyq->count_mutex);
1501 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1505 pthread_mutex_unlock(&replyq->count_mutex);
1506 cnt = SSL_write(client->peer.ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1508 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1509 cnt, RADLEN(replyq->replies->buf));
1511 while ((error = ERR_get_error()))
1512 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1513 free(replyq->replies->buf);
1515 pthread_mutex_lock(&replyq->count_mutex);
1517 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1521 void *tlsserverrd(void *arg) {
1524 unsigned long error;
1527 struct client *client = (struct client *)arg;
1528 pthread_t tlsserverwrth;
1531 debug(DBG_DBG, "tlsserverrd starting for %s", client->peer.host);
1532 ssl = client->peer.ssl;
1534 if (SSL_accept(ssl) <= 0) {
1535 while ((error = ERR_get_error()))
1536 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1537 debug(DBG_ERR, "SSL_accept failed");
1540 if (tlsverifycert(&client->peer)) {
1541 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1542 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1546 buf = radtlsget(client->peer.ssl);
1549 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->peer.host);
1550 memset(&rq, 0, sizeof(struct request));
1551 to = radsrv(&rq, buf, client);
1553 debug(DBG_INFO, "tlsserverrd: ignoring request, no place to send it");
1556 sendrq(to, client, &rq);
1558 debug(DBG_ERR, "tlsserverrd: connection lost");
1559 /* stop writer by setting peer.ssl to NULL and give signal in case waiting for data */
1560 client->peer.ssl = NULL;
1561 pthread_mutex_lock(&client->replyq->count_mutex);
1562 pthread_cond_signal(&client->replyq->count_cond);
1563 pthread_mutex_unlock(&client->replyq->count_mutex);
1564 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1565 pthread_join(tlsserverwrth, NULL);
1569 s = SSL_get_fd(ssl);
1571 shutdown(s, SHUT_RDWR);
1573 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->peer.host);
1574 client->peer.ssl = NULL;
1579 pthread_t tlsserverth;
1581 struct sockaddr_storage from;
1582 size_t fromlen = sizeof(from);
1583 struct client *client;
1585 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1586 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1589 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1590 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1593 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1595 debug(DBG_WARN, "accept failed");
1598 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1600 client = find_client('T', (struct sockaddr *)&from, NULL);
1602 debug(DBG_WARN, "ignoring request, not a known TLS client");
1603 shutdown(snew, SHUT_RDWR);
1608 if (client->peer.ssl) {
1609 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1610 shutdown(snew, SHUT_RDWR);
1614 client->peer.ssl = SSL_new(ssl_ctx);
1615 SSL_set_fd(client->peer.ssl, snew);
1616 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1617 debug(DBG_ERR, "tlslistener: pthread_create failed");
1618 SSL_free(client->peer.ssl);
1619 shutdown(snew, SHUT_RDWR);
1621 client->peer.ssl = NULL;
1624 pthread_detach(tlsserverth);
1629 char *parsehostport(char *s, struct peer *peer) {
1634 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1638 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1640 debugx(1, DBG_ERR, "no ] matching initial [");
1644 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1647 debugx(1, DBG_ERR, "missing host/address");
1649 peer->host = stringcopy(field, p - field);
1652 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1653 debugx(1, DBG_ERR, "unexpected character after ]");
1656 /* port number or service name is specified */;
1658 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1660 debugx(1, DBG_ERR, "syntax error, : but no following port");
1661 peer->port = stringcopy(field, p - field);
1663 peer->port = stringcopy(peer->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1667 /* * is default, else longest match ... ";" used for separator */
1668 char *parserealmlist(char *s, struct server *server) {
1672 for (p = s, n = 1; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++)
1677 debugx(1, DBG_ERR, "realm list must be specified");
1679 server->realmdata = stringcopy(s, l);
1680 server->realms = malloc((1+n) * sizeof(char *));
1681 if (!server->realms)
1682 debugx(1, DBG_ERR, "malloc failed");
1683 server->realms[0] = server->realmdata;
1684 for (n = 1, i = 0; i < l; i++)
1685 if (server->realmdata[i] == ';') {
1686 server->realmdata[i] = '\0';
1687 server->realms[n++] = server->realmdata + i + 1;
1689 server->realms[n] = NULL;
1693 FILE *openconfigfile(const char *filename) {
1695 char pathname[100], *base;
1697 f = fopen(filename, "r");
1699 debug(DBG_DBG, "reading config file %s", filename);
1703 if (strlen(filename) + 1 <= sizeof(pathname)) {
1704 /* basename() might modify the string */
1705 strcpy(pathname, filename);
1706 base = basename(pathname);
1707 f = fopen(base, "r");
1711 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1713 debug(DBG_DBG, "reading config file %s", base);
1717 /* exactly one argument must be non-NULL */
1718 void getconfig(const char *serverfile, const char *clientfile) {
1721 char *p, *field, **r;
1722 struct client *client;
1723 struct server *server;
1725 int i, count, *ucount, *tcount;
1727 f = openconfigfile(serverfile ? serverfile : clientfile);
1729 ucount = &server_udp_count;
1730 tcount = &server_tls_count;
1732 ucount = &client_udp_count;
1733 tcount = &client_tls_count;
1735 while (fgets(line, 1024, f)) {
1736 for (p = line; *p == ' ' || *p == '\t'; p++);
1748 debugx(1, DBG_ERR, "type must be U or T, got %c", *p);
1753 count = server_count = server_udp_count + server_tls_count;
1754 servers = calloc(count, sizeof(struct server));
1756 debugx(1, DBG_ERR, "malloc failed");
1758 count = client_count = client_udp_count + client_tls_count;
1759 clients = calloc(count, sizeof(struct client));
1761 debugx(1, DBG_ERR, "malloc failed");
1764 if (client_udp_count) {
1765 udp_server_replyq.replies = malloc(client_udp_count * MAX_REQUESTS * sizeof(struct reply));
1766 if (!udp_server_replyq.replies)
1767 debugx(1, DBG_ERR, "malloc failed");
1768 udp_server_replyq.size = client_udp_count * MAX_REQUESTS;
1769 udp_server_replyq.count = 0;
1770 pthread_mutex_init(&udp_server_replyq.count_mutex, NULL);
1771 pthread_cond_init(&udp_server_replyq.count_cond, NULL);
1775 for (i = 0; i < count && fgets(line, 1024, f);) {
1777 server = &servers[i];
1778 peer = &server->peer;
1780 client = &clients[i];
1781 peer = &client->peer;
1783 for (p = line; *p == ' ' || *p == '\t'; p++);
1784 if (*p == '#' || *p == '\n')
1786 peer->type = *p; /* we already know it must be U or T */
1787 for (p++; *p == ' ' || *p == '\t'; p++);
1788 p = parsehostport(p, peer);
1789 for (; *p == ' ' || *p == '\t'; p++);
1791 p = parserealmlist(p, server);
1792 for (; *p == ' ' || *p == '\t'; p++);
1795 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1797 /* no secret set and end of line, line is complete if TLS */
1798 if (peer->type == 'U')
1799 debugx(1, DBG_ERR, "secret must be specified for UDP");
1800 peer->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
1802 peer->secret = stringcopy(field, p - field);
1803 /* check that rest of line only white space */
1804 for (; *p == ' ' || *p == '\t'; p++);
1805 if (*p && *p != '\n')
1806 debugx(1, DBG_ERR, "max 4 fields per line, found a 5th");
1809 if ((serverfile && !resolvepeer(&server->peer, 0)) ||
1810 (clientfile && !resolvepeer(&client->peer, 0)))
1811 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", peer->host, peer->port);
1814 pthread_mutex_init(&server->lock, NULL);
1816 server->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1817 if (!server->requests)
1818 debugx(1, DBG_ERR, "malloc failed");
1820 pthread_mutex_init(&server->newrq_mutex, NULL);
1821 pthread_cond_init(&server->newrq_cond, NULL);
1823 if (peer->type == 'U')
1824 client->replyq = &udp_server_replyq;
1826 client->replyq = malloc(sizeof(struct replyq));
1827 if (!client->replyq)
1828 debugx(1, DBG_ERR, "malloc failed");
1829 client->replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1830 if (!client->replyq->replies)
1831 debugx(1, DBG_ERR, "malloc failed");
1832 client->replyq->size = MAX_REQUESTS;
1833 client->replyq->count = 0;
1834 pthread_mutex_init(&client->replyq->count_mutex, NULL);
1835 pthread_cond_init(&client->replyq->count_cond, NULL);
1838 debug(DBG_DBG, "got type %c, host %s, port %s, secret %s", peer->type, peer->host, peer->port, peer->secret);
1840 debug(DBG_DBG, " with realms:");
1841 for (r = server->realms; *r; r++)
1842 debug(DBG_DBG, "\t%s", *r);
1849 struct peer *server_create(char type) {
1850 struct peer *server;
1853 server = malloc(sizeof(struct peer));
1855 debugx(1, DBG_ERR, "malloc failed");
1856 memset(server, 0, sizeof(struct peer));
1857 server->type = type;
1858 conf = (type == 'T' ? options.listentcp : options.listenudp);
1860 parsehostport(conf, server);
1861 if (!strcmp(server->host, "*")) {
1863 server->host = NULL;
1866 server->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1867 if (!resolvepeer(server, AI_PASSIVE))
1868 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", server->host, server->port);
1872 void getmainconfig(const char *configfile) {
1875 char *p, *opt, *endopt, *val, *endval;
1877 f = openconfigfile(configfile);
1878 memset(&options, 0, sizeof(options));
1880 while (fgets(line, 1024, f)) {
1881 for (p = line; *p == ' ' || *p == '\t'; p++);
1882 if (!*p || *p == '#' || *p == '\n')
1885 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1887 for (; *p == ' ' || *p == '\t'; p++);
1888 if (!*p || *p == '\n') {
1890 debugx(1, DBG_ERR, "error in %s, option %s has no value", configfile, opt);
1893 for (; *p && *p != '\n'; p++)
1894 if (*p != ' ' && *p != '\t')
1898 debug(DBG_DBG, "getmainconfig: %s = %s", opt, val);
1900 if (!strcasecmp(opt, "TLSCACertificateFile")) {
1901 options.tlscacertificatefile = stringcopy(val, 0);
1904 if (!strcasecmp(opt, "TLSCACertificatePath")) {
1905 options.tlscacertificatepath = stringcopy(val, 0);
1908 if (!strcasecmp(opt, "TLSCertificateFile")) {
1909 options.tlscertificatefile = stringcopy(val, 0);
1912 if (!strcasecmp(opt, "TLSCertificateKeyFile")) {
1913 options.tlscertificatekeyfile = stringcopy(val, 0);
1916 if (!strcasecmp(opt, "TLSCertificateKeyPassword")) {
1917 options.tlscertificatekeypassword = stringcopy(val, 0);
1920 if (!strcasecmp(opt, "ListenUDP")) {
1921 options.listenudp = stringcopy(val, 0);
1924 if (!strcasecmp(opt, "ListenTCP")) {
1925 options.listentcp = stringcopy(val, 0);
1928 if (!strcasecmp(opt, "StatusServer")) {
1929 if (!strcasecmp(val, "on"))
1930 options.statusserver = 1;
1931 else if (strcasecmp(val, "off")) {
1932 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be on or off", configfile, opt, val);
1936 if (!strcasecmp(opt, "LogLevel")) {
1937 if (strlen(val) != 1 || *val < '1' || *val > '4')
1938 debugx(1, DBG_ERR, "error in %s, value of option %s is %s, must be 1, 2, 3 or 4", configfile, opt, val);
1939 options.loglevel = *val - '0';
1942 if (!strcasecmp(opt, "LogDestination")) {
1943 options.logdestination = stringcopy(val, 0);
1946 debugx(1, DBG_ERR, "error in %s, unknown option %s", configfile, opt);
1951 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel) {
1954 while ((c = getopt(argc, argv, "d:f")) != -1) {
1957 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
1958 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
1959 *loglevel = *optarg - '0';
1968 if (!(argc - optind))
1972 debug(DBG_ERR, "Usage:\n%s [ -f ] [ -d debuglevel ]", argv[0]);
1976 int main(int argc, char **argv) {
1977 pthread_t udpserverth;
1979 uint8_t foreground = 0, loglevel = 0;
1981 debug_init("radsecproxy");
1982 debug_set_level(DEBUG_LEVEL);
1983 getargs(argc, argv, &foreground, &loglevel);
1985 debug_set_level(loglevel);
1986 getmainconfig(CONFIG_MAIN);
1988 options.loglevel = loglevel;
1989 else if (options.loglevel)
1990 debug_set_level(options.loglevel);
1992 options.logdestination = NULL;
1994 if (!options.logdestination)
1995 options.logdestination = "x-syslog://";
1996 debug_set_destination(options.logdestination);
1998 getconfig(CONFIG_SERVERS, NULL);
1999 getconfig(NULL, CONFIG_CLIENTS);
2001 if (!foreground && (daemon(0, 0) < 0))
2002 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2004 if (client_udp_count) {
2005 udp_server_listen = server_create('U');
2006 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2007 debugx(1, DBG_ERR, "pthread_create failed");
2010 if (client_tls_count || server_tls_count)
2011 ssl_ctx = ssl_init();
2013 for (i = 0; i < server_count; i++)
2014 if (pthread_create(&servers[i].clientth, NULL, clientwr, (void *)&servers[i]))
2015 debugx(1, DBG_ERR, "pthread_create failed");
2017 if (client_tls_count) {
2018 tcp_server_listen = server_create('T');
2019 return tlslistener();
2022 /* just hang around doing nothing, anything to do here? */