2 * Copyright (C) 2006-2008 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 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
59 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
71 #include "radsecproxy.h"
77 static struct options options;
78 static struct list *clconfs, *srvconfs;
79 static struct list *realms;
80 static struct hash *rewriteconfs;
82 static pthread_mutex_t *ssl_locks = NULL;
83 static long *ssl_lock_count;
86 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
88 /* minimum required declarations to avoid reordering code */
89 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
90 int dynamicconfig(struct server *server);
91 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
92 void freerealm(struct realm *realm);
93 void freeclsrvconf(struct clsrvconf *conf);
94 void freerq(struct request *rq);
95 void freerqoutdata(struct rqout *rqout);
96 void rmclientrq(struct request *rq, uint8_t id);
98 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
100 uint8_t protoname2int(const char *name) {
103 for (i = 0; i < RAD_PROTOCOUNT; i++)
104 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
109 /* callbacks for making OpenSSL thread safe */
110 unsigned long ssl_thread_id() {
111 return (unsigned long)pthread_self();
114 void ssl_locking_callback(int mode, int type, const char *file, int line) {
115 if (mode & CRYPTO_LOCK) {
116 pthread_mutex_lock(&ssl_locks[type]);
117 ssl_lock_count[type]++;
119 pthread_mutex_unlock(&ssl_locks[type]);
122 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
123 struct addrinfo hints, *addrinfo, *res;
127 slash = conf->host ? strchr(conf->host, '/') : NULL;
131 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
135 if (*s < '0' || *s > '9') {
136 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
139 plen = atoi(slash + 1);
140 if (plen < 0 || plen > 128) {
141 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
146 memset(&hints, 0, sizeof(hints));
147 hints.ai_socktype = conf->pdef->socktype;
148 hints.ai_family = AF_UNSPEC;
149 hints.ai_flags = ai_flags;
150 if (!conf->host && !conf->port) {
151 /* getaddrinfo() doesn't like host and port to be NULL */
152 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
153 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
156 for (res = addrinfo; res; res = res->ai_next)
157 port_set(res->ai_addr, 0);
160 hints.ai_flags |= AI_NUMERICHOST;
161 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
162 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
167 switch (addrinfo->ai_family) {
170 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
171 freeaddrinfo(addrinfo);
178 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
179 freeaddrinfo(addrinfo);
182 conf->prefixlen = (uint8_t)plen;
184 conf->prefixlen = 255;
187 freeaddrinfo(conf->addrinfo);
188 conf->addrinfo = addrinfo;
192 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
197 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
201 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
203 debugx(1, DBG_ERR, "no ] matching initial [");
207 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
210 debugx(1, DBG_ERR, "missing host/address");
212 conf->host = stringcopy(field, p - field);
215 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
216 debugx(1, DBG_ERR, "unexpected character after ]");
219 /* port number or service name is specified */;
221 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
223 debugx(1, DBG_ERR, "syntax error, : but no following port");
224 conf->port = stringcopy(field, p - field);
226 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
230 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
231 struct clsrvconf *conf;
233 conf = malloc(sizeof(struct clsrvconf));
235 debugx(1, DBG_ERR, "malloc failed");
236 memset(conf, 0, sizeof(struct clsrvconf));
238 conf->pdef = protodefs[conf->type];
240 parsehostport(lconf, conf, default_port);
241 if (!strcmp(conf->host, "*")) {
246 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
247 if (!resolvepeer(conf, AI_PASSIVE))
248 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
252 void freeclsrvres(struct clsrvconf *res) {
256 freeaddrinfo(res->addrinfo);
260 struct addrinfo *resolve_hostport_addrinfo(uint8_t type, char *hostport) {
262 struct clsrvconf *res;
264 res = resolve_hostport(type, hostport, NULL);
266 res->addrinfo = NULL;
271 /* returns 1 if the len first bits are equal, else 0 */
272 int prefixmatch(void *a1, void *a2, uint8_t len) {
273 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
274 uint8_t r, l = len / 8;
275 if (l && memcmp(a1, a2, l))
280 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
283 /* returns next config with matching address, or NULL */
284 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
285 struct sockaddr_in6 *sa6 = NULL;
286 struct in_addr *a4 = NULL;
287 struct addrinfo *res;
288 struct list_node *entry;
289 struct clsrvconf *conf;
291 if (addr->sa_family == AF_INET6) {
292 sa6 = (struct sockaddr_in6 *)addr;
293 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
294 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
298 a4 = &((struct sockaddr_in *)addr)->sin_addr;
300 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
301 conf = (struct clsrvconf *)entry->data;
302 if (conf->type == type) {
303 if (conf->prefixlen == 255) {
304 for (res = conf->addrinfo; res; res = res->ai_next)
305 if ((a4 && res->ai_family == AF_INET &&
306 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
307 (sa6 && res->ai_family == AF_INET6 &&
308 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
314 res = conf->addrinfo;
316 ((a4 && res->ai_family == AF_INET &&
317 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
318 (sa6 && res->ai_family == AF_INET6 &&
319 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
330 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
331 return find_conf(type, addr, clconfs, cur);
334 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
335 return find_conf(type, addr, srvconfs, cur);
338 /* returns next config of given type, or NULL */
339 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
340 struct list_node *entry;
341 struct clsrvconf *conf;
343 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
344 conf = (struct clsrvconf *)entry->data;
345 if (conf->type == type) {
354 struct gqueue *newqueue() {
357 q = malloc(sizeof(struct gqueue));
359 debugx(1, DBG_ERR, "malloc failed");
360 q->entries = list_create();
362 debugx(1, DBG_ERR, "malloc failed");
363 pthread_mutex_init(&q->mutex, NULL);
364 pthread_cond_init(&q->cond, NULL);
368 void removequeue(struct gqueue *q) {
369 struct list_node *entry;
373 pthread_mutex_lock(&q->mutex);
374 for (entry = list_first(q->entries); entry; entry = list_next(entry))
375 freerq((struct request *)entry);
376 list_destroy(q->entries);
377 pthread_cond_destroy(&q->cond);
378 pthread_mutex_unlock(&q->mutex);
379 pthread_mutex_destroy(&q->mutex);
383 void freebios(struct gqueue *q) {
386 pthread_mutex_lock(&q->mutex);
387 while ((bio = (BIO *)list_shift(q->entries)))
389 pthread_mutex_unlock(&q->mutex);
393 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
394 struct client *new = malloc(sizeof(struct client));
397 debug(DBG_ERR, "malloc failed");
402 pthread_mutex_lock(conf->lock);
403 if (!conf->clients) {
404 conf->clients = list_create();
405 if (!conf->clients) {
407 pthread_mutex_unlock(conf->lock);
408 debug(DBG_ERR, "malloc failed");
413 memset(new, 0, sizeof(struct client));
415 if (conf->pdef->addclient)
416 conf->pdef->addclient(new);
418 new->replyq = newqueue();
419 list_push(conf->clients, new);
421 pthread_mutex_unlock(conf->lock);
425 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
426 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
429 pthread_mutex_lock(&lock);
431 pthread_mutex_unlock(&lock);
434 void removeclientrqs(struct client *client) {
439 removeclientrqs_sendrq_freeserver_lock(1);
440 for (i = 0; i < MAX_REQUESTS; i++) {
445 rqout = rq->to->requests + rq->newid;
446 pthread_mutex_lock(rqout->lock);
447 if (rqout->rq == rq) /* still pointing to our request */
448 freerqoutdata(rqout);
449 pthread_mutex_unlock(rqout->lock);
453 removeclientrqs_sendrq_freeserver_lock(0);
456 void removelockedclient(struct client *client) {
457 struct clsrvconf *conf;
461 removeclientrqs(client);
462 removequeue(client->replyq);
463 list_removedata(conf->clients, client);
469 void removeclient(struct client *client) {
470 struct clsrvconf *conf;
476 pthread_mutex_lock(conf->lock);
477 removelockedclient(client);
478 pthread_mutex_unlock(conf->lock);
481 void freeserver(struct server *server, uint8_t destroymutex) {
482 struct rqout *rqout, *end;
487 removeclientrqs_sendrq_freeserver_lock(1);
488 if (server->requests) {
489 rqout = server->requests;
490 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
492 rqout->rq->to = NULL;
493 freerqoutdata(rqout);
494 pthread_mutex_destroy(rqout->lock);
497 free(server->requests);
500 freebios(server->rbios);
501 free(server->dynamiclookuparg);
503 SSL_free(server->ssl);
505 pthread_mutex_destroy(&server->lock);
506 pthread_cond_destroy(&server->newrq_cond);
507 pthread_mutex_destroy(&server->newrq_mutex);
509 removeclientrqs_sendrq_freeserver_lock(0);
513 int addserver(struct clsrvconf *conf) {
517 debug(DBG_ERR, "addserver: currently works with just one server per conf");
520 conf->servers = malloc(sizeof(struct server));
521 if (!conf->servers) {
522 debug(DBG_ERR, "malloc failed");
525 memset(conf->servers, 0, sizeof(struct server));
526 conf->servers->conf = conf;
529 if (conf->type == RAD_DTLS)
530 conf->servers->rbios = newqueue();
532 conf->pdef->setsrcres();
534 conf->servers->sock = -1;
535 if (conf->pdef->addserverextra)
536 conf->pdef->addserverextra(conf);
538 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
539 if (!conf->servers->requests) {
540 debug(DBG_ERR, "malloc failed");
543 for (i = 0; i < MAX_REQUESTS; i++) {
544 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
545 if (!conf->servers->requests[i].lock) {
546 debug(DBG_ERR, "malloc failed");
549 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
550 debug(DBG_ERR, "mutex init failed");
551 free(conf->servers->requests[i].lock);
552 conf->servers->requests[i].lock = NULL;
556 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
557 debug(DBG_ERR, "mutex init failed");
560 conf->servers->newrq = 0;
561 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
562 debug(DBG_ERR, "mutex init failed");
563 pthread_mutex_destroy(&conf->servers->lock);
566 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
567 debug(DBG_ERR, "mutex init failed");
568 pthread_mutex_destroy(&conf->servers->newrq_mutex);
569 pthread_mutex_destroy(&conf->servers->lock);
576 freeserver(conf->servers, 0);
577 conf->servers = NULL;
581 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
583 if (ATTRTYPE(attrs) == type)
585 length -= ATTRLEN(attrs);
586 attrs += ATTRLEN(attrs);
591 struct request *newrqref(struct request *rq) {
597 void freerq(struct request *rq) {
600 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
603 if (rq->origusername)
604 free(rq->origusername);
610 radmsg_free(rq->msg);
614 void freerqoutdata(struct rqout *rqout) {
618 if (rqout->rq->buf) {
619 free(rqout->rq->buf);
620 rqout->rq->buf = NULL;
626 memset(&rqout->expiry, 0, sizeof(struct timeval));
629 void sendrq(struct request *rq) {
633 removeclientrqs_sendrq_freeserver_lock(1);
638 start = to->conf->statusserver ? 1 : 0;
639 pthread_mutex_lock(&to->newrq_mutex);
640 if (start && rq->msg->code == RAD_Status_Server) {
641 pthread_mutex_lock(to->requests[0].lock);
642 if (to->requests[0].rq) {
643 pthread_mutex_unlock(to->requests[0].lock);
644 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
651 /* might simplify if only try nextid, might be ok */
652 for (i = to->nextid; i < MAX_REQUESTS; i++) {
653 if (!to->requests[i].rq) {
654 pthread_mutex_lock(to->requests[i].lock);
655 if (!to->requests[i].rq)
657 pthread_mutex_unlock(to->requests[i].lock);
660 if (i == MAX_REQUESTS) {
661 for (i = start; i < to->nextid; i++) {
662 if (!to->requests[i].rq) {
663 pthread_mutex_lock(to->requests[i].lock);
664 if (!to->requests[i].rq)
666 pthread_mutex_unlock(to->requests[i].lock);
669 if (i == to->nextid) {
670 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
675 rq->newid = (uint8_t)i;
676 rq->msg->id = (uint8_t)i;
677 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
679 pthread_mutex_unlock(to->requests[i].lock);
680 debug(DBG_ERR, "sendrq: radmsg2buf failed");
684 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
685 to->requests[i].rq = rq;
686 pthread_mutex_unlock(to->requests[i].lock);
687 if (i >= start) /* i is not reserved for statusserver */
692 debug(DBG_DBG, "sendrq: signalling client writer");
693 pthread_cond_signal(&to->newrq_cond);
696 pthread_mutex_unlock(&to->newrq_mutex);
697 removeclientrqs_sendrq_freeserver_lock(0);
702 rmclientrq(rq, rq->msg->id);
704 pthread_mutex_unlock(&to->newrq_mutex);
705 removeclientrqs_sendrq_freeserver_lock(0);
708 void sendreply(struct request *rq) {
710 struct client *to = rq->from;
713 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
714 radmsg_free(rq->msg);
718 debug(DBG_ERR, "sendreply: radmsg2buf failed");
722 pthread_mutex_lock(&to->replyq->mutex);
723 first = list_first(to->replyq->entries) == NULL;
725 if (!list_push(to->replyq->entries, rq)) {
726 pthread_mutex_unlock(&to->replyq->mutex);
728 debug(DBG_ERR, "sendreply: malloc failed");
733 debug(DBG_DBG, "signalling server writer");
734 pthread_cond_signal(&to->replyq->cond);
736 pthread_mutex_unlock(&to->replyq->mutex);
739 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
740 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
741 static unsigned char first = 1;
742 static EVP_MD_CTX mdctx;
743 unsigned char hash[EVP_MAX_MD_SIZE], *input;
745 uint8_t i, offset = 0, out[128];
747 pthread_mutex_lock(&lock);
749 EVP_MD_CTX_init(&mdctx);
755 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
756 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
757 !EVP_DigestUpdate(&mdctx, input, 16) ||
758 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
760 pthread_mutex_unlock(&lock);
763 for (i = 0; i < 16; i++)
764 out[offset + i] = hash[i] ^ in[offset + i];
765 input = out + offset - 16;
770 memcpy(in, out, len);
771 pthread_mutex_unlock(&lock);
775 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
776 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
777 static unsigned char first = 1;
778 static EVP_MD_CTX mdctx;
779 unsigned char hash[EVP_MAX_MD_SIZE], *input;
781 uint8_t i, offset = 0, out[128];
783 pthread_mutex_lock(&lock);
785 EVP_MD_CTX_init(&mdctx);
791 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
792 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
793 !EVP_DigestUpdate(&mdctx, input, 16) ||
794 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
796 pthread_mutex_unlock(&lock);
799 for (i = 0; i < 16; i++)
800 out[offset + i] = hash[i] ^ in[offset + i];
806 memcpy(in, out, len);
807 pthread_mutex_unlock(&lock);
811 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
812 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
813 static unsigned char first = 1;
814 static EVP_MD_CTX mdctx;
815 unsigned char hash[EVP_MAX_MD_SIZE];
819 pthread_mutex_lock(&lock);
821 EVP_MD_CTX_init(&mdctx);
826 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
827 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
828 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
831 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
832 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
833 !EVP_DigestUpdate(&mdctx, auth, 16) ||
834 !EVP_DigestUpdate(&mdctx, salt, 2) ||
835 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
836 pthread_mutex_unlock(&lock);
841 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
844 for (i = 0; i < 16; i++)
847 for (offset = 16; offset < len; offset += 16) {
849 printf("text + offset - 16 c(%d): ", offset / 16);
850 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
852 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
853 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
854 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
855 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
857 pthread_mutex_unlock(&lock);
861 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
864 for (i = 0; i < 16; i++)
865 text[offset + i] ^= hash[i];
869 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
872 pthread_mutex_unlock(&lock);
876 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
877 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
878 static unsigned char first = 1;
879 static EVP_MD_CTX mdctx;
880 unsigned char hash[EVP_MAX_MD_SIZE];
885 pthread_mutex_lock(&lock);
887 EVP_MD_CTX_init(&mdctx);
892 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
893 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
894 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
897 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
898 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
899 !EVP_DigestUpdate(&mdctx, auth, 16) ||
900 !EVP_DigestUpdate(&mdctx, salt, 2) ||
901 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
902 pthread_mutex_unlock(&lock);
907 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
910 for (i = 0; i < 16; i++)
911 plain[i] = text[i] ^ hash[i];
913 for (offset = 16; offset < len; offset += 16) {
915 printf("text + offset - 16 c(%d): ", offset / 16);
916 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
918 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
919 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
920 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
921 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
923 pthread_mutex_unlock(&lock);
927 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
930 for (i = 0; i < 16; i++)
931 plain[offset + i] = text[offset + i] ^ hash[i];
934 memcpy(text, plain, len);
936 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
939 pthread_mutex_unlock(&lock);
943 struct realm *newrealmref(struct realm *r) {
949 /* returns with lock on realm */
950 struct realm *id2realm(struct list *realmlist, char *id) {
951 struct list_node *entry;
952 struct realm *realm, *subrealm;
954 /* need to do locking for subrealms and check subrealm timers */
955 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
956 realm = (struct realm *)entry->data;
957 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
958 pthread_mutex_lock(&realm->mutex);
959 if (realm->subrealms) {
960 subrealm = id2realm(realm->subrealms, id);
962 pthread_mutex_unlock(&realm->mutex);
966 return newrealmref(realm);
972 /* helper function, only used by removeserversubrealms() */
973 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
974 struct list_node *entry, *entry2;
977 for (entry = list_first(realmlist); entry;) {
978 realm = newrealmref((struct realm *)entry->data);
979 pthread_mutex_lock(&realm->mutex);
980 entry = list_next(entry);
982 if (realm->srvconfs) {
983 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
984 if (entry2->data == srv)
986 list_removedata(realm->srvconfs, srv);
987 if (!list_first(realm->srvconfs)) {
988 list_destroy(realm->srvconfs);
989 realm->srvconfs = NULL;
992 if (realm->accsrvconfs) {
993 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
994 if (entry2->data == srv)
996 list_removedata(realm->accsrvconfs, srv);
997 if (!list_first(realm->accsrvconfs)) {
998 list_destroy(realm->accsrvconfs);
999 realm->accsrvconfs = NULL;
1003 /* remove subrealm if no servers */
1004 if (!realm->srvconfs && !realm->accsrvconfs)
1005 list_removedata(realmlist, realm);
1007 pthread_mutex_unlock(&realm->mutex);
1012 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1013 struct list_node *entry;
1014 struct realm *realm;
1016 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1017 realm = (struct realm *)entry->data;
1018 pthread_mutex_lock(&realm->mutex);
1019 if (realm->subrealms) {
1020 _internal_removeserversubrealms(realm->subrealms, srv);
1021 if (!list_first(realm->subrealms)) {
1022 list_destroy(realm->subrealms);
1023 realm->subrealms = NULL;
1026 pthread_mutex_unlock(&realm->mutex);
1030 int attrvalidate(unsigned char *attrs, int length) {
1031 while (length > 1) {
1032 if (ATTRLEN(attrs) < 2) {
1033 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1036 length -= ATTRLEN(attrs);
1038 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1041 attrs += ATTRLEN(attrs);
1044 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1048 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1049 if (len < 16 || len > 128 || len % 16) {
1050 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1054 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1055 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1059 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1061 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1062 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1068 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1071 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1072 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1075 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1076 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1082 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1083 char *oldsecret, char *newsecret) {
1084 unsigned char *attr;
1086 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1087 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1088 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1094 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
1098 for (; attrs[0]; attrs += 2)
1099 if (attrs[0] == vendor && attrs[1] == subattr)
1104 /* returns 1 if entire element is to be removed, else 0 */
1105 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1106 uint8_t alen, sublen;
1110 if (!removevendorattrs)
1113 memcpy(&vendor, attr->v, 4);
1114 vendor = ntohl(vendor);
1115 while (*removevendorattrs && *removevendorattrs != vendor)
1116 removevendorattrs += 2;
1117 if (!*removevendorattrs)
1120 if (findvendorsubattr(removevendorattrs, vendor, 256))
1121 return 1; /* remove entire vendor attribute */
1123 sublen = attr->l - 4;
1124 subattrs = attr->v + 4;
1126 if (!attrvalidate(subattrs, sublen)) {
1127 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1131 while (sublen > 1) {
1132 alen = ATTRLEN(subattrs);
1134 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1135 memmove(subattrs, subattrs + alen, sublen);
1143 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1144 struct list_node *n, *p;
1148 n = list_first(msg->attrs);
1150 attr = (struct tlv *)n->data;
1151 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1152 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1153 list_removedata(msg->attrs, attr);
1155 n = p ? list_next(p) : list_first(msg->attrs);
1162 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1163 struct list_node *n;
1166 for (n = list_first(addattrs); n; n = list_next(n)) {
1167 a = copytlv((struct tlv *)n->data);
1170 if (!radmsg_add(msg, a)) {
1178 int resizeattr(struct tlv *attr, uint8_t newlen) {
1181 if (newlen != attr->l) {
1182 newv = realloc(attr->v, newlen);
1191 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1192 size_t nmatch = 10, reslen = 0, start = 0;
1193 regmatch_t pmatch[10], *pfield;
1197 in = stringcopy((char *)attr->v, attr->l);
1201 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1206 out = modattr->replacement;
1208 for (i = start; out[i]; i++) {
1209 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1210 pfield = &pmatch[out[i + 1] - '0'];
1211 if (pfield->rm_so >= 0) {
1212 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1218 reslen += i - start;
1220 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1225 if (!resizeattr(attr, reslen)) {
1232 for (i = start; out[i]; i++) {
1233 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1234 pfield = &pmatch[out[i + 1] - '0'];
1235 if (pfield->rm_so >= 0) {
1236 memcpy(attr->v + reslen, out + start, i - start);
1237 reslen += i - start;
1238 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1239 reslen += pfield->rm_eo - pfield->rm_so;
1246 memcpy(attr->v + reslen, out + start, i - start);
1250 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1251 struct list_node *n, *m;
1253 for (n = list_first(msg->attrs); n; n = list_next(n))
1254 for (m = list_first(modattrs); m; m = list_next(m))
1255 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1256 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1261 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1264 if (rewrite->removeattrs || rewrite->removevendorattrs)
1265 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1266 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1268 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1273 int rewriteusername(struct request *rq, struct tlv *attr) {
1274 char *orig = (char *)tlv2str(attr);
1275 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1279 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1280 rq->origusername = (char *)orig;
1286 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1293 vendor = htonl(vendor);
1294 memcpy(v, &vendor, 4);
1295 tlv2buf(v + 4, attr);
1297 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1298 if (vattr && radmsg_add(msg, vattr))
1305 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1312 if (attrtype[1] == 256) { /* not vendor */
1313 attr = maketlv(attrtype[0], 4, ttl);
1314 if (attr && !radmsg_add(msg, attr))
1317 attr = maketlv(attrtype[1], 4, ttl);
1319 addvendorattr(msg, attrtype[0], attr);
1325 int decttl(uint8_t l, uint8_t *v) {
1332 while (i >= 0 && !v[i])
1336 for (i--; i >= 0 && !v[i]; i--);
1345 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1346 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1347 uint8_t alen, *subattrs;
1349 struct list_node *node;
1353 if (attrtype[1] == 256) { /* not vendor */
1354 attr = radmsg_gettype(msg, attrtype[0]);
1356 return decttl(attr->l, attr->v);
1358 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1359 attr = (struct tlv *)node->data;
1360 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1362 memcpy(&vendor, attr->v, 4);
1363 if (ntohl(vendor) != attrtype[0])
1365 sublen = attr->l - 4;
1366 subattrs = attr->v + 4;
1367 if (!attrvalidate(subattrs, sublen))
1369 while (sublen > 1) {
1370 if (ATTRTYPE(subattrs) == attrtype[1])
1371 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1372 alen = ATTRLEN(subattrs);
1380 const char *radmsgtype2string(uint8_t code) {
1381 static const char *rad_msg_names[] = {
1382 "", "Access-Request", "Access-Accept", "Access-Reject",
1383 "Accounting-Request", "Accounting-Response", "", "",
1384 "", "", "", "Access-Challenge",
1385 "Status-Server", "Status-Client"
1387 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1390 void char2hex(char *h, unsigned char c) {
1391 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1392 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1393 h[0] = hexdigits[c / 16];
1394 h[1] = hexdigits[c % 16];
1398 uint8_t *radattr2ascii(struct tlv *attr) {
1406 for (i = 0; i < attr->l; i++)
1407 if (attr->v[i] < 32 || attr->v[i] > 126)
1410 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1417 for (i = 0; i < attr->l; i++)
1418 if (attr->v[i] < 32 || attr->v[i] > 126) {
1420 char2hex((char *)d, attr->v[i]);
1428 void acclog(struct radmsg *msg, char *host) {
1432 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1434 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1437 username = radattr2ascii(attr);
1439 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1444 void respond(struct request *rq, uint8_t code, char *message) {
1448 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1450 debug(DBG_ERR, "respond: malloc failed");
1453 if (message && *message) {
1454 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1455 if (!attr || !radmsg_add(msg, attr)) {
1458 debug(DBG_ERR, "respond: malloc failed");
1463 radmsg_free(rq->msg);
1465 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1466 sendreply(newrqref(rq));
1469 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1470 struct list_node *entry;
1471 struct clsrvconf *server, *best = NULL, *first = NULL;
1473 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1474 server = (struct clsrvconf *)entry->data;
1475 if (!server->servers)
1479 if (!server->servers->connectionok)
1481 if (!server->servers->lostrqs)
1487 if (server->servers->lostrqs < best->servers->lostrqs)
1490 return best ? best : first;
1493 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1494 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1495 struct clsrvconf *srvconf;
1496 struct realm *subrealm;
1497 struct server *server = NULL;
1498 char *id = (char *)tlv2str(username);
1502 /* returns with lock on realm */
1503 *realm = id2realm(realms, id);
1506 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1507 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1510 server = srvconf->servers;
1511 if (!acc && !(*realm)->parent && !srvconf->servers) {
1512 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1514 pthread_mutex_lock(&subrealm->mutex);
1515 pthread_mutex_unlock(&(*realm)->mutex);
1518 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1527 struct request *newrequest() {
1530 rq = malloc(sizeof(struct request));
1532 debug(DBG_ERR, "newrequest: malloc failed");
1535 memset(rq, 0, sizeof(struct request));
1537 gettimeofday(&rq->created, NULL);
1541 int addclientrq(struct request *rq) {
1545 r = rq->from->rqs[rq->rqid];
1547 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1548 gettimeofday(&now, NULL);
1549 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1551 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1552 sendreply(newrqref(r));
1554 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1560 rq->from->rqs[rq->rqid] = newrqref(rq);
1564 void rmclientrq(struct request *rq, uint8_t id) {
1567 r = rq->from->rqs[id];
1570 rq->from->rqs[id] = NULL;
1574 /* returns 0 if validation/authentication fails, else 1 */
1575 int radsrv(struct request *rq) {
1576 struct radmsg *msg = NULL;
1578 uint8_t *userascii = NULL;
1579 struct realm *realm = NULL;
1580 struct server *to = NULL;
1581 struct client *from = rq->from;
1584 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1589 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1596 memcpy(rq->rqauth, msg->auth, 16);
1598 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1599 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1600 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1604 if (!addclientrq(rq))
1607 if (msg->code == RAD_Status_Server) {
1608 respond(rq, RAD_Access_Accept, NULL);
1612 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1614 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1617 ttlres = checkttl(msg, options.ttlattrtype);
1619 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1623 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1625 if (msg->code == RAD_Accounting_Request) {
1626 acclog(msg, from->conf->host);
1627 respond(rq, RAD_Accounting_Response, NULL);
1629 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1633 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1634 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1638 userascii = radattr2ascii(attr);
1641 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1643 /* will return with lock on the realm */
1644 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1646 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1651 if (realm->message && msg->code == RAD_Access_Request) {
1652 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1653 respond(rq, RAD_Access_Reject, realm->message);
1654 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1655 acclog(msg, from->conf->host);
1656 respond(rq, RAD_Accounting_Response, NULL);
1661 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1662 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1663 from->conf->name, addr2string(from->addr), to->conf->name);
1667 if (msg->code == RAD_Accounting_Request)
1668 memset(msg->auth, 0, 16);
1669 else if (!RAND_bytes(msg->auth, 16)) {
1670 debug(DBG_WARN, "radsrv: failed to generate random auth");
1675 printfchars(NULL, "auth", "%02x ", auth, 16);
1678 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1680 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1681 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1685 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1687 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1688 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1692 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1695 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1696 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1701 pthread_mutex_unlock(&realm->mutex);
1706 rmclientrq(rq, msg->id);
1711 pthread_mutex_unlock(&realm->mutex);
1717 void replyh(struct server *server, unsigned char *buf) {
1718 struct client *from;
1719 struct rqout *rqout;
1721 unsigned char *subattrs;
1722 uint8_t *username, *stationid, *replymsg;
1723 struct radmsg *msg = NULL;
1725 struct list_node *node;
1727 server->connectionok = 1;
1728 server->lostrqs = 0;
1730 rqout = server->requests + buf[1];
1731 pthread_mutex_lock(rqout->lock);
1732 if (!rqout->tries) {
1735 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1739 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1743 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1746 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1747 && msg->code != RAD_Accounting_Response) {
1748 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1751 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1753 gettimeofday(&server->lastrcv, NULL);
1755 if (rqout->rq->msg->code == RAD_Status_Server) {
1756 freerqoutdata(rqout);
1757 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1761 gettimeofday(&server->lastreply, NULL);
1762 from = rqout->rq->from;
1764 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1765 debug(DBG_WARN, "replyh: rewritein failed");
1769 ttlres = checkttl(msg, options.ttlattrtype);
1771 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
1776 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1777 attr = (struct tlv *)node->data;
1778 if (attr->t != RAD_Attr_Vendor_Specific)
1782 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1785 sublen = attr->l - 4;
1786 subattrs = attr->v + 4;
1787 if (!attrvalidate(subattrs, sublen) ||
1788 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1789 rqout->rq, server->conf->secret, from->conf->secret) ||
1790 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1791 rqout->rq, server->conf->secret, from->conf->secret))
1795 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1799 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1800 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1802 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1803 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1806 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1807 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1810 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1811 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1815 debug(DBG_INFO, "%s for user %s from %s (%s)",
1816 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1819 debug(DBG_INFO, "%s for user %s from %s",
1820 radmsgtype2string(msg->code), username, server->conf->host);
1826 msg->id = (char)rqout->rq->rqid;
1827 memcpy(msg->auth, rqout->rq->rqauth, 16);
1830 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1833 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1834 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1835 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1838 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1841 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1842 debug(DBG_WARN, "replyh: rewriteout failed");
1846 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1847 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1849 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
1850 radmsg_free(rqout->rq->msg);
1851 rqout->rq->msg = msg;
1852 sendreply(newrqref(rqout->rq));
1853 freerqoutdata(rqout);
1854 pthread_mutex_unlock(rqout->lock);
1859 pthread_mutex_unlock(rqout->lock);
1863 struct request *createstatsrvrq() {
1870 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1873 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1876 if (!radmsg_add(rq->msg, attr)) {
1887 /* code for removing state not finished */
1888 void *clientwr(void *arg) {
1889 struct server *server = (struct server *)arg;
1890 struct rqout *rqout = NULL;
1891 pthread_t clientrdth;
1892 int i, dynconffail = 0;
1895 struct timeval now, laststatsrv;
1896 struct timespec timeout;
1897 struct request *statsrvrq;
1898 struct clsrvconf *conf;
1900 conf = server->conf;
1902 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1907 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
1908 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
1912 memset(&timeout, 0, sizeof(struct timespec));
1914 if (conf->statusserver) {
1915 gettimeofday(&server->lastrcv, NULL);
1916 gettimeofday(&laststatsrv, NULL);
1919 if (conf->pdef->connecter) {
1920 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
1922 server->connectionok = 1;
1923 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1924 debug(DBG_ERR, "clientwr: pthread_create failed");
1928 server->connectionok = 1;
1931 pthread_mutex_lock(&server->newrq_mutex);
1932 if (!server->newrq) {
1933 gettimeofday(&now, NULL);
1934 /* random 0-7 seconds */
1935 RAND_bytes(&rnd, 1);
1937 if (conf->statusserver) {
1938 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1939 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1941 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1942 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1944 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1945 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1948 if (timeout.tv_sec > now.tv_sec)
1949 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1951 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1954 if (server->newrq) {
1955 debug(DBG_DBG, "clientwr: got new request");
1960 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1962 pthread_mutex_unlock(&server->newrq_mutex);
1964 for (i = 0; i < MAX_REQUESTS; i++) {
1965 if (server->clientrdgone) {
1966 pthread_join(clientrdth, NULL);
1970 for (; i < MAX_REQUESTS; i++) {
1971 rqout = server->requests + i;
1973 pthread_mutex_lock(rqout->lock);
1976 pthread_mutex_unlock(rqout->lock);
1980 if (i == MAX_REQUESTS)
1983 gettimeofday(&now, NULL);
1984 if (now.tv_sec < rqout->expiry.tv_sec) {
1985 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1986 timeout.tv_sec = rqout->expiry.tv_sec;
1987 pthread_mutex_unlock(rqout->lock);
1991 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1992 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1993 if (conf->statusserver) {
1994 if (*rqout->rq->buf == RAD_Status_Server) {
1995 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
1996 if (server->lostrqs < 255)
2000 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2001 if (server->lostrqs < 255)
2004 freerqoutdata(rqout);
2005 pthread_mutex_unlock(rqout->lock);
2009 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2010 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2011 timeout.tv_sec = rqout->expiry.tv_sec;
2013 conf->pdef->clientradput(server, rqout->rq->buf);
2014 pthread_mutex_unlock(rqout->lock);
2016 if (conf->statusserver && server->connectionok) {
2017 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2018 gettimeofday(&now, NULL);
2019 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2021 statsrvrq = createstatsrvrq();
2023 statsrvrq->to = server;
2024 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2031 conf->servers = NULL;
2032 if (server->dynamiclookuparg) {
2033 removeserversubrealms(realms, conf);
2037 freeclsrvconf(conf);
2039 freeserver(server, 1);
2040 ERR_remove_state(0);
2044 void createlistener(uint8_t type, char *arg) {
2046 struct clsrvconf *listenres;
2047 struct addrinfo *res;
2048 int s = -1, on = 1, *sp = NULL;
2050 listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2052 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2054 for (res = listenres->addrinfo; res; res = res->ai_next) {
2055 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2057 debug(DBG_WARN, "createlistener: socket failed");
2060 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2062 if (res->ai_family == AF_INET6)
2063 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2065 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2066 debug(DBG_WARN, "createlistener: bind failed");
2072 sp = malloc(sizeof(int));
2074 debugx(1, DBG_ERR, "malloc failed");
2076 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2077 debugx(1, DBG_ERR, "pthread_create failed");
2081 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2083 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2084 listenres->host ? listenres->host : "*", listenres->port);
2085 freeclsrvres(listenres);
2088 void createlisteners(uint8_t type) {
2092 args = protodefs[type]->getlistenerargs();
2094 for (i = 0; args[i]; i++)
2095 createlistener(type, args[i]);
2097 createlistener(type, NULL);
2105 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2106 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2107 for (i = 0; i < CRYPTO_num_locks(); i++) {
2108 ssl_lock_count[i] = 0;
2109 pthread_mutex_init(&ssl_locks[i], NULL);
2111 CRYPTO_set_id_callback(ssl_thread_id);
2112 CRYPTO_set_locking_callback(ssl_locking_callback);
2114 SSL_load_error_strings();
2117 while (!RAND_status()) {
2120 RAND_seed((unsigned char *)&t, sizeof(time_t));
2121 RAND_seed((unsigned char *)&pid, sizeof(pid));
2125 struct list *addsrvconfs(char *value, char **names) {
2126 struct list *conflist;
2128 struct list_node *entry;
2129 struct clsrvconf *conf = NULL;
2131 if (!names || !*names)
2134 conflist = list_create();
2136 debug(DBG_ERR, "malloc failed");
2140 for (n = 0; names[n]; n++) {
2141 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2142 conf = (struct clsrvconf *)entry->data;
2143 if (!strcasecmp(names[n], conf->name))
2147 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2148 list_destroy(conflist);
2151 if (!list_push(conflist, conf)) {
2152 debug(DBG_ERR, "malloc failed");
2153 list_destroy(conflist);
2156 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2161 void freerealm(struct realm *realm) {
2164 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2165 if (--realm->refcount)
2169 free(realm->message);
2170 regfree(&realm->regex);
2171 pthread_mutex_destroy(&realm->mutex);
2172 /* if refcount == 0, all subrealms gone */
2173 list_destroy(realm->subrealms);
2174 /* if refcount == 0, all srvconfs gone */
2175 list_destroy(realm->srvconfs);
2176 /* if refcount == 0, all accsrvconfs gone */
2177 list_destroy(realm->accsrvconfs);
2178 freerealm(realm->parent);
2182 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2184 struct realm *realm;
2185 char *s, *regex = NULL;
2187 if (*value == '/') {
2188 /* regexp, remove optional trailing / if present */
2189 if (value[strlen(value) - 1] == '/')
2190 value[strlen(value) - 1] = '\0';
2192 /* not a regexp, let us make it one */
2193 if (*value == '*' && !value[1])
2194 regex = stringcopy(".*", 0);
2196 for (n = 0, s = value; *s;)
2199 regex = malloc(strlen(value) + n + 3);
2202 for (n = 1, s = value; *s; s++) {
2212 debug(DBG_ERR, "malloc failed");
2216 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2219 realm = malloc(sizeof(struct realm));
2221 debug(DBG_ERR, "malloc failed");
2224 memset(realm, 0, sizeof(struct realm));
2226 if (pthread_mutex_init(&realm->mutex, NULL)) {
2227 debug(DBG_ERR, "mutex init failed");
2233 realm->name = stringcopy(value, 0);
2235 debug(DBG_ERR, "malloc failed");
2238 if (message && strlen(message) > 253) {
2239 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2242 realm->message = message;
2243 realm->accresp = accresp;
2245 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2246 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2250 if (servers && *servers) {
2251 realm->srvconfs = addsrvconfs(value, servers);
2252 if (!realm->srvconfs)
2256 if (accservers && *accservers) {
2257 realm->accsrvconfs = addsrvconfs(value, accservers);
2258 if (!realm->accsrvconfs)
2262 if (!list_push(realmlist, realm)) {
2263 debug(DBG_ERR, "malloc failed");
2264 pthread_mutex_destroy(&realm->mutex);
2268 debug(DBG_DBG, "addrealm: added realm %s", value);
2272 while (list_shift(realm->srvconfs));
2273 while (list_shift(realm->accsrvconfs));
2280 for (n = 0; servers[n]; n++)
2282 freegconfmstr(servers);
2286 for (n = 0; accservers[n]; n++)
2288 freegconfmstr(accservers);
2290 return newrealmref(realm);
2293 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2294 struct clsrvconf *srvconf;
2295 struct realm *newrealm = NULL;
2296 char *realmname, *s;
2299 if (!conf->dynamiclookupcommand)
2302 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2303 realmname = strrchr(id, '@');
2309 for (s = realmname; *s; s++)
2310 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2313 srvconf = malloc(sizeof(struct clsrvconf));
2315 debug(DBG_ERR, "malloc failed");
2319 if (!addserver(srvconf))
2322 if (!realm->subrealms)
2323 realm->subrealms = list_create();
2324 if (!realm->subrealms)
2326 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2329 newrealm->parent = newrealmref(realm);
2331 /* add server and accserver to newrealm */
2332 newrealm->srvconfs = list_create();
2333 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2334 debug(DBG_ERR, "malloc failed");
2337 newrealmref(newrealm);
2338 newrealm->accsrvconfs = list_create();
2339 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2340 debug(DBG_ERR, "malloc failed");
2341 list_shift(realm->srvconfs);
2342 freerealm(newrealm);
2345 newrealmref(newrealm);
2347 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2348 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2349 debug(DBG_ERR, "pthread_create failed");
2350 list_shift(realm->srvconfs);
2351 freerealm(newrealm);
2352 list_shift(realm->accsrvconfs);
2353 freerealm(newrealm);
2356 pthread_detach(clientth);
2361 list_removedata(realm->subrealms, newrealm);
2362 freerealm(newrealm);
2363 if (!list_first(realm->subrealms)) {
2364 list_destroy(realm->subrealms);
2365 realm->subrealms = NULL;
2368 freeserver(srvconf->servers, 1);
2370 debug(DBG_ERR, "failed to create dynamic server");
2374 int dynamicconfig(struct server *server) {
2375 int ok, fd[2], status;
2377 struct clsrvconf *conf = server->conf;
2378 struct gconffile *cf = NULL;
2380 /* for now we only learn hostname/address */
2381 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2384 debug(DBG_ERR, "dynamicconfig: pipe error");
2389 debug(DBG_ERR, "dynamicconfig: fork error");
2393 } else if (pid == 0) {
2396 if (fd[1] != STDOUT_FILENO) {
2397 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2398 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2401 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2402 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2406 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2407 ok = getgenericconfig(&cf, NULL,
2408 "Server", CONF_CBK, confserver_cb, (void *)conf,
2413 if (waitpid(pid, &status, 0) < 0) {
2414 debug(DBG_ERR, "dynamicconfig: wait error");
2419 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2427 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2431 /* should accept both names and numeric values, only numeric right now */
2432 uint8_t attrname2val(char *attrname) {
2435 val = atoi(attrname);
2436 return val > 0 && val < 256 ? val : 0;
2439 /* should accept both names and numeric values, only numeric right now */
2440 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2443 *vendor = atoi(attrname);
2444 s = strchr(attrname, ':');
2449 *type = atoi(s + 1);
2453 /* should accept both names and numeric values, only numeric right now */
2454 struct tlv *extractattr(char *nameval) {
2459 s = strchr(nameval, ':');
2460 name = atoi(nameval);
2461 if (!s || name < 1 || name > 255)
2463 len = strlen(s + 1);
2466 a = malloc(sizeof(struct tlv));
2469 a->v = (uint8_t *)stringcopy(s + 1, 0);
2479 /* should accept both names and numeric values, only numeric right now */
2480 struct modattr *extractmodattr(char *nameval) {
2485 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2489 s = strchr(nameval, ':');
2490 name = atoi(nameval);
2491 if (!s || name < 1 || name > 255 || s[1] != '/')
2495 /* regexp, remove optional trailing / if present */
2496 if (s[strlen(s) - 1] == '/')
2497 s[strlen(s) - 1] = '\0';
2505 m = malloc(sizeof(struct modattr));
2507 debug(DBG_ERR, "malloc failed");
2512 m->replacement = stringcopy(t, 0);
2513 if (!m->replacement) {
2515 debug(DBG_ERR, "malloc failed");
2519 m->regex = malloc(sizeof(regex_t));
2521 free(m->replacement);
2523 debug(DBG_ERR, "malloc failed");
2527 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2529 free(m->replacement);
2531 debug(DBG_ERR, "failed to compile regular expression %s", s);
2538 struct rewrite *getrewrite(char *alt1, char *alt2) {
2541 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2543 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2548 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2549 struct rewrite *rewrite = NULL;
2551 uint8_t *rma = NULL;
2552 uint32_t *p, *rmva = NULL;
2553 struct list *adda = NULL, *moda = NULL;
2558 for (n = 0; rmattrs[n]; n++);
2559 rma = calloc(n + 1, sizeof(uint8_t));
2561 debugx(1, DBG_ERR, "malloc failed");
2563 for (i = 0; i < n; i++)
2564 if (!(rma[i] = attrname2val(rmattrs[i])))
2565 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2566 freegconfmstr(rmattrs);
2571 for (n = 0; rmvattrs[n]; n++);
2572 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2574 debugx(1, DBG_ERR, "malloc failed");
2576 for (p = rmva, i = 0; i < n; i++, p += 2)
2577 if (!vattrname2val(rmvattrs[i], p, p + 1))
2578 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2579 freegconfmstr(rmvattrs);
2584 adda = list_create();
2586 debugx(1, DBG_ERR, "malloc failed");
2587 for (i = 0; addattrs[i]; i++) {
2588 a = extractattr(addattrs[i]);
2590 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2591 if (!list_push(adda, a))
2592 debugx(1, DBG_ERR, "malloc failed");
2594 freegconfmstr(addattrs);
2598 moda = list_create();
2600 debugx(1, DBG_ERR, "malloc failed");
2601 for (i = 0; modattrs[i]; i++) {
2602 m = extractmodattr(modattrs[i]);
2604 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2605 if (!list_push(moda, m))
2606 debugx(1, DBG_ERR, "malloc failed");
2608 freegconfmstr(modattrs);
2611 if (rma || rmva || adda || moda) {
2612 rewrite = malloc(sizeof(struct rewrite));
2614 debugx(1, DBG_ERR, "malloc failed");
2615 rewrite->removeattrs = rma;
2616 rewrite->removevendorattrs = rmva;
2617 rewrite->addattrs = adda;
2618 rewrite->modattrs = moda;
2621 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2622 debugx(1, DBG_ERR, "malloc failed");
2623 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2626 int setttlattr(struct options *opts, char *defaultattr) {
2627 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2629 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2630 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2632 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2636 void freeclsrvconf(struct clsrvconf *conf) {
2642 free(conf->matchcertattr);
2643 if (conf->certcnregex)
2644 regfree(conf->certcnregex);
2645 if (conf->certuriregex)
2646 regfree(conf->certuriregex);
2647 free(conf->confrewritein);
2648 free(conf->confrewriteout);
2649 if (conf->rewriteusername) {
2650 if (conf->rewriteusername->regex)
2651 regfree(conf->rewriteusername->regex);
2652 free(conf->rewriteusername->replacement);
2653 free(conf->rewriteusername);
2655 free(conf->dynamiclookupcommand);
2656 free(conf->rewritein);
2657 free(conf->rewriteout);
2659 freeaddrinfo(conf->addrinfo);
2661 pthread_mutex_destroy(conf->lock);
2664 /* not touching ssl_ctx, clients and servers */
2668 int mergeconfstring(char **dst, char **src) {
2677 t = stringcopy(*dst, 0);
2679 debug(DBG_ERR, "malloc failed");
2687 /* assumes dst is a shallow copy */
2688 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2689 if (!mergeconfstring(&dst->name, &src->name) ||
2690 !mergeconfstring(&dst->host, &src->host) ||
2691 !mergeconfstring(&dst->port, &src->port) ||
2692 !mergeconfstring(&dst->secret, &src->secret) ||
2693 !mergeconfstring(&dst->tls, &src->tls) ||
2694 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2695 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2696 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2697 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2700 dst->pdef = src->pdef;
2701 dst->statusserver = src->statusserver;
2702 dst->certnamecheck = src->certnamecheck;
2703 if (src->retryinterval != 255)
2704 dst->retryinterval = src->retryinterval;
2705 if (src->retrycount != 255)
2706 dst->retrycount = src->retrycount;
2710 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2711 struct clsrvconf *conf;
2712 char *conftype = NULL, *rewriteinalias = NULL;
2713 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2715 debug(DBG_DBG, "confclient_cb called for %s", block);
2717 conf = malloc(sizeof(struct clsrvconf));
2719 debugx(1, DBG_ERR, "malloc failed");
2720 memset(conf, 0, sizeof(struct clsrvconf));
2721 conf->certnamecheck = 1;
2723 if (!getgenericconfig(cf, block,
2724 "type", CONF_STR, &conftype,
2725 "host", CONF_STR, &conf->host,
2726 "secret", CONF_STR, &conf->secret,
2727 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2728 "tls", CONF_STR, &conf->tls,
2729 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2730 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2732 "DuplicateInterval", CONF_LINT, &dupinterval,
2733 "addTTL", CONF_LINT, &addttl,
2734 "rewrite", CONF_STR, &rewriteinalias,
2735 "rewriteIn", CONF_STR, &conf->confrewritein,
2736 "rewriteOut", CONF_STR, &conf->confrewriteout,
2737 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2740 debugx(1, DBG_ERR, "configuration error");
2742 conf->name = stringcopy(val, 0);
2744 conf->host = stringcopy(val, 0);
2745 if (!conf->name || !conf->host)
2746 debugx(1, DBG_ERR, "malloc failed");
2749 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2750 conf->type = protoname2int(conftype);
2751 if (conf->type == 255)
2752 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2754 conf->pdef = protodefs[conf->type];
2756 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2757 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2758 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2760 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2761 if (conf->matchcertattr && !addmatchcertattr(conf))
2762 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2766 if (dupinterval != LONG_MIN) {
2767 if (dupinterval < 0 || dupinterval > 255)
2768 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2769 conf->dupinterval = (uint8_t)dupinterval;
2771 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2773 if (addttl != LONG_MIN) {
2774 if (addttl < 1 || addttl > 255)
2775 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2776 conf->addttl = (uint8_t)addttl;
2779 if (!conf->confrewritein)
2780 conf->confrewritein = rewriteinalias;
2782 free(rewriteinalias);
2783 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2784 if (conf->confrewriteout)
2785 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2787 if (conf->confrewriteusername) {
2788 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2789 if (!conf->rewriteusername)
2790 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2793 if (!resolvepeer(conf, 0))
2794 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2796 if (!conf->secret) {
2797 if (!conf->pdef->secretdefault)
2798 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2799 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2801 debugx(1, DBG_ERR, "malloc failed");
2804 conf->lock = malloc(sizeof(pthread_mutex_t));
2806 debugx(1, DBG_ERR, "malloc failed");
2808 pthread_mutex_init(conf->lock, NULL);
2809 if (!list_push(clconfs, conf))
2810 debugx(1, DBG_ERR, "malloc failed");
2814 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2815 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2816 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2817 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2818 if (!conf->tlsconf) {
2819 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2822 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2823 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2830 conf->port = stringcopy(conf->pdef->portdefault, 0);
2832 debug(DBG_ERR, "malloc failed");
2837 if (conf->retryinterval == 255)
2838 conf->retryinterval = conf->pdef->retryintervaldefault;
2839 if (conf->retrycount == 255)
2840 conf->retrycount = conf->pdef->retrycountdefault;
2842 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2843 if (conf->confrewriteout)
2844 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2846 if (!conf->secret) {
2847 if (!conf->pdef->secretdefault) {
2848 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2851 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2852 if (!conf->secret) {
2853 debug(DBG_ERR, "malloc failed");
2858 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
2859 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2865 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2866 struct clsrvconf *conf, *resconf;
2867 char *conftype = NULL, *rewriteinalias = NULL;
2868 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2870 debug(DBG_DBG, "confserver_cb called for %s", block);
2872 conf = malloc(sizeof(struct clsrvconf));
2874 debug(DBG_ERR, "malloc failed");
2877 memset(conf, 0, sizeof(struct clsrvconf));
2878 resconf = (struct clsrvconf *)arg;
2880 conf->statusserver = resconf->statusserver;
2881 conf->certnamecheck = resconf->certnamecheck;
2883 conf->certnamecheck = 1;
2885 if (!getgenericconfig(cf, block,
2886 "type", CONF_STR, &conftype,
2887 "host", CONF_STR, &conf->host,
2888 "port", CONF_STR, &conf->port,
2889 "secret", CONF_STR, &conf->secret,
2890 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2891 "tls", CONF_STR, &conf->tls,
2892 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2893 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2895 "addTTL", CONF_LINT, &addttl,
2896 "rewrite", CONF_STR, &rewriteinalias,
2897 "rewriteIn", CONF_STR, &conf->confrewritein,
2898 "rewriteOut", CONF_STR, &conf->confrewriteout,
2899 "StatusServer", CONF_BLN, &conf->statusserver,
2900 "RetryInterval", CONF_LINT, &retryinterval,
2901 "RetryCount", CONF_LINT, &retrycount,
2902 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2905 debug(DBG_ERR, "configuration error");
2909 conf->name = stringcopy(val, 0);
2911 debug(DBG_ERR, "malloc failed");
2915 conf->host = stringcopy(val, 0);
2917 debug(DBG_ERR, "malloc failed");
2923 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2924 conf->type = protoname2int(conftype);
2925 if (conf->type == 255) {
2926 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2932 conf->pdef = protodefs[conf->type];
2934 if (!conf->confrewritein)
2935 conf->confrewritein = rewriteinalias;
2937 free(rewriteinalias);
2938 rewriteinalias = NULL;
2940 if (retryinterval != LONG_MIN) {
2941 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2942 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2945 conf->retryinterval = (uint8_t)retryinterval;
2947 conf->retryinterval = 255;
2949 if (retrycount != LONG_MIN) {
2950 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2951 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2954 conf->retrycount = (uint8_t)retrycount;
2956 conf->retrycount = 255;
2958 if (addttl != LONG_MIN) {
2959 if (addttl < 1 || addttl > 255) {
2960 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2963 conf->addttl = (uint8_t)addttl;
2967 if (!mergesrvconf(resconf, conf))
2971 if (conf->dynamiclookupcommand) {
2972 free(conf->dynamiclookupcommand);
2973 conf->dynamiclookupcommand = NULL;
2977 if (resconf || !conf->dynamiclookupcommand) {
2978 if (!compileserverconfig(conf, block))
2985 if (!list_push(srvconfs, conf)) {
2986 debug(DBG_ERR, "malloc failed");
2993 free(rewriteinalias);
2994 freeclsrvconf(conf);
2998 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2999 char **servers = NULL, **accservers = NULL, *msg = NULL;
3000 uint8_t accresp = 0;
3002 debug(DBG_DBG, "confrealm_cb called for %s", block);
3004 if (!getgenericconfig(cf, block,
3005 "server", CONF_MSTR, &servers,
3006 "accountingServer", CONF_MSTR, &accservers,
3007 "ReplyMessage", CONF_STR, &msg,
3008 "AccountingResponse", CONF_BLN, &accresp,
3011 debugx(1, DBG_ERR, "configuration error");
3013 addrealm(realms, val, servers, accservers, msg, accresp);
3017 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3018 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3020 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3022 if (!getgenericconfig(cf, block,
3023 "removeAttribute", CONF_MSTR, &rmattrs,
3024 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3025 "addAttribute", CONF_MSTR, &addattrs,
3026 "modifyAttribute", CONF_MSTR, &modattrs,
3029 debugx(1, DBG_ERR, "configuration error");
3030 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3034 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3035 struct commonprotoopts *protoopts;
3037 protoopts = malloc(sizeof(struct commonprotoopts));
3040 memset(protoopts, 0, sizeof(struct commonprotoopts));
3041 protoopts->listenargs = listenargs;
3042 protoopts->sourcearg = sourcearg;
3043 protodefs[type]->setprotoopts(protoopts);
3047 void getmainconfig(const char *configfile) {
3048 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3049 struct gconffile *cfs;
3050 char **listenargs[RAD_PROTOCOUNT];
3051 char *sourcearg[RAD_PROTOCOUNT];
3054 cfs = openconfigfile(configfile);
3055 memset(&options, 0, sizeof(options));
3056 memset(&listenargs, 0, sizeof(listenargs));
3057 memset(&sourcearg, 0, sizeof(sourcearg));
3059 clconfs = list_create();
3061 debugx(1, DBG_ERR, "malloc failed");
3063 srvconfs = list_create();
3065 debugx(1, DBG_ERR, "malloc failed");
3067 realms = list_create();
3069 debugx(1, DBG_ERR, "malloc failed");
3071 rewriteconfs = hash_create();
3073 debugx(1, DBG_ERR, "malloc failed");
3075 if (!getgenericconfig(&cfs, NULL,
3077 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3078 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3081 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3082 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3085 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3086 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3089 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3090 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3092 "TTLAttribute", CONF_STR, &options.ttlattr,
3093 "addTTL", CONF_LINT, &addttl,
3094 "LogLevel", CONF_LINT, &loglevel,
3095 "LogDestination", CONF_STR, &options.logdestination,
3096 "LoopPrevention", CONF_BLN, &options.loopprevention,
3097 "Client", CONF_CBK, confclient_cb, NULL,
3098 "Server", CONF_CBK, confserver_cb, NULL,
3099 "Realm", CONF_CBK, confrealm_cb, NULL,
3100 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3101 "TLS", CONF_CBK, conftls_cb, NULL,
3103 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3106 debugx(1, DBG_ERR, "configuration error");
3108 if (loglevel != LONG_MIN) {
3109 if (loglevel < 1 || loglevel > 4)
3110 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3111 options.loglevel = (uint8_t)loglevel;
3113 if (addttl != LONG_MIN) {
3114 if (addttl < 1 || addttl > 255)
3115 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3116 options.addttl = (uint8_t)addttl;
3118 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3119 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3121 for (i = 0; i < RAD_PROTOCOUNT; i++)
3122 if (listenargs[i] || sourcearg[i])
3123 setprotoopts(i, listenargs[i], sourcearg[i]);
3126 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3129 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3132 *configfile = optarg;
3135 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3136 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3137 *loglevel = *optarg - '0';
3146 debug(DBG_ERR, "radsecproxy revision $Rev$");
3147 debug(DBG_ERR, "This binary was built with support for the following transports:");
3149 debug(DBG_ERR, " UDP");
3152 debug(DBG_ERR, " TCP");
3155 debug(DBG_ERR, " TLS");
3158 debug(DBG_ERR, " DTLS");
3165 if (!(argc - optind))
3169 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3173 int daemon(int a, int b) {
3181 for (i = 0; i < 3; i++) {
3183 open("/dev/null", O_RDWR);
3189 void *sighandler(void *arg) {
3194 sigemptyset(&sigset);
3195 sigaddset(&sigset, SIGPIPE);
3196 sigwait(&sigset, &sig);
3197 /* only get SIGPIPE right now, so could simplify below code */
3200 /* completely ignoring this */
3203 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3206 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3211 int main(int argc, char **argv) {
3214 struct list_node *entry;
3215 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3216 char *configfile = NULL;
3217 struct clsrvconf *srvconf;
3220 debug_init("radsecproxy");
3221 debug_set_level(DEBUG_LEVEL);
3223 for (i = 0; i < RAD_PROTOCOUNT; i++)
3224 protodefs[i] = protoinits[i](i);
3226 /* needed even if no TLS/DTLS transport */
3229 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3231 debug_set_level(loglevel);
3232 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3234 options.loglevel = loglevel;
3235 else if (options.loglevel)
3236 debug_set_level(options.loglevel);
3238 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3239 free(options.logdestination);
3241 if (!list_first(clconfs))
3242 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3243 if (!list_first(realms))
3244 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3247 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3249 if (!foreground && (daemon(0, 0) < 0))
3250 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3252 debug_timestamp_on();
3253 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3255 sigemptyset(&sigset);
3256 /* exit on all but SIGPIPE, ignore more? */
3257 sigaddset(&sigset, SIGPIPE);
3258 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3259 pthread_create(&sigth, NULL, sighandler, NULL);
3261 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3262 srvconf = (struct clsrvconf *)entry->data;
3263 if (srvconf->dynamiclookupcommand)
3265 if (!addserver(srvconf))
3266 debugx(1, DBG_ERR, "failed to add server");
3267 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3268 (void *)(srvconf->servers)))
3269 debugx(1, DBG_ERR, "pthread_create failed");
3272 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3275 if (protodefs[i]->initextra)
3276 protodefs[i]->initextra();
3277 if (find_clconf_type(i, NULL))
3281 /* just hang around doing nothing, anything to do here? */