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>
38 #include <sys/types.h>
39 #include <arpa/inet.h>
43 #include <openssl/ssl.h>
44 #include <openssl/rand.h>
45 #include <openssl/err.h>
46 #include <openssl/md5.h>
47 #include <openssl/hmac.h>
48 #include <openssl/x509v3.h>
51 #include "radsecproxy.h"
53 static struct options options;
54 struct list *clconfs, *srvconfs, *realms, *tlsconfs;
56 static int client_udp_count = 0;
57 static int client_tls_count = 0;
58 static int server_udp_count = 0;
59 static int server_tls_count = 0;
61 static struct clsrvconf *tcp_server_listen;
62 static struct clsrvconf *udp_server_listen;
63 static struct clsrvconf *udp_accserver_listen;
64 static struct replyq *udp_server_replyq = NULL;
65 static int udp_server_sock = -1;
66 static int udp_accserver_sock = -1;
67 static pthread_mutex_t *ssl_locks;
68 static long *ssl_lock_count;
72 /* callbacks for making OpenSSL thread safe */
73 unsigned long ssl_thread_id() {
74 return (unsigned long)pthread_self();
77 void ssl_locking_callback(int mode, int type, const char *file, int line) {
78 if (mode & CRYPTO_LOCK) {
79 pthread_mutex_lock(&ssl_locks[type]);
80 ssl_lock_count[type]++;
82 pthread_mutex_unlock(&ssl_locks[type]);
85 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
86 int pwdlen = strlen(userdata);
87 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
89 memcpy(buf, userdata, pwdlen);
93 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
98 err_cert = X509_STORE_CTX_get_current_cert(ctx);
99 err = X509_STORE_CTX_get_error(ctx);
100 depth = X509_STORE_CTX_get_error_depth(ctx);
102 if (depth > MAX_CERT_DEPTH) {
104 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
105 X509_STORE_CTX_set_error(ctx, err);
109 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
110 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
113 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
114 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
115 debug(DBG_WARN, "\tIssuer=%s", buf);
117 case X509_V_ERR_CERT_NOT_YET_VALID:
118 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
119 debug(DBG_WARN, "\tCertificate not yet valid");
121 case X509_V_ERR_CERT_HAS_EXPIRED:
122 debug(DBG_WARN, "Certificate has expired");
124 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
125 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
130 printf("certificate verify returns %d\n", ok);
135 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
136 struct addrinfo hints, *addrinfo;
140 slash = conf->host ? strchr(conf->host, '/') : NULL;
144 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
148 if (*s < '0' || *s > '9') {
149 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
152 plen = atoi(slash + 1);
153 if (plen < 0 || plen > 128) {
154 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
159 memset(&hints, 0, sizeof(hints));
160 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
161 hints.ai_family = AF_UNSPEC;
162 hints.ai_flags = ai_flags;
164 hints.ai_flags |= AI_NUMERICHOST;
165 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
166 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host, conf->port);
172 switch (addrinfo->ai_family) {
175 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
176 freeaddrinfo(addrinfo);
183 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
184 freeaddrinfo(addrinfo);
187 conf->prefixlen = plen;
189 conf->prefixlen = 255;
192 freeaddrinfo(conf->addrinfo);
193 conf->addrinfo = addrinfo;
197 int connecttoserver(struct addrinfo *addrinfo) {
199 struct addrinfo *res;
202 for (res = addrinfo; res; res = res->ai_next) {
203 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
205 debug(DBG_WARN, "connecttoserver: socket failed");
208 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
210 debug(DBG_WARN, "connecttoserver: connect failed");
217 int bindtoaddr(struct addrinfo *addrinfo) {
219 struct addrinfo *res;
221 for (res = addrinfo; res; res = res->ai_next) {
222 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
224 debug(DBG_WARN, "bindtoaddr: socket failed");
227 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
228 if (!bind(s, res->ai_addr, res->ai_addrlen))
230 debug(DBG_WARN, "bindtoaddr: bind failed");
236 /* returns 1 if the len first bits are equal, else 0 */
237 int prefixmatch(void *a1, void *a2, uint8_t len) {
238 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
240 if (l && memcmp(a1, a2, l))
245 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
248 /* returns the config with matching address, or NULL */
249 /* if conf argument is not NULL, we only check that one */
250 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
251 struct sockaddr_in6 *sa6 = NULL;
252 struct in_addr *a4 = NULL;
253 struct addrinfo *res;
254 struct list_node *entry;
256 if (addr->sa_family == AF_INET6) {
257 sa6 = (struct sockaddr_in6 *)addr;
258 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
259 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
263 a4 = &((struct sockaddr_in *)addr)->sin_addr;
266 if (conf->type == type) {
267 if (conf->prefixlen == 255) {
268 for (res = conf->addrinfo; res; res = res->ai_next)
269 if ((a4 && res->ai_family == AF_INET &&
270 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
271 (sa6 && res->ai_family == AF_INET6 &&
272 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
275 res = conf->addrinfo;
277 ((a4 && res->ai_family == AF_INET &&
278 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
279 (sa6 && res->ai_family == AF_INET6 &&
280 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
287 for (entry = list_first(confs); entry; entry = list_next(entry)) {
288 conf = (struct clsrvconf *)entry->data;
289 if (conf->type == type) {
290 if (conf->prefixlen == 255) {
291 for (res = conf->addrinfo; res; res = res->ai_next)
292 if ((a4 && res->ai_family == AF_INET &&
293 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
294 (sa6 && res->ai_family == AF_INET6 &&
295 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
298 res = conf->addrinfo;
300 ((a4 && res->ai_family == AF_INET &&
301 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
302 (sa6 && res->ai_family == AF_INET6 &&
303 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
311 struct replyq *newreplyq() {
312 struct replyq *replyq;
314 replyq = malloc(sizeof(struct replyq));
316 debugx(1, DBG_ERR, "malloc failed");
317 replyq->replies = list_create();
318 if (!replyq->replies)
319 debugx(1, DBG_ERR, "malloc failed");
320 pthread_mutex_init(&replyq->mutex, NULL);
321 pthread_cond_init(&replyq->cond, NULL);
325 struct client *addclient(struct clsrvconf *conf) {
326 struct client *new = malloc(sizeof(struct client));
329 debug(DBG_ERR, "malloc failed");
332 if (!conf->clients) {
333 conf->clients = list_create();
334 if (!conf->clients) {
335 debug(DBG_ERR, "malloc failed");
340 memset(new, 0, sizeof(struct client));
342 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
344 list_push(conf->clients, new);
348 void removeclient(struct client *client) {
349 if (!client || !client->conf->clients)
352 list_removedata(client->conf->clients, client);
356 void addserver(struct clsrvconf *conf) {
358 debugx(1, DBG_ERR, "currently works with just one server per conf");
360 conf->servers = malloc(sizeof(struct server));
362 debugx(1, DBG_ERR, "malloc failed");
363 memset(conf->servers, 0, sizeof(struct server));
364 conf->servers->conf = conf;
366 conf->servers->sock = -1;
367 pthread_mutex_init(&conf->servers->lock, NULL);
368 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
369 if (!conf->servers->requests)
370 debugx(1, DBG_ERR, "malloc failed");
371 conf->servers->newrq = 0;
372 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
373 pthread_cond_init(&conf->servers->newrq_cond, NULL);
376 /* exactly one of client and server must be non-NULL */
377 /* should probably take peer list (client(s) or server(s)) as argument instead */
378 /* if *peer == NULL we return who we received from, else require it to be from peer */
379 /* return from in sa if not NULL */
380 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
382 unsigned char buf[65536], *rad;
383 struct sockaddr_storage from;
384 socklen_t fromlen = sizeof(from);
386 struct list_node *node;
389 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
391 debug(DBG_WARN, "radudpget: recv failed");
394 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
397 debug(DBG_WARN, "radudpget: packet too small");
403 debug(DBG_WARN, "radudpget: length too small");
408 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
412 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
416 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
418 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
421 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
423 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
426 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
432 debug(DBG_ERR, "radudpget: malloc failed");
436 if (client && !*client) {
437 node = list_first(p->clients);
438 *client = node ? (struct client *)node->data : addclient(p);
443 } else if (server && !*server)
444 *server = p->servers;
448 memcpy(rad, buf, len);
454 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
455 int loc, i, l, n, r = 0;
458 STACK_OF(GENERAL_NAME) *alt;
461 debug(DBG_DBG, "subjectaltnameaddr");
463 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
467 ex = X509_get_ext(cert, loc);
468 alt = X509V3_EXT_d2i(ex);
472 n = sk_GENERAL_NAME_num(alt);
473 for (i = 0; i < n; i++) {
474 gn = sk_GENERAL_NAME_value(alt, i);
475 if (gn->type != GEN_IPADD)
478 v = (char *)ASN1_STRING_data(gn->d.ia5);
479 l = ASN1_STRING_length(gn->d.ia5);
480 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
481 && !memcmp(v, &addr, l)) {
486 GENERAL_NAMES_free(alt);
490 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
491 int loc, i, l, n, r = 0;
494 STACK_OF(GENERAL_NAME) *alt;
497 debug(DBG_DBG, "subjectaltnameregexp");
499 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
503 ex = X509_get_ext(cert, loc);
504 alt = X509V3_EXT_d2i(ex);
508 n = sk_GENERAL_NAME_num(alt);
509 for (i = 0; i < n; i++) {
510 gn = sk_GENERAL_NAME_value(alt, i);
511 if (gn->type != type)
514 v = (char *)ASN1_STRING_data(gn->d.ia5);
515 l = ASN1_STRING_length(gn->d.ia5);
519 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
522 if (memcmp(v, exact, l))
525 s = stringcopy((char *)v, l);
527 debug(DBG_ERR, "malloc failed");
530 if (regexec(regex, s, 0, NULL, 0)) {
539 GENERAL_NAMES_free(alt);
543 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
550 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
552 struct in6_addr addr;
554 if (SSL_get_verify_result(ssl) != X509_V_OK) {
555 debug(DBG_ERR, "tlsverifycert: basic validation failed");
556 while ((error = ERR_get_error()))
557 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
561 cert = SSL_get_peer_certificate(ssl);
563 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
567 if (inet_pton(AF_INET, conf->host, &addr))
569 else if (inet_pton(AF_INET6, conf->host, &addr))
572 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
576 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
579 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
581 nm = X509_get_subject_name(cert);
584 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
587 e = X509_NAME_get_entry(nm, loc);
588 s = X509_NAME_ENTRY_get_data(e);
589 v = (char *) ASN1_STRING_data(s);
590 l = ASN1_STRING_length(s);
594 printfchars(NULL, "cn", NULL, v, l);
596 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
598 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
604 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
608 if (conf->certuriregex) {
609 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
611 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
615 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
621 void tlsconnect(struct server *server, struct timeval *when, char *text) {
625 debug(DBG_DBG, "tlsconnect called from %s", text);
626 pthread_mutex_lock(&server->lock);
627 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
628 /* already reconnected, nothing to do */
629 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
630 pthread_mutex_unlock(&server->lock);
634 debug(DBG_DBG, "tlsconnect %s", text);
637 gettimeofday(&now, NULL);
638 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
639 if (server->connectionok) {
640 server->connectionok = 0;
642 } else if (elapsed < 5)
644 else if (elapsed < 300) {
645 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
647 } else if (elapsed < 100000) {
648 debug(DBG_INFO, "tlsconnect: sleeping %ds", 600);
651 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
652 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
653 if (server->sock >= 0)
655 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0) {
656 debug(DBG_ERR, "tlsconnect: connecttoserver failed");
660 SSL_free(server->ssl);
661 server->ssl = SSL_new(server->conf->ssl_ctx);
662 SSL_set_fd(server->ssl, server->sock);
663 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
666 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
667 gettimeofday(&server->lastconnecttry, NULL);
668 pthread_mutex_unlock(&server->lock);
671 unsigned char *radtlsget(SSL *ssl) {
673 unsigned char buf[4], *rad;
676 for (total = 0; total < 4; total += cnt) {
677 cnt = SSL_read(ssl, buf + total, 4 - total);
679 debug(DBG_ERR, "radtlsget: connection lost");
680 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
681 /* remote end sent close_notify, send one back */
691 debug(DBG_ERR, "radtlsget: malloc failed");
696 for (; total < len; total += cnt) {
697 cnt = SSL_read(ssl, rad + total, len - total);
699 debug(DBG_ERR, "radtlsget: connection lost");
700 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
701 /* remote end sent close_notify, send one back */
713 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
716 debug(DBG_DBG, "radtlsget: got %d bytes", total);
720 int clientradput(struct server *server, unsigned char *rad) {
724 struct timeval lastconnecttry;
727 if (server->conf->type == 'U') {
728 if (send(server->sock, rad, len, 0) >= 0) {
729 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, server->conf->host, server->conf->port);
732 debug(DBG_WARN, "clientradput: send failed");
736 lastconnecttry = server->lastconnecttry;
737 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
738 while ((error = ERR_get_error()))
739 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
740 tlsconnect(server, &lastconnecttry, "clientradput");
741 lastconnecttry = server->lastconnecttry;
744 server->connectionok = 1;
745 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s",
746 cnt, len, server->conf->host);
750 int radsign(unsigned char *rad, unsigned char *sec) {
751 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
752 static unsigned char first = 1;
753 static EVP_MD_CTX mdctx;
757 pthread_mutex_lock(&lock);
759 EVP_MD_CTX_init(&mdctx);
763 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
764 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
765 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
766 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
768 pthread_mutex_unlock(&lock);
772 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
773 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
774 static unsigned char first = 1;
775 static EVP_MD_CTX mdctx;
776 unsigned char hash[EVP_MAX_MD_SIZE];
780 pthread_mutex_lock(&lock);
782 EVP_MD_CTX_init(&mdctx);
788 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
789 EVP_DigestUpdate(&mdctx, rad, 4) &&
790 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
791 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
792 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
793 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
795 !memcmp(hash, rad + 4, 16));
796 pthread_mutex_unlock(&lock);
800 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
801 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
802 static unsigned char first = 1;
803 static HMAC_CTX hmacctx;
805 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
807 pthread_mutex_lock(&lock);
809 HMAC_CTX_init(&hmacctx);
813 memcpy(auth, authattr, 16);
814 memset(authattr, 0, 16);
816 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
817 HMAC_Update(&hmacctx, rad, RADLEN(rad));
818 HMAC_Final(&hmacctx, hash, &md_len);
819 memcpy(authattr, auth, 16);
821 debug(DBG_WARN, "message auth computation failed");
822 pthread_mutex_unlock(&lock);
826 if (memcmp(auth, hash, 16)) {
827 debug(DBG_WARN, "message authenticator, wrong value");
828 pthread_mutex_unlock(&lock);
832 pthread_mutex_unlock(&lock);
836 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
837 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
838 static unsigned char first = 1;
839 static HMAC_CTX hmacctx;
845 pthread_mutex_lock(&lock);
847 HMAC_CTX_init(&hmacctx);
851 memset(authattrval, 0, 16);
853 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
854 HMAC_Update(&hmacctx, rad, RADLEN(rad));
855 HMAC_Final(&hmacctx, authattrval, &md_len);
857 debug(DBG_WARN, "message auth computation failed");
858 pthread_mutex_unlock(&lock);
862 pthread_mutex_unlock(&lock);
866 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
868 if (ATTRTYPE(attrs) == type)
870 length -= ATTRLEN(attrs);
871 attrs += ATTRLEN(attrs);
876 void sendrq(struct server *to, struct request *rq) {
880 pthread_mutex_lock(&to->newrq_mutex);
881 /* might simplify if only try nextid, might be ok */
882 for (i = to->nextid; i < MAX_REQUESTS; i++)
883 if (!to->requests[i].buf)
885 if (i == MAX_REQUESTS) {
886 for (i = 0; i < to->nextid; i++)
887 if (!to->requests[i].buf)
889 if (i == to->nextid) {
890 debug(DBG_WARN, "No room in queue, dropping request");
892 pthread_mutex_unlock(&to->newrq_mutex);
897 rq->buf[1] = (char)i;
899 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
900 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
902 pthread_mutex_unlock(&to->newrq_mutex);
906 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
907 to->requests[i] = *rq;
912 debug(DBG_DBG, "signalling client writer");
913 pthread_cond_signal(&to->newrq_cond);
915 pthread_mutex_unlock(&to->newrq_mutex);
918 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
922 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
924 debug(DBG_WARN, "sendreply: failed to sign message");
928 reply = malloc(sizeof(struct reply));
931 debug(DBG_ERR, "sendreply: malloc failed");
934 memset(reply, 0, sizeof(struct reply));
939 pthread_mutex_lock(&to->replyq->mutex);
941 first = list_first(to->replyq->replies) == NULL;
943 if (!list_push(to->replyq->replies, reply)) {
944 pthread_mutex_unlock(&to->replyq->mutex);
947 debug(DBG_ERR, "sendreply: malloc failed");
952 debug(DBG_DBG, "signalling server writer");
953 pthread_cond_signal(&to->replyq->cond);
955 pthread_mutex_unlock(&to->replyq->mutex);
958 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
959 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
960 static unsigned char first = 1;
961 static EVP_MD_CTX mdctx;
962 unsigned char hash[EVP_MAX_MD_SIZE], *input;
964 uint8_t i, offset = 0, out[128];
966 pthread_mutex_lock(&lock);
968 EVP_MD_CTX_init(&mdctx);
974 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
975 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
976 !EVP_DigestUpdate(&mdctx, input, 16) ||
977 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
979 pthread_mutex_unlock(&lock);
982 for (i = 0; i < 16; i++)
983 out[offset + i] = hash[i] ^ in[offset + i];
984 input = out + offset - 16;
989 memcpy(in, out, len);
990 pthread_mutex_unlock(&lock);
994 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
995 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
996 static unsigned char first = 1;
997 static EVP_MD_CTX mdctx;
998 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1000 uint8_t i, offset = 0, out[128];
1002 pthread_mutex_lock(&lock);
1004 EVP_MD_CTX_init(&mdctx);
1010 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1011 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1012 !EVP_DigestUpdate(&mdctx, input, 16) ||
1013 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1015 pthread_mutex_unlock(&lock);
1018 for (i = 0; i < 16; i++)
1019 out[offset + i] = hash[i] ^ in[offset + i];
1020 input = in + offset;
1025 memcpy(in, out, len);
1026 pthread_mutex_unlock(&lock);
1030 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1031 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1032 static unsigned char first = 1;
1033 static EVP_MD_CTX mdctx;
1034 unsigned char hash[EVP_MAX_MD_SIZE];
1035 unsigned int md_len;
1038 pthread_mutex_lock(&lock);
1040 EVP_MD_CTX_init(&mdctx);
1045 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1046 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1047 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1050 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1051 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1052 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1053 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1054 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1055 pthread_mutex_unlock(&lock);
1060 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1063 for (i = 0; i < 16; i++)
1066 for (offset = 16; offset < len; offset += 16) {
1068 printf("text + offset - 16 c(%d): ", offset / 16);
1069 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1071 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1072 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1073 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1074 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1076 pthread_mutex_unlock(&lock);
1080 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1083 for (i = 0; i < 16; i++)
1084 text[offset + i] ^= hash[i];
1088 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1091 pthread_mutex_unlock(&lock);
1095 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1096 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1097 static unsigned char first = 1;
1098 static EVP_MD_CTX mdctx;
1099 unsigned char hash[EVP_MAX_MD_SIZE];
1100 unsigned int md_len;
1104 pthread_mutex_lock(&lock);
1106 EVP_MD_CTX_init(&mdctx);
1111 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1112 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1113 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1116 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1117 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1118 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1119 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1120 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1121 pthread_mutex_unlock(&lock);
1126 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1129 for (i = 0; i < 16; i++)
1130 plain[i] = text[i] ^ hash[i];
1132 for (offset = 16; offset < len; offset += 16) {
1134 printf("text + offset - 16 c(%d): ", offset / 16);
1135 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1137 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1138 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1139 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1140 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1142 pthread_mutex_unlock(&lock);
1146 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1149 for (i = 0; i < 16; i++)
1150 plain[offset + i] = text[offset + i] ^ hash[i];
1153 memcpy(text, plain, len);
1155 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1158 pthread_mutex_unlock(&lock);
1162 struct realm *id2realm(char *id, uint8_t len) {
1163 struct list_node *entry;
1164 struct realm *realm;
1166 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1167 realm = (struct realm *)entry->data;
1168 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1169 debug(DBG_DBG, "found matching realm: %s", realm->name);
1176 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1179 pthread_mutex_lock(&to->newrq_mutex);
1180 for (i = 0; i < MAX_REQUESTS; i++)
1181 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1183 pthread_mutex_unlock(&to->newrq_mutex);
1185 return i < MAX_REQUESTS;
1188 int attrvalidate(unsigned char *attrs, int length) {
1189 while (length > 1) {
1190 if (ATTRLEN(attrs) < 2) {
1191 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1194 length -= ATTRLEN(attrs);
1196 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1199 attrs += ATTRLEN(attrs);
1202 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1206 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1207 if (len < 16 || len > 128 || len % 16) {
1208 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1212 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1213 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1217 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1219 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1220 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1226 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1229 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1230 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1233 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1234 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1240 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1241 char *oldsecret, char *newsecret) {
1242 unsigned char *attr;
1244 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1245 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1246 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1252 void acclog(unsigned char *attrs, int length, char *host) {
1253 unsigned char *attr;
1256 attr = attrget(attrs, length, RAD_Attr_User_Name);
1258 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1261 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1262 username[ATTRVALLEN(attr)] = '\0';
1263 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1266 void respondaccounting(struct request *rq) {
1267 unsigned char *resp;
1271 debug(DBG_ERR, "respondstatusserver: malloc failed");
1274 memcpy(resp, rq->buf, 20);
1275 resp[0] = RAD_Accounting_Response;
1278 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1279 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1282 void respondstatusserver(struct request *rq) {
1283 unsigned char *resp;
1287 debug(DBG_ERR, "respondstatusserver: malloc failed");
1290 memcpy(resp, rq->buf, 20);
1291 resp[0] = RAD_Access_Accept;
1294 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1295 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1298 void respondreject(struct request *rq, char *message) {
1299 unsigned char *resp;
1302 if (message && *message)
1303 len += 2 + strlen(message);
1307 debug(DBG_ERR, "respondreject: malloc failed");
1310 memcpy(resp, rq->buf, 20);
1311 resp[0] = RAD_Access_Reject;
1312 *(uint16_t *)(resp + 2) = htons(len);
1313 if (message && *message) {
1314 resp[20] = RAD_Attr_Reply_Message;
1315 resp[21] = len - 20;
1316 memcpy(resp + 22, message, len - 22);
1318 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1321 struct server *realm2server(struct realm *realm) {
1322 struct list_node *entry;
1323 struct server *server, *best = NULL;
1325 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1326 server = ((struct clsrvconf *)entry->data)->servers;
1327 if (!server->connectionok)
1329 if (!server->loststatsrv)
1335 if (server->loststatsrv < best->loststatsrv)
1341 void radsrv(struct request *rq) {
1342 uint8_t code, id, *auth, *attrs, *attr;
1344 struct server *to = NULL;
1346 unsigned char *buf, newauth[16];
1347 struct realm *realm = NULL;
1350 code = *(uint8_t *)buf;
1351 id = *(uint8_t *)(buf + 1);
1353 auth = (uint8_t *)(buf + 4);
1355 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1357 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1358 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1366 if (!attrvalidate(attrs, len)) {
1367 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1372 if (code == RAD_Access_Request) {
1373 attr = attrget(attrs, len, RAD_Attr_User_Name);
1375 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1379 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1380 username[ATTRVALLEN(attr)] = '\0';
1381 debug(DBG_DBG, "Access Request with username: %s", username);
1383 realm = id2realm(username, strlen(username));
1385 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1390 to = realm2server(realm);
1391 if (to && rqinqueue(to, rq->from, id)) {
1392 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1398 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1399 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(buf, ATTRVAL(attr), rq->from->conf->secret))) {
1400 debug(DBG_WARN, "radsrv: message authentication failed");
1405 if (code == RAD_Accounting_Request) {
1406 acclog(attrs, len, rq->from->conf->host);
1407 respondaccounting(rq);
1412 if (code == RAD_Status_Server) {
1413 respondstatusserver(rq);
1419 if (realm->message) {
1420 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1421 respondreject(rq, realm->message);
1427 if (!RAND_bytes(newauth, 16)) {
1428 debug(DBG_WARN, "radsrv: failed to generate random auth");
1434 printfchars(NULL, "auth", "%02x ", auth, 16);
1437 attr = attrget(attrs, len, RAD_Attr_User_Password);
1439 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1440 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1446 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1448 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1449 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1456 memcpy(rq->origauth, auth, 16);
1457 memcpy(auth, newauth, 16);
1461 void *clientrd(void *arg) {
1462 struct server *server = (struct server *)arg;
1463 struct client *from;
1465 unsigned char *buf, *messageauth, *subattrs, *attrs, *attr;
1466 struct sockaddr_storage fromsa;
1467 struct timeval lastconnecttry;
1471 lastconnecttry = server->lastconnecttry;
1472 buf = (server->conf->type == 'U' ? radudpget(server->sock, NULL, &server, NULL) : radtlsget(server->ssl));
1473 if (!buf && server->conf->type == 'T') {
1474 tlsconnect(server, &lastconnecttry, "clientrd");
1478 server->connectionok = 1;
1479 server->loststatsrv = 0;
1481 i = buf[1]; /* i is the id */
1484 case RAD_Access_Accept:
1485 debug(DBG_DBG, "got Access Accept with id %d", i);
1487 case RAD_Access_Reject:
1488 debug(DBG_DBG, "got Access Reject with id %d", i);
1490 case RAD_Access_Challenge:
1491 debug(DBG_DBG, "got Access Challenge with id %d", i);
1495 debug(DBG_INFO, "clientrd: discarding, only accept access accept, access reject and access challenge messages");
1499 pthread_mutex_lock(&server->newrq_mutex);
1500 if (!server->requests[i].buf || !server->requests[i].tries) {
1501 pthread_mutex_unlock(&server->newrq_mutex);
1503 debug(DBG_INFO, "clientrd: no matching request sent with this id, ignoring");
1507 if (server->requests[i].received) {
1508 pthread_mutex_unlock(&server->newrq_mutex);
1510 debug(DBG_INFO, "clientrd: already received, ignoring");
1514 if (!validauth(buf, server->requests[i].buf + 4, (unsigned char *)server->conf->secret)) {
1515 pthread_mutex_unlock(&server->newrq_mutex);
1517 debug(DBG_WARN, "clientrd: invalid auth, ignoring");
1521 from = server->requests[i].from;
1522 len = RADLEN(buf) - 20;
1525 if (!attrvalidate(attrs, len)) {
1526 pthread_mutex_unlock(&server->newrq_mutex);
1528 debug(DBG_WARN, "clientrd: attribute validation failed, ignoring packet");
1532 /* Message Authenticator */
1533 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1535 if (ATTRVALLEN(messageauth) != 16) {
1536 pthread_mutex_unlock(&server->newrq_mutex);
1538 debug(DBG_WARN, "clientrd: illegal message auth attribute length, ignoring packet");
1541 memcpy(tmp, buf + 4, 16);
1542 memcpy(buf + 4, server->requests[i].buf + 4, 16);
1543 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1544 pthread_mutex_unlock(&server->newrq_mutex);
1546 debug(DBG_WARN, "clientrd: message authentication failed");
1549 memcpy(buf + 4, tmp, 16);
1550 debug(DBG_DBG, "clientrd: message auth ok");
1553 if (*server->requests[i].buf == RAD_Status_Server) {
1554 server->requests[i].received = 1;
1555 pthread_mutex_unlock(&server->newrq_mutex);
1557 debug(DBG_INFO, "clientrd: got status server response from %s", server->conf->host);
1562 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1563 if (ATTRVALLEN(attr) <= 4)
1566 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1569 sublen = ATTRVALLEN(attr) - 4;
1570 subattrs = ATTRVAL(attr) + 4;
1571 if (!attrvalidate(subattrs, sublen) ||
1572 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1573 server->requests + i, server->conf->secret, from->conf->secret) ||
1574 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1575 server->requests + i, server->conf->secret, from->conf->secret))
1579 pthread_mutex_unlock(&server->newrq_mutex);
1581 debug(DBG_WARN, "clientrd: MS attribute handling failed, ignoring packet");
1585 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1586 attr = attrget(server->requests[i].buf + 20, RADLEN(server->requests[i].buf) - 20, RAD_Attr_User_Name);
1587 /* we know the attribute exists */
1588 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1589 tmp[ATTRVALLEN(attr)] = '\0';
1591 case RAD_Access_Accept:
1592 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1594 case RAD_Access_Reject:
1595 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1600 /* once we set received = 1, requests[i] may be reused */
1601 buf[1] = (char)server->requests[i].origid;
1602 memcpy(buf + 4, server->requests[i].origauth, 16);
1604 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1608 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1609 pthread_mutex_unlock(&server->newrq_mutex);
1613 debug(DBG_DBG, "clientrd: computed messageauthattr");
1616 if (from->conf->type == 'U')
1617 fromsa = server->requests[i].fromsa;
1618 server->requests[i].received = 1;
1619 pthread_mutex_unlock(&server->newrq_mutex);
1621 debug(DBG_DBG, "clientrd: giving packet back to where it came from");
1622 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1626 void *clientwr(void *arg) {
1627 struct server *server = (struct server *)arg;
1629 pthread_t clientrdth;
1632 struct timeval now, lastsend;
1633 struct timespec timeout;
1634 struct request statsrvrq;
1635 unsigned char statsrvbuf[38];
1637 memset(&timeout, 0, sizeof(struct timespec));
1639 if (server->conf->statusserver) {
1640 memset(&statsrvrq, 0, sizeof(struct request));
1641 memset(statsrvbuf, 0, sizeof(statsrvbuf));
1642 statsrvbuf[0] = RAD_Status_Server;
1644 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
1645 statsrvbuf[21] = 18;
1646 gettimeofday(&lastsend, NULL);
1649 if (server->conf->type == 'U') {
1650 if ((server->sock = connecttoserver(server->conf->addrinfo)) < 0)
1651 debugx(1, DBG_ERR, "clientwr: connecttoserver failed");
1653 tlsconnect(server, NULL, "new client");
1655 server->connectionok = 1;
1657 if (pthread_create(&clientrdth, NULL, clientrd, (void *)server))
1658 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
1661 pthread_mutex_lock(&server->newrq_mutex);
1662 if (!server->newrq) {
1663 gettimeofday(&now, NULL);
1664 if (server->conf->statusserver) {
1665 /* random 0-7 seconds */
1666 RAND_bytes(&rnd, 1);
1668 if (!timeout.tv_sec || timeout.tv_sec - now.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
1669 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
1671 if (timeout.tv_sec) {
1672 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1673 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1676 debug(DBG_DBG, "clientwr: waiting for new request");
1677 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
1680 if (server->newrq) {
1681 debug(DBG_DBG, "clientwr: got new request");
1684 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1685 pthread_mutex_unlock(&server->newrq_mutex);
1687 for (i = 0; i < MAX_REQUESTS; i++) {
1688 pthread_mutex_lock(&server->newrq_mutex);
1689 while (i < MAX_REQUESTS && !server->requests[i].buf)
1691 if (i == MAX_REQUESTS) {
1692 pthread_mutex_unlock(&server->newrq_mutex);
1695 rq = server->requests + i;
1698 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
1700 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
1702 /* setting this to NULL means that it can be reused */
1705 pthread_mutex_unlock(&server->newrq_mutex);
1709 gettimeofday(&now, NULL);
1710 if (now.tv_sec < rq->expiry.tv_sec) {
1711 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1712 timeout.tv_sec = rq->expiry.tv_sec;
1713 pthread_mutex_unlock(&server->newrq_mutex);
1717 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1718 ? 1 : REQUEST_RETRIES)) {
1719 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1720 if (*rq->buf == RAD_Status_Server) {
1721 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
1722 if (server->loststatsrv < 255)
1723 server->loststatsrv++;
1726 /* setting this to NULL means that it can be reused */
1728 pthread_mutex_unlock(&server->newrq_mutex);
1731 pthread_mutex_unlock(&server->newrq_mutex);
1733 rq->expiry.tv_sec = now.tv_sec +
1734 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
1735 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
1736 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
1737 timeout.tv_sec = rq->expiry.tv_sec;
1739 clientradput(server, server->requests[i].buf);
1740 gettimeofday(&lastsend, NULL);
1742 if (server->conf->statusserver) {
1743 gettimeofday(&now, NULL);
1744 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
1745 if (!RAND_bytes(statsrvbuf + 4, 16)) {
1746 debug(DBG_WARN, "clientwr: failed to generate random auth");
1749 statsrvrq.buf = malloc(sizeof(statsrvbuf));
1750 if (!statsrvrq.buf) {
1751 debug(DBG_ERR, "clientwr: malloc failed");
1754 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
1755 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
1756 lastsend.tv_sec = now.tv_sec;
1757 sendrq(server, &statsrvrq);
1763 void *udpserverwr(void *arg) {
1764 struct replyq *replyq = udp_server_replyq;
1765 struct reply *reply;
1768 pthread_mutex_lock(&replyq->mutex);
1769 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
1770 debug(DBG_DBG, "udp server writer, waiting for signal");
1771 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1772 debug(DBG_DBG, "udp server writer, got signal");
1774 pthread_mutex_unlock(&replyq->mutex);
1776 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
1777 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
1778 debug(DBG_WARN, "sendudp: send failed");
1784 void *udpserverrd(void *arg) {
1786 pthread_t udpserverwrth;
1788 if ((udp_server_sock = bindtoaddr(udp_server_listen->addrinfo)) < 0)
1789 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1791 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
1792 udp_server_listen->host ? udp_server_listen->host : "*", udp_server_listen->port);
1794 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
1795 debugx(1, DBG_ERR, "pthread_create failed");
1798 memset(&rq, 0, sizeof(struct request));
1799 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
1804 void *udpaccserverrd(void *arg) {
1807 if ((udp_accserver_sock = bindtoaddr(udp_accserver_listen->addrinfo)) < 0)
1808 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
1810 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
1811 udp_accserver_listen->host ? udp_accserver_listen->host : "*", udp_accserver_listen->port);
1814 memset(&rq, 0, sizeof(struct request));
1815 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
1816 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
1820 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
1825 void *tlsserverwr(void *arg) {
1827 unsigned long error;
1828 struct client *client = (struct client *)arg;
1829 struct replyq *replyq;
1830 struct reply *reply;
1832 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
1833 replyq = client->replyq;
1835 pthread_mutex_lock(&replyq->mutex);
1836 while (!list_first(replyq->replies)) {
1838 debug(DBG_DBG, "tls server writer, waiting for signal");
1839 pthread_cond_wait(&replyq->cond, &replyq->mutex);
1840 debug(DBG_DBG, "tls server writer, got signal");
1843 /* ssl might have changed while waiting */
1844 pthread_mutex_unlock(&replyq->mutex);
1845 debug(DBG_DBG, "tlsserverwr: exiting as requested");
1849 reply = (struct reply *)list_shift(replyq->replies);
1850 pthread_mutex_unlock(&replyq->mutex);
1851 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
1853 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
1854 cnt, RADLEN(reply->buf));
1856 while ((error = ERR_get_error()))
1857 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
1863 void *tlsserverrd(void *arg) {
1865 unsigned long error;
1867 struct client *client = (struct client *)arg;
1868 pthread_t tlsserverwrth;
1871 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
1874 if (SSL_accept(ssl) <= 0) {
1875 while ((error = ERR_get_error()))
1876 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
1877 debug(DBG_ERR, "SSL_accept failed");
1880 if (tlsverifycert(client->ssl, client->conf)) {
1881 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
1882 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
1886 memset(&rq, 0, sizeof(struct request));
1887 rq.buf = radtlsget(client->ssl);
1890 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
1894 debug(DBG_ERR, "tlsserverrd: connection lost");
1895 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
1897 pthread_mutex_lock(&client->replyq->mutex);
1898 pthread_cond_signal(&client->replyq->cond);
1899 pthread_mutex_unlock(&client->replyq->mutex);
1900 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
1901 pthread_join(tlsserverwrth, NULL);
1905 s = SSL_get_fd(ssl);
1907 shutdown(s, SHUT_RDWR);
1909 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
1910 removeclient(client);
1915 pthread_t tlsserverth;
1917 struct sockaddr_storage from;
1918 size_t fromlen = sizeof(from);
1919 struct clsrvconf *conf;
1920 struct client *client;
1922 if ((s = bindtoaddr(tcp_server_listen->addrinfo)) < 0)
1923 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
1926 debug(DBG_WARN, "listening for incoming TCP on %s:%s",
1927 tcp_server_listen->host ? tcp_server_listen->host : "*", tcp_server_listen->port);
1930 snew = accept(s, (struct sockaddr *)&from, &fromlen);
1932 debug(DBG_WARN, "accept failed");
1935 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
1937 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
1939 debug(DBG_WARN, "ignoring request, not a known TLS client");
1940 shutdown(snew, SHUT_RDWR);
1945 client = addclient(conf);
1948 debug(DBG_WARN, "Failed to create new client instance");
1949 shutdown(snew, SHUT_RDWR);
1953 client->ssl = SSL_new(client->conf->ssl_ctx);
1954 SSL_set_fd(client->ssl, snew);
1955 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
1956 debug(DBG_ERR, "tlslistener: pthread_create failed");
1957 SSL_free(client->ssl);
1958 removeclient(client);
1959 shutdown(snew, SHUT_RDWR);
1963 pthread_detach(tlsserverth);
1968 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
1972 unsigned long error;
1974 if (!certfile || !certkeyfile)
1975 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
1977 if (!cacertfile && !cacertpath)
1978 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
1981 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
1982 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1983 for (i = 0; i < CRYPTO_num_locks(); i++) {
1984 ssl_lock_count[i] = 0;
1985 pthread_mutex_init(&ssl_locks[i], NULL);
1987 CRYPTO_set_id_callback(ssl_thread_id);
1988 CRYPTO_set_locking_callback(ssl_locking_callback);
1990 SSL_load_error_strings();
1993 while (!RAND_status()) {
1994 time_t t = time(NULL);
1995 pid_t pid = getpid();
1996 RAND_seed((unsigned char *)&t, sizeof(time_t));
1997 RAND_seed((unsigned char *)&pid, sizeof(pid));
2000 ctx = SSL_CTX_new(TLSv1_method());
2002 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2003 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2005 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2006 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2007 !SSL_CTX_check_private_key(ctx) ||
2008 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2009 while ((error = ERR_get_error()))
2010 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2011 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2014 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2015 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2017 new = malloc(sizeof(struct tls));
2018 if (!new || !list_push(tlsconfs, new))
2019 debugx(1, DBG_ERR, "malloc failed");
2021 memset(new, 0, sizeof(struct tls));
2022 new->name = stringcopy(value, 0);
2024 debugx(1, DBG_ERR, "malloc failed");
2027 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2031 struct list_node *entry;
2034 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2035 t = (struct tls *)entry->data;
2039 SSL_CTX_free(t->ctx);
2041 list_destroy(tlsconfs);
2045 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2046 struct list_node *entry;
2047 struct tls *t, *t1 = NULL, *t2 = NULL;
2049 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2050 t = (struct tls *)entry->data;
2051 if (!strcasecmp(t->name, alt1)) {
2055 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2066 void addrealm(char *value, char **servers, char *message) {
2068 struct realm *realm;
2069 char *s, *regex = NULL;
2070 struct list_node *entry;
2071 struct clsrvconf *conf;
2073 if (*value == '/') {
2074 /* regexp, remove optional trailing / if present */
2075 if (value[strlen(value) - 1] == '/')
2076 value[strlen(value) - 1] = '\0';
2078 /* not a regexp, let us make it one */
2079 if (*value == '*' && !value[1])
2080 regex = stringcopy(".*", 0);
2082 for (n = 0, s = value; *s;)
2085 regex = malloc(strlen(value) + n + 3);
2088 for (n = 1, s = value; *s; s++) {
2098 debugx(1, DBG_ERR, "malloc failed");
2099 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2102 realm = malloc(sizeof(struct realm));
2104 debugx(1, DBG_ERR, "malloc failed");
2106 memset(realm, 0, sizeof(struct realm));
2107 realm->name = stringcopy(value, 0);
2109 debugx(1, DBG_ERR, "malloc failed");
2110 if (message && strlen(message) > 253)
2111 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2112 realm->message = message;
2114 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2115 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2119 if (servers && *servers) {
2120 realm->srvconfs = list_create();
2121 if (!realm->srvconfs)
2122 debugx(1, DBG_ERR, "malloc failed");
2123 for (n = 0; servers[n]; n++) {
2124 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2125 conf = (struct clsrvconf *)entry->data;
2126 if (!strcasecmp(servers[n], conf->name))
2130 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2131 if (!list_push(realm->srvconfs, conf))
2132 debugx(1, DBG_ERR, "malloc failed");
2133 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2136 realm->srvconfs = NULL;
2138 if (!list_push(realms, realm))
2139 debugx(1, DBG_ERR, "malloc failed");
2140 debug(DBG_DBG, "addrealm: added realm %s", value);
2143 char *parsehostport(char *s, struct clsrvconf *conf) {
2148 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
2152 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2154 debugx(1, DBG_ERR, "no ] matching initial [");
2158 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2161 debugx(1, DBG_ERR, "missing host/address");
2163 conf->host = stringcopy(field, p - field);
2166 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
2167 debugx(1, DBG_ERR, "unexpected character after ]");
2170 /* port number or service name is specified */;
2172 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
2174 debugx(1, DBG_ERR, "syntax error, : but no following port");
2175 conf->port = stringcopy(field, p - field);
2177 conf->port = stringcopy(conf->type == 'U' ? DEFAULT_UDP_PORT : DEFAULT_TLS_PORT, 0);
2181 FILE *openconfigfile(const char *filename) {
2183 char pathname[100], *base = NULL;
2185 f = fopen(filename, "r");
2187 debug(DBG_DBG, "reading config file %s", filename);
2191 if (strlen(filename) + 1 <= sizeof(pathname)) {
2192 /* basename() might modify the string */
2193 strcpy(pathname, filename);
2194 base = basename(pathname);
2195 f = fopen(base, "r");
2199 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2201 debug(DBG_DBG, "reading config file %s", base);
2205 struct clsrvconf *server_create(char type, char *lconf) {
2206 struct clsrvconf *conf;
2208 conf = malloc(sizeof(struct clsrvconf));
2210 debugx(1, DBG_ERR, "malloc failed");
2211 memset(conf, 0, sizeof(struct clsrvconf));
2214 parsehostport(lconf, conf);
2215 if (!strcmp(conf->host, "*")) {
2220 conf->port = stringcopy(type == 'T' ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT, 0);
2221 if (!resolvepeer(conf, AI_PASSIVE))
2222 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2226 /* returns NULL on error, where to continue parsing if token and ok. E.g. "" will return token with empty string */
2227 char *strtokenquote(char *s, char **token, char *del, char *quote, char *comment) {
2228 char *t = s, *q, *r;
2230 if (!t || !token || !del)
2232 while (*t && strchr(del, *t))
2234 if (!*t || (comment && strchr(comment, *t))) {
2236 return t + 1; /* needs to be non-NULL, but value doesn't matter */
2238 if (quote && (q = strchr(quote, *t))) {
2241 while (*t && *t != *q)
2243 if (!*t || (t[1] && !strchr(del, t[1])))
2251 while (*t && !strchr(del, *t))
2257 /* Parses config with following syntax:
2260 * option-name = value
2262 * option-name value {
2263 * option-name [=] value
2267 void getgeneralconfig(FILE *f, char *block, ...) {
2270 /* initialise lots of stuff to avoid stupid compiler warnings */
2271 char *tokens[3], *s, *opt = NULL, *val = NULL, *word, *optval, **str = NULL, ***mstr = NULL;
2272 int type = 0, tcount, conftype = 0, n;
2273 void (*cbk)(FILE *, char *, char *, char *) = NULL;
2275 while (fgets(line, 1024, f)) {
2277 for (tcount = 0; tcount < 3; tcount++) {
2278 s = strtokenquote(s, &tokens[tcount], " \t\n", "\"'", tcount ? NULL : "#");
2280 debugx(1, DBG_ERR, "Syntax error in line starting with: %s", line);
2281 if (!tokens[tcount])
2284 if (!tcount || **tokens == '#')
2287 if (**tokens == '}') {
2290 debugx(1, DBG_ERR, "configuration error, found } with no matching {");
2297 conftype = CONF_STR;
2300 if (tokens[1][0] == '=' && tokens[1][1] == '\0') {
2303 conftype = CONF_STR;
2306 if (tokens[2][0] == '{' && tokens[2][1] == '\0') {
2309 conftype = CONF_CBK;
2315 debugx(1, DBG_ERR, "configuration error in block %s, line starting with %s", block, tokens[0]);
2316 debugx(1, DBG_ERR, "configuration error, syntax error in line starting with %s", tokens[0]);
2320 debugx(1, DBG_ERR, "configuration error, option %s needs a non-empty value", opt);
2322 va_start(ap, block);
2323 while ((word = va_arg(ap, char *))) {
2324 type = va_arg(ap, int);
2327 str = va_arg(ap, char **);
2329 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2332 mstr = va_arg(ap, char ***);
2334 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2337 cbk = va_arg(ap, void (*)(FILE *, char *, char *, char *));
2340 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2342 if (!strcasecmp(opt, word))
2349 debugx(1, DBG_ERR, "configuration error in block %s, unknown option %s", block, opt);
2350 debugx(1, DBG_ERR, "configuration error, unknown option %s", opt);
2353 if (((type == CONF_STR || type == CONF_MSTR) && conftype != CONF_STR) ||
2354 (type == CONF_CBK && conftype != CONF_CBK)) {
2356 debugx(1, DBG_ERR, "configuration error in block %s, wrong syntax for option %s", block, opt);
2357 debugx(1, DBG_ERR, "configuration error, wrong syntax for option %s", opt);
2363 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2365 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2366 *str = stringcopy(val, 0);
2368 debugx(1, DBG_ERR, "malloc failed");
2372 debug(DBG_DBG, "getgeneralconfig: block %s: %s = %s", block, opt, val);
2374 debug(DBG_DBG, "getgeneralconfig: %s = %s", opt, val);
2376 for (n = 0; (*mstr)[n]; n++);
2379 *mstr = realloc(*mstr, sizeof(char *) * (n + 2));
2381 debugx(1, DBG_ERR, "malloc failed");
2382 (*mstr)[n] = stringcopy(val, 0);
2383 (*mstr)[n + 1] = NULL;
2386 optval = malloc(strlen(opt) + strlen(val) + 2);
2388 debugx(1, DBG_ERR, "malloc failed");
2389 sprintf(optval, "%s %s", opt, val);
2390 cbk(f, optval, opt, val);
2394 debugx(1, DBG_ERR, "getgeneralconfig: internal parameter error");
2399 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2402 v = matchcertattr + 20;
2403 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2405 /* regexp, remove optional trailing / if present */
2406 if (v[strlen(v) - 1] == '/')
2407 v[strlen(v) - 1] = '\0';
2411 conf->certuriregex = malloc(sizeof(regex_t));
2412 if (!conf->certuriregex) {
2413 debug(DBG_ERR, "malloc failed");
2416 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2417 free(conf->certuriregex);
2418 conf->certuriregex = NULL;
2419 debug(DBG_ERR, "failed to compile regular expression %s", v);
2425 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2428 v = rewriteattr + 11;
2429 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2431 /* regexp, remove optional trailing / if present */
2432 if (v[strlen(v) - 1] == '/')
2433 v[strlen(v) - 1] = '\0';
2440 conf->rewriteattrregex = malloc(sizeof(regex_t));
2441 if (!conf->rewriteattrregex) {
2442 debug(DBG_ERR, "malloc failed");
2446 conf->rewriteattrreplacement = stringcopy(w, 0);
2447 if (!conf->rewriteattrreplacement) {
2448 free(conf->rewriteattrregex);
2449 conf->rewriteattrregex = NULL;
2453 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2454 free(conf->rewriteattrregex);
2455 conf->rewriteattrregex = NULL;
2456 free(conf->rewriteattrreplacement);
2457 conf->rewriteattrreplacement = NULL;
2458 debug(DBG_ERR, "failed to compile regular expression %s", v);
2465 void confclient_cb(FILE *f, char *block, char *opt, char *val) {
2466 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewriteattr = NULL;
2467 struct clsrvconf *conf;
2469 debug(DBG_DBG, "confclient_cb called for %s", block);
2471 conf = malloc(sizeof(struct clsrvconf));
2472 if (!conf || !list_push(clconfs, conf))
2473 debugx(1, DBG_ERR, "malloc failed");
2474 memset(conf, 0, sizeof(struct clsrvconf));
2476 getgeneralconfig(f, block,
2477 "type", CONF_STR, &type,
2478 "host", CONF_STR, &conf->host,
2479 "secret", CONF_STR, &conf->secret,
2480 "tls", CONF_STR, &tls,
2481 "matchcertificateattribute", CONF_STR, &matchcertattr,
2482 "rewriteattribute", CONF_STR, &rewriteattr,
2486 /* leave conf->name to be NULL for clients */
2488 conf->host = stringcopy(val, 0);
2490 if (type && !strcasecmp(type, "udp")) {
2493 } else if (type && !strcasecmp(type, "tls")) {
2494 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2496 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2497 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2498 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2502 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2507 free(matchcertattr);
2510 if (!addrewriteattr(conf, rewriteattr))
2511 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2515 if (!resolvepeer(conf, 0))
2516 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2518 if (!conf->secret) {
2519 if (conf->type == 'U')
2520 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2521 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2525 void confserver_cb(FILE *f, char *block, char *opt, char *val) {
2526 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL;
2527 struct clsrvconf *conf;
2529 debug(DBG_DBG, "confserver_cb called for %s", block);
2531 conf = malloc(sizeof(struct clsrvconf));
2532 if (!conf || !list_push(srvconfs, conf))
2533 debugx(1, DBG_ERR, "malloc failed");
2534 memset(conf, 0, sizeof(struct clsrvconf));
2536 getgeneralconfig(f, block,
2537 "type", CONF_STR, &type,
2538 "host", CONF_STR, &conf->host,
2539 "port", CONF_STR, &conf->port,
2540 "secret", CONF_STR, &conf->secret,
2541 "tls", CONF_STR, &tls,
2542 "matchcertificateattribute", CONF_STR, &matchcertattr,
2543 "StatusServer", CONF_STR, &statusserver,
2547 conf->name = stringcopy(val, 0);
2549 conf->host = stringcopy(val, 0);
2551 if (type && !strcasecmp(type, "udp")) {
2555 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2556 } else if (type && !strcasecmp(type, "tls")) {
2557 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2559 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2560 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2561 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2563 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2567 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2572 free(matchcertattr);
2574 if (!resolvepeer(conf, 0))
2575 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host, conf->port);
2577 if (!conf->secret) {
2578 if (conf->type == 'U')
2579 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2580 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2584 if (!strcasecmp(statusserver, "on"))
2585 conf->statusserver = 1;
2586 else if (strcasecmp(statusserver, "off"))
2587 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2592 void confrealm_cb(FILE *f, char *block, char *opt, char *val) {
2593 char **servers = NULL, *msg = NULL;
2595 debug(DBG_DBG, "confrealm_cb called for %s", block);
2597 getgeneralconfig(f, block,
2598 "server", CONF_MSTR, &servers,
2599 "ReplyMessage", CONF_STR, &msg,
2603 addrealm(val, servers, msg);
2607 void conftls_cb(FILE *f, char *block, char *opt, char *val) {
2608 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2610 debug(DBG_DBG, "conftls_cb called for %s", block);
2612 getgeneralconfig(f, block,
2613 "CACertificateFile", CONF_STR, &cacertfile,
2614 "CACertificatePath", CONF_STR, &cacertpath,
2615 "CertificateFile", CONF_STR, &certfile,
2616 "CertificateKeyFile", CONF_STR, &certkeyfile,
2617 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2621 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2629 void getmainconfig(const char *configfile) {
2631 char *loglevel = NULL;
2633 f = openconfigfile(configfile);
2634 memset(&options, 0, sizeof(options));
2636 clconfs = list_create();
2638 debugx(1, DBG_ERR, "malloc failed");
2640 srvconfs = list_create();
2642 debugx(1, DBG_ERR, "malloc failed");
2644 realms = list_create();
2646 debugx(1, DBG_ERR, "malloc failed");
2648 tlsconfs = list_create();
2650 debugx(1, DBG_ERR, "malloc failed");
2652 getgeneralconfig(f, NULL,
2653 "ListenUDP", CONF_STR, &options.listenudp,
2654 "ListenTCP", CONF_STR, &options.listentcp,
2655 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2656 "LogLevel", CONF_STR, &loglevel,
2657 "LogDestination", CONF_STR, &options.logdestination,
2658 "Client", CONF_CBK, confclient_cb,
2659 "Server", CONF_CBK, confserver_cb,
2660 "Realm", CONF_CBK, confrealm_cb,
2661 "TLS", CONF_CBK, conftls_cb,
2668 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2669 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
2670 options.loglevel = *loglevel - '0';
2675 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *loglevel, char **configfile) {
2678 while ((c = getopt(argc, argv, "c:d:fv")) != -1) {
2681 *configfile = optarg;
2684 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
2685 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
2686 *loglevel = *optarg - '0';
2692 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
2697 if (!(argc - optind))
2701 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -v ]", argv[0]);
2705 int main(int argc, char **argv) {
2706 pthread_t udpserverth, udpaccserverth;
2707 struct list_node *entry;
2708 uint8_t foreground = 0, loglevel = 0;
2709 char *configfile = NULL;
2711 debug_init("radsecproxy");
2712 debug_set_level(DEBUG_LEVEL);
2713 getargs(argc, argv, &foreground, &loglevel, &configfile);
2715 debug_set_level(loglevel);
2716 getmainconfig(configfile ? configfile : CONFIG_MAIN);
2718 options.loglevel = loglevel;
2719 else if (options.loglevel)
2720 debug_set_level(options.loglevel);
2722 options.logdestination = NULL;
2724 if (!options.logdestination)
2725 options.logdestination = "x-syslog:///";
2726 debug_set_destination(options.logdestination);
2729 if (!list_first(clconfs))
2730 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
2731 if (!list_first(srvconfs))
2732 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
2733 if (!list_first(realms))
2734 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
2736 if (!foreground && (daemon(0, 0) < 0))
2737 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
2739 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
2741 if (client_udp_count) {
2742 udp_server_listen = server_create('U', options.listenudp);
2743 udp_server_replyq = newreplyq();
2744 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
2745 debugx(1, DBG_ERR, "pthread_create failed");
2746 if (options.listenaccudp) {
2747 udp_accserver_listen = server_create('U', options.listenaccudp);
2748 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
2749 debugx(1, DBG_ERR, "pthread_create failed");
2753 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2754 addserver((struct clsrvconf *)entry->data);
2755 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
2756 (void *)((struct clsrvconf *)entry->data)->servers))
2757 debugx(1, DBG_ERR, "pthread_create failed");
2760 if (client_tls_count) {
2761 tcp_server_listen = server_create('T', options.listentcp);
2762 return tlslistener();
2765 /* just hang around doing nothing, anything to do here? */