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.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
32 #include <sys/socket.h>
33 #include <netinet/in.h>
41 #include <openssl/ssl.h>
42 #include <openssl/rand.h>
43 #include <openssl/err.h>
44 #include <openssl/md5.h>
45 #include <openssl/hmac.h>
47 #include "radsecproxy.h"
49 static struct options options;
50 static struct clsrvconf *clconfs = NULL;
51 static struct clsrvconf *srvconfs = NULL;
52 static struct realm *realms = NULL;
53 static struct tls *tls = NULL;
55 static int client_udp_count = 0;
56 static int client_tls_count = 0;
57 static int clconf_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
60 static int srvconf_count = 0;
61 static int realm_count = 0;
62 static int tls_count = 0;
64 static struct clsrvconf *tcp_server_listen;
65 static struct clsrvconf *udp_server_listen;
66 static struct replyq *udp_server_replyq = NULL;
67 static int udp_server_sock = -1;
68 static pthread_mutex_t *ssl_locks;
69 static long *ssl_lock_count;
73 /* callbacks for making OpenSSL thread safe */
74 unsigned long ssl_thread_id() {
75 return (unsigned long)pthread_self();
78 void ssl_locking_callback(int mode, int type, const char *file, int line) {
79 if (mode & CRYPTO_LOCK) {
80 pthread_mutex_lock(&ssl_locks[type]);
81 ssl_lock_count[type]++;
83 pthread_mutex_unlock(&ssl_locks[type]);
86 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
87 int pwdlen = strlen(userdata);
88 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
90 memcpy(buf, userdata, pwdlen);
94 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
99 err_cert = X509_STORE_CTX_get_current_cert(ctx);
100 err = X509_STORE_CTX_get_error(ctx);
101 depth = X509_STORE_CTX_get_error_depth(ctx);
103 if (depth > MAX_CERT_DEPTH) {
105 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
106 X509_STORE_CTX_set_error(ctx, err);
110 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
111 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
114 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
115 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
116 debug(DBG_WARN, "\tIssuer=%s", buf);
118 case X509_V_ERR_CERT_NOT_YET_VALID:
119 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
120 debug(DBG_WARN, "\tCertificate not yet valid");
122 case X509_V_ERR_CERT_HAS_EXPIRED:
123 debug(DBG_WARN, "Certificate has expired");
125 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
126 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
131 printf("certificate verify returns %d\n", ok);
137 void printauth(char *s, unsigned char *t) {
140 for (i = 0; i < 16; i++)
141 printf("%02x ", t[i]);
146 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
147 struct addrinfo hints, *addrinfo;
149 memset(&hints, 0, sizeof(hints));
150 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
151 hints.ai_family = AF_UNSPEC;
152 hints.ai_flags = ai_flags;
153 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
154 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
159 freeaddrinfo(conf->addrinfo);
160 conf->addrinfo = addrinfo;
164 int connecttoserver(struct addrinfo *addrinfo) {
166 struct addrinfo *res;
169 for (res = addrinfo; res; res = res->ai_next) {
170 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
172 debug(DBG_WARN, "connecttoserver: socket failed");
175 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
177 debug(DBG_WARN, "connecttoserver: connect failed");
184 int bindtoaddr(struct addrinfo *addrinfo) {
186 struct addrinfo *res;
188 for (res = addrinfo; res; res = res->ai_next) {
189 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
191 debug(DBG_WARN, "bindtoaddr: socket failed");
194 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
195 if (!bind(s, res->ai_addr, res->ai_addrlen))
197 debug(DBG_WARN, "bindtoaddr: bind failed");
203 /* returns the peer with matching address, or NULL */
204 /* if peer argument is not NULL, we only check that one client */
205 struct clsrvconf *find_peer(char type, struct sockaddr *addr, struct clsrvconf *confs, int count) {
206 struct sockaddr_in6 *sa6 = NULL;
207 struct in_addr *a4 = NULL;
209 struct addrinfo *res;
211 if (addr->sa_family == AF_INET6) {
212 sa6 = (struct sockaddr_in6 *)addr;
213 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
214 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
216 a4 = &((struct sockaddr_in *)addr)->sin_addr;
218 for (i = 0; i < count; i++) {
219 if (confs->type == type)
220 for (res = confs->addrinfo; res; res = res->ai_next)
221 if ((a4 && res->ai_family == AF_INET &&
222 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
223 (sa6 && res->ai_family == AF_INET6 &&
224 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
231 /* exactly one of client and server must be non-NULL */
232 /* should probably take peer list (client(s) or server(s)) as argument instead */
233 /* if *peer == NULL we return who we received from, else require it to be from peer */
234 /* return from in sa if not NULL */
235 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
236 int cnt, len, confcount;
237 unsigned char buf[65536], *rad;
238 struct sockaddr_storage from;
239 socklen_t fromlen = sizeof(from);
240 struct clsrvconf *confs, *p;
243 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
245 debug(DBG_WARN, "radudpget: recv failed");
248 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
251 debug(DBG_WARN, "radudpget: packet too small");
257 debug(DBG_WARN, "radudpget: length too small");
262 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
266 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
271 confs = (*client)->conf;
273 confcount = clconf_count;
279 confs = (*server)->conf;
281 confcount = srvconf_count;
285 p = find_peer('U', (struct sockaddr *)&from, confs, confcount);
287 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
294 debug(DBG_ERR, "radudpget: malloc failed");
296 memcpy(rad, buf, len);
297 if (client && !*client)
298 *client = p->clients;
299 else if (server && !*server)
300 *server = p->servers;
306 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
314 if (SSL_get_verify_result(ssl) != X509_V_OK) {
315 debug(DBG_ERR, "tlsverifycert: basic validation failed");
316 while ((error = ERR_get_error()))
317 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
321 cert = SSL_get_peer_certificate(ssl);
323 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
326 nm = X509_get_subject_name(cert);
329 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
332 e = X509_NAME_get_entry(nm, loc);
333 l = ASN1_STRING_to_UTF8(&v, X509_NAME_ENTRY_get_data(e));
340 for (i = 0; i < l; i++)
345 if (l == strlen(conf->host) && !strncasecmp(conf->host, (char *)v, l)) {
346 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s, All OK", conf->host);
349 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
355 void tlsconnect(struct server *server, struct timeval *when, char *text) {
359 debug(DBG_DBG, "tlsconnect called from %s", text);
360 pthread_mutex_lock(&server->lock);
361 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
362 /* already reconnected, nothing to do */
363 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
364 pthread_mutex_unlock(&server->lock);
368 debug(DBG_DBG, "tlsconnect %s", text);
371 gettimeofday(&now, NULL);
372 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
373 if (server->connectionok) {
374 server->connectionok = 0;
376 } else if (elapsed < 5)
378 else if (elapsed < 300) {
379 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
381 } else if (elapsed < 100000) {
382 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
385 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
386 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
387 if (server->sock >= 0)
389 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
390 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
394 SSL_free(server->ssl);
395 server->ssl = SSL_new(server->conf->ssl_ctx);
396 SSL_set_fd(server->ssl, server->sock);
397 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
400 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
401 gettimeofday(&server->lastconnecttry, NULL);
402 pthread_mutex_unlock(&server->lock);
405 unsigned char *radtlsget(SSL *ssl) {
407 unsigned char buf[4], *rad;
410 for (total = 0; total < 4; total += cnt) {
411 cnt = SSL_read(ssl, buf + total, 4 - total);
413 debug(DBG_ERR, "radtlsget: connection lost");
414 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
415 /* remote end sent close_notify, send one back */
425 debug(DBG_ERR, "radtlsget: malloc failed");
430 for (; total < len; total += cnt) {
431 cnt = SSL_read(ssl, rad + total, len - total);
433 debug(DBG_ERR, "radtlsget: connection lost");
434 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
435 /* remote end sent close_notify, send one back */
447 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
450 debug(DBG_DBG, "radtlsget: got %d bytes", total);
454 int clientradput(struct server *server, unsigned char *rad) {
458 struct timeval lastconnecttry;
461 if (server->conf->type == 'U') {
462 if (send(server->sock, rad, len, 0) >= 0) {
463 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
466 debug(DBG_WARN, "clientradput: send failed");
470 lastconnecttry = server->lastconnecttry;
471 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
472 while ((error = ERR_get_error()))
473 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
474 tlsconnect(server, &lastconnecttry, "clientradput");
475 lastconnecttry = server->lastconnecttry;
478 server->connectionok = 1;
479 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
480 cnt, len, server->conf->host);
484 int radsign(unsigned char *rad, unsigned char *sec) {
485 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
486 static unsigned char first = 1;
487 static EVP_MD_CTX mdctx;
491 pthread_mutex_lock(&lock);
493 EVP_MD_CTX_init(&mdctx);
497 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
498 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
499 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
500 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
502 pthread_mutex_unlock(&lock);
506 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
507 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
508 static unsigned char first = 1;
509 static EVP_MD_CTX mdctx;
510 unsigned char hash[EVP_MAX_MD_SIZE];
514 pthread_mutex_lock(&lock);
516 EVP_MD_CTX_init(&mdctx);
522 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
523 EVP_DigestUpdate(&mdctx, rad, 4) &&
524 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
525 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
526 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
527 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
529 !memcmp(hash, rad + 4, 16));
530 pthread_mutex_unlock(&lock);
534 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
535 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
536 static unsigned char first = 1;
537 static HMAC_CTX hmacctx;
539 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
541 pthread_mutex_lock(&lock);
543 HMAC_CTX_init(&hmacctx);
547 memcpy(auth, authattr, 16);
548 memset(authattr, 0, 16);
550 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
551 HMAC_Update(&hmacctx, rad, RADLEN(rad));
552 HMAC_Final(&hmacctx, hash, &md_len);
553 memcpy(authattr, auth, 16);
555 debug(DBG_WARN, "message auth computation failed");
556 pthread_mutex_unlock(&lock);
560 if (memcmp(auth, hash, 16)) {
561 debug(DBG_WARN, "message authenticator, wrong value");
562 pthread_mutex_unlock(&lock);
566 pthread_mutex_unlock(&lock);
570 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
571 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
572 static unsigned char first = 1;
573 static HMAC_CTX hmacctx;
579 pthread_mutex_lock(&lock);
581 HMAC_CTX_init(&hmacctx);
585 memset(authattrval, 0, 16);
587 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
588 HMAC_Update(&hmacctx, rad, RADLEN(rad));
589 HMAC_Final(&hmacctx, authattrval, &md_len);
591 debug(DBG_WARN, "message auth computation failed");
592 pthread_mutex_unlock(&lock);
596 pthread_mutex_unlock(&lock);
600 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
602 if (ATTRTYPE(attrs) == type)
604 length -= ATTRLEN(attrs);
605 attrs += ATTRLEN(attrs);
610 void sendrq(struct server *to, struct request *rq) {
614 pthread_mutex_lock(&to->newrq_mutex);
615 /* might simplify if only try nextid, might be ok */
616 for (i = to->nextid; i < MAX_REQUESTS; i++)
617 if (!to->requests[i].buf)
619 if (i == MAX_REQUESTS) {
620 for (i = 0; i < to->nextid; i++)
621 if (!to->requests[i].buf)
623 if (i == to->nextid) {
624 debug(DBG_WARN, "No room in queue, dropping request");
626 pthread_mutex_unlock(&to->newrq_mutex);
631 rq->buf[1] = (char)i;
633 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
634 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
636 pthread_mutex_unlock(&to->newrq_mutex);
640 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
641 to->requests[i] = *rq;
646 debug(DBG_DBG, "signalling client writer");
647 pthread_cond_signal(&to->newrq_cond);
649 pthread_mutex_unlock(&to->newrq_mutex);
652 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
653 struct replyq *replyq = to->replyq;
655 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
657 debug(DBG_WARN, "sendreply: failed to sign message");
661 pthread_mutex_lock(&replyq->count_mutex);
662 if (replyq->count == replyq->size) {
663 debug(DBG_WARN, "No room in queue, dropping request");
664 pthread_mutex_unlock(&replyq->count_mutex);
669 replyq->replies[replyq->count].buf = buf;
671 replyq->replies[replyq->count].tosa = *tosa;
674 if (replyq->count == 1) {
675 debug(DBG_DBG, "signalling server writer");
676 pthread_cond_signal(&replyq->count_cond);
678 pthread_mutex_unlock(&replyq->count_mutex);
681 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
682 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
683 static unsigned char first = 1;
684 static EVP_MD_CTX mdctx;
685 unsigned char hash[EVP_MAX_MD_SIZE], *input;
687 uint8_t i, offset = 0, out[128];
689 pthread_mutex_lock(&lock);
691 EVP_MD_CTX_init(&mdctx);
697 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
698 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
699 !EVP_DigestUpdate(&mdctx, input, 16) ||
700 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
702 pthread_mutex_unlock(&lock);
705 for (i = 0; i < 16; i++)
706 out[offset + i] = hash[i] ^ in[offset + i];
707 input = out + offset - 16;
712 memcpy(in, out, len);
713 pthread_mutex_unlock(&lock);
717 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
718 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
719 static unsigned char first = 1;
720 static EVP_MD_CTX mdctx;
721 unsigned char hash[EVP_MAX_MD_SIZE], *input;
723 uint8_t i, offset = 0, out[128];
725 pthread_mutex_lock(&lock);
727 EVP_MD_CTX_init(&mdctx);
733 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
734 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
735 !EVP_DigestUpdate(&mdctx, input, 16) ||
736 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
738 pthread_mutex_unlock(&lock);
741 for (i = 0; i < 16; i++)
742 out[offset + i] = hash[i] ^ in[offset + i];
748 memcpy(in, out, len);
749 pthread_mutex_unlock(&lock);
753 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
754 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
755 static unsigned char first = 1;
756 static EVP_MD_CTX mdctx;
757 unsigned char hash[EVP_MAX_MD_SIZE];
761 pthread_mutex_lock(&lock);
763 EVP_MD_CTX_init(&mdctx);
768 printf("msppencrypt auth in: ");
769 for (i = 0; i < 16; i++)
770 printf("%02x ", auth[i]);
773 printf("msppencrypt salt in: ");
774 for (i = 0; i < 2; i++)
775 printf("%02x ", salt[i]);
778 printf("msppencrypt in: ");
779 for (i = 0; i < len; i++)
780 printf("%02x ", text[i]);
784 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
785 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
786 !EVP_DigestUpdate(&mdctx, auth, 16) ||
787 !EVP_DigestUpdate(&mdctx, salt, 2) ||
788 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
789 pthread_mutex_unlock(&lock);
794 printf("msppencrypt hash: ");
795 for (i = 0; i < 16; i++)
796 printf("%02x ", hash[i]);
800 for (i = 0; i < 16; i++)
803 for (offset = 16; offset < len; offset += 16) {
805 printf("text + offset - 16 c(%d): ", offset / 16);
806 for (i = 0; i < 16; i++)
807 printf("%02x ", (text + offset - 16)[i]);
810 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
811 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
812 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
813 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
815 pthread_mutex_unlock(&lock);
819 printf("msppencrypt hash: ");
820 for (i = 0; i < 16; i++)
821 printf("%02x ", hash[i]);
825 for (i = 0; i < 16; i++)
826 text[offset + i] ^= hash[i];
830 printf("msppencrypt out: ");
831 for (i = 0; i < len; i++)
832 printf("%02x ", text[i]);
836 pthread_mutex_unlock(&lock);
840 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
841 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
842 static unsigned char first = 1;
843 static EVP_MD_CTX mdctx;
844 unsigned char hash[EVP_MAX_MD_SIZE];
849 pthread_mutex_lock(&lock);
851 EVP_MD_CTX_init(&mdctx);
856 printf("msppdecrypt auth in: ");
857 for (i = 0; i < 16; i++)
858 printf("%02x ", auth[i]);
861 printf("msppedecrypt salt in: ");
862 for (i = 0; i < 2; i++)
863 printf("%02x ", salt[i]);
866 printf("msppedecrypt in: ");
867 for (i = 0; i < len; i++)
868 printf("%02x ", text[i]);
872 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
873 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
874 !EVP_DigestUpdate(&mdctx, auth, 16) ||
875 !EVP_DigestUpdate(&mdctx, salt, 2) ||
876 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
877 pthread_mutex_unlock(&lock);
882 printf("msppedecrypt hash: ");
883 for (i = 0; i < 16; i++)
884 printf("%02x ", hash[i]);
888 for (i = 0; i < 16; i++)
889 plain[i] = text[i] ^ hash[i];
891 for (offset = 16; offset < len; offset += 16) {
893 printf("text + offset - 16 c(%d): ", offset / 16);
894 for (i = 0; i < 16; i++)
895 printf("%02x ", (text + offset - 16)[i]);
898 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
899 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
900 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
901 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
903 pthread_mutex_unlock(&lock);
907 printf("msppedecrypt hash: ");
908 for (i = 0; i < 16; i++)
909 printf("%02x ", hash[i]);
913 for (i = 0; i < 16; i++)
914 plain[offset + i] = text[offset + i] ^ hash[i];
917 memcpy(text, plain, len);
919 printf("msppedecrypt out: ");
920 for (i = 0; i < len; i++)
921 printf("%02x ", text[i]);
925 pthread_mutex_unlock(&lock);
929 struct realm *id2realm(char *id, uint8_t len) {
931 for (i = 0; i < realm_count; i++)
932 if (!regexec(&realms[i].regex, id, 0, NULL, 0)) {
933 debug(DBG_DBG, "found matching realm: %s", realms[i].name);
939 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
942 pthread_mutex_lock(&to->newrq_mutex);
943 for (i = 0; i < MAX_REQUESTS; i++)
944 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
946 pthread_mutex_unlock(&to->newrq_mutex);
948 return i < MAX_REQUESTS;
951 int attrvalidate(unsigned char *attrs, int length) {
953 if (ATTRLEN(attrs) < 2) {
954 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
957 length -= ATTRLEN(attrs);
959 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
962 attrs += ATTRLEN(attrs);
965 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
969 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
973 if (len < 16 || len > 128 || len % 16) {
974 debug(DBG_WARN, "pwdrecrypt: invalid password length");
978 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
979 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
983 printf("pwdrecrypt: password: ");
984 for (i = 0; i < len; i++)
985 printf("%02x ", pwd[i]);
988 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
989 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
995 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
998 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
999 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1002 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1003 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1009 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1010 char *oldsecret, char *newsecret) {
1011 unsigned char *attr;
1013 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1014 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1015 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1021 void respondstatusserver(struct request *rq) {
1022 unsigned char *resp;
1026 debug(DBG_ERR, "respondstatusserver: malloc failed");
1029 memcpy(resp, rq->buf, 20);
1030 resp[0] = RAD_Access_Accept;
1033 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1034 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1037 void respondreject(struct request *rq, char *message) {
1038 unsigned char *resp;
1042 len += 2 + strlen(message);
1046 debug(DBG_ERR, "respondreject: malloc failed");
1049 memcpy(resp, rq->buf, 20);
1050 resp[0] = RAD_Access_Reject;
1051 *(uint16_t *)(resp + 2) = htons(len);
1053 resp[20] = RAD_Attr_Reply_Message;
1054 resp[21] = len - 20;
1055 memcpy(resp + 22, message, len - 22);
1057 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1060 void radsrv(struct request *rq) {
1061 uint8_t code, id, *auth, *attrs, *attr;
1063 struct server *to = NULL;
1065 unsigned char *buf, newauth[16];
1066 struct realm *realm = NULL;
1069 code = *(uint8_t *)buf;
1070 id = *(uint8_t *)(buf + 1);
1072 auth = (uint8_t *)(buf + 4);
1074 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1076 if (code != RAD_Access_Request && code != RAD_Status_Server) {
1077 debug(DBG_INFO, "radsrv: server currently accepts only access-requests and status-server, ignoring");
1085 if (!attrvalidate(attrs, len)) {
1086 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1091 if (code == RAD_Access_Request) {
1092 attr = attrget(attrs, len, RAD_Attr_User_Name);
1094 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1098 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1099 username[ATTRVALLEN(attr)] = '\0';
1100 debug(DBG_DBG, "Access Request with username: %s", username);
1102 realm = id2realm(username, strlen(username));
1104 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1108 to = realm->srvconf->servers;
1110 if (to && rqinqueue(to, rq->from, id)) {
1111 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1117 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1118 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->conf->secret))) {
1119 debug(DBG_WARN, "radsrv: message authentication failed");
1124 if (code == RAD_Status_Server) {
1125 respondstatusserver(rq);
1130 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1131 respondreject(rq, realm->message);
1135 if (!RAND_bytes(newauth, 16)) {
1136 debug(DBG_WARN, "radsrv: failed to generate random auth");
1142 printauth("auth", auth);
1145 attr = attrget(attrs, len, RAD_Attr_User_Password);
1147 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1148 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1154 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1156 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1157 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1164 memcpy(rq->origauth, auth, 16);
1165 memcpy(auth, newauth, 16);
1169 void *clientrd(void *arg) {
1170 struct server *server = (struct server *)arg;
1171 struct client *from;
1173 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1174 struct sockaddr_storage fromsa;
1175 struct timeval lastconnecttry;
1179 lastconnecttry = server->lastconnecttry;
1180 buf = (server->conf->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
1181 if (!buf && server->conf->type == 'T') {
1182 tlsconnect(server, &lastconnecttry, "clientrd");
1186 server->connectionok = 1;
1188 i = buf[1]; /* i is the id */
1191 case RAD_Access_Accept:
1192 debug(DBG_DBG, "got Access Accept with id %d", i);
1194 case RAD_Access_Reject:
1195 debug(DBG_DBG, "got Access Reject with id %d", i);
1197 case RAD_Access_Challenge:
1198 debug(DBG_DBG, "got Access Challenge with id %d", i);
1202 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1206 pthread_mutex_lock(&server->newrq_mutex);
1207 if (!server->requests[i].buf || !server->requests[i].tries) {
1208 pthread_mutex_unlock(&server->newrq_mutex);
1210 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1214 if (server->requests[i].received) {
1215 pthread_mutex_unlock(&server->newrq_mutex);
1217 debug(DBG_INFO, "clientrd: already received, ignoring");
1221 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->conf->secret)) {
1222 pthread_mutex_unlock(&server->newrq_mutex);
1224 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1228 from = server->requests[i].from;
1229 len = RADLEN(buf) - 20;
1232 if (!attrvalidate(attrs, len)) {
1233 pthread_mutex_unlock(&server->newrq_mutex);
1235 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1239 /* Message Authenticator */
1240 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1242 if (ATTRVALLEN(messageauth) != 16) {
1243 pthread_mutex_unlock(&server->newrq_mutex);
1245 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1248 memcpy(tmp, buf + 4, 16);
1249 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1250 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1251 pthread_mutex_unlock(&server->newrq_mutex);
1253 debug(DBG_WARN, "clientrd: message authentication failed");
1256 memcpy(buf + 4, tmp, 16);
1257 debug(DBG_DBG, "clientrd: message auth ok");
1260 if (*server->requests[i].buf == RAD_Status_Server) {
1261 server->requests[i].received = 1;
1262 pthread_mutex_unlock(&server->newrq_mutex);
1264 debug(DBG_INFO, "clientrd: got status server response from %s", server->conf->host);
1269 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1270 if (ATTRVALLEN(attr) <= 4)
1273 if (((uint16_t *)attr)[1] != 0 || ntohs(((uint16_t *)attr)[2]) != 311) /* 311 == MS */
1276 sublen = ATTRVALLEN(attr) - 4;
1277 subattrs = ATTRVAL(attr) + 4;
1278 if (!attrvalidate(subattrs, sublen) ||
1279 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1280 server->requests + i, server->conf->secret, from->conf->secret) ||
1281 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1282 server->requests + i, server->conf->secret, from->conf->secret))
1286 pthread_mutex_unlock(&server->newrq_mutex);
1288 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1292 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1293 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1294 /* we know the attribute exists */
1295 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1296 tmp[ATTRVALLEN(attr)] = '\0';
1298 case RAD_Access_Accept:
1299 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1301 case RAD_Access_Reject:
1302 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1307 /* once we set received = 1, requests[i] may be reused */
1308 buf[1] = (char)server->requests[i].origid;
1309 memcpy(buf + 4, server->requests[i].origauth, 16);
1311 printauth("origauth/buf+4", buf + 4);
1315 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1316 pthread_mutex_unlock(&server->newrq_mutex);
1320 debug(DBG_DBG, "clientrd: computed messageauthattr");
1323 if (from->conf->type == 'U')
1324 fromsa = server->requests[i].fromsa;
1325 server->requests[i].received = 1;
1326 pthread_mutex_unlock(&server->newrq_mutex);
1328 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1329 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1333 void *clientwr(void *arg) {
1334 struct server *server = (struct server *)arg;
1336 pthread_t clientrdth;
1339 struct timeval now, lastsend;
1340 struct timespec timeout;
1341 struct request statsrvrq;
1342 unsigned char statsrvbuf[38];
1344 memset(&timeout, 0, sizeof(struct timespec));
1346 if (server->conf->statusserver) {
1347 memset(&statsrvrq, 0, sizeof(struct request));
1348 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1349 statsrvbuf[0] = RAD_Status_Server;
1351 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1352 statsrvbuf[21] = 18;
1353 gettimeofday(&lastsend, NULL);
1356 if (server->conf->type == 'U') {
1357 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1358 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1360 tlsconnect(server, NULL, "new client");
1362 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1363 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1366 pthread_mutex_lock(&server->newrq_mutex);
1367 if (!server->newrq) {
1368 gettimeofday(&now, NULL);
1369 if (server->conf->statusserver) {
1370 /* random 0-7 seconds */
1371 RAND_bytes(&rnd, 1);
1373 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1374 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1376 if (timeout.tv_sec) {
1377 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1378 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1381 debug(DBG_DBG, "clientwr: waiting for new request");
1382 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1385 if (server->newrq) {
1386 debug(DBG_DBG, "clientwr: got new request");
1389 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1390 pthread_mutex_unlock(&server->newrq_mutex);
1392 for (i = 0; i < MAX_REQUESTS; i++) {
1393 pthread_mutex_lock(&server->newrq_mutex);
1394 while (!server->requests[i].buf && i < MAX_REQUESTS)
1396 if (i == MAX_REQUESTS) {
1397 pthread_mutex_unlock(&server->newrq_mutex);
1400 rq = server->requests + i;
1403 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1405 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1407 /* setting this to NULL means that it can be reused */
1410 pthread_mutex_unlock(&server->newrq_mutex);
1414 gettimeofday(&now, NULL);
1415 if (now.tv_sec < rq->expiry.tv_sec) {
1416 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1417 timeout.tv_sec = rq->expiry.tv_sec;
1418 pthread_mutex_unlock(&server->newrq_mutex);
1422 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1423 ? 1 : REQUEST_RETRIES)) {
1424 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1425 if (*rq->buf == RAD_Status_Server)
1426 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1428 /* setting this to NULL means that it can be reused */
1430 pthread_mutex_unlock(&server->newrq_mutex);
1433 pthread_mutex_unlock(&server->newrq_mutex);
1435 rq->expiry.tv_sec = now.tv_sec +
1436 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1437 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1438 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1439 timeout.tv_sec = rq->expiry.tv_sec;
1441 clientradput(server, server->requests[i].buf);
1442 gettimeofday(&lastsend, NULL);
1444 if (server->conf->statusserver) {
1445 gettimeofday(&now, NULL);
1446 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1447 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1448 debug(DBG_WARN, "clientwr: failed to generate random auth");
1451 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1452 if (!statsrvrq.buf) {
1453 debug(DBG_ERR, "clientwr: malloc failed");
1456 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1457 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1458 lastsend.tv_sec = now.tv_sec;
1459 sendrq(server, &statsrvrq);
1465 void *udpserverwr(void *arg) {
1466 struct replyq *replyq = udp_server_replyq;
1467 struct reply *reply = replyq->replies;
1469 pthread_mutex_lock(&replyq->count_mutex);
1471 while (!replyq->count) {
1472 debug(DBG_DBG, "udp server writer, waiting for signal");
1473 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1474 debug(DBG_DBG, "udp server writer, got signal");
1476 pthread_mutex_unlock(&replyq->count_mutex);
1478 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1479 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1480 debug(DBG_WARN, "sendudp: send failed");
1483 pthread_mutex_lock(&replyq->count_mutex);
1485 memmove(replyq->replies, replyq->replies + 1,
1486 replyq->count * sizeof(struct reply));
1490 void *udpserverrd(void *arg) {
1492 pthread_t udpserverwrth;
1494 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1495 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1497 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1498 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1500 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1501 debugx(1, DBG_ERR, "pthread_create failed");
1504 memset(&rq, 0, sizeof(struct request));
1505 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1510 void *tlsserverwr(void *arg) {
1512 unsigned long error;
1513 struct client *client = (struct client *)arg;
1514 struct replyq *replyq;
1516 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1517 replyq = client->replyq;
1518 pthread_mutex_lock(&replyq->count_mutex);
1520 while (!replyq->count) {
1522 debug(DBG_DBG, "tls server writer, waiting for signal");
1523 pthread_cond_wait(&replyq->count_cond, &replyq->count_mutex);
1524 debug(DBG_DBG, "tls server writer, got signal");
1527 /* ssl might have changed while waiting */
1528 pthread_mutex_unlock(&replyq->count_mutex);
1529 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1533 pthread_mutex_unlock(&replyq->count_mutex);
1534 cnt = SSL_write(client->ssl, replyq->replies->buf, RADLEN(replyq->replies->buf));
1536 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1537 cnt, RADLEN(replyq->replies->buf));
1539 while ((error = ERR_get_error()))
1540 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1541 free(replyq->replies->buf);
1543 pthread_mutex_lock(&replyq->count_mutex);
1545 memmove(replyq->replies, replyq->replies + 1, replyq->count * sizeof(struct reply));
1549 void *tlsserverrd(void *arg) {
1551 unsigned long error;
1553 struct client *client = (struct client *)arg;
1554 pthread_t tlsserverwrth;
1557 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
1560 if (SSL_accept(ssl) <= 0) {
1561 while ((error = ERR_get_error()))
1562 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1563 debug(DBG_ERR, "SSL_accept failed");
1566 if (tlsverifycert(client->ssl, client->conf)) {
1567 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1568 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1572 memset(&rq, 0, sizeof(struct request));
1573 rq.buf = radtlsget(client->ssl);
1576 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
1580 debug(DBG_ERR, "tlsserverrd: connection lost");
1581 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
1583 pthread_mutex_lock(&client->replyq->count_mutex);
1584 pthread_cond_signal(&client->replyq->count_cond);
1585 pthread_mutex_unlock(&client->replyq->count_mutex);
1586 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1587 pthread_join(tlsserverwrth, NULL);
1591 s = SSL_get_fd(ssl);
1593 shutdown(s, SHUT_RDWR);
1595 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
1601 pthread_t tlsserverth;
1603 struct sockaddr_storage from;
1604 size_t fromlen = sizeof(from);
1605 struct clsrvconf *conf;
1606 struct client *client;
1608 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1609 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1612 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1613 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1616 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1618 debug(DBG_WARN, "accept failed");
1621 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1623 conf = find_peer('T', (struct sockaddr *)&from, clconfs, clconf_count);
1625 debug(DBG_WARN, "ignoring request, not a known TLS client");
1626 shutdown(snew, SHUT_RDWR);
1630 client = conf->clients;
1633 debug(DBG_WARN, "Ignoring incoming TLS connection, already have one from this client");
1634 shutdown(snew, SHUT_RDWR);
1638 client->ssl = SSL_new(client->conf->ssl_ctx);
1639 SSL_set_fd(client->ssl, snew);
1640 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1641 debug(DBG_ERR, "tlslistener: pthread_create failed");
1642 SSL_free(client->ssl);
1643 shutdown(snew, SHUT_RDWR);
1648 pthread_detach(tlsserverth);
1653 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1657 unsigned long error;
1659 if (!certfile || !certkeyfile)
1660 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1662 if (!cacertfile && !cacertpath)
1663 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1666 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1667 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1668 for (i = 0; i < CRYPTO_num_locks(); i++) {
1669 ssl_lock_count[i] = 0;
1670 pthread_mutex_init(&ssl_locks[i], NULL);
1672 CRYPTO_set_id_callback(ssl_thread_id);
1673 CRYPTO_set_locking_callback(ssl_locking_callback);
1675 SSL_load_error_strings();
1678 while (!RAND_status()) {
1679 time_t t = time(NULL);
1680 pid_t pid = getpid();
1681 RAND_seed((unsigned char *)&t, sizeof(time_t));
1682 RAND_seed((unsigned char *)&pid, sizeof(pid));
1685 ctx = SSL_CTX_new(TLSv1_method());
1687 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
1688 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
1690 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
1691 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
1692 !SSL_CTX_check_private_key(ctx) ||
1693 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
1694 while ((error = ERR_get_error()))
1695 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
1696 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
1699 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
1700 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
1703 tls = realloc(tls, tls_count * sizeof(struct tls));
1705 debugx(1, DBG_ERR, "malloc failed");
1706 new = tls + tls_count - 1;
1707 memset(new, 0, sizeof(struct tls));
1708 new->name = stringcopy(value, 0);
1710 debugx(1, DBG_ERR, "malloc failed");
1713 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
1718 for (i = 0; i < tls_count; i++)
1720 SSL_CTX_free(tls[i].ctx);
1726 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
1727 int i, c1 = -1, c2 = -1;
1728 for (i = 0; i < tls_count; i++) {
1729 if (!strcasecmp(tls[i].name, alt1)) {
1733 if (c2 == -1 && alt2 && !strcasecmp(tls[i].name, alt2))
1737 i = (c1 == -1 ? c2 : c1);
1744 struct replyq *newreplyq(int size) {
1745 struct replyq *replyq;
1747 replyq = malloc(sizeof(struct replyq));
1749 debugx(1, DBG_ERR, "malloc failed");
1750 replyq->replies = calloc(MAX_REQUESTS, sizeof(struct reply));
1751 if (!replyq->replies)
1752 debugx(1, DBG_ERR, "malloc failed");
1754 replyq->size = size;
1755 pthread_mutex_init(&replyq->count_mutex, NULL);
1756 pthread_cond_init(&replyq->count_cond, NULL);
1760 void addclient(struct clsrvconf *conf) {
1762 debugx(1, DBG_ERR, "currently works with just one client per conf");
1764 conf->clients = malloc(sizeof(struct client));
1766 debugx(1, DBG_ERR, "malloc failed");
1767 memset(conf->clients, 0, sizeof(struct client));
1768 conf->clients->conf = conf;
1770 if (conf->type == 'T')
1771 conf->clients->replyq = newreplyq(MAX_REQUESTS);
1773 if (!udp_server_replyq)
1774 udp_server_replyq = newreplyq(client_udp_count * MAX_REQUESTS);
1775 conf->clients->replyq = udp_server_replyq;
1779 void addserver(struct clsrvconf *conf) {
1781 debugx(1, DBG_ERR, "currently works with just one server per conf");
1783 conf->servers = malloc(sizeof(struct server));
1785 debugx(1, DBG_ERR, "malloc failed");
1786 memset(conf->servers, 0, sizeof(struct server));
1787 conf->servers->conf = conf;
1789 conf->servers->sock = -1;
1790 pthread_mutex_init(&conf->servers->lock, NULL);
1791 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
1792 if (!conf->servers->requests)
1793 debugx(1, DBG_ERR, "malloc failed");
1794 conf->servers->newrq = 0;
1795 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
1796 pthread_cond_init(&conf->servers->newrq_cond, NULL);
1799 void addrealm(char *value, char *server, char *message) {
1801 struct realm *realm;
1802 char *s, *regex = NULL;
1805 for (i = 0; i < srvconf_count; i++)
1806 if (!strcasecmp(server, srvconfs[i].host))
1808 if (i == srvconf_count)
1809 debugx(1, DBG_ERR, "addrealm failed, no server %s", server);
1812 if (*value == '/') {
1813 /* regexp, remove optional trailing / if present */
1814 if (value[strlen(value) - 1] == '/')
1815 value[strlen(value) - 1] = '\0';
1817 /* not a regexp, let us make it one */
1818 if (*value == '*' && !value[1])
1819 regex = stringcopy(".*", 0);
1821 for (n = 0, s = value; *s;)
1824 regex = malloc(strlen(value) + n + 3);
1827 for (n = 1, s = value; *s; s++) {
1837 debugx(1, DBG_ERR, "malloc failed");
1838 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
1842 realms = realloc(realms, realm_count * sizeof(struct realm));
1844 debugx(1, DBG_ERR, "malloc failed");
1845 realm = realms + realm_count - 1;
1846 memset(realm, 0, sizeof(struct realm));
1847 realm->name = stringcopy(value, 0);
1849 debugx(1, DBG_ERR, "malloc failed");
1850 if (message && strlen(message) > 253)
1851 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
1852 realm->message = message;
1854 realm->srvconf = srvconfs + i;
1855 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
1856 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
1859 debug(DBG_DBG, "addrealm: added realm %s for server %s", value, server);
1862 char *parsehostport(char *s, struct clsrvconf *conf) {
1867 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
1871 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1873 debugx(1, DBG_ERR, "no ] matching initial [");
1877 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1880 debugx(1, DBG_ERR, "missing host/address");
1882 conf->host = stringcopy(field, p - field);
1885 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
1886 debugx(1, DBG_ERR, "unexpected character after ]");
1889 /* port number or service name is specified */;
1891 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
1893 debugx(1, DBG_ERR, "syntax error, : but no following port");
1894 conf->port = stringcopy(field, p - field);
1896 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
1900 FILE *openconfigfile(const char *filename) {
1902 char pathname[100], *base = NULL;
1904 f = fopen(filename, "r");
1906 debug(DBG_DBG, "reading config file %s", filename);
1910 if (strlen(filename) + 1 <= sizeof(pathname)) {
1911 /* basename() might modify the string */
1912 strcpy(pathname, filename);
1913 base = basename(pathname);
1914 f = fopen(base, "r");
1918 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
1920 debug(DBG_DBG, "reading config file %s", base);
1924 struct clsrvconf *server_create(char type) {
1925 struct clsrvconf *conf;
1928 conf = malloc(sizeof(struct clsrvconf));
1930 debugx(1, DBG_ERR, "malloc failed");
1931 memset(conf, 0, sizeof(struct clsrvconf));
1933 lconf = (type == 'T' ? options.listentcp : options.listenudp);
1935 parsehostport(lconf, conf);
1936 if (!strcmp(conf->host, "*")) {
1941 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
1942 if (!resolvepeer(conf, AI_PASSIVE))
1943 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
1947 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
1948 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
1949 char *t = s, *q, *r;
1951 if (!t || !token || !del)
1953 while (*t && strchr(del, *t))
1955 if (!*t || (comment && strchr(comment, *t))) {
1957 return t + 1; /* needs to be non-NULL, but value doesn't matter */
1959 if (quote && (q = strchr(quote, *t))) {
1962 while (*t && *t != *q)
1964 if (!*t || (t[1] && !strchr(del, t[1])))
1972 while (*t && !strchr(del, *t))
1978 /* Parses config with following syntax:
1981 * option-name = value
1983 * option-name value {
1984 * option-name [=] value
1988 void getgeneralconfig(FILE *f, char *block, ...) {
1991 /* initialise lots of stuff to avoid stupid compiler warnings */
1992 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL;
1993 int type = 0, tcount, conftype = 0;
1994 void (*cbk)(FILE *, char *, char *, char *) = NULL;
1996 while (fgets(line, 1024, f)) {
1998 for (tcount = 0; tcount < 3; tcount++) {
1999 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
2001 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2002 if (!tokens[tcount])
2005 if (!tcount || **tokens == '#')
2008 if (**tokens == '}') {
2011 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2018 conftype = CONF_STR;
2021 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2024 conftype = CONF_STR;
2027 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2030 conftype = CONF_CBK;
2036 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2037 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2041 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2043 va_start(ap, block);
2044 while ((word = va_arg(ap, char *))) {
2045 type = va_arg(ap, int);
2048 str = va_arg(ap, char **);
2050 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2053 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2056 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2058 if (!strcasecmp(opt, word))
2065 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2066 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2069 if (type != conftype) {
2071 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2072 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2078 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2080 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2081 *str = stringcopy(val, 0);
2084 optval = malloc(strlen(opt) + strlen(val) + 2);
2086 debugx(1, DBG_ERR, "malloc failed");
2087 sprintf(optval, "%s %s", opt, val);
2088 cbk(f, optval, opt, val);
2092 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2097 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2098 char *type = NULL, *secret = NULL, *tls = NULL;
2099 struct clsrvconf *conf;
2101 debug(DBG_DBG, "confclient_cb called for %s", block);
2103 getgeneralconfig(f, block,
2104 "type", CONF_STR, &type,
2105 "secret", CONF_STR, &secret,
2106 "tls", CONF_STR, &tls,
2110 clconfs = realloc(clconfs, clconf_count * sizeof(struct clsrvconf));
2112 debugx(1, DBG_ERR, "malloc failed");
2113 conf = clconfs + clconf_count - 1;
2114 memset(conf, 0, sizeof(struct clsrvconf));
2116 conf->host = stringcopy(val, 0);
2118 if (type && !strcasecmp(type, "udp")) {
2121 } else if (type && !strcasecmp(type, "tls")) {
2122 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2124 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2128 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2131 if (!resolvepeer(conf, 0))
2132 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2135 conf->secret = secret;
2137 if (conf->type == 'U')
2138 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2139 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2143 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2144 char *type = NULL, *secret = NULL, *port = NULL, *tls = NULL, *statusserver = NULL;
2145 struct clsrvconf *conf;
2147 debug(DBG_DBG, "confserver_cb called for %s", block);
2149 getgeneralconfig(f, block,
2150 "type", CONF_STR, &type,
2151 "secret", CONF_STR, &secret,
2152 "port", CONF_STR, &port,
2153 "tls", CONF_STR, &tls,
2154 "StatusServer", CONF_STR, &statusserver,
2158 srvconfs = realloc(srvconfs, srvconf_count * sizeof(struct clsrvconf));
2160 debugx(1, DBG_ERR, "malloc failed");
2161 conf = srvconfs + srvconf_count - 1;
2162 memset(conf, 0, sizeof(struct clsrvconf));
2166 if (!strcasecmp(statusserver, "on"))
2167 conf->statusserver = 1;
2168 else if (strcasecmp(statusserver, "off"))
2169 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2173 conf->host = stringcopy(val, 0);
2175 if (type && !strcasecmp(type, "udp")) {
2179 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2180 } else if (type && !strcasecmp(type, "tls")) {
2181 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2183 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2185 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2189 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2192 if (!resolvepeer(conf, 0))
2193 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2196 conf->secret = secret;
2198 if (conf->type == 'U')
2199 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2200 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2204 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2205 char *server = NULL, *msg = NULL;
2207 debug(DBG_DBG, "confrealm_cb called for %s", block);
2209 getgeneralconfig(f, block,
2210 "server", CONF_STR, &server,
2211 "ReplyMessage", CONF_STR, &msg,
2215 addrealm(val, server, msg);
2219 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2220 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2222 debug(DBG_DBG, "conftls_cb called for %s", block);
2224 getgeneralconfig(f, block,
2225 "CACertificateFile", CONF_STR, &cacertfile,
2226 "CACertificatePath", CONF_STR, &cacertpath,
2227 "CertificateFile", CONF_STR, &certfile,
2228 "CertificateKeyFile", CONF_STR, &certkeyfile,
2229 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2233 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2241 void getmainconfig(const char *configfile) {
2243 char *loglevel = NULL;
2245 f = openconfigfile(configfile);
2246 memset(&options, 0, sizeof(options));
2248 getgeneralconfig(f, NULL,
2249 "ListenUDP", CONF_STR, &options.listenudp,
2250 "ListenTCP", CONF_STR, &options.listentcp,
2251 "LogLevel", CONF_STR, &loglevel,
2252 "LogDestination", CONF_STR, &options.logdestination,
2253 "Client", CONF_CBK, confclient_cb,
2254 "Server", CONF_CBK, confserver_cb,
2255 "Realm", CONF_CBK, confrealm_cb,
2256 "TLS", CONF_CBK, conftls_cb,
2263 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2264 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2265 options.loglevel = *loglevel - '0';
2270 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2273 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2276 *configfile = optarg;
2279 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2280 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2281 *loglevel = *optarg - '0';
2287 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2292 if (!(argc - optind))
2296 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2300 int main(int argc, char **argv) {
2301 pthread_t udpserverth;
2303 uint8_t foreground = 0, loglevel = 0;
2304 char *configfile = NULL;
2306 debug_init("radsecproxy");
2307 debug_set_level(DEBUG_LEVEL);
2308 getargs(argc, argv, &foreground, &loglevel, &configfile);
2310 debug_set_level(loglevel);
2311 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2313 options.loglevel = loglevel;
2314 else if (options.loglevel)
2315 debug_set_level(options.loglevel);
2317 options.logdestination = NULL;
2319 if (!options.logdestination)
2320 options.logdestination = "x-syslog:///";
2321 debug_set_destination(options.logdestination);
2325 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2327 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2329 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2331 if (!foreground && (daemon(0, 0) < 0))
2332 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2334 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2336 for (i = 0; i < clconf_count; i++)
2337 addclient(clconfs + i);
2339 for (i = 0; i < srvconf_count; i++)
2340 addserver(srvconfs + i);
2342 if (client_udp_count) {
2343 udp_server_listen = server_create('U');
2344 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2345 debugx(1, DBG_ERR, "pthread_create failed");
2348 for (i = 0; i < srvconf_count; i++)
2349 if (pthread_create(&srvconfs[i].servers->clientth, NULL, clientwr, (void *)srvconfs[i].servers))
2350 debugx(1, DBG_ERR, "pthread_create failed");
2352 if (client_tls_count) {
2353 tcp_server_listen = server_create('T');
2354 return tlslistener();
2357 /* just hang around doing nothing, anything to do here? */