2 * Copyright (C) 2006-2009 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>
72 #include "radsecproxy.h"
78 static struct options options;
79 static struct list *clconfs, *srvconfs;
80 static struct list *realms;
81 static struct hash *rewriteconfs;
83 static pthread_mutex_t *ssl_locks = NULL;
84 static long *ssl_lock_count;
87 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
89 /* minimum required declarations to avoid reordering code */
90 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
91 int dynamicconfig(struct server *server);
92 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
93 void freerealm(struct realm *realm);
94 void freeclsrvconf(struct clsrvconf *conf);
95 void freerq(struct request *rq);
96 void freerqoutdata(struct rqout *rqout);
97 void rmclientrq(struct request *rq, uint8_t id);
99 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
101 uint8_t protoname2int(const char *name) {
104 for (i = 0; i < RAD_PROTOCOUNT; i++)
105 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
110 /* callbacks for making OpenSSL thread safe */
111 unsigned long ssl_thread_id() {
112 return (unsigned long)pthread_self();
115 void ssl_locking_callback(int mode, int type, const char *file, int line) {
116 if (mode & CRYPTO_LOCK) {
117 pthread_mutex_lock(&ssl_locks[type]);
118 ssl_lock_count[type]++;
120 pthread_mutex_unlock(&ssl_locks[type]);
123 /* returns 1 if the len first bits are equal, else 0 */
124 int prefixmatch(void *a1, void *a2, uint8_t len) {
125 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
126 uint8_t r, l = len / 8;
127 if (l && memcmp(a1, a2, l))
132 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
135 /* returns next config with matching address, or NULL */
136 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
137 struct list_node *entry;
138 struct clsrvconf *conf;
140 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
141 conf = (struct clsrvconf *)entry->data;
142 if (conf->type == type && addressmatches(conf->hostports, addr)) {
151 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
152 return find_conf(type, addr, clconfs, cur);
155 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
156 return find_conf(type, addr, srvconfs, cur);
159 /* returns next config of given type, or NULL */
160 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
161 struct list_node *entry;
162 struct clsrvconf *conf;
164 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
165 conf = (struct clsrvconf *)entry->data;
166 if (conf->type == type) {
175 struct gqueue *newqueue() {
178 q = malloc(sizeof(struct gqueue));
180 debugx(1, DBG_ERR, "malloc failed");
181 q->entries = list_create();
183 debugx(1, DBG_ERR, "malloc failed");
184 pthread_mutex_init(&q->mutex, NULL);
185 pthread_cond_init(&q->cond, NULL);
189 void removequeue(struct gqueue *q) {
190 struct list_node *entry;
194 pthread_mutex_lock(&q->mutex);
195 for (entry = list_first(q->entries); entry; entry = list_next(entry))
196 freerq((struct request *)entry);
197 list_destroy(q->entries);
198 pthread_cond_destroy(&q->cond);
199 pthread_mutex_unlock(&q->mutex);
200 pthread_mutex_destroy(&q->mutex);
204 void freebios(struct gqueue *q) {
207 pthread_mutex_lock(&q->mutex);
208 while ((bio = (BIO *)list_shift(q->entries)))
210 pthread_mutex_unlock(&q->mutex);
214 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
215 struct client *new = malloc(sizeof(struct client));
218 debug(DBG_ERR, "malloc failed");
223 pthread_mutex_lock(conf->lock);
224 if (!conf->clients) {
225 conf->clients = list_create();
226 if (!conf->clients) {
228 pthread_mutex_unlock(conf->lock);
229 debug(DBG_ERR, "malloc failed");
234 memset(new, 0, sizeof(struct client));
236 if (conf->pdef->addclient)
237 conf->pdef->addclient(new);
239 new->replyq = newqueue();
240 list_push(conf->clients, new);
242 pthread_mutex_unlock(conf->lock);
246 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
247 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
250 pthread_mutex_lock(&lock);
252 pthread_mutex_unlock(&lock);
255 void removeclientrqs(struct client *client) {
260 removeclientrqs_sendrq_freeserver_lock(1);
261 for (i = 0; i < MAX_REQUESTS; i++) {
266 rqout = rq->to->requests + rq->newid;
267 pthread_mutex_lock(rqout->lock);
268 if (rqout->rq == rq) /* still pointing to our request */
269 freerqoutdata(rqout);
270 pthread_mutex_unlock(rqout->lock);
274 removeclientrqs_sendrq_freeserver_lock(0);
277 void removelockedclient(struct client *client) {
278 struct clsrvconf *conf;
282 removeclientrqs(client);
283 removequeue(client->replyq);
284 list_removedata(conf->clients, client);
290 void removeclient(struct client *client) {
291 struct clsrvconf *conf;
297 pthread_mutex_lock(conf->lock);
298 removelockedclient(client);
299 pthread_mutex_unlock(conf->lock);
302 void freeserver(struct server *server, uint8_t destroymutex) {
303 struct rqout *rqout, *end;
308 removeclientrqs_sendrq_freeserver_lock(1);
309 if (server->requests) {
310 rqout = server->requests;
311 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
313 rqout->rq->to = NULL;
314 freerqoutdata(rqout);
315 pthread_mutex_destroy(rqout->lock);
318 free(server->requests);
321 freebios(server->rbios);
322 free(server->dynamiclookuparg);
324 SSL_free(server->ssl);
326 pthread_mutex_destroy(&server->lock);
327 pthread_cond_destroy(&server->newrq_cond);
328 pthread_mutex_destroy(&server->newrq_mutex);
330 removeclientrqs_sendrq_freeserver_lock(0);
334 int addserver(struct clsrvconf *conf) {
338 debug(DBG_ERR, "addserver: currently works with just one server per conf");
341 conf->servers = malloc(sizeof(struct server));
342 if (!conf->servers) {
343 debug(DBG_ERR, "malloc failed");
346 memset(conf->servers, 0, sizeof(struct server));
347 conf->servers->conf = conf;
350 if (conf->type == RAD_DTLS)
351 conf->servers->rbios = newqueue();
353 conf->pdef->setsrcres();
355 conf->servers->sock = -1;
356 if (conf->pdef->addserverextra)
357 conf->pdef->addserverextra(conf);
359 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
360 if (!conf->servers->requests) {
361 debug(DBG_ERR, "malloc failed");
364 for (i = 0; i < MAX_REQUESTS; i++) {
365 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
366 if (!conf->servers->requests[i].lock) {
367 debug(DBG_ERR, "malloc failed");
370 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
371 debug(DBG_ERR, "mutex init failed");
372 free(conf->servers->requests[i].lock);
373 conf->servers->requests[i].lock = NULL;
377 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
378 debug(DBG_ERR, "mutex init failed");
381 conf->servers->newrq = 0;
382 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
383 debug(DBG_ERR, "mutex init failed");
384 pthread_mutex_destroy(&conf->servers->lock);
387 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
388 debug(DBG_ERR, "mutex init failed");
389 pthread_mutex_destroy(&conf->servers->newrq_mutex);
390 pthread_mutex_destroy(&conf->servers->lock);
397 freeserver(conf->servers, 0);
398 conf->servers = NULL;
402 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
404 if (ATTRTYPE(attrs) == type)
406 length -= ATTRLEN(attrs);
407 attrs += ATTRLEN(attrs);
412 struct request *newrqref(struct request *rq) {
418 void freerq(struct request *rq) {
421 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
424 if (rq->origusername)
425 free(rq->origusername);
431 radmsg_free(rq->msg);
435 void freerqoutdata(struct rqout *rqout) {
439 if (rqout->rq->buf) {
440 free(rqout->rq->buf);
441 rqout->rq->buf = NULL;
447 memset(&rqout->expiry, 0, sizeof(struct timeval));
450 void sendrq(struct request *rq) {
454 removeclientrqs_sendrq_freeserver_lock(1);
459 start = to->conf->statusserver ? 1 : 0;
460 pthread_mutex_lock(&to->newrq_mutex);
461 if (start && rq->msg->code == RAD_Status_Server) {
462 pthread_mutex_lock(to->requests[0].lock);
463 if (to->requests[0].rq) {
464 pthread_mutex_unlock(to->requests[0].lock);
465 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
472 /* might simplify if only try nextid, might be ok */
473 for (i = to->nextid; i < MAX_REQUESTS; i++) {
474 if (!to->requests[i].rq) {
475 pthread_mutex_lock(to->requests[i].lock);
476 if (!to->requests[i].rq)
478 pthread_mutex_unlock(to->requests[i].lock);
481 if (i == MAX_REQUESTS) {
482 for (i = start; i < to->nextid; i++) {
483 if (!to->requests[i].rq) {
484 pthread_mutex_lock(to->requests[i].lock);
485 if (!to->requests[i].rq)
487 pthread_mutex_unlock(to->requests[i].lock);
490 if (i == to->nextid) {
491 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
496 rq->newid = (uint8_t)i;
497 rq->msg->id = (uint8_t)i;
498 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
500 pthread_mutex_unlock(to->requests[i].lock);
501 debug(DBG_ERR, "sendrq: radmsg2buf failed");
505 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
506 to->requests[i].rq = rq;
507 pthread_mutex_unlock(to->requests[i].lock);
508 if (i >= start) /* i is not reserved for statusserver */
513 debug(DBG_DBG, "sendrq: signalling client writer");
514 pthread_cond_signal(&to->newrq_cond);
517 pthread_mutex_unlock(&to->newrq_mutex);
518 removeclientrqs_sendrq_freeserver_lock(0);
523 rmclientrq(rq, rq->msg->id);
525 pthread_mutex_unlock(&to->newrq_mutex);
526 removeclientrqs_sendrq_freeserver_lock(0);
529 void sendreply(struct request *rq) {
531 struct client *to = rq->from;
534 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
535 radmsg_free(rq->msg);
539 debug(DBG_ERR, "sendreply: radmsg2buf failed");
543 pthread_mutex_lock(&to->replyq->mutex);
544 first = list_first(to->replyq->entries) == NULL;
546 if (!list_push(to->replyq->entries, rq)) {
547 pthread_mutex_unlock(&to->replyq->mutex);
549 debug(DBG_ERR, "sendreply: malloc failed");
554 debug(DBG_DBG, "signalling server writer");
555 pthread_cond_signal(&to->replyq->cond);
557 pthread_mutex_unlock(&to->replyq->mutex);
560 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
561 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
562 static unsigned char first = 1;
563 static EVP_MD_CTX mdctx;
564 unsigned char hash[EVP_MAX_MD_SIZE], *input;
566 uint8_t i, offset = 0, out[128];
568 pthread_mutex_lock(&lock);
570 EVP_MD_CTX_init(&mdctx);
576 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
577 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
578 !EVP_DigestUpdate(&mdctx, input, 16) ||
579 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
581 pthread_mutex_unlock(&lock);
584 for (i = 0; i < 16; i++)
585 out[offset + i] = hash[i] ^ in[offset + i];
586 input = out + offset - 16;
591 memcpy(in, out, len);
592 pthread_mutex_unlock(&lock);
596 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
597 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
598 static unsigned char first = 1;
599 static EVP_MD_CTX mdctx;
600 unsigned char hash[EVP_MAX_MD_SIZE], *input;
602 uint8_t i, offset = 0, out[128];
604 pthread_mutex_lock(&lock);
606 EVP_MD_CTX_init(&mdctx);
612 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
613 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
614 !EVP_DigestUpdate(&mdctx, input, 16) ||
615 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
617 pthread_mutex_unlock(&lock);
620 for (i = 0; i < 16; i++)
621 out[offset + i] = hash[i] ^ in[offset + i];
627 memcpy(in, out, len);
628 pthread_mutex_unlock(&lock);
632 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
633 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
634 static unsigned char first = 1;
635 static EVP_MD_CTX mdctx;
636 unsigned char hash[EVP_MAX_MD_SIZE];
640 pthread_mutex_lock(&lock);
642 EVP_MD_CTX_init(&mdctx);
647 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
648 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
649 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
652 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
653 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
654 !EVP_DigestUpdate(&mdctx, auth, 16) ||
655 !EVP_DigestUpdate(&mdctx, salt, 2) ||
656 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
657 pthread_mutex_unlock(&lock);
662 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
665 for (i = 0; i < 16; i++)
668 for (offset = 16; offset < len; offset += 16) {
670 printf("text + offset - 16 c(%d): ", offset / 16);
671 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
673 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
674 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
675 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
676 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
678 pthread_mutex_unlock(&lock);
682 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
685 for (i = 0; i < 16; i++)
686 text[offset + i] ^= hash[i];
690 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
693 pthread_mutex_unlock(&lock);
697 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
698 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
699 static unsigned char first = 1;
700 static EVP_MD_CTX mdctx;
701 unsigned char hash[EVP_MAX_MD_SIZE];
706 pthread_mutex_lock(&lock);
708 EVP_MD_CTX_init(&mdctx);
713 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
714 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
715 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
718 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
719 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
720 !EVP_DigestUpdate(&mdctx, auth, 16) ||
721 !EVP_DigestUpdate(&mdctx, salt, 2) ||
722 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
723 pthread_mutex_unlock(&lock);
728 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
731 for (i = 0; i < 16; i++)
732 plain[i] = text[i] ^ hash[i];
734 for (offset = 16; offset < len; offset += 16) {
736 printf("text + offset - 16 c(%d): ", offset / 16);
737 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
739 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
740 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
741 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
742 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
744 pthread_mutex_unlock(&lock);
748 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
751 for (i = 0; i < 16; i++)
752 plain[offset + i] = text[offset + i] ^ hash[i];
755 memcpy(text, plain, len);
757 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
760 pthread_mutex_unlock(&lock);
764 struct realm *newrealmref(struct realm *r) {
770 /* returns with lock on realm */
771 struct realm *id2realm(struct list *realmlist, char *id) {
772 struct list_node *entry;
773 struct realm *realm, *subrealm;
775 /* need to do locking for subrealms and check subrealm timers */
776 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
777 realm = (struct realm *)entry->data;
778 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
779 pthread_mutex_lock(&realm->mutex);
780 if (realm->subrealms) {
781 subrealm = id2realm(realm->subrealms, id);
783 pthread_mutex_unlock(&realm->mutex);
787 return newrealmref(realm);
793 int hasdynamicserver(struct list *srvconfs) {
794 struct list_node *entry;
796 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
797 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
802 /* helper function, only used by removeserversubrealms() */
803 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
804 struct list_node *entry, *entry2;
807 for (entry = list_first(realmlist); entry;) {
808 realm = newrealmref((struct realm *)entry->data);
809 pthread_mutex_lock(&realm->mutex);
810 entry = list_next(entry);
812 if (realm->srvconfs) {
813 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
814 if (entry2->data == srv)
816 list_removedata(realm->srvconfs, srv);
818 if (realm->accsrvconfs) {
819 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
820 if (entry2->data == srv)
822 list_removedata(realm->accsrvconfs, srv);
825 /* remove subrealm if no dynamic servers left */
826 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
827 while (list_shift(realm->srvconfs))
829 list_destroy(realm->srvconfs);
830 realm->srvconfs = NULL;
831 while (list_shift(realm->accsrvconfs))
833 list_destroy(realm->accsrvconfs);
834 realm->accsrvconfs = NULL;
835 list_removedata(realmlist, realm);
837 pthread_mutex_unlock(&realm->mutex);
842 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
843 struct list_node *entry;
846 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
847 realm = (struct realm *)entry->data;
848 pthread_mutex_lock(&realm->mutex);
849 if (realm->subrealms) {
850 _internal_removeserversubrealms(realm->subrealms, srv);
851 if (!list_first(realm->subrealms)) {
852 list_destroy(realm->subrealms);
853 realm->subrealms = NULL;
856 pthread_mutex_unlock(&realm->mutex);
860 int attrvalidate(unsigned char *attrs, int length) {
862 if (ATTRLEN(attrs) < 2) {
863 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
866 length -= ATTRLEN(attrs);
868 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
871 attrs += ATTRLEN(attrs);
874 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
878 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
879 if (len < 16 || len > 128 || len % 16) {
880 debug(DBG_WARN, "pwdrecrypt: invalid password length");
884 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
885 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
889 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
891 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
892 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
898 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
901 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
902 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
905 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
906 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
912 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
913 char *oldsecret, char *newsecret) {
916 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
917 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
918 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
924 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
928 for (; attrs[0]; attrs += 2)
929 if (attrs[0] == vendor && attrs[1] == subattr)
934 /* returns 1 if entire element is to be removed, else 0 */
935 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
936 uint8_t alen, sublen;
940 if (!removevendorattrs)
943 memcpy(&vendor, attr->v, 4);
944 vendor = ntohl(vendor);
945 while (*removevendorattrs && *removevendorattrs != vendor)
946 removevendorattrs += 2;
947 if (!*removevendorattrs)
950 if (findvendorsubattr(removevendorattrs, vendor, 256))
951 return 1; /* remove entire vendor attribute */
953 sublen = attr->l - 4;
954 subattrs = attr->v + 4;
956 if (!attrvalidate(subattrs, sublen)) {
957 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
962 alen = ATTRLEN(subattrs);
964 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
965 memmove(subattrs, subattrs + alen, sublen);
973 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
974 struct list_node *n, *p;
978 n = list_first(msg->attrs);
980 attr = (struct tlv *)n->data;
981 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
982 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
983 list_removedata(msg->attrs, attr);
985 n = p ? list_next(p) : list_first(msg->attrs);
992 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
996 for (n = list_first(addattrs); n; n = list_next(n)) {
997 a = copytlv((struct tlv *)n->data);
1000 if (!radmsg_add(msg, a)) {
1008 int resizeattr(struct tlv *attr, uint8_t newlen) {
1011 if (newlen != attr->l) {
1012 newv = realloc(attr->v, newlen);
1021 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1022 size_t nmatch = 10, reslen = 0, start = 0;
1023 regmatch_t pmatch[10], *pfield;
1027 in = stringcopy((char *)attr->v, attr->l);
1031 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1036 out = modattr->replacement;
1038 for (i = start; out[i]; i++) {
1039 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1040 pfield = &pmatch[out[i + 1] - '0'];
1041 if (pfield->rm_so >= 0) {
1042 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1048 reslen += i - start;
1050 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1055 if (!resizeattr(attr, reslen)) {
1062 for (i = start; out[i]; i++) {
1063 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1064 pfield = &pmatch[out[i + 1] - '0'];
1065 if (pfield->rm_so >= 0) {
1066 memcpy(attr->v + reslen, out + start, i - start);
1067 reslen += i - start;
1068 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1069 reslen += pfield->rm_eo - pfield->rm_so;
1076 memcpy(attr->v + reslen, out + start, i - start);
1080 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1081 struct list_node *n, *m;
1083 for (n = list_first(msg->attrs); n; n = list_next(n))
1084 for (m = list_first(modattrs); m; m = list_next(m))
1085 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1086 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1091 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1094 if (rewrite->removeattrs || rewrite->removevendorattrs)
1095 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1096 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1098 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1103 int rewriteusername(struct request *rq, struct tlv *attr) {
1104 char *orig = (char *)tlv2str(attr);
1105 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1109 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1110 rq->origusername = (char *)orig;
1116 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1123 vendor = htonl(vendor);
1124 memcpy(v, &vendor, 4);
1125 tlv2buf(v + 4, attr);
1127 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1128 if (vattr && radmsg_add(msg, vattr))
1135 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1142 if (attrtype[1] == 256) { /* not vendor */
1143 attr = maketlv(attrtype[0], 4, ttl);
1144 if (attr && !radmsg_add(msg, attr))
1147 attr = maketlv(attrtype[1], 4, ttl);
1149 addvendorattr(msg, attrtype[0], attr);
1155 int decttl(uint8_t l, uint8_t *v) {
1162 while (i >= 0 && !v[i])
1166 for (i--; i >= 0 && !v[i]; i--);
1175 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1176 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1177 uint8_t alen, *subattrs;
1179 struct list_node *node;
1183 if (attrtype[1] == 256) { /* not vendor */
1184 attr = radmsg_gettype(msg, attrtype[0]);
1186 return decttl(attr->l, attr->v);
1188 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1189 attr = (struct tlv *)node->data;
1190 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1192 memcpy(&vendor, attr->v, 4);
1193 if (ntohl(vendor) != attrtype[0])
1195 sublen = attr->l - 4;
1196 subattrs = attr->v + 4;
1197 if (!attrvalidate(subattrs, sublen))
1199 while (sublen > 1) {
1200 if (ATTRTYPE(subattrs) == attrtype[1])
1201 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1202 alen = ATTRLEN(subattrs);
1210 const char *radmsgtype2string(uint8_t code) {
1211 static const char *rad_msg_names[] = {
1212 "", "Access-Request", "Access-Accept", "Access-Reject",
1213 "Accounting-Request", "Accounting-Response", "", "",
1214 "", "", "", "Access-Challenge",
1215 "Status-Server", "Status-Client"
1217 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1220 void char2hex(char *h, unsigned char c) {
1221 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1222 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1223 h[0] = hexdigits[c / 16];
1224 h[1] = hexdigits[c % 16];
1228 uint8_t *radattr2ascii(struct tlv *attr) {
1236 for (i = 0; i < attr->l; i++)
1237 if (attr->v[i] < 32 || attr->v[i] > 126)
1240 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1247 for (i = 0; i < attr->l; i++)
1248 if (attr->v[i] < 32 || attr->v[i] > 126) {
1250 char2hex((char *)d, attr->v[i]);
1258 void acclog(struct radmsg *msg, struct client *from) {
1262 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1264 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1267 username = radattr2ascii(attr);
1269 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1275 void respond(struct request *rq, uint8_t code, char *message) {
1279 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1281 debug(DBG_ERR, "respond: malloc failed");
1284 if (message && *message) {
1285 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1286 if (!attr || !radmsg_add(msg, attr)) {
1289 debug(DBG_ERR, "respond: malloc failed");
1294 radmsg_free(rq->msg);
1296 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1297 sendreply(newrqref(rq));
1300 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1301 struct list_node *entry;
1302 struct clsrvconf *server, *best = NULL, *first = NULL;
1304 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1305 server = (struct clsrvconf *)entry->data;
1306 if (!server->servers)
1310 if (!server->servers->connectionok && !server->servers->dynstartup)
1312 if (!server->servers->lostrqs)
1318 if (server->servers->lostrqs < best->servers->lostrqs)
1321 return best ? best : first;
1324 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1325 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1326 struct clsrvconf *srvconf;
1327 struct realm *subrealm;
1328 struct server *server = NULL;
1329 char *id = (char *)tlv2str(username);
1333 /* returns with lock on realm */
1334 *realm = id2realm(realms, id);
1337 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1338 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1339 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1340 subrealm = adddynamicrealmserver(*realm, id);
1342 pthread_mutex_lock(&subrealm->mutex);
1343 pthread_mutex_unlock(&(*realm)->mutex);
1346 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1350 server = srvconf->servers;
1358 struct request *newrequest() {
1361 rq = malloc(sizeof(struct request));
1363 debug(DBG_ERR, "newrequest: malloc failed");
1366 memset(rq, 0, sizeof(struct request));
1368 gettimeofday(&rq->created, NULL);
1372 int addclientrq(struct request *rq) {
1376 r = rq->from->rqs[rq->rqid];
1378 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1379 gettimeofday(&now, NULL);
1380 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1382 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1383 sendreply(newrqref(r));
1385 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1391 rq->from->rqs[rq->rqid] = newrqref(rq);
1395 void rmclientrq(struct request *rq, uint8_t id) {
1398 r = rq->from->rqs[id];
1401 rq->from->rqs[id] = NULL;
1405 /* returns 0 if validation/authentication fails, else 1 */
1406 int radsrv(struct request *rq) {
1407 struct radmsg *msg = NULL;
1409 uint8_t *userascii = NULL;
1410 struct realm *realm = NULL;
1411 struct server *to = NULL;
1412 struct client *from = rq->from;
1415 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1420 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1427 memcpy(rq->rqauth, msg->auth, 16);
1429 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1430 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1431 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1435 if (!addclientrq(rq))
1438 if (msg->code == RAD_Status_Server) {
1439 respond(rq, RAD_Access_Accept, NULL);
1443 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1445 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1448 ttlres = checkttl(msg, options.ttlattrtype);
1450 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1454 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1456 if (msg->code == RAD_Accounting_Request) {
1458 respond(rq, RAD_Accounting_Response, NULL);
1460 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1464 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1465 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1469 userascii = radattr2ascii(attr);
1472 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1474 /* will return with lock on the realm */
1475 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1477 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1482 if (realm->message && msg->code == RAD_Access_Request) {
1483 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1484 respond(rq, RAD_Access_Reject, realm->message);
1485 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1487 respond(rq, RAD_Accounting_Response, NULL);
1492 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1493 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1494 from->conf->name, addr2string(from->addr), to->conf->name);
1498 if (msg->code == RAD_Accounting_Request)
1499 memset(msg->auth, 0, 16);
1500 else if (!RAND_bytes(msg->auth, 16)) {
1501 debug(DBG_WARN, "radsrv: failed to generate random auth");
1506 printfchars(NULL, "auth", "%02x ", auth, 16);
1509 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1511 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1512 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1516 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1518 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1519 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1523 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1526 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1527 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1532 pthread_mutex_unlock(&realm->mutex);
1537 rmclientrq(rq, msg->id);
1542 pthread_mutex_unlock(&realm->mutex);
1548 void replyh(struct server *server, unsigned char *buf) {
1549 struct client *from;
1550 struct rqout *rqout;
1552 unsigned char *subattrs;
1553 uint8_t *username, *stationid, *replymsg;
1554 struct radmsg *msg = NULL;
1556 struct list_node *node;
1558 server->connectionok = 1;
1559 server->lostrqs = 0;
1561 rqout = server->requests + buf[1];
1562 pthread_mutex_lock(rqout->lock);
1563 if (!rqout->tries) {
1566 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1570 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1574 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1577 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1578 && msg->code != RAD_Accounting_Response) {
1579 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1582 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1584 gettimeofday(&server->lastrcv, NULL);
1586 if (rqout->rq->msg->code == RAD_Status_Server) {
1587 freerqoutdata(rqout);
1588 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1592 gettimeofday(&server->lastreply, NULL);
1593 from = rqout->rq->from;
1595 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1596 debug(DBG_WARN, "replyh: rewritein failed");
1600 ttlres = checkttl(msg, options.ttlattrtype);
1602 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1607 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1608 attr = (struct tlv *)node->data;
1609 if (attr->t != RAD_Attr_Vendor_Specific)
1613 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1616 sublen = attr->l - 4;
1617 subattrs = attr->v + 4;
1618 if (!attrvalidate(subattrs, sublen) ||
1619 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1620 rqout->rq, server->conf->secret, from->conf->secret) ||
1621 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1622 rqout->rq, server->conf->secret, from->conf->secret))
1626 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1630 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1631 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1633 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1634 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1637 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1638 radmsgtype2string(msg->code), username, stationid, server->conf->name, replymsg);
1641 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1642 radmsgtype2string(msg->code), username, stationid, server->conf->name);
1646 debug(DBG_INFO, "%s for user %s from %s (%s)",
1647 radmsgtype2string(msg->code), username, server->conf->name, replymsg);
1650 debug(DBG_INFO, "%s for user %s from %s",
1651 radmsgtype2string(msg->code), username, server->conf->name);
1657 msg->id = (char)rqout->rq->rqid;
1658 memcpy(msg->auth, rqout->rq->rqauth, 16);
1661 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1664 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1665 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1666 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1669 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1672 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1673 debug(DBG_WARN, "replyh: rewriteout failed");
1677 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1678 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1680 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
1681 radmsg_free(rqout->rq->msg);
1682 rqout->rq->msg = msg;
1683 sendreply(newrqref(rqout->rq));
1684 freerqoutdata(rqout);
1685 pthread_mutex_unlock(rqout->lock);
1690 pthread_mutex_unlock(rqout->lock);
1694 struct request *createstatsrvrq() {
1701 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1704 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1707 if (!radmsg_add(rq->msg, attr)) {
1718 /* code for removing state not finished */
1719 void *clientwr(void *arg) {
1720 struct server *server = (struct server *)arg;
1721 struct rqout *rqout = NULL;
1722 pthread_t clientrdth;
1723 int i, dynconffail = 0;
1726 struct timeval now, laststatsrv;
1727 struct timespec timeout;
1728 struct request *statsrvrq;
1729 struct clsrvconf *conf;
1731 conf = server->conf;
1733 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1735 server->dynstartup = 0;
1740 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1741 debug(DBG_WARN, "clientwr: resolve failed");
1742 server->dynstartup = 0;
1747 memset(&timeout, 0, sizeof(struct timespec));
1749 if (conf->statusserver) {
1750 gettimeofday(&server->lastrcv, NULL);
1751 gettimeofday(&laststatsrv, NULL);
1754 if (conf->pdef->connecter) {
1755 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr")) {
1756 if (server->dynamiclookuparg) {
1757 server->dynstartup = 0;
1762 server->connectionok = 1;
1763 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1764 debug(DBG_ERR, "clientwr: pthread_create failed");
1768 server->connectionok = 1;
1769 server->dynstartup = 0;
1772 pthread_mutex_lock(&server->newrq_mutex);
1773 if (!server->newrq) {
1774 gettimeofday(&now, NULL);
1775 /* random 0-7 seconds */
1776 RAND_bytes(&rnd, 1);
1778 if (conf->statusserver) {
1779 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1780 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1782 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1783 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1785 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1786 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1789 if (timeout.tv_sec > now.tv_sec)
1790 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1792 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1795 if (server->newrq) {
1796 debug(DBG_DBG, "clientwr: got new request");
1801 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1803 pthread_mutex_unlock(&server->newrq_mutex);
1805 for (i = 0; i < MAX_REQUESTS; i++) {
1806 if (server->clientrdgone) {
1807 pthread_join(clientrdth, NULL);
1811 for (; i < MAX_REQUESTS; i++) {
1812 rqout = server->requests + i;
1814 pthread_mutex_lock(rqout->lock);
1817 pthread_mutex_unlock(rqout->lock);
1821 if (i == MAX_REQUESTS)
1824 gettimeofday(&now, NULL);
1825 if (now.tv_sec < rqout->expiry.tv_sec) {
1826 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1827 timeout.tv_sec = rqout->expiry.tv_sec;
1828 pthread_mutex_unlock(rqout->lock);
1832 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1833 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1834 if (conf->statusserver) {
1835 if (*rqout->rq->buf == RAD_Status_Server) {
1836 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1837 if (server->lostrqs < 255)
1841 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1842 if (server->lostrqs < 255)
1845 freerqoutdata(rqout);
1846 pthread_mutex_unlock(rqout->lock);
1850 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1851 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1852 timeout.tv_sec = rqout->expiry.tv_sec;
1854 conf->pdef->clientradput(server, rqout->rq->buf);
1855 pthread_mutex_unlock(rqout->lock);
1857 if (conf->statusserver && server->connectionok) {
1858 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1859 gettimeofday(&now, NULL);
1860 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1862 statsrvrq = createstatsrvrq();
1864 statsrvrq->to = server;
1865 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1872 conf->servers = NULL;
1873 if (server->dynamiclookuparg) {
1874 removeserversubrealms(realms, conf);
1878 freeclsrvconf(conf);
1880 freeserver(server, 1);
1881 ERR_remove_state(0);
1885 void createlistener(uint8_t type, char *arg) {
1887 struct addrinfo *res;
1888 int s = -1, on = 1, *sp = NULL;
1889 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1891 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1892 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1894 for (res = hp->addrinfo; res; res = res->ai_next) {
1895 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1897 debug(DBG_WARN, "createlistener: socket failed");
1900 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1902 if (res->ai_family == AF_INET6)
1903 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1905 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1906 debug(DBG_WARN, "createlistener: bind failed");
1912 sp = malloc(sizeof(int));
1914 debugx(1, DBG_ERR, "malloc failed");
1916 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1917 debugx(1, DBG_ERR, "pthread_create failed");
1921 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1923 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1927 void createlisteners(uint8_t type) {
1931 args = protodefs[type]->getlistenerargs();
1933 for (i = 0; args[i]; i++)
1934 createlistener(type, args[i]);
1936 createlistener(type, NULL);
1944 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1945 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1946 for (i = 0; i < CRYPTO_num_locks(); i++) {
1947 ssl_lock_count[i] = 0;
1948 pthread_mutex_init(&ssl_locks[i], NULL);
1950 CRYPTO_set_id_callback(ssl_thread_id);
1951 CRYPTO_set_locking_callback(ssl_locking_callback);
1953 SSL_load_error_strings();
1956 while (!RAND_status()) {
1959 RAND_seed((unsigned char *)&t, sizeof(time_t));
1960 RAND_seed((unsigned char *)&pid, sizeof(pid));
1964 struct list *addsrvconfs(char *value, char **names) {
1965 struct list *conflist;
1967 struct list_node *entry;
1968 struct clsrvconf *conf = NULL;
1970 if (!names || !*names)
1973 conflist = list_create();
1975 debug(DBG_ERR, "malloc failed");
1979 for (n = 0; names[n]; n++) {
1980 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1981 conf = (struct clsrvconf *)entry->data;
1982 if (!strcasecmp(names[n], conf->name))
1986 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
1987 list_destroy(conflist);
1990 if (!list_push(conflist, conf)) {
1991 debug(DBG_ERR, "malloc failed");
1992 list_destroy(conflist);
1995 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2000 void freerealm(struct realm *realm) {
2003 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2004 if (--realm->refcount)
2008 free(realm->message);
2009 regfree(&realm->regex);
2010 pthread_mutex_destroy(&realm->mutex);
2011 /* if refcount == 0, all subrealms gone */
2012 list_destroy(realm->subrealms);
2013 /* if refcount == 0, all srvconfs gone */
2014 list_destroy(realm->srvconfs);
2015 /* if refcount == 0, all accsrvconfs gone */
2016 list_destroy(realm->accsrvconfs);
2017 freerealm(realm->parent);
2021 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2023 struct realm *realm;
2024 char *s, *regex = NULL;
2026 if (*value == '/') {
2027 /* regexp, remove optional trailing / if present */
2028 if (value[strlen(value) - 1] == '/')
2029 value[strlen(value) - 1] = '\0';
2031 /* not a regexp, let us make it one */
2032 if (*value == '*' && !value[1])
2033 regex = stringcopy(".*", 0);
2035 for (n = 0, s = value; *s;)
2038 regex = malloc(strlen(value) + n + 3);
2041 for (n = 1, s = value; *s; s++) {
2051 debug(DBG_ERR, "malloc failed");
2055 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2058 realm = malloc(sizeof(struct realm));
2060 debug(DBG_ERR, "malloc failed");
2063 memset(realm, 0, sizeof(struct realm));
2065 if (pthread_mutex_init(&realm->mutex, NULL)) {
2066 debug(DBG_ERR, "mutex init failed");
2072 realm->name = stringcopy(value, 0);
2074 debug(DBG_ERR, "malloc failed");
2077 if (message && strlen(message) > 253) {
2078 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2081 realm->message = message;
2082 realm->accresp = accresp;
2084 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2085 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2089 if (servers && *servers) {
2090 realm->srvconfs = addsrvconfs(value, servers);
2091 if (!realm->srvconfs)
2095 if (accservers && *accservers) {
2096 realm->accsrvconfs = addsrvconfs(value, accservers);
2097 if (!realm->accsrvconfs)
2101 if (!list_push(realmlist, realm)) {
2102 debug(DBG_ERR, "malloc failed");
2103 pthread_mutex_destroy(&realm->mutex);
2107 debug(DBG_DBG, "addrealm: added realm %s", value);
2111 while (list_shift(realm->srvconfs));
2112 while (list_shift(realm->accsrvconfs));
2119 for (n = 0; servers[n]; n++)
2121 freegconfmstr(servers);
2125 for (n = 0; accservers[n]; n++)
2127 freegconfmstr(accservers);
2129 return newrealmref(realm);
2132 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2133 struct list_node *entry;
2134 struct clsrvconf *conf, *srvconf;
2135 struct list *subrealmservers = NULL;
2138 if (list_first(srvconfs)) {
2139 subrealmservers = list_create();
2140 if (!subrealmservers)
2144 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2145 conf = (struct clsrvconf *)entry->data;
2146 if (!conf->servers && conf->dynamiclookupcommand) {
2147 srvconf = malloc(sizeof(struct clsrvconf));
2149 debug(DBG_ERR, "malloc failed");
2153 if (addserver(srvconf)) {
2154 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2155 srvconf->servers->dynstartup = 1;
2156 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2157 debug(DBG_ERR, "pthread_create failed");
2158 freeserver(srvconf->servers, 1);
2159 srvconf->servers = NULL;
2161 pthread_detach(clientth);
2165 if (conf->servers) {
2166 if (list_push(subrealmservers, conf))
2169 debug(DBG_ERR, "malloc failed");
2172 return subrealmservers;
2175 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2176 struct realm *newrealm = NULL;
2177 char *realmname, *s;
2179 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2180 realmname = strrchr(id, '@');
2186 for (s = realmname; *s; s++)
2187 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2190 if (!realm->subrealms)
2191 realm->subrealms = list_create();
2192 if (!realm->subrealms)
2195 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2197 list_destroy(realm->subrealms);
2198 realm->subrealms = NULL;
2202 newrealm->parent = newrealmref(realm);
2203 /* add server and accserver to newrealm */
2204 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2205 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2209 int dynamicconfig(struct server *server) {
2210 int ok, fd[2], status;
2212 struct clsrvconf *conf = server->conf;
2213 struct gconffile *cf = NULL;
2215 /* for now we only learn hostname/address */
2216 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2219 debug(DBG_ERR, "dynamicconfig: pipe error");
2224 debug(DBG_ERR, "dynamicconfig: fork error");
2228 } else if (pid == 0) {
2231 if (fd[1] != STDOUT_FILENO) {
2232 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2233 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2236 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2237 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2241 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2242 ok = getgenericconfig(&cf, NULL,
2243 "Server", CONF_CBK, confserver_cb, (void *)conf,
2248 if (waitpid(pid, &status, 0) < 0) {
2249 debug(DBG_ERR, "dynamicconfig: wait error");
2254 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2262 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2266 /* should accept both names and numeric values, only numeric right now */
2267 uint8_t attrname2val(char *attrname) {
2270 val = atoi(attrname);
2271 return val > 0 && val < 256 ? val : 0;
2274 /* should accept both names and numeric values, only numeric right now */
2275 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2278 *vendor = atoi(attrname);
2279 s = strchr(attrname, ':');
2284 *type = atoi(s + 1);
2288 /* should accept both names and numeric values, only numeric right now */
2289 struct tlv *extractattr(char *nameval) {
2294 s = strchr(nameval, ':');
2295 name = atoi(nameval);
2296 if (!s || name < 1 || name > 255)
2298 len = strlen(s + 1);
2301 a = malloc(sizeof(struct tlv));
2304 a->v = (uint8_t *)stringcopy(s + 1, 0);
2314 /* should accept both names and numeric values, only numeric right now */
2315 struct modattr *extractmodattr(char *nameval) {
2320 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2324 s = strchr(nameval, ':');
2325 name = atoi(nameval);
2326 if (!s || name < 1 || name > 255 || s[1] != '/')
2330 /* regexp, remove optional trailing / if present */
2331 if (s[strlen(s) - 1] == '/')
2332 s[strlen(s) - 1] = '\0';
2340 m = malloc(sizeof(struct modattr));
2342 debug(DBG_ERR, "malloc failed");
2347 m->replacement = stringcopy(t, 0);
2348 if (!m->replacement) {
2350 debug(DBG_ERR, "malloc failed");
2354 m->regex = malloc(sizeof(regex_t));
2356 free(m->replacement);
2358 debug(DBG_ERR, "malloc failed");
2362 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2364 free(m->replacement);
2366 debug(DBG_ERR, "failed to compile regular expression %s", s);
2373 struct rewrite *getrewrite(char *alt1, char *alt2) {
2376 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2378 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2383 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2384 struct rewrite *rewrite = NULL;
2386 uint8_t *rma = NULL;
2387 uint32_t *p, *rmva = NULL;
2388 struct list *adda = NULL, *moda = NULL;
2393 for (n = 0; rmattrs[n]; n++);
2394 rma = calloc(n + 1, sizeof(uint8_t));
2396 debugx(1, DBG_ERR, "malloc failed");
2398 for (i = 0; i < n; i++)
2399 if (!(rma[i] = attrname2val(rmattrs[i])))
2400 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2401 freegconfmstr(rmattrs);
2406 for (n = 0; rmvattrs[n]; n++);
2407 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2409 debugx(1, DBG_ERR, "malloc failed");
2411 for (p = rmva, i = 0; i < n; i++, p += 2)
2412 if (!vattrname2val(rmvattrs[i], p, p + 1))
2413 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2414 freegconfmstr(rmvattrs);
2419 adda = list_create();
2421 debugx(1, DBG_ERR, "malloc failed");
2422 for (i = 0; addattrs[i]; i++) {
2423 a = extractattr(addattrs[i]);
2425 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2426 if (!list_push(adda, a))
2427 debugx(1, DBG_ERR, "malloc failed");
2429 freegconfmstr(addattrs);
2433 moda = list_create();
2435 debugx(1, DBG_ERR, "malloc failed");
2436 for (i = 0; modattrs[i]; i++) {
2437 m = extractmodattr(modattrs[i]);
2439 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2440 if (!list_push(moda, m))
2441 debugx(1, DBG_ERR, "malloc failed");
2443 freegconfmstr(modattrs);
2446 if (rma || rmva || adda || moda) {
2447 rewrite = malloc(sizeof(struct rewrite));
2449 debugx(1, DBG_ERR, "malloc failed");
2450 rewrite->removeattrs = rma;
2451 rewrite->removevendorattrs = rmva;
2452 rewrite->addattrs = adda;
2453 rewrite->modattrs = moda;
2456 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2457 debugx(1, DBG_ERR, "malloc failed");
2458 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2461 int setttlattr(struct options *opts, char *defaultattr) {
2462 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2464 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2465 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2467 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2471 void freeclsrvconf(struct clsrvconf *conf) {
2474 freegconfmstr(conf->hostsrc);
2475 free(conf->portsrc);
2478 free(conf->matchcertattr);
2479 if (conf->certcnregex)
2480 regfree(conf->certcnregex);
2481 if (conf->certuriregex)
2482 regfree(conf->certuriregex);
2483 free(conf->confrewritein);
2484 free(conf->confrewriteout);
2485 if (conf->rewriteusername) {
2486 if (conf->rewriteusername->regex)
2487 regfree(conf->rewriteusername->regex);
2488 free(conf->rewriteusername->replacement);
2489 free(conf->rewriteusername);
2491 free(conf->dynamiclookupcommand);
2492 free(conf->rewritein);
2493 free(conf->rewriteout);
2494 if (conf->hostports)
2495 freehostports(conf->hostports);
2497 pthread_mutex_destroy(conf->lock);
2500 /* not touching ssl_ctx, clients and servers */
2504 int mergeconfstring(char **dst, char **src) {
2513 t = stringcopy(*dst, 0);
2515 debug(DBG_ERR, "malloc failed");
2523 char **mstringcopy(char **in) {
2530 for (n = 0; in[n]; n++);
2531 out = malloc((n + 1) * sizeof(char *));
2534 for (n = 0; in[n]; n++) {
2535 out[n] = stringcopy(in[n], 0);
2545 int mergeconfmstring(char ***dst, char ***src) {
2554 t = mstringcopy(*dst);
2556 debug(DBG_ERR, "malloc failed");
2564 /* assumes dst is a shallow copy */
2565 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2566 if (!mergeconfstring(&dst->name, &src->name) ||
2567 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2568 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2569 !mergeconfstring(&dst->secret, &src->secret) ||
2570 !mergeconfstring(&dst->tls, &src->tls) ||
2571 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2572 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2573 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2574 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2577 dst->pdef = src->pdef;
2578 dst->statusserver = src->statusserver;
2579 dst->certnamecheck = src->certnamecheck;
2580 if (src->retryinterval != 255)
2581 dst->retryinterval = src->retryinterval;
2582 if (src->retrycount != 255)
2583 dst->retrycount = src->retrycount;
2587 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2588 struct clsrvconf *conf;
2589 char *conftype = NULL, *rewriteinalias = NULL;
2590 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2592 debug(DBG_DBG, "confclient_cb called for %s", block);
2594 conf = malloc(sizeof(struct clsrvconf));
2596 debugx(1, DBG_ERR, "malloc failed");
2597 memset(conf, 0, sizeof(struct clsrvconf));
2598 conf->certnamecheck = 1;
2600 if (!getgenericconfig(cf, block,
2601 "type", CONF_STR, &conftype,
2602 "host", CONF_MSTR, &conf->hostsrc,
2603 "secret", CONF_STR, &conf->secret,
2604 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2605 "tls", CONF_STR, &conf->tls,
2606 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2607 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2609 "DuplicateInterval", CONF_LINT, &dupinterval,
2610 "addTTL", CONF_LINT, &addttl,
2611 "rewrite", CONF_STR, &rewriteinalias,
2612 "rewriteIn", CONF_STR, &conf->confrewritein,
2613 "rewriteOut", CONF_STR, &conf->confrewriteout,
2614 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2617 debugx(1, DBG_ERR, "configuration error");
2619 conf->name = stringcopy(val, 0);
2620 if (conf->name && !conf->hostsrc) {
2621 conf->hostsrc = malloc(2 * sizeof(char *));
2622 if (conf->hostsrc) {
2623 conf->hostsrc[0] = stringcopy(val, 0);
2624 conf->hostsrc[1] = NULL;
2627 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2628 debugx(1, DBG_ERR, "malloc failed");
2631 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2632 conf->type = protoname2int(conftype);
2633 if (conf->type == 255)
2634 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2636 conf->pdef = protodefs[conf->type];
2638 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2639 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2640 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2642 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2643 if (conf->matchcertattr && !addmatchcertattr(conf))
2644 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2648 if (dupinterval != LONG_MIN) {
2649 if (dupinterval < 0 || dupinterval > 255)
2650 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2651 conf->dupinterval = (uint8_t)dupinterval;
2653 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2655 if (addttl != LONG_MIN) {
2656 if (addttl < 1 || addttl > 255)
2657 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2658 conf->addttl = (uint8_t)addttl;
2661 if (!conf->confrewritein)
2662 conf->confrewritein = rewriteinalias;
2664 free(rewriteinalias);
2665 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2666 if (conf->confrewriteout)
2667 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2669 if (conf->confrewriteusername) {
2670 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2671 if (!conf->rewriteusername)
2672 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2675 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2676 !resolvehostports(conf->hostports, conf->pdef->socktype))
2677 debugx(1, DBG_ERR, "resolve failed, exiting");
2679 if (!conf->secret) {
2680 if (!conf->pdef->secretdefault)
2681 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2682 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2684 debugx(1, DBG_ERR, "malloc failed");
2687 conf->lock = malloc(sizeof(pthread_mutex_t));
2689 debugx(1, DBG_ERR, "malloc failed");
2691 pthread_mutex_init(conf->lock, NULL);
2692 if (!list_push(clconfs, conf))
2693 debugx(1, DBG_ERR, "malloc failed");
2697 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2698 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2699 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2700 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2701 if (!conf->tlsconf) {
2702 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2705 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2706 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2712 if (!conf->portsrc) {
2713 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2714 if (!conf->portsrc) {
2715 debug(DBG_ERR, "malloc failed");
2720 if (conf->retryinterval == 255)
2721 conf->retryinterval = conf->pdef->retryintervaldefault;
2722 if (conf->retrycount == 255)
2723 conf->retrycount = conf->pdef->retrycountdefault;
2725 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2726 if (conf->confrewriteout)
2727 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2729 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2730 debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2734 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2735 debug(DBG_ERR, "resolve failed, exiting");
2741 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2742 struct clsrvconf *conf, *resconf;
2743 char *conftype = NULL, *rewriteinalias = NULL;
2744 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2746 debug(DBG_DBG, "confserver_cb called for %s", block);
2748 conf = malloc(sizeof(struct clsrvconf));
2750 debug(DBG_ERR, "malloc failed");
2753 memset(conf, 0, sizeof(struct clsrvconf));
2754 resconf = (struct clsrvconf *)arg;
2756 conf->statusserver = resconf->statusserver;
2757 conf->certnamecheck = resconf->certnamecheck;
2759 conf->certnamecheck = 1;
2761 if (!getgenericconfig(cf, block,
2762 "type", CONF_STR, &conftype,
2763 "host", CONF_MSTR, &conf->hostsrc,
2764 "port", CONF_STR, &conf->portsrc,
2765 "secret", CONF_STR, &conf->secret,
2766 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2767 "tls", CONF_STR, &conf->tls,
2768 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2769 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2771 "addTTL", CONF_LINT, &addttl,
2772 "rewrite", CONF_STR, &rewriteinalias,
2773 "rewriteIn", CONF_STR, &conf->confrewritein,
2774 "rewriteOut", CONF_STR, &conf->confrewriteout,
2775 "StatusServer", CONF_BLN, &conf->statusserver,
2776 "RetryInterval", CONF_LINT, &retryinterval,
2777 "RetryCount", CONF_LINT, &retrycount,
2778 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2781 debug(DBG_ERR, "configuration error");
2785 conf->name = stringcopy(val, 0);
2786 if (conf->name && !conf->hostsrc) {
2787 conf->hostsrc = malloc(2 * sizeof(char *));
2788 if (conf->hostsrc) {
2789 conf->hostsrc[0] = stringcopy(val, 0);
2790 conf->hostsrc[1] = NULL;
2793 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2794 debug(DBG_ERR, "malloc failed");
2799 debug(DBG_ERR, "error in block %s, option type missing", block);
2802 conf->type = protoname2int(conftype);
2803 if (conf->type == 255) {
2804 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2810 conf->pdef = protodefs[conf->type];
2812 if (!conf->confrewritein)
2813 conf->confrewritein = rewriteinalias;
2815 free(rewriteinalias);
2816 rewriteinalias = NULL;
2818 if (retryinterval != LONG_MIN) {
2819 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2820 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2823 conf->retryinterval = (uint8_t)retryinterval;
2825 conf->retryinterval = 255;
2827 if (retrycount != LONG_MIN) {
2828 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2829 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2832 conf->retrycount = (uint8_t)retrycount;
2834 conf->retrycount = 255;
2836 if (addttl != LONG_MIN) {
2837 if (addttl < 1 || addttl > 255) {
2838 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2841 conf->addttl = (uint8_t)addttl;
2845 if (!mergesrvconf(resconf, conf))
2849 if (conf->dynamiclookupcommand) {
2850 free(conf->dynamiclookupcommand);
2851 conf->dynamiclookupcommand = NULL;
2855 if (resconf || !conf->dynamiclookupcommand) {
2856 if (!compileserverconfig(conf, block))
2860 if (!conf->secret) {
2861 if (!conf->pdef->secretdefault) {
2862 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2865 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2866 if (!conf->secret) {
2867 debug(DBG_ERR, "malloc failed");
2875 if (!list_push(srvconfs, conf)) {
2876 debug(DBG_ERR, "malloc failed");
2883 free(rewriteinalias);
2884 freeclsrvconf(conf);
2888 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2889 char **servers = NULL, **accservers = NULL, *msg = NULL;
2890 uint8_t accresp = 0;
2892 debug(DBG_DBG, "confrealm_cb called for %s", block);
2894 if (!getgenericconfig(cf, block,
2895 "server", CONF_MSTR, &servers,
2896 "accountingServer", CONF_MSTR, &accservers,
2897 "ReplyMessage", CONF_STR, &msg,
2898 "AccountingResponse", CONF_BLN, &accresp,
2901 debugx(1, DBG_ERR, "configuration error");
2903 addrealm(realms, val, servers, accservers, msg, accresp);
2907 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2908 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
2910 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2912 if (!getgenericconfig(cf, block,
2913 "removeAttribute", CONF_MSTR, &rmattrs,
2914 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2915 "addAttribute", CONF_MSTR, &addattrs,
2916 "modifyAttribute", CONF_MSTR, &modattrs,
2919 debugx(1, DBG_ERR, "configuration error");
2920 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
2924 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2925 struct commonprotoopts *protoopts;
2927 protoopts = malloc(sizeof(struct commonprotoopts));
2930 memset(protoopts, 0, sizeof(struct commonprotoopts));
2931 protoopts->listenargs = listenargs;
2932 protoopts->sourcearg = sourcearg;
2933 protodefs[type]->setprotoopts(protoopts);
2937 void getmainconfig(const char *configfile) {
2938 long int addttl = LONG_MIN, loglevel = LONG_MIN;
2939 struct gconffile *cfs;
2940 char **listenargs[RAD_PROTOCOUNT];
2941 char *sourcearg[RAD_PROTOCOUNT];
2944 cfs = openconfigfile(configfile);
2945 memset(&options, 0, sizeof(options));
2946 memset(&listenargs, 0, sizeof(listenargs));
2947 memset(&sourcearg, 0, sizeof(sourcearg));
2949 clconfs = list_create();
2951 debugx(1, DBG_ERR, "malloc failed");
2953 srvconfs = list_create();
2955 debugx(1, DBG_ERR, "malloc failed");
2957 realms = list_create();
2959 debugx(1, DBG_ERR, "malloc failed");
2961 rewriteconfs = hash_create();
2963 debugx(1, DBG_ERR, "malloc failed");
2965 if (!getgenericconfig(&cfs, NULL,
2967 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
2968 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
2971 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
2972 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
2975 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
2976 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
2979 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
2980 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
2982 "TTLAttribute", CONF_STR, &options.ttlattr,
2983 "addTTL", CONF_LINT, &addttl,
2984 "LogLevel", CONF_LINT, &loglevel,
2985 "LogDestination", CONF_STR, &options.logdestination,
2986 "LoopPrevention", CONF_BLN, &options.loopprevention,
2987 "Client", CONF_CBK, confclient_cb, NULL,
2988 "Server", CONF_CBK, confserver_cb, NULL,
2989 "Realm", CONF_CBK, confrealm_cb, NULL,
2990 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2991 "TLS", CONF_CBK, conftls_cb, NULL,
2993 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
2996 debugx(1, DBG_ERR, "configuration error");
2998 if (loglevel != LONG_MIN) {
2999 if (loglevel < 1 || loglevel > 4)
3000 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3001 options.loglevel = (uint8_t)loglevel;
3003 if (addttl != LONG_MIN) {
3004 if (addttl < 1 || addttl > 255)
3005 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3006 options.addttl = (uint8_t)addttl;
3008 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3009 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3011 for (i = 0; i < RAD_PROTOCOUNT; i++)
3012 if (listenargs[i] || sourcearg[i])
3013 setprotoopts(i, listenargs[i], sourcearg[i]);
3016 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3019 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3022 *configfile = optarg;
3025 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3026 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3027 *loglevel = *optarg - '0';
3036 debug(DBG_ERR, "radsecproxy revision $Rev$");
3037 debug(DBG_ERR, "This binary was built with support for the following transports:");
3039 debug(DBG_ERR, " UDP");
3042 debug(DBG_ERR, " TCP");
3045 debug(DBG_ERR, " TLS");
3048 debug(DBG_ERR, " DTLS");
3055 if (!(argc - optind))
3059 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3063 int daemon(int a, int b) {
3071 for (i = 0; i < 3; i++) {
3073 open("/dev/null", O_RDWR);
3079 void *sighandler(void *arg) {
3084 sigemptyset(&sigset);
3085 sigaddset(&sigset, SIGPIPE);
3086 sigwait(&sigset, &sig);
3087 /* only get SIGPIPE right now, so could simplify below code */
3090 /* completely ignoring this */
3093 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3096 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3101 int main(int argc, char **argv) {
3104 struct list_node *entry;
3105 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3106 char *configfile = NULL;
3107 struct clsrvconf *srvconf;
3110 debug_init("radsecproxy");
3111 debug_set_level(DEBUG_LEVEL);
3113 for (i = 0; i < RAD_PROTOCOUNT; i++)
3114 protodefs[i] = protoinits[i](i);
3116 /* needed even if no TLS/DTLS transport */
3119 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3121 debug_set_level(loglevel);
3122 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3124 options.loglevel = loglevel;
3125 else if (options.loglevel)
3126 debug_set_level(options.loglevel);
3128 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3129 free(options.logdestination);
3131 if (!list_first(clconfs))
3132 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3133 if (!list_first(realms))
3134 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3137 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3139 if (!foreground && (daemon(0, 0) < 0))
3140 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3142 debug_timestamp_on();
3143 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3145 sigemptyset(&sigset);
3146 /* exit on all but SIGPIPE, ignore more? */
3147 sigaddset(&sigset, SIGPIPE);
3148 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3149 pthread_create(&sigth, NULL, sighandler, NULL);
3151 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3152 srvconf = (struct clsrvconf *)entry->data;
3153 if (srvconf->dynamiclookupcommand)
3155 if (!addserver(srvconf))
3156 debugx(1, DBG_ERR, "failed to add server");
3157 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3158 (void *)(srvconf->servers)))
3159 debugx(1, DBG_ERR, "pthread_create failed");
3162 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3165 if (protodefs[i]->initextra)
3166 protodefs[i]->initextra();
3167 if (find_clconf_type(i, NULL))
3171 /* just hang around doing nothing, anything to do here? */