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 peers 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, 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 int hasdynamicserver(struct list *srvconfs) {
973 struct list_node *entry;
975 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
976 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
981 /* helper function, only used by removeserversubrealms() */
982 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
983 struct list_node *entry, *entry2;
986 for (entry = list_first(realmlist); entry;) {
987 realm = newrealmref((struct realm *)entry->data);
988 pthread_mutex_lock(&realm->mutex);
989 entry = list_next(entry);
991 if (realm->srvconfs) {
992 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
993 if (entry2->data == srv)
995 list_removedata(realm->srvconfs, srv);
997 if (realm->accsrvconfs) {
998 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
999 if (entry2->data == srv)
1001 list_removedata(realm->accsrvconfs, srv);
1004 /* remove subrealm if no dynamic servers left */
1005 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
1006 while (list_shift(realm->srvconfs))
1008 list_destroy(realm->srvconfs);
1009 realm->srvconfs = NULL;
1010 while (list_shift(realm->accsrvconfs))
1012 list_destroy(realm->accsrvconfs);
1013 realm->accsrvconfs = NULL;
1014 list_removedata(realmlist, realm);
1016 pthread_mutex_unlock(&realm->mutex);
1021 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1022 struct list_node *entry;
1023 struct realm *realm;
1025 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1026 realm = (struct realm *)entry->data;
1027 pthread_mutex_lock(&realm->mutex);
1028 if (realm->subrealms) {
1029 _internal_removeserversubrealms(realm->subrealms, srv);
1030 if (!list_first(realm->subrealms)) {
1031 list_destroy(realm->subrealms);
1032 realm->subrealms = NULL;
1035 pthread_mutex_unlock(&realm->mutex);
1039 int attrvalidate(unsigned char *attrs, int length) {
1040 while (length > 1) {
1041 if (ATTRLEN(attrs) < 2) {
1042 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1045 length -= ATTRLEN(attrs);
1047 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1050 attrs += ATTRLEN(attrs);
1053 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1057 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1058 if (len < 16 || len > 128 || len % 16) {
1059 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1063 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1064 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1068 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1070 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1071 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1077 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1080 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1081 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1084 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1085 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1091 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1092 char *oldsecret, char *newsecret) {
1093 unsigned char *attr;
1095 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1096 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1097 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1103 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
1107 for (; attrs[0]; attrs += 2)
1108 if (attrs[0] == vendor && attrs[1] == subattr)
1113 /* returns 1 if entire element is to be removed, else 0 */
1114 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1115 uint8_t alen, sublen;
1119 if (!removevendorattrs)
1122 memcpy(&vendor, attr->v, 4);
1123 vendor = ntohl(vendor);
1124 while (*removevendorattrs && *removevendorattrs != vendor)
1125 removevendorattrs += 2;
1126 if (!*removevendorattrs)
1129 if (findvendorsubattr(removevendorattrs, vendor, 256))
1130 return 1; /* remove entire vendor attribute */
1132 sublen = attr->l - 4;
1133 subattrs = attr->v + 4;
1135 if (!attrvalidate(subattrs, sublen)) {
1136 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1140 while (sublen > 1) {
1141 alen = ATTRLEN(subattrs);
1143 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1144 memmove(subattrs, subattrs + alen, sublen);
1152 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1153 struct list_node *n, *p;
1157 n = list_first(msg->attrs);
1159 attr = (struct tlv *)n->data;
1160 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1161 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1162 list_removedata(msg->attrs, attr);
1164 n = p ? list_next(p) : list_first(msg->attrs);
1171 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1172 struct list_node *n;
1175 for (n = list_first(addattrs); n; n = list_next(n)) {
1176 a = copytlv((struct tlv *)n->data);
1179 if (!radmsg_add(msg, a)) {
1187 int resizeattr(struct tlv *attr, uint8_t newlen) {
1190 if (newlen != attr->l) {
1191 newv = realloc(attr->v, newlen);
1200 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1201 size_t nmatch = 10, reslen = 0, start = 0;
1202 regmatch_t pmatch[10], *pfield;
1206 in = stringcopy((char *)attr->v, attr->l);
1210 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1215 out = modattr->replacement;
1217 for (i = start; out[i]; i++) {
1218 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1219 pfield = &pmatch[out[i + 1] - '0'];
1220 if (pfield->rm_so >= 0) {
1221 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1227 reslen += i - start;
1229 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1234 if (!resizeattr(attr, reslen)) {
1241 for (i = start; out[i]; i++) {
1242 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1243 pfield = &pmatch[out[i + 1] - '0'];
1244 if (pfield->rm_so >= 0) {
1245 memcpy(attr->v + reslen, out + start, i - start);
1246 reslen += i - start;
1247 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1248 reslen += pfield->rm_eo - pfield->rm_so;
1255 memcpy(attr->v + reslen, out + start, i - start);
1259 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1260 struct list_node *n, *m;
1262 for (n = list_first(msg->attrs); n; n = list_next(n))
1263 for (m = list_first(modattrs); m; m = list_next(m))
1264 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1265 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1270 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1273 if (rewrite->removeattrs || rewrite->removevendorattrs)
1274 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1275 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1277 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1282 int rewriteusername(struct request *rq, struct tlv *attr) {
1283 char *orig = (char *)tlv2str(attr);
1284 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1288 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1289 rq->origusername = (char *)orig;
1295 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1302 vendor = htonl(vendor);
1303 memcpy(v, &vendor, 4);
1304 tlv2buf(v + 4, attr);
1306 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1307 if (vattr && radmsg_add(msg, vattr))
1314 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1321 if (attrtype[1] == 256) { /* not vendor */
1322 attr = maketlv(attrtype[0], 4, ttl);
1323 if (attr && !radmsg_add(msg, attr))
1326 attr = maketlv(attrtype[1], 4, ttl);
1328 addvendorattr(msg, attrtype[0], attr);
1334 int decttl(uint8_t l, uint8_t *v) {
1341 while (i >= 0 && !v[i])
1345 for (i--; i >= 0 && !v[i]; i--);
1354 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1355 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1356 uint8_t alen, *subattrs;
1358 struct list_node *node;
1362 if (attrtype[1] == 256) { /* not vendor */
1363 attr = radmsg_gettype(msg, attrtype[0]);
1365 return decttl(attr->l, attr->v);
1367 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1368 attr = (struct tlv *)node->data;
1369 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1371 memcpy(&vendor, attr->v, 4);
1372 if (ntohl(vendor) != attrtype[0])
1374 sublen = attr->l - 4;
1375 subattrs = attr->v + 4;
1376 if (!attrvalidate(subattrs, sublen))
1378 while (sublen > 1) {
1379 if (ATTRTYPE(subattrs) == attrtype[1])
1380 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1381 alen = ATTRLEN(subattrs);
1389 const char *radmsgtype2string(uint8_t code) {
1390 static const char *rad_msg_names[] = {
1391 "", "Access-Request", "Access-Accept", "Access-Reject",
1392 "Accounting-Request", "Accounting-Response", "", "",
1393 "", "", "", "Access-Challenge",
1394 "Status-Server", "Status-Client"
1396 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1399 void char2hex(char *h, unsigned char c) {
1400 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1401 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1402 h[0] = hexdigits[c / 16];
1403 h[1] = hexdigits[c % 16];
1407 uint8_t *radattr2ascii(struct tlv *attr) {
1415 for (i = 0; i < attr->l; i++)
1416 if (attr->v[i] < 32 || attr->v[i] > 126)
1419 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1426 for (i = 0; i < attr->l; i++)
1427 if (attr->v[i] < 32 || attr->v[i] > 126) {
1429 char2hex((char *)d, attr->v[i]);
1437 void acclog(struct radmsg *msg, char *host) {
1441 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1443 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1446 username = radattr2ascii(attr);
1448 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1453 void respond(struct request *rq, uint8_t code, char *message) {
1457 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1459 debug(DBG_ERR, "respond: malloc failed");
1462 if (message && *message) {
1463 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1464 if (!attr || !radmsg_add(msg, attr)) {
1467 debug(DBG_ERR, "respond: malloc failed");
1472 radmsg_free(rq->msg);
1474 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1475 sendreply(newrqref(rq));
1478 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1479 struct list_node *entry;
1480 struct clsrvconf *server, *best = NULL, *first = NULL;
1482 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1483 server = (struct clsrvconf *)entry->data;
1484 if (!server->servers)
1488 if (!server->servers->connectionok && !server->servers->dynstartup)
1490 if (!server->servers->lostrqs)
1496 if (server->servers->lostrqs < best->servers->lostrqs)
1499 return best ? best : first;
1502 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1503 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1504 struct clsrvconf *srvconf;
1505 struct realm *subrealm;
1506 struct server *server = NULL;
1507 char *id = (char *)tlv2str(username);
1511 /* returns with lock on realm */
1512 *realm = id2realm(realms, id);
1515 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1516 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1517 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1518 subrealm = adddynamicrealmserver(*realm, id);
1520 pthread_mutex_lock(&subrealm->mutex);
1521 pthread_mutex_unlock(&(*realm)->mutex);
1524 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1528 server = srvconf->servers;
1536 struct request *newrequest() {
1539 rq = malloc(sizeof(struct request));
1541 debug(DBG_ERR, "newrequest: malloc failed");
1544 memset(rq, 0, sizeof(struct request));
1546 gettimeofday(&rq->created, NULL);
1550 int addclientrq(struct request *rq) {
1554 r = rq->from->rqs[rq->rqid];
1556 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1557 gettimeofday(&now, NULL);
1558 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1560 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1561 sendreply(newrqref(r));
1563 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1569 rq->from->rqs[rq->rqid] = newrqref(rq);
1573 void rmclientrq(struct request *rq, uint8_t id) {
1576 r = rq->from->rqs[id];
1579 rq->from->rqs[id] = NULL;
1583 /* returns 0 if validation/authentication fails, else 1 */
1584 int radsrv(struct request *rq) {
1585 struct radmsg *msg = NULL;
1587 uint8_t *userascii = NULL;
1588 struct realm *realm = NULL;
1589 struct server *to = NULL;
1590 struct client *from = rq->from;
1593 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1598 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1605 memcpy(rq->rqauth, msg->auth, 16);
1607 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1608 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1609 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1613 if (!addclientrq(rq))
1616 if (msg->code == RAD_Status_Server) {
1617 respond(rq, RAD_Access_Accept, NULL);
1621 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1623 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1626 ttlres = checkttl(msg, options.ttlattrtype);
1628 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1632 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1634 if (msg->code == RAD_Accounting_Request) {
1635 acclog(msg, from->conf->host);
1636 respond(rq, RAD_Accounting_Response, NULL);
1638 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1642 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1643 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1647 userascii = radattr2ascii(attr);
1650 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1652 /* will return with lock on the realm */
1653 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1655 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1660 if (realm->message && msg->code == RAD_Access_Request) {
1661 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1662 respond(rq, RAD_Access_Reject, realm->message);
1663 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1664 acclog(msg, from->conf->host);
1665 respond(rq, RAD_Accounting_Response, NULL);
1670 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1671 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1672 from->conf->name, addr2string(from->addr), to->conf->name);
1676 if (msg->code == RAD_Accounting_Request)
1677 memset(msg->auth, 0, 16);
1678 else if (!RAND_bytes(msg->auth, 16)) {
1679 debug(DBG_WARN, "radsrv: failed to generate random auth");
1684 printfchars(NULL, "auth", "%02x ", auth, 16);
1687 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1689 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1690 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1694 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1696 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1697 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1701 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1704 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1705 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1710 pthread_mutex_unlock(&realm->mutex);
1715 rmclientrq(rq, msg->id);
1720 pthread_mutex_unlock(&realm->mutex);
1726 void replyh(struct server *server, unsigned char *buf) {
1727 struct client *from;
1728 struct rqout *rqout;
1730 unsigned char *subattrs;
1731 uint8_t *username, *stationid, *replymsg;
1732 struct radmsg *msg = NULL;
1734 struct list_node *node;
1736 server->connectionok = 1;
1737 server->lostrqs = 0;
1739 rqout = server->requests + buf[1];
1740 pthread_mutex_lock(rqout->lock);
1741 if (!rqout->tries) {
1744 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1748 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1752 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1755 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1756 && msg->code != RAD_Accounting_Response) {
1757 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1760 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1762 gettimeofday(&server->lastrcv, NULL);
1764 if (rqout->rq->msg->code == RAD_Status_Server) {
1765 freerqoutdata(rqout);
1766 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1770 gettimeofday(&server->lastreply, NULL);
1771 from = rqout->rq->from;
1773 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1774 debug(DBG_WARN, "replyh: rewritein failed");
1778 ttlres = checkttl(msg, options.ttlattrtype);
1780 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
1785 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1786 attr = (struct tlv *)node->data;
1787 if (attr->t != RAD_Attr_Vendor_Specific)
1791 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1794 sublen = attr->l - 4;
1795 subattrs = attr->v + 4;
1796 if (!attrvalidate(subattrs, sublen) ||
1797 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1798 rqout->rq, server->conf->secret, from->conf->secret) ||
1799 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1800 rqout->rq, server->conf->secret, from->conf->secret))
1804 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1808 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1809 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1811 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1812 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1815 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1816 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1819 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1820 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1824 debug(DBG_INFO, "%s for user %s from %s (%s)",
1825 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1828 debug(DBG_INFO, "%s for user %s from %s",
1829 radmsgtype2string(msg->code), username, server->conf->host);
1835 msg->id = (char)rqout->rq->rqid;
1836 memcpy(msg->auth, rqout->rq->rqauth, 16);
1839 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1842 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1843 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1844 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1847 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1850 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1851 debug(DBG_WARN, "replyh: rewriteout failed");
1855 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1856 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1858 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
1859 radmsg_free(rqout->rq->msg);
1860 rqout->rq->msg = msg;
1861 sendreply(newrqref(rqout->rq));
1862 freerqoutdata(rqout);
1863 pthread_mutex_unlock(rqout->lock);
1868 pthread_mutex_unlock(rqout->lock);
1872 struct request *createstatsrvrq() {
1879 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1882 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1885 if (!radmsg_add(rq->msg, attr)) {
1896 /* code for removing state not finished */
1897 void *clientwr(void *arg) {
1898 struct server *server = (struct server *)arg;
1899 struct rqout *rqout = NULL;
1900 pthread_t clientrdth;
1901 int i, dynconffail = 0;
1904 struct timeval now, laststatsrv;
1905 struct timespec timeout;
1906 struct request *statsrvrq;
1907 struct clsrvconf *conf;
1909 conf = server->conf;
1911 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1916 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
1917 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
1921 memset(&timeout, 0, sizeof(struct timespec));
1923 if (conf->statusserver) {
1924 gettimeofday(&server->lastrcv, NULL);
1925 gettimeofday(&laststatsrv, NULL);
1928 if (conf->pdef->connecter) {
1929 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr")) {
1930 if (server->dynamiclookuparg) {
1931 server->dynstartup = 0;
1936 server->connectionok = 1;
1937 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1938 debug(DBG_ERR, "clientwr: pthread_create failed");
1942 server->connectionok = 1;
1943 server->dynstartup = 0;
1946 pthread_mutex_lock(&server->newrq_mutex);
1947 if (!server->newrq) {
1948 gettimeofday(&now, NULL);
1949 /* random 0-7 seconds */
1950 RAND_bytes(&rnd, 1);
1952 if (conf->statusserver) {
1953 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1954 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1956 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1957 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1959 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1960 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1963 if (timeout.tv_sec > now.tv_sec)
1964 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1966 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1969 if (server->newrq) {
1970 debug(DBG_DBG, "clientwr: got new request");
1975 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1977 pthread_mutex_unlock(&server->newrq_mutex);
1979 for (i = 0; i < MAX_REQUESTS; i++) {
1980 if (server->clientrdgone) {
1981 pthread_join(clientrdth, NULL);
1985 for (; i < MAX_REQUESTS; i++) {
1986 rqout = server->requests + i;
1988 pthread_mutex_lock(rqout->lock);
1991 pthread_mutex_unlock(rqout->lock);
1995 if (i == MAX_REQUESTS)
1998 gettimeofday(&now, NULL);
1999 if (now.tv_sec < rqout->expiry.tv_sec) {
2000 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2001 timeout.tv_sec = rqout->expiry.tv_sec;
2002 pthread_mutex_unlock(rqout->lock);
2006 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2007 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2008 if (conf->statusserver) {
2009 if (*rqout->rq->buf == RAD_Status_Server) {
2010 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2011 if (server->lostrqs < 255)
2015 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2016 if (server->lostrqs < 255)
2019 freerqoutdata(rqout);
2020 pthread_mutex_unlock(rqout->lock);
2024 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2025 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2026 timeout.tv_sec = rqout->expiry.tv_sec;
2028 conf->pdef->clientradput(server, rqout->rq->buf);
2029 pthread_mutex_unlock(rqout->lock);
2031 if (conf->statusserver && server->connectionok) {
2032 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2033 gettimeofday(&now, NULL);
2034 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2036 statsrvrq = createstatsrvrq();
2038 statsrvrq->to = server;
2039 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2046 conf->servers = NULL;
2047 if (server->dynamiclookuparg) {
2048 removeserversubrealms(realms, conf);
2052 freeclsrvconf(conf);
2054 freeserver(server, 1);
2055 ERR_remove_state(0);
2059 void createlistener(uint8_t type, char *arg) {
2061 struct clsrvconf *listenres;
2062 struct addrinfo *res;
2063 int s = -1, on = 1, *sp = NULL;
2065 listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2067 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2069 for (res = listenres->addrinfo; res; res = res->ai_next) {
2070 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2072 debug(DBG_WARN, "createlistener: socket failed");
2075 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2077 if (res->ai_family == AF_INET6)
2078 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2080 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2081 debug(DBG_WARN, "createlistener: bind failed");
2087 sp = malloc(sizeof(int));
2089 debugx(1, DBG_ERR, "malloc failed");
2091 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2092 debugx(1, DBG_ERR, "pthread_create failed");
2096 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2098 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2099 listenres->host ? listenres->host : "*", listenres->port);
2100 freeclsrvres(listenres);
2103 void createlisteners(uint8_t type) {
2107 args = protodefs[type]->getlistenerargs();
2109 for (i = 0; args[i]; i++)
2110 createlistener(type, args[i]);
2112 createlistener(type, NULL);
2120 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2121 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2122 for (i = 0; i < CRYPTO_num_locks(); i++) {
2123 ssl_lock_count[i] = 0;
2124 pthread_mutex_init(&ssl_locks[i], NULL);
2126 CRYPTO_set_id_callback(ssl_thread_id);
2127 CRYPTO_set_locking_callback(ssl_locking_callback);
2129 SSL_load_error_strings();
2132 while (!RAND_status()) {
2135 RAND_seed((unsigned char *)&t, sizeof(time_t));
2136 RAND_seed((unsigned char *)&pid, sizeof(pid));
2140 struct list *addsrvconfs(char *value, char **names) {
2141 struct list *conflist;
2143 struct list_node *entry;
2144 struct clsrvconf *conf = NULL;
2146 if (!names || !*names)
2149 conflist = list_create();
2151 debug(DBG_ERR, "malloc failed");
2155 for (n = 0; names[n]; n++) {
2156 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2157 conf = (struct clsrvconf *)entry->data;
2158 if (!strcasecmp(names[n], conf->name))
2162 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2163 list_destroy(conflist);
2166 if (!list_push(conflist, conf)) {
2167 debug(DBG_ERR, "malloc failed");
2168 list_destroy(conflist);
2171 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2176 void freerealm(struct realm *realm) {
2179 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2180 if (--realm->refcount)
2184 free(realm->message);
2185 regfree(&realm->regex);
2186 pthread_mutex_destroy(&realm->mutex);
2187 /* if refcount == 0, all subrealms gone */
2188 list_destroy(realm->subrealms);
2189 /* if refcount == 0, all srvconfs gone */
2190 list_destroy(realm->srvconfs);
2191 /* if refcount == 0, all accsrvconfs gone */
2192 list_destroy(realm->accsrvconfs);
2193 freerealm(realm->parent);
2197 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2199 struct realm *realm;
2200 char *s, *regex = NULL;
2202 if (*value == '/') {
2203 /* regexp, remove optional trailing / if present */
2204 if (value[strlen(value) - 1] == '/')
2205 value[strlen(value) - 1] = '\0';
2207 /* not a regexp, let us make it one */
2208 if (*value == '*' && !value[1])
2209 regex = stringcopy(".*", 0);
2211 for (n = 0, s = value; *s;)
2214 regex = malloc(strlen(value) + n + 3);
2217 for (n = 1, s = value; *s; s++) {
2227 debug(DBG_ERR, "malloc failed");
2231 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2234 realm = malloc(sizeof(struct realm));
2236 debug(DBG_ERR, "malloc failed");
2239 memset(realm, 0, sizeof(struct realm));
2241 if (pthread_mutex_init(&realm->mutex, NULL)) {
2242 debug(DBG_ERR, "mutex init failed");
2248 realm->name = stringcopy(value, 0);
2250 debug(DBG_ERR, "malloc failed");
2253 if (message && strlen(message) > 253) {
2254 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2257 realm->message = message;
2258 realm->accresp = accresp;
2260 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2261 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2265 if (servers && *servers) {
2266 realm->srvconfs = addsrvconfs(value, servers);
2267 if (!realm->srvconfs)
2271 if (accservers && *accservers) {
2272 realm->accsrvconfs = addsrvconfs(value, accservers);
2273 if (!realm->accsrvconfs)
2277 if (!list_push(realmlist, realm)) {
2278 debug(DBG_ERR, "malloc failed");
2279 pthread_mutex_destroy(&realm->mutex);
2283 debug(DBG_DBG, "addrealm: added realm %s", value);
2287 while (list_shift(realm->srvconfs));
2288 while (list_shift(realm->accsrvconfs));
2295 for (n = 0; servers[n]; n++)
2297 freegconfmstr(servers);
2301 for (n = 0; accservers[n]; n++)
2303 freegconfmstr(accservers);
2305 return newrealmref(realm);
2308 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2309 struct list_node *entry;
2310 struct clsrvconf *conf, *srvconf;
2311 struct list *subrealmservers = NULL;
2314 if (list_first(srvconfs)) {
2315 subrealmservers = list_create();
2316 if (!subrealmservers)
2320 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2321 conf = (struct clsrvconf *)entry->data;
2322 if (!conf->servers && conf->dynamiclookupcommand) {
2323 srvconf = malloc(sizeof(struct clsrvconf));
2325 debug(DBG_ERR, "malloc failed");
2329 if (addserver(srvconf)) {
2330 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2331 srvconf->servers->dynstartup = 1;
2332 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2333 debug(DBG_ERR, "pthread_create failed");
2334 freeserver(srvconf->servers, 1);
2335 srvconf->servers = NULL;
2337 pthread_detach(clientth);
2341 if (conf->servers) {
2342 if (list_push(subrealmservers, conf))
2345 debug(DBG_ERR, "malloc failed");
2348 return subrealmservers;
2351 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2352 struct realm *newrealm = NULL;
2353 char *realmname, *s;
2355 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2356 realmname = strrchr(id, '@');
2362 for (s = realmname; *s; s++)
2363 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2366 if (!realm->subrealms)
2367 realm->subrealms = list_create();
2368 if (!realm->subrealms)
2371 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2373 list_destroy(realm->subrealms);
2374 realm->subrealms = NULL;
2378 newrealm->parent = newrealmref(realm);
2379 /* add server and accserver to newrealm */
2380 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2381 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2385 int dynamicconfig(struct server *server) {
2386 int ok, fd[2], status;
2388 struct clsrvconf *conf = server->conf;
2389 struct gconffile *cf = NULL;
2391 /* for now we only learn hostname/address */
2392 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2395 debug(DBG_ERR, "dynamicconfig: pipe error");
2400 debug(DBG_ERR, "dynamicconfig: fork error");
2404 } else if (pid == 0) {
2407 if (fd[1] != STDOUT_FILENO) {
2408 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2409 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2412 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2413 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2417 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2418 ok = getgenericconfig(&cf, NULL,
2419 "Server", CONF_CBK, confserver_cb, (void *)conf,
2424 if (waitpid(pid, &status, 0) < 0) {
2425 debug(DBG_ERR, "dynamicconfig: wait error");
2430 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2438 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2442 /* should accept both names and numeric values, only numeric right now */
2443 uint8_t attrname2val(char *attrname) {
2446 val = atoi(attrname);
2447 return val > 0 && val < 256 ? val : 0;
2450 /* should accept both names and numeric values, only numeric right now */
2451 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2454 *vendor = atoi(attrname);
2455 s = strchr(attrname, ':');
2460 *type = atoi(s + 1);
2464 /* should accept both names and numeric values, only numeric right now */
2465 struct tlv *extractattr(char *nameval) {
2470 s = strchr(nameval, ':');
2471 name = atoi(nameval);
2472 if (!s || name < 1 || name > 255)
2474 len = strlen(s + 1);
2477 a = malloc(sizeof(struct tlv));
2480 a->v = (uint8_t *)stringcopy(s + 1, 0);
2490 /* should accept both names and numeric values, only numeric right now */
2491 struct modattr *extractmodattr(char *nameval) {
2496 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2500 s = strchr(nameval, ':');
2501 name = atoi(nameval);
2502 if (!s || name < 1 || name > 255 || s[1] != '/')
2506 /* regexp, remove optional trailing / if present */
2507 if (s[strlen(s) - 1] == '/')
2508 s[strlen(s) - 1] = '\0';
2516 m = malloc(sizeof(struct modattr));
2518 debug(DBG_ERR, "malloc failed");
2523 m->replacement = stringcopy(t, 0);
2524 if (!m->replacement) {
2526 debug(DBG_ERR, "malloc failed");
2530 m->regex = malloc(sizeof(regex_t));
2532 free(m->replacement);
2534 debug(DBG_ERR, "malloc failed");
2538 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2540 free(m->replacement);
2542 debug(DBG_ERR, "failed to compile regular expression %s", s);
2549 struct rewrite *getrewrite(char *alt1, char *alt2) {
2552 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2554 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2559 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2560 struct rewrite *rewrite = NULL;
2562 uint8_t *rma = NULL;
2563 uint32_t *p, *rmva = NULL;
2564 struct list *adda = NULL, *moda = NULL;
2569 for (n = 0; rmattrs[n]; n++);
2570 rma = calloc(n + 1, sizeof(uint8_t));
2572 debugx(1, DBG_ERR, "malloc failed");
2574 for (i = 0; i < n; i++)
2575 if (!(rma[i] = attrname2val(rmattrs[i])))
2576 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2577 freegconfmstr(rmattrs);
2582 for (n = 0; rmvattrs[n]; n++);
2583 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2585 debugx(1, DBG_ERR, "malloc failed");
2587 for (p = rmva, i = 0; i < n; i++, p += 2)
2588 if (!vattrname2val(rmvattrs[i], p, p + 1))
2589 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2590 freegconfmstr(rmvattrs);
2595 adda = list_create();
2597 debugx(1, DBG_ERR, "malloc failed");
2598 for (i = 0; addattrs[i]; i++) {
2599 a = extractattr(addattrs[i]);
2601 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2602 if (!list_push(adda, a))
2603 debugx(1, DBG_ERR, "malloc failed");
2605 freegconfmstr(addattrs);
2609 moda = list_create();
2611 debugx(1, DBG_ERR, "malloc failed");
2612 for (i = 0; modattrs[i]; i++) {
2613 m = extractmodattr(modattrs[i]);
2615 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2616 if (!list_push(moda, m))
2617 debugx(1, DBG_ERR, "malloc failed");
2619 freegconfmstr(modattrs);
2622 if (rma || rmva || adda || moda) {
2623 rewrite = malloc(sizeof(struct rewrite));
2625 debugx(1, DBG_ERR, "malloc failed");
2626 rewrite->removeattrs = rma;
2627 rewrite->removevendorattrs = rmva;
2628 rewrite->addattrs = adda;
2629 rewrite->modattrs = moda;
2632 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2633 debugx(1, DBG_ERR, "malloc failed");
2634 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2637 int setttlattr(struct options *opts, char *defaultattr) {
2638 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2640 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2641 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2643 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2647 void freeclsrvconf(struct clsrvconf *conf) {
2653 free(conf->matchcertattr);
2654 if (conf->certcnregex)
2655 regfree(conf->certcnregex);
2656 if (conf->certuriregex)
2657 regfree(conf->certuriregex);
2658 free(conf->confrewritein);
2659 free(conf->confrewriteout);
2660 if (conf->rewriteusername) {
2661 if (conf->rewriteusername->regex)
2662 regfree(conf->rewriteusername->regex);
2663 free(conf->rewriteusername->replacement);
2664 free(conf->rewriteusername);
2666 free(conf->dynamiclookupcommand);
2667 free(conf->rewritein);
2668 free(conf->rewriteout);
2670 freeaddrinfo(conf->addrinfo);
2672 pthread_mutex_destroy(conf->lock);
2675 /* not touching ssl_ctx, clients and servers */
2679 int mergeconfstring(char **dst, char **src) {
2688 t = stringcopy(*dst, 0);
2690 debug(DBG_ERR, "malloc failed");
2698 /* assumes dst is a shallow copy */
2699 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2700 if (!mergeconfstring(&dst->name, &src->name) ||
2701 !mergeconfstring(&dst->host, &src->host) ||
2702 !mergeconfstring(&dst->port, &src->port) ||
2703 !mergeconfstring(&dst->secret, &src->secret) ||
2704 !mergeconfstring(&dst->tls, &src->tls) ||
2705 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2706 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2707 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2708 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2711 dst->pdef = src->pdef;
2712 dst->statusserver = src->statusserver;
2713 dst->certnamecheck = src->certnamecheck;
2714 if (src->retryinterval != 255)
2715 dst->retryinterval = src->retryinterval;
2716 if (src->retrycount != 255)
2717 dst->retrycount = src->retrycount;
2721 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2722 struct clsrvconf *conf;
2723 char *conftype = NULL, *rewriteinalias = NULL;
2724 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2726 debug(DBG_DBG, "confclient_cb called for %s", block);
2728 conf = malloc(sizeof(struct clsrvconf));
2730 debugx(1, DBG_ERR, "malloc failed");
2731 memset(conf, 0, sizeof(struct clsrvconf));
2732 conf->certnamecheck = 1;
2734 if (!getgenericconfig(cf, block,
2735 "type", CONF_STR, &conftype,
2736 "host", CONF_STR, &conf->host,
2737 "secret", CONF_STR, &conf->secret,
2738 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2739 "tls", CONF_STR, &conf->tls,
2740 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2741 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2743 "DuplicateInterval", CONF_LINT, &dupinterval,
2744 "addTTL", CONF_LINT, &addttl,
2745 "rewrite", CONF_STR, &rewriteinalias,
2746 "rewriteIn", CONF_STR, &conf->confrewritein,
2747 "rewriteOut", CONF_STR, &conf->confrewriteout,
2748 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2751 debugx(1, DBG_ERR, "configuration error");
2753 conf->name = stringcopy(val, 0);
2755 conf->host = stringcopy(val, 0);
2756 if (!conf->name || !conf->host)
2757 debugx(1, DBG_ERR, "malloc failed");
2760 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2761 conf->type = protoname2int(conftype);
2762 if (conf->type == 255)
2763 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2765 conf->pdef = protodefs[conf->type];
2767 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2768 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2769 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2771 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2772 if (conf->matchcertattr && !addmatchcertattr(conf))
2773 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2777 if (dupinterval != LONG_MIN) {
2778 if (dupinterval < 0 || dupinterval > 255)
2779 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2780 conf->dupinterval = (uint8_t)dupinterval;
2782 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2784 if (addttl != LONG_MIN) {
2785 if (addttl < 1 || addttl > 255)
2786 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2787 conf->addttl = (uint8_t)addttl;
2790 if (!conf->confrewritein)
2791 conf->confrewritein = rewriteinalias;
2793 free(rewriteinalias);
2794 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2795 if (conf->confrewriteout)
2796 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2798 if (conf->confrewriteusername) {
2799 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2800 if (!conf->rewriteusername)
2801 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2804 if (!resolvepeer(conf, 0))
2805 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2807 if (!conf->secret) {
2808 if (!conf->pdef->secretdefault)
2809 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2810 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2812 debugx(1, DBG_ERR, "malloc failed");
2815 conf->lock = malloc(sizeof(pthread_mutex_t));
2817 debugx(1, DBG_ERR, "malloc failed");
2819 pthread_mutex_init(conf->lock, NULL);
2820 if (!list_push(clconfs, conf))
2821 debugx(1, DBG_ERR, "malloc failed");
2825 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2826 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2827 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2828 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2829 if (!conf->tlsconf) {
2830 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2833 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2834 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2841 conf->port = stringcopy(conf->pdef->portdefault, 0);
2843 debug(DBG_ERR, "malloc failed");
2848 if (conf->retryinterval == 255)
2849 conf->retryinterval = conf->pdef->retryintervaldefault;
2850 if (conf->retrycount == 255)
2851 conf->retrycount = conf->pdef->retrycountdefault;
2853 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2854 if (conf->confrewriteout)
2855 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2857 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
2858 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2864 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2865 struct clsrvconf *conf, *resconf;
2866 char *conftype = NULL, *rewriteinalias = NULL;
2867 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2869 debug(DBG_DBG, "confserver_cb called for %s", block);
2871 conf = malloc(sizeof(struct clsrvconf));
2873 debug(DBG_ERR, "malloc failed");
2876 memset(conf, 0, sizeof(struct clsrvconf));
2877 resconf = (struct clsrvconf *)arg;
2879 conf->statusserver = resconf->statusserver;
2880 conf->certnamecheck = resconf->certnamecheck;
2882 conf->certnamecheck = 1;
2884 if (!getgenericconfig(cf, block,
2885 "type", CONF_STR, &conftype,
2886 "host", CONF_STR, &conf->host,
2887 "port", CONF_STR, &conf->port,
2888 "secret", CONF_STR, &conf->secret,
2889 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2890 "tls", CONF_STR, &conf->tls,
2891 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2892 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2894 "addTTL", CONF_LINT, &addttl,
2895 "rewrite", CONF_STR, &rewriteinalias,
2896 "rewriteIn", CONF_STR, &conf->confrewritein,
2897 "rewriteOut", CONF_STR, &conf->confrewriteout,
2898 "StatusServer", CONF_BLN, &conf->statusserver,
2899 "RetryInterval", CONF_LINT, &retryinterval,
2900 "RetryCount", CONF_LINT, &retrycount,
2901 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2904 debug(DBG_ERR, "configuration error");
2908 conf->name = stringcopy(val, 0);
2910 debug(DBG_ERR, "malloc failed");
2914 conf->host = stringcopy(val, 0);
2916 debug(DBG_ERR, "malloc failed");
2922 debug(DBG_ERR, "error in block %s, option type missing", block);
2925 conf->type = protoname2int(conftype);
2926 if (conf->type == 255) {
2927 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2933 conf->pdef = protodefs[conf->type];
2935 if (!conf->confrewritein)
2936 conf->confrewritein = rewriteinalias;
2938 free(rewriteinalias);
2939 rewriteinalias = NULL;
2941 if (retryinterval != LONG_MIN) {
2942 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2943 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2946 conf->retryinterval = (uint8_t)retryinterval;
2948 conf->retryinterval = 255;
2950 if (retrycount != LONG_MIN) {
2951 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2952 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2955 conf->retrycount = (uint8_t)retrycount;
2957 conf->retrycount = 255;
2959 if (addttl != LONG_MIN) {
2960 if (addttl < 1 || addttl > 255) {
2961 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2964 conf->addttl = (uint8_t)addttl;
2968 if (!mergesrvconf(resconf, conf))
2972 if (conf->dynamiclookupcommand) {
2973 free(conf->dynamiclookupcommand);
2974 conf->dynamiclookupcommand = NULL;
2978 if (resconf || !conf->dynamiclookupcommand) {
2979 if (!compileserverconfig(conf, block))
2983 if (!conf->secret) {
2984 if (!conf->pdef->secretdefault) {
2985 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2988 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2989 if (!conf->secret) {
2990 debug(DBG_ERR, "malloc failed");
2998 if (!list_push(srvconfs, conf)) {
2999 debug(DBG_ERR, "malloc failed");
3006 free(rewriteinalias);
3007 freeclsrvconf(conf);
3011 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3012 char **servers = NULL, **accservers = NULL, *msg = NULL;
3013 uint8_t accresp = 0;
3015 debug(DBG_DBG, "confrealm_cb called for %s", block);
3017 if (!getgenericconfig(cf, block,
3018 "server", CONF_MSTR, &servers,
3019 "accountingServer", CONF_MSTR, &accservers,
3020 "ReplyMessage", CONF_STR, &msg,
3021 "AccountingResponse", CONF_BLN, &accresp,
3024 debugx(1, DBG_ERR, "configuration error");
3026 addrealm(realms, val, servers, accservers, msg, accresp);
3030 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3031 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3033 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3035 if (!getgenericconfig(cf, block,
3036 "removeAttribute", CONF_MSTR, &rmattrs,
3037 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3038 "addAttribute", CONF_MSTR, &addattrs,
3039 "modifyAttribute", CONF_MSTR, &modattrs,
3042 debugx(1, DBG_ERR, "configuration error");
3043 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3047 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3048 struct commonprotoopts *protoopts;
3050 protoopts = malloc(sizeof(struct commonprotoopts));
3053 memset(protoopts, 0, sizeof(struct commonprotoopts));
3054 protoopts->listenargs = listenargs;
3055 protoopts->sourcearg = sourcearg;
3056 protodefs[type]->setprotoopts(protoopts);
3060 void getmainconfig(const char *configfile) {
3061 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3062 struct gconffile *cfs;
3063 char **listenargs[RAD_PROTOCOUNT];
3064 char *sourcearg[RAD_PROTOCOUNT];
3067 cfs = openconfigfile(configfile);
3068 memset(&options, 0, sizeof(options));
3069 memset(&listenargs, 0, sizeof(listenargs));
3070 memset(&sourcearg, 0, sizeof(sourcearg));
3072 clconfs = list_create();
3074 debugx(1, DBG_ERR, "malloc failed");
3076 srvconfs = list_create();
3078 debugx(1, DBG_ERR, "malloc failed");
3080 realms = list_create();
3082 debugx(1, DBG_ERR, "malloc failed");
3084 rewriteconfs = hash_create();
3086 debugx(1, DBG_ERR, "malloc failed");
3088 if (!getgenericconfig(&cfs, NULL,
3090 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3091 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3094 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3095 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3098 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3099 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3102 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3103 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3105 "TTLAttribute", CONF_STR, &options.ttlattr,
3106 "addTTL", CONF_LINT, &addttl,
3107 "LogLevel", CONF_LINT, &loglevel,
3108 "LogDestination", CONF_STR, &options.logdestination,
3109 "LoopPrevention", CONF_BLN, &options.loopprevention,
3110 "Client", CONF_CBK, confclient_cb, NULL,
3111 "Server", CONF_CBK, confserver_cb, NULL,
3112 "Realm", CONF_CBK, confrealm_cb, NULL,
3113 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3114 "TLS", CONF_CBK, conftls_cb, NULL,
3116 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3119 debugx(1, DBG_ERR, "configuration error");
3121 if (loglevel != LONG_MIN) {
3122 if (loglevel < 1 || loglevel > 4)
3123 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3124 options.loglevel = (uint8_t)loglevel;
3126 if (addttl != LONG_MIN) {
3127 if (addttl < 1 || addttl > 255)
3128 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3129 options.addttl = (uint8_t)addttl;
3131 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3132 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3134 for (i = 0; i < RAD_PROTOCOUNT; i++)
3135 if (listenargs[i] || sourcearg[i])
3136 setprotoopts(i, listenargs[i], sourcearg[i]);
3139 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3142 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3145 *configfile = optarg;
3148 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3149 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3150 *loglevel = *optarg - '0';
3159 debug(DBG_ERR, "radsecproxy revision $Rev$");
3160 debug(DBG_ERR, "This binary was built with support for the following transports:");
3162 debug(DBG_ERR, " UDP");
3165 debug(DBG_ERR, " TCP");
3168 debug(DBG_ERR, " TLS");
3171 debug(DBG_ERR, " DTLS");
3178 if (!(argc - optind))
3182 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3186 int daemon(int a, int b) {
3194 for (i = 0; i < 3; i++) {
3196 open("/dev/null", O_RDWR);
3202 void *sighandler(void *arg) {
3207 sigemptyset(&sigset);
3208 sigaddset(&sigset, SIGPIPE);
3209 sigwait(&sigset, &sig);
3210 /* only get SIGPIPE right now, so could simplify below code */
3213 /* completely ignoring this */
3216 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3219 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3224 int main(int argc, char **argv) {
3227 struct list_node *entry;
3228 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3229 char *configfile = NULL;
3230 struct clsrvconf *srvconf;
3233 debug_init("radsecproxy");
3234 debug_set_level(DEBUG_LEVEL);
3236 for (i = 0; i < RAD_PROTOCOUNT; i++)
3237 protodefs[i] = protoinits[i](i);
3239 /* needed even if no TLS/DTLS transport */
3242 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3244 debug_set_level(loglevel);
3245 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3247 options.loglevel = loglevel;
3248 else if (options.loglevel)
3249 debug_set_level(options.loglevel);
3251 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3252 free(options.logdestination);
3254 if (!list_first(clconfs))
3255 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3256 if (!list_first(realms))
3257 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3260 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3262 if (!foreground && (daemon(0, 0) < 0))
3263 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3265 debug_timestamp_on();
3266 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3268 sigemptyset(&sigset);
3269 /* exit on all but SIGPIPE, ignore more? */
3270 sigaddset(&sigset, SIGPIPE);
3271 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3272 pthread_create(&sigth, NULL, sighandler, NULL);
3274 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3275 srvconf = (struct clsrvconf *)entry->data;
3276 if (srvconf->dynamiclookupcommand)
3278 if (!addserver(srvconf))
3279 debugx(1, DBG_ERR, "failed to add server");
3280 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3281 (void *)(srvconf->servers)))
3282 debugx(1, DBG_ERR, "pthread_create failed");
3285 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3288 if (protodefs[i]->initextra)
3289 protodefs[i]->initextra();
3290 if (find_clconf_type(i, NULL))
3294 /* just hang around doing nothing, anything to do here? */