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>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
73 #include "radsecproxy.h"
79 static struct options options;
80 static struct list *clconfs, *srvconfs;
81 static struct list *realms;
82 static struct hash *rewriteconfs;
84 static pthread_mutex_t *ssl_locks = NULL;
85 static long *ssl_lock_count;
88 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
90 /* minimum required declarations to avoid reordering code */
91 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
92 int dynamicconfig(struct server *server);
93 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
94 void freerealm(struct realm *realm);
95 void freeclsrvconf(struct clsrvconf *conf);
96 void freerq(struct request *rq);
97 void freerqoutdata(struct rqout *rqout);
98 void rmclientrq(struct request *rq, uint8_t id);
100 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
102 uint8_t protoname2int(const char *name) {
105 for (i = 0; i < RAD_PROTOCOUNT; i++)
106 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
111 /* callbacks for making OpenSSL thread safe */
112 unsigned long ssl_thread_id() {
113 return (unsigned long)pthread_self();
116 void ssl_locking_callback(int mode, int type, const char *file, int line) {
117 if (mode & CRYPTO_LOCK) {
118 pthread_mutex_lock(&ssl_locks[type]);
119 ssl_lock_count[type]++;
121 pthread_mutex_unlock(&ssl_locks[type]);
124 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
125 struct addrinfo hints, *addrinfo, *res;
129 slash = conf->host ? strchr(conf->host, '/') : NULL;
133 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
137 if (*s < '0' || *s > '9') {
138 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
141 plen = atoi(slash + 1);
142 if (plen < 0 || plen > 128) {
143 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
148 memset(&hints, 0, sizeof(hints));
149 hints.ai_socktype = conf->pdef->socktype;
150 hints.ai_family = AF_UNSPEC;
151 hints.ai_flags = ai_flags;
152 if (!conf->host && !conf->port) {
153 /* getaddrinfo() doesn't like host and port to be NULL */
154 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
155 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
158 for (res = addrinfo; res; res = res->ai_next)
159 port_set(res->ai_addr, 0);
162 hints.ai_flags |= AI_NUMERICHOST;
163 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
164 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
169 switch (addrinfo->ai_family) {
172 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
173 freeaddrinfo(addrinfo);
180 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
181 freeaddrinfo(addrinfo);
184 conf->prefixlen = (uint8_t)plen;
186 conf->prefixlen = 255;
189 freeaddrinfo(conf->addrinfo);
190 conf->addrinfo = addrinfo;
194 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
199 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
203 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
205 debugx(1, DBG_ERR, "no ] matching initial [");
209 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
212 debugx(1, DBG_ERR, "missing host/address");
214 conf->host = stringcopy(field, p - field);
217 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
218 debugx(1, DBG_ERR, "unexpected character after ]");
221 /* port number or service name is specified */;
223 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
225 debugx(1, DBG_ERR, "syntax error, : but no following port");
226 conf->port = stringcopy(field, p - field);
228 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
232 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
233 struct clsrvconf *conf;
235 conf = malloc(sizeof(struct clsrvconf));
237 debugx(1, DBG_ERR, "malloc failed");
238 memset(conf, 0, sizeof(struct clsrvconf));
240 conf->pdef = protodefs[conf->type];
242 parsehostport(lconf, conf, default_port);
243 if (!strcmp(conf->host, "*")) {
248 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
249 if (!resolvepeer(conf, AI_PASSIVE))
250 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
254 void freeclsrvres(struct clsrvconf *res) {
258 freeaddrinfo(res->addrinfo);
262 struct addrinfo *resolve_hostport_addrinfo(uint8_t type, char *hostport) {
264 struct clsrvconf *res;
266 res = resolve_hostport(type, hostport, NULL);
268 res->addrinfo = NULL;
273 /* returns 1 if the len first bits are equal, else 0 */
274 int prefixmatch(void *a1, void *a2, uint8_t len) {
275 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
276 uint8_t r, l = len / 8;
277 if (l && memcmp(a1, a2, l))
282 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
285 /* returns next config with matching address, or NULL */
286 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
287 struct sockaddr_in6 *sa6 = NULL;
288 struct in_addr *a4 = NULL;
289 struct addrinfo *res;
290 struct list_node *entry;
291 struct clsrvconf *conf;
293 if (addr->sa_family == AF_INET6) {
294 sa6 = (struct sockaddr_in6 *)addr;
295 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
296 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
300 a4 = &((struct sockaddr_in *)addr)->sin_addr;
302 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
303 conf = (struct clsrvconf *)entry->data;
304 if (conf->type == type) {
305 if (conf->prefixlen == 255) {
306 for (res = conf->addrinfo; res; res = res->ai_next)
307 if ((a4 && res->ai_family == AF_INET &&
308 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
309 (sa6 && res->ai_family == AF_INET6 &&
310 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
316 res = conf->addrinfo;
318 ((a4 && res->ai_family == AF_INET &&
319 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
320 (sa6 && res->ai_family == AF_INET6 &&
321 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
332 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
333 return find_conf(type, addr, clconfs, cur);
336 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
337 return find_conf(type, addr, srvconfs, cur);
340 /* returns next config of given type, or NULL */
341 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
342 struct list_node *entry;
343 struct clsrvconf *conf;
345 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
346 conf = (struct clsrvconf *)entry->data;
347 if (conf->type == type) {
356 struct queue *newqueue() {
359 q = malloc(sizeof(struct queue));
361 debugx(1, DBG_ERR, "malloc failed");
362 q->entries = list_create();
364 debugx(1, DBG_ERR, "malloc failed");
365 pthread_mutex_init(&q->mutex, NULL);
366 pthread_cond_init(&q->cond, NULL);
370 void removequeue(struct queue *q) {
371 struct list_node *entry;
375 pthread_mutex_lock(&q->mutex);
376 for (entry = list_first(q->entries); entry; entry = list_next(entry))
377 freerq((struct request *)entry);
378 list_destroy(q->entries);
379 pthread_cond_destroy(&q->cond);
380 pthread_mutex_unlock(&q->mutex);
381 pthread_mutex_destroy(&q->mutex);
385 void freebios(struct queue *q) {
388 pthread_mutex_lock(&q->mutex);
389 while ((bio = (BIO *)list_shift(q->entries)))
391 pthread_mutex_unlock(&q->mutex);
395 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
396 struct client *new = malloc(sizeof(struct client));
399 debug(DBG_ERR, "malloc failed");
404 pthread_mutex_lock(conf->lock);
405 if (!conf->clients) {
406 conf->clients = list_create();
407 if (!conf->clients) {
409 pthread_mutex_unlock(conf->lock);
410 debug(DBG_ERR, "malloc failed");
415 memset(new, 0, sizeof(struct client));
417 if (conf->pdef->addclient)
418 conf->pdef->addclient(new);
420 new->replyq = newqueue();
421 list_push(conf->clients, new);
423 pthread_mutex_unlock(conf->lock);
427 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
428 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
431 pthread_mutex_lock(&lock);
433 pthread_mutex_unlock(&lock);
436 void removeclientrqs(struct client *client) {
441 removeclientrqs_sendrq_freeserver_lock(1);
442 for (i = 0; i < MAX_REQUESTS; i++) {
447 rqout = rq->to->requests + rq->newid;
448 pthread_mutex_lock(rqout->lock);
449 if (rqout->rq == rq) /* still pointing to our request */
450 freerqoutdata(rqout);
451 pthread_mutex_unlock(rqout->lock);
455 removeclientrqs_sendrq_freeserver_lock(0);
458 void removelockedclient(struct client *client) {
459 struct clsrvconf *conf;
463 removeclientrqs(client);
464 removequeue(client->replyq);
465 list_removedata(conf->clients, client);
471 void removeclient(struct client *client) {
472 struct clsrvconf *conf;
478 pthread_mutex_lock(conf->lock);
479 removelockedclient(client);
480 pthread_mutex_unlock(conf->lock);
483 void freeserver(struct server *server, uint8_t destroymutex) {
484 struct rqout *rqout, *end;
489 removeclientrqs_sendrq_freeserver_lock(1);
490 if (server->requests) {
491 rqout = server->requests;
492 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
494 rqout->rq->to = NULL;
495 freerqoutdata(rqout);
496 pthread_mutex_destroy(rqout->lock);
499 free(server->requests);
502 freebios(server->rbios);
503 free(server->dynamiclookuparg);
505 SSL_free(server->ssl);
507 pthread_mutex_destroy(&server->lock);
508 pthread_cond_destroy(&server->newrq_cond);
509 pthread_mutex_destroy(&server->newrq_mutex);
511 removeclientrqs_sendrq_freeserver_lock(0);
515 int addserver(struct clsrvconf *conf) {
519 debug(DBG_ERR, "addserver: currently works with just one server per conf");
522 conf->servers = malloc(sizeof(struct server));
523 if (!conf->servers) {
524 debug(DBG_ERR, "malloc failed");
527 memset(conf->servers, 0, sizeof(struct server));
528 conf->servers->conf = conf;
531 if (conf->type == RAD_DTLS)
532 conf->servers->rbios = newqueue();
534 conf->pdef->setsrcres();
536 conf->servers->sock = -1;
537 if (conf->pdef->addserverextra)
538 conf->pdef->addserverextra(conf);
540 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
541 if (!conf->servers->requests) {
542 debug(DBG_ERR, "malloc failed");
545 for (i = 0; i < MAX_REQUESTS; i++) {
546 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
547 if (!conf->servers->requests[i].lock) {
548 debug(DBG_ERR, "malloc failed");
551 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
552 debug(DBG_ERR, "mutex init failed");
553 free(conf->servers->requests[i].lock);
554 conf->servers->requests[i].lock = NULL;
558 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
559 debug(DBG_ERR, "mutex init failed");
562 conf->servers->newrq = 0;
563 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
564 debug(DBG_ERR, "mutex init failed");
565 pthread_mutex_destroy(&conf->servers->lock);
568 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
569 debug(DBG_ERR, "mutex init failed");
570 pthread_mutex_destroy(&conf->servers->newrq_mutex);
571 pthread_mutex_destroy(&conf->servers->lock);
578 freeserver(conf->servers, 0);
579 conf->servers = NULL;
583 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
585 if (ATTRTYPE(attrs) == type)
587 length -= ATTRLEN(attrs);
588 attrs += ATTRLEN(attrs);
593 struct request *newrqref(struct request *rq) {
599 void freerq(struct request *rq) {
602 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
605 if (rq->origusername)
606 free(rq->origusername);
612 radmsg_free(rq->msg);
616 void freerqoutdata(struct rqout *rqout) {
620 if (rqout->rq->buf) {
621 free(rqout->rq->buf);
622 rqout->rq->buf = NULL;
628 memset(&rqout->expiry, 0, sizeof(struct timeval));
631 void sendrq(struct request *rq) {
635 removeclientrqs_sendrq_freeserver_lock(1);
640 start = to->conf->statusserver ? 1 : 0;
641 pthread_mutex_lock(&to->newrq_mutex);
642 if (start && rq->msg->code == RAD_Status_Server) {
643 pthread_mutex_lock(to->requests[0].lock);
644 if (to->requests[0].rq) {
645 pthread_mutex_unlock(to->requests[0].lock);
646 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
653 /* might simplify if only try nextid, might be ok */
654 for (i = to->nextid; i < MAX_REQUESTS; i++) {
655 if (!to->requests[i].rq) {
656 pthread_mutex_lock(to->requests[i].lock);
657 if (!to->requests[i].rq)
659 pthread_mutex_unlock(to->requests[i].lock);
662 if (i == MAX_REQUESTS) {
663 for (i = start; i < to->nextid; i++) {
664 if (!to->requests[i].rq) {
665 pthread_mutex_lock(to->requests[i].lock);
666 if (!to->requests[i].rq)
668 pthread_mutex_unlock(to->requests[i].lock);
671 if (i == to->nextid) {
672 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
677 rq->newid = (uint8_t)i;
678 rq->msg->id = (uint8_t)i;
679 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
681 pthread_mutex_unlock(to->requests[i].lock);
682 debug(DBG_ERR, "sendrq: radmsg2buf failed");
686 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
687 to->requests[i].rq = rq;
688 pthread_mutex_unlock(to->requests[i].lock);
689 if (i >= start) /* i is not reserved for statusserver */
694 debug(DBG_DBG, "sendrq: signalling client writer");
695 pthread_cond_signal(&to->newrq_cond);
698 pthread_mutex_unlock(&to->newrq_mutex);
699 removeclientrqs_sendrq_freeserver_lock(0);
704 rmclientrq(rq, rq->msg->id);
706 pthread_mutex_unlock(&to->newrq_mutex);
707 removeclientrqs_sendrq_freeserver_lock(0);
710 void sendreply(struct request *rq) {
712 struct client *to = rq->from;
715 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
716 radmsg_free(rq->msg);
720 debug(DBG_ERR, "sendreply: radmsg2buf failed");
724 pthread_mutex_lock(&to->replyq->mutex);
725 first = list_first(to->replyq->entries) == NULL;
727 if (!list_push(to->replyq->entries, rq)) {
728 pthread_mutex_unlock(&to->replyq->mutex);
730 debug(DBG_ERR, "sendreply: malloc failed");
735 debug(DBG_DBG, "signalling server writer");
736 pthread_cond_signal(&to->replyq->cond);
738 pthread_mutex_unlock(&to->replyq->mutex);
741 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
742 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
743 static unsigned char first = 1;
744 static EVP_MD_CTX mdctx;
745 unsigned char hash[EVP_MAX_MD_SIZE], *input;
747 uint8_t i, offset = 0, out[128];
749 pthread_mutex_lock(&lock);
751 EVP_MD_CTX_init(&mdctx);
757 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
758 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
759 !EVP_DigestUpdate(&mdctx, input, 16) ||
760 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
762 pthread_mutex_unlock(&lock);
765 for (i = 0; i < 16; i++)
766 out[offset + i] = hash[i] ^ in[offset + i];
767 input = out + offset - 16;
772 memcpy(in, out, len);
773 pthread_mutex_unlock(&lock);
777 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
778 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
779 static unsigned char first = 1;
780 static EVP_MD_CTX mdctx;
781 unsigned char hash[EVP_MAX_MD_SIZE], *input;
783 uint8_t i, offset = 0, out[128];
785 pthread_mutex_lock(&lock);
787 EVP_MD_CTX_init(&mdctx);
793 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
794 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
795 !EVP_DigestUpdate(&mdctx, input, 16) ||
796 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
798 pthread_mutex_unlock(&lock);
801 for (i = 0; i < 16; i++)
802 out[offset + i] = hash[i] ^ in[offset + i];
808 memcpy(in, out, len);
809 pthread_mutex_unlock(&lock);
813 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
814 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
815 static unsigned char first = 1;
816 static EVP_MD_CTX mdctx;
817 unsigned char hash[EVP_MAX_MD_SIZE];
821 pthread_mutex_lock(&lock);
823 EVP_MD_CTX_init(&mdctx);
828 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
829 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
830 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
833 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
834 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
835 !EVP_DigestUpdate(&mdctx, auth, 16) ||
836 !EVP_DigestUpdate(&mdctx, salt, 2) ||
837 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
838 pthread_mutex_unlock(&lock);
843 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
846 for (i = 0; i < 16; i++)
849 for (offset = 16; offset < len; offset += 16) {
851 printf("text + offset - 16 c(%d): ", offset / 16);
852 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
854 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
855 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
856 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
857 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
859 pthread_mutex_unlock(&lock);
863 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
866 for (i = 0; i < 16; i++)
867 text[offset + i] ^= hash[i];
871 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
874 pthread_mutex_unlock(&lock);
878 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
879 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
880 static unsigned char first = 1;
881 static EVP_MD_CTX mdctx;
882 unsigned char hash[EVP_MAX_MD_SIZE];
887 pthread_mutex_lock(&lock);
889 EVP_MD_CTX_init(&mdctx);
894 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
895 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
896 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
899 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
900 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
901 !EVP_DigestUpdate(&mdctx, auth, 16) ||
902 !EVP_DigestUpdate(&mdctx, salt, 2) ||
903 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
904 pthread_mutex_unlock(&lock);
909 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
912 for (i = 0; i < 16; i++)
913 plain[i] = text[i] ^ hash[i];
915 for (offset = 16; offset < len; offset += 16) {
917 printf("text + offset - 16 c(%d): ", offset / 16);
918 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
920 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
921 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
922 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
923 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
925 pthread_mutex_unlock(&lock);
929 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
932 for (i = 0; i < 16; i++)
933 plain[offset + i] = text[offset + i] ^ hash[i];
936 memcpy(text, plain, len);
938 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
941 pthread_mutex_unlock(&lock);
945 struct realm *newrealmref(struct realm *r) {
951 /* returns with lock on realm */
952 struct realm *id2realm(struct list *realmlist, char *id) {
953 struct list_node *entry;
954 struct realm *realm, *subrealm;
956 /* need to do locking for subrealms and check subrealm timers */
957 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
958 realm = (struct realm *)entry->data;
959 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
960 pthread_mutex_lock(&realm->mutex);
961 if (realm->subrealms) {
962 subrealm = id2realm(realm->subrealms, id);
964 pthread_mutex_unlock(&realm->mutex);
968 return newrealmref(realm);
974 /* helper function, only used by removeserversubrealms() */
975 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
976 struct list_node *entry, *entry2;
979 for (entry = list_first(realmlist); entry;) {
980 realm = newrealmref((struct realm *)entry->data);
981 pthread_mutex_lock(&realm->mutex);
982 entry = list_next(entry);
984 if (realm->srvconfs) {
985 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
986 if (entry2->data == srv)
988 list_removedata(realm->srvconfs, srv);
989 if (!list_first(realm->srvconfs)) {
990 list_destroy(realm->srvconfs);
991 realm->srvconfs = NULL;
994 if (realm->accsrvconfs) {
995 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
996 if (entry2->data == srv)
998 list_removedata(realm->accsrvconfs, srv);
999 if (!list_first(realm->accsrvconfs)) {
1000 list_destroy(realm->accsrvconfs);
1001 realm->accsrvconfs = NULL;
1005 /* remove subrealm if no servers */
1006 if (!realm->srvconfs && !realm->accsrvconfs)
1007 list_removedata(realmlist, realm);
1009 pthread_mutex_unlock(&realm->mutex);
1014 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1015 struct list_node *entry;
1016 struct realm *realm;
1018 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1019 realm = (struct realm *)entry->data;
1020 pthread_mutex_lock(&realm->mutex);
1021 if (realm->subrealms) {
1022 _internal_removeserversubrealms(realm->subrealms, srv);
1023 if (!list_first(realm->subrealms)) {
1024 list_destroy(realm->subrealms);
1025 realm->subrealms = NULL;
1028 pthread_mutex_unlock(&realm->mutex);
1032 int attrvalidate(unsigned char *attrs, int length) {
1033 while (length > 1) {
1034 if (ATTRLEN(attrs) < 2) {
1035 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1038 length -= ATTRLEN(attrs);
1040 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1043 attrs += ATTRLEN(attrs);
1046 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1050 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1051 if (len < 16 || len > 128 || len % 16) {
1052 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1056 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1057 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1061 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1063 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1064 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1070 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1073 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1074 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1077 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1078 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1084 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1085 char *oldsecret, char *newsecret) {
1086 unsigned char *attr;
1088 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1089 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1090 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1096 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
1100 for (; attrs[0]; attrs += 2)
1101 if (attrs[0] == vendor && attrs[1] == subattr)
1106 /* returns 1 if entire element is to be removed, else 0 */
1107 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1108 uint8_t alen, sublen;
1112 if (!removevendorattrs)
1115 memcpy(&vendor, attr->v, 4);
1116 vendor = ntohl(vendor);
1117 while (*removevendorattrs && *removevendorattrs != vendor)
1118 removevendorattrs += 2;
1119 if (!*removevendorattrs)
1122 if (findvendorsubattr(removevendorattrs, vendor, 256))
1123 return 1; /* remove entire vendor attribute */
1125 sublen = attr->l - 4;
1126 subattrs = attr->v + 4;
1128 if (!attrvalidate(subattrs, sublen)) {
1129 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1133 while (sublen > 1) {
1134 alen = ATTRLEN(subattrs);
1136 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1137 memmove(subattrs, subattrs + alen, sublen);
1145 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1146 struct list_node *n, *p;
1150 n = list_first(msg->attrs);
1152 attr = (struct tlv *)n->data;
1153 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1154 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1155 list_removedata(msg->attrs, attr);
1157 n = p ? list_next(p) : list_first(msg->attrs);
1164 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1165 struct list_node *n;
1168 for (n = list_first(addattrs); n; n = list_next(n)) {
1169 a = copytlv((struct tlv *)n->data);
1172 if (!radmsg_add(msg, a)) {
1180 int resizeattr(struct tlv *attr, uint8_t newlen) {
1183 if (newlen != attr->l) {
1184 newv = realloc(attr->v, newlen);
1193 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1194 size_t nmatch = 10, reslen = 0, start = 0;
1195 regmatch_t pmatch[10], *pfield;
1199 in = stringcopy((char *)attr->v, attr->l);
1203 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1208 out = modattr->replacement;
1210 for (i = start; out[i]; i++) {
1211 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1212 pfield = &pmatch[out[i + 1] - '0'];
1213 if (pfield->rm_so >= 0) {
1214 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1220 reslen += i - start;
1222 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1227 if (!resizeattr(attr, reslen)) {
1234 for (i = start; out[i]; i++) {
1235 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1236 pfield = &pmatch[out[i + 1] - '0'];
1237 if (pfield->rm_so >= 0) {
1238 memcpy(attr->v + reslen, out + start, i - start);
1239 reslen += i - start;
1240 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1241 reslen += pfield->rm_eo - pfield->rm_so;
1248 memcpy(attr->v + reslen, out + start, i - start);
1252 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1253 struct list_node *n, *m;
1255 for (n = list_first(msg->attrs); n; n = list_next(n))
1256 for (m = list_first(modattrs); m; m = list_next(m))
1257 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1258 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1263 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1266 if (rewrite->removeattrs || rewrite->removevendorattrs)
1267 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1268 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1270 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1275 int rewriteusername(struct request *rq, struct tlv *attr) {
1276 char *orig = (char *)tlv2str(attr);
1277 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1281 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1282 rq->origusername = (char *)orig;
1288 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1295 vendor = htonl(vendor);
1296 memcpy(v, &vendor, 4);
1297 tlv2buf(v + 4, attr);
1299 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1300 if (vattr && radmsg_add(msg, vattr))
1307 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1314 if (attrtype[1] == 256) { /* not vendor */
1315 attr = maketlv(attrtype[0], 4, ttl);
1316 if (attr && !radmsg_add(msg, attr))
1319 attr = maketlv(attrtype[1], 4, ttl);
1321 addvendorattr(msg, attrtype[0], attr);
1327 int decttl(uint8_t l, uint8_t *v) {
1334 while (i >= 0 && !v[i])
1338 for (i--; i >= 0 && !v[i]; i--);
1347 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1348 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1349 uint8_t alen, *subattrs;
1351 struct list_node *node;
1355 if (attrtype[1] == 256) { /* not vendor */
1356 attr = radmsg_gettype(msg, attrtype[0]);
1358 return decttl(attr->l, attr->v);
1360 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1361 attr = (struct tlv *)node->data;
1362 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1364 memcpy(&vendor, attr->v, 4);
1365 if (ntohl(vendor) != attrtype[0])
1367 sublen = attr->l - 4;
1368 subattrs = attr->v + 4;
1369 if (!attrvalidate(subattrs, sublen))
1371 while (sublen > 1) {
1372 if (ATTRTYPE(subattrs) == attrtype[1])
1373 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1374 alen = ATTRLEN(subattrs);
1382 const char *radmsgtype2string(uint8_t code) {
1383 static const char *rad_msg_names[] = {
1384 "", "Access-Request", "Access-Accept", "Access-Reject",
1385 "Accounting-Request", "Accounting-Response", "", "",
1386 "", "", "", "Access-Challenge",
1387 "Status-Server", "Status-Client"
1389 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1392 void char2hex(char *h, unsigned char c) {
1393 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1394 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1395 h[0] = hexdigits[c / 16];
1396 h[1] = hexdigits[c % 16];
1400 uint8_t *radattr2ascii(struct tlv *attr) {
1408 for (i = 0; i < attr->l; i++)
1409 if (attr->v[i] < 32 || attr->v[i] > 126)
1412 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1419 for (i = 0; i < attr->l; i++)
1420 if (attr->v[i] < 32 || attr->v[i] > 126) {
1422 char2hex((char *)d, attr->v[i]);
1430 void acclog(struct radmsg *msg, char *host) {
1434 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1436 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1439 username = radattr2ascii(attr);
1441 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1446 void respond(struct request *rq, uint8_t code, char *message) {
1450 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1452 debug(DBG_ERR, "respond: malloc failed");
1455 if (message && *message) {
1456 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1457 if (!attr || !radmsg_add(msg, attr)) {
1460 debug(DBG_ERR, "respond: malloc failed");
1465 radmsg_free(rq->msg);
1467 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1468 sendreply(newrqref(rq));
1471 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1472 struct list_node *entry;
1473 struct clsrvconf *server, *best = NULL, *first = NULL;
1475 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1476 server = (struct clsrvconf *)entry->data;
1477 if (!server->servers)
1481 if (!server->servers->connectionok)
1483 if (!server->servers->lostrqs)
1489 if (server->servers->lostrqs < best->servers->lostrqs)
1492 return best ? best : first;
1495 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1496 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1497 struct clsrvconf *srvconf;
1498 struct realm *subrealm;
1499 struct server *server = NULL;
1500 char *id = (char *)tlv2str(username);
1504 /* returns with lock on realm */
1505 *realm = id2realm(realms, id);
1508 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1509 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1512 server = srvconf->servers;
1513 if (!acc && !(*realm)->parent && !srvconf->servers) {
1514 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1516 pthread_mutex_lock(&subrealm->mutex);
1517 pthread_mutex_unlock(&(*realm)->mutex);
1520 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1529 struct request *newrequest() {
1532 rq = malloc(sizeof(struct request));
1534 debug(DBG_ERR, "newrequest: malloc failed");
1537 memset(rq, 0, sizeof(struct request));
1539 gettimeofday(&rq->created, NULL);
1543 int addclientrq(struct request *rq) {
1547 r = rq->from->rqs[rq->rqid];
1549 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1550 gettimeofday(&now, NULL);
1551 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1553 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1554 sendreply(newrqref(r));
1556 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1562 rq->from->rqs[rq->rqid] = newrqref(rq);
1566 void rmclientrq(struct request *rq, uint8_t id) {
1569 r = rq->from->rqs[id];
1572 rq->from->rqs[id] = NULL;
1576 /* returns 0 if validation/authentication fails, else 1 */
1577 int radsrv(struct request *rq) {
1578 struct radmsg *msg = NULL;
1580 uint8_t *userascii = NULL;
1581 struct realm *realm = NULL;
1582 struct server *to = NULL;
1583 struct client *from = rq->from;
1586 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1591 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1598 memcpy(rq->rqauth, msg->auth, 16);
1600 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1601 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1602 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1606 if (!addclientrq(rq))
1609 if (msg->code == RAD_Status_Server) {
1610 respond(rq, RAD_Access_Accept, NULL);
1614 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1616 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1619 ttlres = checkttl(msg, options.ttlattrtype);
1621 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1625 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1627 if (msg->code == RAD_Accounting_Request) {
1628 acclog(msg, from->conf->host);
1629 respond(rq, RAD_Accounting_Response, NULL);
1631 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1635 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1636 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1640 userascii = radattr2ascii(attr);
1643 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1645 /* will return with lock on the realm */
1646 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1648 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1653 if (realm->message && msg->code == RAD_Access_Request) {
1654 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1655 respond(rq, RAD_Access_Reject, realm->message);
1656 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1657 acclog(msg, from->conf->host);
1658 respond(rq, RAD_Accounting_Response, NULL);
1663 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1664 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1665 from->conf->name, addr2string(from->addr), to->conf->name);
1669 if (msg->code == RAD_Accounting_Request)
1670 memset(msg->auth, 0, 16);
1671 else if (!RAND_bytes(msg->auth, 16)) {
1672 debug(DBG_WARN, "radsrv: failed to generate random auth");
1677 printfchars(NULL, "auth", "%02x ", auth, 16);
1680 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1682 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1683 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1687 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1689 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1690 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1694 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1697 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1698 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1703 pthread_mutex_unlock(&realm->mutex);
1708 rmclientrq(rq, msg->id);
1713 pthread_mutex_unlock(&realm->mutex);
1719 void replyh(struct server *server, unsigned char *buf) {
1720 struct client *from;
1721 struct rqout *rqout;
1723 unsigned char *subattrs;
1724 uint8_t *username, *stationid, *replymsg;
1725 struct radmsg *msg = NULL;
1727 struct list_node *node;
1729 server->connectionok = 1;
1730 server->lostrqs = 0;
1732 rqout = server->requests + buf[1];
1733 pthread_mutex_lock(rqout->lock);
1734 if (!rqout->tries) {
1737 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1741 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1745 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1748 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1749 && msg->code != RAD_Accounting_Response) {
1750 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1753 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1755 gettimeofday(&server->lastrcv, NULL);
1757 if (rqout->rq->msg->code == RAD_Status_Server) {
1758 freerqoutdata(rqout);
1759 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1763 gettimeofday(&server->lastreply, NULL);
1764 from = rqout->rq->from;
1766 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1767 debug(DBG_WARN, "replyh: rewritein failed");
1771 ttlres = checkttl(msg, options.ttlattrtype);
1773 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
1778 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1779 attr = (struct tlv *)node->data;
1780 if (attr->t != RAD_Attr_Vendor_Specific)
1784 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1787 sublen = attr->l - 4;
1788 subattrs = attr->v + 4;
1789 if (!attrvalidate(subattrs, sublen) ||
1790 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1791 rqout->rq, server->conf->secret, from->conf->secret) ||
1792 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1793 rqout->rq, server->conf->secret, from->conf->secret))
1797 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1801 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1802 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1804 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1805 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1808 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1809 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1812 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1813 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1817 debug(DBG_INFO, "%s for user %s from %s (%s)",
1818 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1821 debug(DBG_INFO, "%s for user %s from %s",
1822 radmsgtype2string(msg->code), username, server->conf->host);
1828 msg->id = (char)rqout->rq->rqid;
1829 memcpy(msg->auth, rqout->rq->rqauth, 16);
1832 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1835 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1836 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1837 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1840 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1843 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1844 debug(DBG_WARN, "replyh: rewriteout failed");
1848 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1849 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1851 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
1852 radmsg_free(rqout->rq->msg);
1853 rqout->rq->msg = msg;
1854 sendreply(newrqref(rqout->rq));
1855 freerqoutdata(rqout);
1856 pthread_mutex_unlock(rqout->lock);
1861 pthread_mutex_unlock(rqout->lock);
1865 struct request *createstatsrvrq() {
1872 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1875 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1878 if (!radmsg_add(rq->msg, attr)) {
1889 /* code for removing state not finished */
1890 void *clientwr(void *arg) {
1891 struct server *server = (struct server *)arg;
1892 struct rqout *rqout = NULL;
1893 pthread_t clientrdth;
1894 int i, dynconffail = 0;
1897 struct timeval now, laststatsrv;
1898 struct timespec timeout;
1899 struct request *statsrvrq;
1900 struct clsrvconf *conf;
1902 conf = server->conf;
1904 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1909 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
1910 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
1914 memset(&timeout, 0, sizeof(struct timespec));
1916 if (conf->statusserver) {
1917 gettimeofday(&server->lastrcv, NULL);
1918 gettimeofday(&laststatsrv, NULL);
1921 if (conf->pdef->connecter) {
1922 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
1924 server->connectionok = 1;
1925 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1926 debug(DBG_ERR, "clientwr: pthread_create failed");
1930 server->connectionok = 1;
1933 pthread_mutex_lock(&server->newrq_mutex);
1934 if (!server->newrq) {
1935 gettimeofday(&now, NULL);
1936 /* random 0-7 seconds */
1937 RAND_bytes(&rnd, 1);
1939 if (conf->statusserver) {
1940 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1941 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1943 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1944 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1946 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1947 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1950 if (timeout.tv_sec > now.tv_sec)
1951 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1953 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1956 if (server->newrq) {
1957 debug(DBG_DBG, "clientwr: got new request");
1962 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1964 pthread_mutex_unlock(&server->newrq_mutex);
1966 for (i = 0; i < MAX_REQUESTS; i++) {
1967 if (server->clientrdgone) {
1968 pthread_join(clientrdth, NULL);
1972 for (; i < MAX_REQUESTS; i++) {
1973 rqout = server->requests + i;
1975 pthread_mutex_lock(rqout->lock);
1978 pthread_mutex_unlock(rqout->lock);
1982 if (i == MAX_REQUESTS)
1985 gettimeofday(&now, NULL);
1986 if (now.tv_sec < rqout->expiry.tv_sec) {
1987 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1988 timeout.tv_sec = rqout->expiry.tv_sec;
1989 pthread_mutex_unlock(rqout->lock);
1993 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1994 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1995 if (conf->statusserver) {
1996 if (*rqout->rq->buf == RAD_Status_Server) {
1997 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
1998 if (server->lostrqs < 255)
2002 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2003 if (server->lostrqs < 255)
2006 freerqoutdata(rqout);
2007 pthread_mutex_unlock(rqout->lock);
2011 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2012 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2013 timeout.tv_sec = rqout->expiry.tv_sec;
2015 conf->pdef->clientradput(server, rqout->rq->buf);
2016 pthread_mutex_unlock(rqout->lock);
2018 if (conf->statusserver && server->connectionok) {
2019 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2020 gettimeofday(&now, NULL);
2021 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2023 statsrvrq = createstatsrvrq();
2025 statsrvrq->to = server;
2026 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2033 conf->servers = NULL;
2034 if (server->dynamiclookuparg) {
2035 removeserversubrealms(realms, conf);
2039 freeclsrvconf(conf);
2041 freeserver(server, 1);
2042 ERR_remove_state(0);
2046 void createlistener(uint8_t type, char *arg) {
2048 struct clsrvconf *listenres;
2049 struct addrinfo *res;
2050 int s = -1, on = 1, *sp = NULL;
2052 listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2054 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2056 for (res = listenres->addrinfo; res; res = res->ai_next) {
2057 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2059 debug(DBG_WARN, "createlistener: socket failed");
2062 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2064 if (res->ai_family == AF_INET6)
2065 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2067 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2068 debug(DBG_WARN, "createlistener: bind failed");
2074 sp = malloc(sizeof(int));
2076 debugx(1, DBG_ERR, "malloc failed");
2078 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2079 debugx(1, DBG_ERR, "pthread_create failed");
2083 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2085 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2086 listenres->host ? listenres->host : "*", listenres->port);
2087 freeclsrvres(listenres);
2090 void createlisteners(uint8_t type) {
2094 args = protodefs[type]->getlistenerargs();
2096 for (i = 0; args[i]; i++)
2097 createlistener(type, args[i]);
2099 createlistener(type, NULL);
2107 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2108 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2109 for (i = 0; i < CRYPTO_num_locks(); i++) {
2110 ssl_lock_count[i] = 0;
2111 pthread_mutex_init(&ssl_locks[i], NULL);
2113 CRYPTO_set_id_callback(ssl_thread_id);
2114 CRYPTO_set_locking_callback(ssl_locking_callback);
2116 SSL_load_error_strings();
2119 while (!RAND_status()) {
2122 RAND_seed((unsigned char *)&t, sizeof(time_t));
2123 RAND_seed((unsigned char *)&pid, sizeof(pid));
2127 struct list *addsrvconfs(char *value, char **names) {
2128 struct list *conflist;
2130 struct list_node *entry;
2131 struct clsrvconf *conf = NULL;
2133 if (!names || !*names)
2136 conflist = list_create();
2138 debug(DBG_ERR, "malloc failed");
2142 for (n = 0; names[n]; n++) {
2143 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2144 conf = (struct clsrvconf *)entry->data;
2145 if (!strcasecmp(names[n], conf->name))
2149 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2150 list_destroy(conflist);
2153 if (!list_push(conflist, conf)) {
2154 debug(DBG_ERR, "malloc failed");
2155 list_destroy(conflist);
2158 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2163 void freerealm(struct realm *realm) {
2166 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2167 if (--realm->refcount)
2171 free(realm->message);
2172 regfree(&realm->regex);
2173 pthread_mutex_destroy(&realm->mutex);
2174 /* if refcount == 0, all subrealms gone */
2175 list_destroy(realm->subrealms);
2176 /* if refcount == 0, all srvconfs gone */
2177 list_destroy(realm->srvconfs);
2178 /* if refcount == 0, all accsrvconfs gone */
2179 list_destroy(realm->accsrvconfs);
2180 freerealm(realm->parent);
2184 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2186 struct realm *realm;
2187 char *s, *regex = NULL;
2189 if (*value == '/') {
2190 /* regexp, remove optional trailing / if present */
2191 if (value[strlen(value) - 1] == '/')
2192 value[strlen(value) - 1] = '\0';
2194 /* not a regexp, let us make it one */
2195 if (*value == '*' && !value[1])
2196 regex = stringcopy(".*", 0);
2198 for (n = 0, s = value; *s;)
2201 regex = malloc(strlen(value) + n + 3);
2204 for (n = 1, s = value; *s; s++) {
2214 debug(DBG_ERR, "malloc failed");
2218 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2221 realm = malloc(sizeof(struct realm));
2223 debug(DBG_ERR, "malloc failed");
2226 memset(realm, 0, sizeof(struct realm));
2228 if (pthread_mutex_init(&realm->mutex, NULL)) {
2229 debug(DBG_ERR, "mutex init failed");
2235 realm->name = stringcopy(value, 0);
2237 debug(DBG_ERR, "malloc failed");
2240 if (message && strlen(message) > 253) {
2241 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2244 realm->message = message;
2245 realm->accresp = accresp;
2247 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2248 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2252 if (servers && *servers) {
2253 realm->srvconfs = addsrvconfs(value, servers);
2254 if (!realm->srvconfs)
2258 if (accservers && *accservers) {
2259 realm->accsrvconfs = addsrvconfs(value, accservers);
2260 if (!realm->accsrvconfs)
2264 if (!list_push(realmlist, realm)) {
2265 debug(DBG_ERR, "malloc failed");
2266 pthread_mutex_destroy(&realm->mutex);
2270 debug(DBG_DBG, "addrealm: added realm %s", value);
2274 while (list_shift(realm->srvconfs));
2275 while (list_shift(realm->accsrvconfs));
2282 for (n = 0; servers[n]; n++)
2284 freegconfmstr(servers);
2288 for (n = 0; accservers[n]; n++)
2290 freegconfmstr(accservers);
2292 return newrealmref(realm);
2295 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2296 struct clsrvconf *srvconf;
2297 struct realm *newrealm = NULL;
2298 char *realmname, *s;
2301 if (!conf->dynamiclookupcommand)
2304 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2305 realmname = strrchr(id, '@');
2311 for (s = realmname; *s; s++)
2312 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2315 srvconf = malloc(sizeof(struct clsrvconf));
2317 debug(DBG_ERR, "malloc failed");
2321 if (!addserver(srvconf))
2324 if (!realm->subrealms)
2325 realm->subrealms = list_create();
2326 if (!realm->subrealms)
2328 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2331 newrealm->parent = newrealmref(realm);
2333 /* add server and accserver to newrealm */
2334 newrealm->srvconfs = list_create();
2335 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2336 debug(DBG_ERR, "malloc failed");
2339 newrealmref(newrealm);
2340 newrealm->accsrvconfs = list_create();
2341 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2342 debug(DBG_ERR, "malloc failed");
2343 list_shift(realm->srvconfs);
2344 freerealm(newrealm);
2347 newrealmref(newrealm);
2349 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2350 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2351 debug(DBG_ERR, "pthread_create failed");
2352 list_shift(realm->srvconfs);
2353 freerealm(newrealm);
2354 list_shift(realm->accsrvconfs);
2355 freerealm(newrealm);
2358 pthread_detach(clientth);
2363 list_removedata(realm->subrealms, newrealm);
2364 freerealm(newrealm);
2365 if (!list_first(realm->subrealms)) {
2366 list_destroy(realm->subrealms);
2367 realm->subrealms = NULL;
2370 freeserver(srvconf->servers, 1);
2372 debug(DBG_ERR, "failed to create dynamic server");
2376 int dynamicconfig(struct server *server) {
2377 int ok, fd[2], status;
2379 struct clsrvconf *conf = server->conf;
2380 struct gconffile *cf = NULL;
2382 /* for now we only learn hostname/address */
2383 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2386 debug(DBG_ERR, "dynamicconfig: pipe error");
2391 debug(DBG_ERR, "dynamicconfig: fork error");
2395 } else if (pid == 0) {
2398 if (fd[1] != STDOUT_FILENO) {
2399 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2400 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2403 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2404 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2408 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2409 ok = getgenericconfig(&cf, NULL,
2410 "Server", CONF_CBK, confserver_cb, (void *)conf,
2415 if (waitpid(pid, &status, 0) < 0) {
2416 debug(DBG_ERR, "dynamicconfig: wait error");
2421 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2429 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2433 /* should accept both names and numeric values, only numeric right now */
2434 uint8_t attrname2val(char *attrname) {
2437 val = atoi(attrname);
2438 return val > 0 && val < 256 ? val : 0;
2441 /* should accept both names and numeric values, only numeric right now */
2442 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2445 *vendor = atoi(attrname);
2446 s = strchr(attrname, ':');
2451 *type = atoi(s + 1);
2455 /* should accept both names and numeric values, only numeric right now */
2456 struct tlv *extractattr(char *nameval) {
2461 s = strchr(nameval, ':');
2462 name = atoi(nameval);
2463 if (!s || name < 1 || name > 255)
2465 len = strlen(s + 1);
2468 a = malloc(sizeof(struct tlv));
2471 a->v = (uint8_t *)stringcopy(s + 1, 0);
2481 /* should accept both names and numeric values, only numeric right now */
2482 struct modattr *extractmodattr(char *nameval) {
2487 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2491 s = strchr(nameval, ':');
2492 name = atoi(nameval);
2493 if (!s || name < 1 || name > 255 || s[1] != '/')
2497 /* regexp, remove optional trailing / if present */
2498 if (s[strlen(s) - 1] == '/')
2499 s[strlen(s) - 1] = '\0';
2507 m = malloc(sizeof(struct modattr));
2509 debug(DBG_ERR, "malloc failed");
2514 m->replacement = stringcopy(t, 0);
2515 if (!m->replacement) {
2517 debug(DBG_ERR, "malloc failed");
2521 m->regex = malloc(sizeof(regex_t));
2523 free(m->replacement);
2525 debug(DBG_ERR, "malloc failed");
2529 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2531 free(m->replacement);
2533 debug(DBG_ERR, "failed to compile regular expression %s", s);
2540 struct rewrite *getrewrite(char *alt1, char *alt2) {
2543 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2545 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2550 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2551 struct rewrite *rewrite = NULL;
2553 uint8_t *rma = NULL;
2554 uint32_t *p, *rmva = NULL;
2555 struct list *adda = NULL, *moda = NULL;
2560 for (n = 0; rmattrs[n]; n++);
2561 rma = calloc(n + 1, sizeof(uint8_t));
2563 debugx(1, DBG_ERR, "malloc failed");
2565 for (i = 0; i < n; i++)
2566 if (!(rma[i] = attrname2val(rmattrs[i])))
2567 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2568 freegconfmstr(rmattrs);
2573 for (n = 0; rmvattrs[n]; n++);
2574 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2576 debugx(1, DBG_ERR, "malloc failed");
2578 for (p = rmva, i = 0; i < n; i++, p += 2)
2579 if (!vattrname2val(rmvattrs[i], p, p + 1))
2580 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2581 freegconfmstr(rmvattrs);
2586 adda = list_create();
2588 debugx(1, DBG_ERR, "malloc failed");
2589 for (i = 0; addattrs[i]; i++) {
2590 a = extractattr(addattrs[i]);
2592 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2593 if (!list_push(adda, a))
2594 debugx(1, DBG_ERR, "malloc failed");
2596 freegconfmstr(addattrs);
2600 moda = list_create();
2602 debugx(1, DBG_ERR, "malloc failed");
2603 for (i = 0; modattrs[i]; i++) {
2604 m = extractmodattr(modattrs[i]);
2606 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2607 if (!list_push(moda, m))
2608 debugx(1, DBG_ERR, "malloc failed");
2610 freegconfmstr(modattrs);
2613 if (rma || rmva || adda || moda) {
2614 rewrite = malloc(sizeof(struct rewrite));
2616 debugx(1, DBG_ERR, "malloc failed");
2617 rewrite->removeattrs = rma;
2618 rewrite->removevendorattrs = rmva;
2619 rewrite->addattrs = adda;
2620 rewrite->modattrs = moda;
2623 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2624 debugx(1, DBG_ERR, "malloc failed");
2625 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2628 int setttlattr(struct options *opts, char *defaultattr) {
2629 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2631 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2632 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2634 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2638 void freeclsrvconf(struct clsrvconf *conf) {
2644 free(conf->matchcertattr);
2645 if (conf->certcnregex)
2646 regfree(conf->certcnregex);
2647 if (conf->certuriregex)
2648 regfree(conf->certuriregex);
2649 free(conf->confrewritein);
2650 free(conf->confrewriteout);
2651 if (conf->rewriteusername) {
2652 if (conf->rewriteusername->regex)
2653 regfree(conf->rewriteusername->regex);
2654 free(conf->rewriteusername->replacement);
2655 free(conf->rewriteusername);
2657 free(conf->dynamiclookupcommand);
2658 free(conf->rewritein);
2659 free(conf->rewriteout);
2661 freeaddrinfo(conf->addrinfo);
2663 pthread_mutex_destroy(conf->lock);
2666 /* not touching ssl_ctx, clients and servers */
2670 int mergeconfstring(char **dst, char **src) {
2679 t = stringcopy(*dst, 0);
2681 debug(DBG_ERR, "malloc failed");
2689 /* assumes dst is a shallow copy */
2690 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2691 if (!mergeconfstring(&dst->name, &src->name) ||
2692 !mergeconfstring(&dst->host, &src->host) ||
2693 !mergeconfstring(&dst->port, &src->port) ||
2694 !mergeconfstring(&dst->secret, &src->secret) ||
2695 !mergeconfstring(&dst->tls, &src->tls) ||
2696 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2697 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2698 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2699 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2702 dst->pdef = src->pdef;
2703 dst->statusserver = src->statusserver;
2704 dst->certnamecheck = src->certnamecheck;
2705 if (src->retryinterval != 255)
2706 dst->retryinterval = src->retryinterval;
2707 if (src->retrycount != 255)
2708 dst->retrycount = src->retrycount;
2712 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2713 struct clsrvconf *conf;
2714 char *conftype = NULL, *rewriteinalias = NULL;
2715 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2717 debug(DBG_DBG, "confclient_cb called for %s", block);
2719 conf = malloc(sizeof(struct clsrvconf));
2721 debugx(1, DBG_ERR, "malloc failed");
2722 memset(conf, 0, sizeof(struct clsrvconf));
2723 conf->certnamecheck = 1;
2725 if (!getgenericconfig(cf, block,
2726 "type", CONF_STR, &conftype,
2727 "host", CONF_STR, &conf->host,
2728 "secret", CONF_STR, &conf->secret,
2729 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2730 "tls", CONF_STR, &conf->tls,
2731 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2732 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2734 "DuplicateInterval", CONF_LINT, &dupinterval,
2735 "addTTL", CONF_LINT, &addttl,
2736 "rewrite", CONF_STR, &rewriteinalias,
2737 "rewriteIn", CONF_STR, &conf->confrewritein,
2738 "rewriteOut", CONF_STR, &conf->confrewriteout,
2739 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2742 debugx(1, DBG_ERR, "configuration error");
2744 conf->name = stringcopy(val, 0);
2746 conf->host = stringcopy(val, 0);
2747 if (!conf->name || !conf->host)
2748 debugx(1, DBG_ERR, "malloc failed");
2751 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2752 conf->type = protoname2int(conftype);
2753 if (conf->type == 255)
2754 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2756 conf->pdef = protodefs[conf->type];
2758 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2759 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2760 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2762 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2763 if (conf->matchcertattr && !addmatchcertattr(conf))
2764 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2768 if (dupinterval != LONG_MIN) {
2769 if (dupinterval < 0 || dupinterval > 255)
2770 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2771 conf->dupinterval = (uint8_t)dupinterval;
2773 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2775 if (addttl != LONG_MIN) {
2776 if (addttl < 1 || addttl > 255)
2777 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2778 conf->addttl = (uint8_t)addttl;
2781 if (!conf->confrewritein)
2782 conf->confrewritein = rewriteinalias;
2784 free(rewriteinalias);
2785 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2786 if (conf->confrewriteout)
2787 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2789 if (conf->confrewriteusername) {
2790 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2791 if (!conf->rewriteusername)
2792 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2795 if (!resolvepeer(conf, 0))
2796 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2798 if (!conf->secret) {
2799 if (!conf->pdef->secretdefault)
2800 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2801 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2803 debugx(1, DBG_ERR, "malloc failed");
2806 conf->lock = malloc(sizeof(pthread_mutex_t));
2808 debugx(1, DBG_ERR, "malloc failed");
2810 pthread_mutex_init(conf->lock, NULL);
2811 if (!list_push(clconfs, conf))
2812 debugx(1, DBG_ERR, "malloc failed");
2816 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2817 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2818 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2819 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2820 if (!conf->tlsconf) {
2821 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2824 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2825 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2832 conf->port = stringcopy(conf->pdef->portdefault, 0);
2834 debug(DBG_ERR, "malloc failed");
2839 if (conf->retryinterval == 255)
2840 conf->retryinterval = conf->pdef->retryintervaldefault;
2841 if (conf->retrycount == 255)
2842 conf->retrycount = conf->pdef->retrycountdefault;
2844 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2845 if (conf->confrewriteout)
2846 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2848 if (!conf->secret) {
2849 if (!conf->pdef->secretdefault) {
2850 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2853 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2854 if (!conf->secret) {
2855 debug(DBG_ERR, "malloc failed");
2860 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
2861 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2867 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2868 struct clsrvconf *conf, *resconf;
2869 char *conftype = NULL, *rewriteinalias = NULL;
2870 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2872 debug(DBG_DBG, "confserver_cb called for %s", block);
2874 conf = malloc(sizeof(struct clsrvconf));
2876 debug(DBG_ERR, "malloc failed");
2879 memset(conf, 0, sizeof(struct clsrvconf));
2880 resconf = (struct clsrvconf *)arg;
2882 conf->statusserver = resconf->statusserver;
2883 conf->certnamecheck = resconf->certnamecheck;
2885 conf->certnamecheck = 1;
2887 if (!getgenericconfig(cf, block,
2888 "type", CONF_STR, &conftype,
2889 "host", CONF_STR, &conf->host,
2890 "port", CONF_STR, &conf->port,
2891 "secret", CONF_STR, &conf->secret,
2892 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2893 "tls", CONF_STR, &conf->tls,
2894 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2895 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2897 "addTTL", CONF_LINT, &addttl,
2898 "rewrite", CONF_STR, &rewriteinalias,
2899 "rewriteIn", CONF_STR, &conf->confrewritein,
2900 "rewriteOut", CONF_STR, &conf->confrewriteout,
2901 "StatusServer", CONF_BLN, &conf->statusserver,
2902 "RetryInterval", CONF_LINT, &retryinterval,
2903 "RetryCount", CONF_LINT, &retrycount,
2904 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2907 debug(DBG_ERR, "configuration error");
2911 conf->name = stringcopy(val, 0);
2913 debug(DBG_ERR, "malloc failed");
2917 conf->host = stringcopy(val, 0);
2919 debug(DBG_ERR, "malloc failed");
2925 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2926 conf->type = protoname2int(conftype);
2927 if (conf->type == 255) {
2928 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2934 conf->pdef = protodefs[conf->type];
2936 if (!conf->confrewritein)
2937 conf->confrewritein = rewriteinalias;
2939 free(rewriteinalias);
2940 rewriteinalias = NULL;
2942 if (retryinterval != LONG_MIN) {
2943 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2944 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2947 conf->retryinterval = (uint8_t)retryinterval;
2949 conf->retryinterval = 255;
2951 if (retrycount != LONG_MIN) {
2952 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2953 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2956 conf->retrycount = (uint8_t)retrycount;
2958 conf->retrycount = 255;
2960 if (addttl != LONG_MIN) {
2961 if (addttl < 1 || addttl > 255) {
2962 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2965 conf->addttl = (uint8_t)addttl;
2969 if (!mergesrvconf(resconf, conf))
2973 if (conf->dynamiclookupcommand) {
2974 free(conf->dynamiclookupcommand);
2975 conf->dynamiclookupcommand = NULL;
2979 if (resconf || !conf->dynamiclookupcommand) {
2980 if (!compileserverconfig(conf, block))
2987 if (!list_push(srvconfs, conf)) {
2988 debug(DBG_ERR, "malloc failed");
2995 free(rewriteinalias);
2996 freeclsrvconf(conf);
3000 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3001 char **servers = NULL, **accservers = NULL, *msg = NULL;
3002 uint8_t accresp = 0;
3004 debug(DBG_DBG, "confrealm_cb called for %s", block);
3006 if (!getgenericconfig(cf, block,
3007 "server", CONF_MSTR, &servers,
3008 "accountingServer", CONF_MSTR, &accservers,
3009 "ReplyMessage", CONF_STR, &msg,
3010 "AccountingResponse", CONF_BLN, &accresp,
3013 debugx(1, DBG_ERR, "configuration error");
3015 addrealm(realms, val, servers, accservers, msg, accresp);
3019 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3020 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3022 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3024 if (!getgenericconfig(cf, block,
3025 "removeAttribute", CONF_MSTR, &rmattrs,
3026 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3027 "addAttribute", CONF_MSTR, &addattrs,
3028 "modifyAttribute", CONF_MSTR, &modattrs,
3031 debugx(1, DBG_ERR, "configuration error");
3032 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3036 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3037 struct commonprotoopts *protoopts;
3039 protoopts = malloc(sizeof(struct commonprotoopts));
3042 memset(protoopts, 0, sizeof(struct commonprotoopts));
3043 protoopts->listenargs = listenargs;
3044 protoopts->sourcearg = sourcearg;
3045 protodefs[type]->setprotoopts(protoopts);
3049 void getmainconfig(const char *configfile) {
3050 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3051 struct gconffile *cfs;
3052 char **listenargs[RAD_PROTOCOUNT];
3053 char *sourcearg[RAD_PROTOCOUNT];
3056 cfs = openconfigfile(configfile);
3057 memset(&options, 0, sizeof(options));
3058 memset(&listenargs, 0, sizeof(listenargs));
3059 memset(&sourcearg, 0, sizeof(sourcearg));
3061 clconfs = list_create();
3063 debugx(1, DBG_ERR, "malloc failed");
3065 srvconfs = list_create();
3067 debugx(1, DBG_ERR, "malloc failed");
3069 realms = list_create();
3071 debugx(1, DBG_ERR, "malloc failed");
3073 rewriteconfs = hash_create();
3075 debugx(1, DBG_ERR, "malloc failed");
3077 if (!getgenericconfig(&cfs, NULL,
3079 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3080 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3083 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3084 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3087 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3088 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3091 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3092 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3094 "TTLAttribute", CONF_STR, &options.ttlattr,
3095 "addTTL", CONF_LINT, &addttl,
3096 "LogLevel", CONF_LINT, &loglevel,
3097 "LogDestination", CONF_STR, &options.logdestination,
3098 "LoopPrevention", CONF_BLN, &options.loopprevention,
3099 "Client", CONF_CBK, confclient_cb, NULL,
3100 "Server", CONF_CBK, confserver_cb, NULL,
3101 "Realm", CONF_CBK, confrealm_cb, NULL,
3102 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3103 "TLS", CONF_CBK, conftls_cb, NULL,
3105 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3108 debugx(1, DBG_ERR, "configuration error");
3110 if (loglevel != LONG_MIN) {
3111 if (loglevel < 1 || loglevel > 4)
3112 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3113 options.loglevel = (uint8_t)loglevel;
3115 if (addttl != LONG_MIN) {
3116 if (addttl < 1 || addttl > 255)
3117 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3118 options.addttl = (uint8_t)addttl;
3120 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3121 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3123 for (i = 0; i < RAD_PROTOCOUNT; i++)
3124 if (listenargs[i] || sourcearg[i])
3125 setprotoopts(i, listenargs[i], sourcearg[i]);
3128 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3131 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3134 *configfile = optarg;
3137 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3138 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3139 *loglevel = *optarg - '0';
3148 debug(DBG_ERR, "radsecproxy revision $Rev$");
3149 debug(DBG_ERR, "This binary was built with support for the following transports:");
3151 debug(DBG_ERR, " UDP");
3154 debug(DBG_ERR, " TCP");
3157 debug(DBG_ERR, " TLS");
3160 debug(DBG_ERR, " DTLS");
3167 if (!(argc - optind))
3171 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3175 int daemon(int a, int b) {
3183 for (i = 0; i < 3; i++) {
3185 open("/dev/null", O_RDWR);
3191 void *sighandler(void *arg) {
3196 sigemptyset(&sigset);
3197 sigaddset(&sigset, SIGPIPE);
3198 sigwait(&sigset, &sig);
3199 /* only get SIGPIPE right now, so could simplify below code */
3202 /* completely ignoring this */
3205 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3208 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3213 int main(int argc, char **argv) {
3216 struct list_node *entry;
3217 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3218 char *configfile = NULL;
3219 struct clsrvconf *srvconf;
3222 debug_init("radsecproxy");
3223 debug_set_level(DEBUG_LEVEL);
3225 for (i = 0; i < RAD_PROTOCOUNT; i++)
3226 protodefs[i] = protoinits[i](i);
3228 /* needed even if no TLS/DTLS transport */
3231 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3233 debug_set_level(loglevel);
3234 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3236 options.loglevel = loglevel;
3237 else if (options.loglevel)
3238 debug_set_level(options.loglevel);
3240 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3241 free(options.logdestination);
3243 if (!list_first(clconfs))
3244 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3245 if (!list_first(realms))
3246 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3249 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3251 if (!foreground && (daemon(0, 0) < 0))
3252 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3254 debug_timestamp_on();
3255 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3257 sigemptyset(&sigset);
3258 /* exit on all but SIGPIPE, ignore more? */
3259 sigaddset(&sigset, SIGPIPE);
3260 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3261 pthread_create(&sigth, NULL, sighandler, NULL);
3263 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3264 srvconf = (struct clsrvconf *)entry->data;
3265 if (srvconf->dynamiclookupcommand)
3267 if (!addserver(srvconf))
3268 debugx(1, DBG_ERR, "failed to add server");
3269 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3270 (void *)(srvconf->servers)))
3271 debugx(1, DBG_ERR, "pthread_create failed");
3274 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3277 if (protodefs[i]->initextra)
3278 protodefs[i]->initextra();
3279 if (find_clconf_type(i, NULL))
3283 /* just hang around doing nothing, anything to do here? */