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>
58 #include <arpa/inet.h>
62 #include <openssl/ssl.h>
63 #include <openssl/rand.h>
64 #include <openssl/err.h>
65 #include <openssl/md5.h>
71 #include "radsecproxy.h"
77 static struct options options;
78 static struct list *clconfs, *srvconfs;
79 static struct list *realms;
80 static struct hash *rewriteconfs;
82 static pthread_mutex_t *ssl_locks = NULL;
83 static long *ssl_lock_count;
86 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
88 /* minimum required declarations to avoid reordering code */
89 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
90 int dynamicconfig(struct server *server);
91 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
92 void freerealm(struct realm *realm);
93 void freeclsrvconf(struct clsrvconf *conf);
94 void freerq(struct request *rq);
95 void freerqoutdata(struct rqout *rqout);
96 void rmclientrq(struct request *rq, uint8_t id);
98 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
100 uint8_t protoname2int(const char *name) {
103 for (i = 0; i < RAD_PROTOCOUNT; i++)
104 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
109 /* callbacks for making OpenSSL thread safe */
110 unsigned long ssl_thread_id() {
111 return (unsigned long)pthread_self();
114 void ssl_locking_callback(int mode, int type, const char *file, int line) {
115 if (mode & CRYPTO_LOCK) {
116 pthread_mutex_lock(&ssl_locks[type]);
117 ssl_lock_count[type]++;
119 pthread_mutex_unlock(&ssl_locks[type]);
122 /* returns 1 if the len first bits are equal, else 0 */
123 int prefixmatch(void *a1, void *a2, uint8_t len) {
124 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
125 uint8_t r, l = len / 8;
126 if (l && memcmp(a1, a2, l))
131 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
134 /* returns next config with matching address, or NULL */
135 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
136 struct list_node *entry;
137 struct clsrvconf *conf;
139 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
140 conf = (struct clsrvconf *)entry->data;
141 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
150 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
151 return find_conf(type, addr, clconfs, cur, 0);
154 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
155 return find_conf(type, addr, srvconfs, cur, 1);
158 /* returns next config of given type, or NULL */
159 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
160 struct list_node *entry;
161 struct clsrvconf *conf;
163 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
164 conf = (struct clsrvconf *)entry->data;
165 if (conf->type == type) {
174 struct gqueue *newqueue() {
177 q = malloc(sizeof(struct gqueue));
179 debugx(1, DBG_ERR, "malloc failed");
180 q->entries = list_create();
182 debugx(1, DBG_ERR, "malloc failed");
183 pthread_mutex_init(&q->mutex, NULL);
184 pthread_cond_init(&q->cond, NULL);
188 void removequeue(struct gqueue *q) {
189 struct list_node *entry;
193 pthread_mutex_lock(&q->mutex);
194 for (entry = list_first(q->entries); entry; entry = list_next(entry))
195 freerq((struct request *)entry);
196 list_destroy(q->entries);
197 pthread_cond_destroy(&q->cond);
198 pthread_mutex_unlock(&q->mutex);
199 pthread_mutex_destroy(&q->mutex);
203 void freebios(struct gqueue *q) {
206 pthread_mutex_lock(&q->mutex);
207 while ((bio = (BIO *)list_shift(q->entries)))
209 pthread_mutex_unlock(&q->mutex);
213 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
214 struct client *new = malloc(sizeof(struct client));
217 debug(DBG_ERR, "malloc failed");
222 pthread_mutex_lock(conf->lock);
223 if (!conf->clients) {
224 conf->clients = list_create();
225 if (!conf->clients) {
227 pthread_mutex_unlock(conf->lock);
228 debug(DBG_ERR, "malloc failed");
233 memset(new, 0, sizeof(struct client));
235 if (conf->pdef->addclient)
236 conf->pdef->addclient(new);
238 new->replyq = newqueue();
239 list_push(conf->clients, new);
241 pthread_mutex_unlock(conf->lock);
245 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
246 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
249 pthread_mutex_lock(&lock);
251 pthread_mutex_unlock(&lock);
254 void removeclientrqs(struct client *client) {
259 removeclientrqs_sendrq_freeserver_lock(1);
260 for (i = 0; i < MAX_REQUESTS; i++) {
265 rqout = rq->to->requests + rq->newid;
266 pthread_mutex_lock(rqout->lock);
267 if (rqout->rq == rq) /* still pointing to our request */
268 freerqoutdata(rqout);
269 pthread_mutex_unlock(rqout->lock);
273 removeclientrqs_sendrq_freeserver_lock(0);
276 void removelockedclient(struct client *client) {
277 struct clsrvconf *conf;
281 removeclientrqs(client);
282 removequeue(client->replyq);
283 list_removedata(conf->clients, client);
289 void removeclient(struct client *client) {
290 struct clsrvconf *conf;
296 pthread_mutex_lock(conf->lock);
297 removelockedclient(client);
298 pthread_mutex_unlock(conf->lock);
301 void freeserver(struct server *server, uint8_t destroymutex) {
302 struct rqout *rqout, *end;
307 removeclientrqs_sendrq_freeserver_lock(1);
308 if (server->requests) {
309 rqout = server->requests;
310 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
312 rqout->rq->to = NULL;
313 freerqoutdata(rqout);
314 pthread_mutex_destroy(rqout->lock);
317 free(server->requests);
320 freebios(server->rbios);
321 free(server->dynamiclookuparg);
323 SSL_free(server->ssl);
325 pthread_mutex_destroy(&server->lock);
326 pthread_cond_destroy(&server->newrq_cond);
327 pthread_mutex_destroy(&server->newrq_mutex);
329 removeclientrqs_sendrq_freeserver_lock(0);
333 int addserver(struct clsrvconf *conf) {
337 debug(DBG_ERR, "addserver: currently works with just one server per conf");
340 conf->servers = malloc(sizeof(struct server));
341 if (!conf->servers) {
342 debug(DBG_ERR, "malloc failed");
345 memset(conf->servers, 0, sizeof(struct server));
346 conf->servers->conf = conf;
349 if (conf->type == RAD_DTLS)
350 conf->servers->rbios = newqueue();
352 conf->pdef->setsrcres();
354 conf->servers->sock = -1;
355 if (conf->pdef->addserverextra)
356 conf->pdef->addserverextra(conf);
358 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
359 if (!conf->servers->requests) {
360 debug(DBG_ERR, "malloc failed");
363 for (i = 0; i < MAX_REQUESTS; i++) {
364 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
365 if (!conf->servers->requests[i].lock) {
366 debug(DBG_ERR, "malloc failed");
369 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
370 debug(DBG_ERR, "mutex init failed");
371 free(conf->servers->requests[i].lock);
372 conf->servers->requests[i].lock = NULL;
376 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
377 debug(DBG_ERR, "mutex init failed");
380 conf->servers->newrq = 0;
381 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
382 debug(DBG_ERR, "mutex init failed");
383 pthread_mutex_destroy(&conf->servers->lock);
386 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
387 debug(DBG_ERR, "mutex init failed");
388 pthread_mutex_destroy(&conf->servers->newrq_mutex);
389 pthread_mutex_destroy(&conf->servers->lock);
396 freeserver(conf->servers, 0);
397 conf->servers = NULL;
401 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
403 if (ATTRTYPE(attrs) == type)
405 length -= ATTRLEN(attrs);
406 attrs += ATTRLEN(attrs);
411 struct request *newrqref(struct request *rq) {
417 void freerq(struct request *rq) {
420 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
423 if (rq->origusername)
424 free(rq->origusername);
430 radmsg_free(rq->msg);
434 void freerqoutdata(struct rqout *rqout) {
438 if (rqout->rq->buf) {
439 free(rqout->rq->buf);
440 rqout->rq->buf = NULL;
446 memset(&rqout->expiry, 0, sizeof(struct timeval));
449 void sendrq(struct request *rq) {
453 removeclientrqs_sendrq_freeserver_lock(1);
458 start = to->conf->statusserver ? 1 : 0;
459 pthread_mutex_lock(&to->newrq_mutex);
460 if (start && rq->msg->code == RAD_Status_Server) {
461 pthread_mutex_lock(to->requests[0].lock);
462 if (to->requests[0].rq) {
463 pthread_mutex_unlock(to->requests[0].lock);
464 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
471 /* might simplify if only try nextid, might be ok */
472 for (i = to->nextid; i < MAX_REQUESTS; i++) {
473 if (!to->requests[i].rq) {
474 pthread_mutex_lock(to->requests[i].lock);
475 if (!to->requests[i].rq)
477 pthread_mutex_unlock(to->requests[i].lock);
480 if (i == MAX_REQUESTS) {
481 for (i = start; i < to->nextid; i++) {
482 if (!to->requests[i].rq) {
483 pthread_mutex_lock(to->requests[i].lock);
484 if (!to->requests[i].rq)
486 pthread_mutex_unlock(to->requests[i].lock);
489 if (i == to->nextid) {
490 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
495 rq->newid = (uint8_t)i;
496 rq->msg->id = (uint8_t)i;
497 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
499 pthread_mutex_unlock(to->requests[i].lock);
500 debug(DBG_ERR, "sendrq: radmsg2buf failed");
504 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
505 to->requests[i].rq = rq;
506 pthread_mutex_unlock(to->requests[i].lock);
507 if (i >= start) /* i is not reserved for statusserver */
512 debug(DBG_DBG, "sendrq: signalling client writer");
513 pthread_cond_signal(&to->newrq_cond);
516 pthread_mutex_unlock(&to->newrq_mutex);
517 removeclientrqs_sendrq_freeserver_lock(0);
522 rmclientrq(rq, rq->msg->id);
524 pthread_mutex_unlock(&to->newrq_mutex);
525 removeclientrqs_sendrq_freeserver_lock(0);
528 void sendreply(struct request *rq) {
530 struct client *to = rq->from;
533 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
534 radmsg_free(rq->msg);
538 debug(DBG_ERR, "sendreply: radmsg2buf failed");
542 pthread_mutex_lock(&to->replyq->mutex);
543 first = list_first(to->replyq->entries) == NULL;
545 if (!list_push(to->replyq->entries, rq)) {
546 pthread_mutex_unlock(&to->replyq->mutex);
548 debug(DBG_ERR, "sendreply: malloc failed");
553 debug(DBG_DBG, "signalling server writer");
554 pthread_cond_signal(&to->replyq->cond);
556 pthread_mutex_unlock(&to->replyq->mutex);
559 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
560 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
561 static unsigned char first = 1;
562 static EVP_MD_CTX mdctx;
563 unsigned char hash[EVP_MAX_MD_SIZE], *input;
565 uint8_t i, offset = 0, out[128];
567 pthread_mutex_lock(&lock);
569 EVP_MD_CTX_init(&mdctx);
575 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
576 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
577 !EVP_DigestUpdate(&mdctx, input, 16) ||
578 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
580 pthread_mutex_unlock(&lock);
583 for (i = 0; i < 16; i++)
584 out[offset + i] = hash[i] ^ in[offset + i];
585 input = out + offset - 16;
590 memcpy(in, out, len);
591 pthread_mutex_unlock(&lock);
595 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
596 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
597 static unsigned char first = 1;
598 static EVP_MD_CTX mdctx;
599 unsigned char hash[EVP_MAX_MD_SIZE], *input;
601 uint8_t i, offset = 0, out[128];
603 pthread_mutex_lock(&lock);
605 EVP_MD_CTX_init(&mdctx);
611 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
612 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
613 !EVP_DigestUpdate(&mdctx, input, 16) ||
614 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
616 pthread_mutex_unlock(&lock);
619 for (i = 0; i < 16; i++)
620 out[offset + i] = hash[i] ^ in[offset + i];
626 memcpy(in, out, len);
627 pthread_mutex_unlock(&lock);
631 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
632 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
633 static unsigned char first = 1;
634 static EVP_MD_CTX mdctx;
635 unsigned char hash[EVP_MAX_MD_SIZE];
639 pthread_mutex_lock(&lock);
641 EVP_MD_CTX_init(&mdctx);
646 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
647 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
648 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
651 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
652 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
653 !EVP_DigestUpdate(&mdctx, auth, 16) ||
654 !EVP_DigestUpdate(&mdctx, salt, 2) ||
655 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
656 pthread_mutex_unlock(&lock);
661 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
664 for (i = 0; i < 16; i++)
667 for (offset = 16; offset < len; offset += 16) {
669 printf("text + offset - 16 c(%d): ", offset / 16);
670 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
672 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
673 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
674 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
675 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
677 pthread_mutex_unlock(&lock);
681 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
684 for (i = 0; i < 16; i++)
685 text[offset + i] ^= hash[i];
689 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
692 pthread_mutex_unlock(&lock);
696 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
697 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
698 static unsigned char first = 1;
699 static EVP_MD_CTX mdctx;
700 unsigned char hash[EVP_MAX_MD_SIZE];
705 pthread_mutex_lock(&lock);
707 EVP_MD_CTX_init(&mdctx);
712 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
713 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
714 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
717 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
718 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
719 !EVP_DigestUpdate(&mdctx, auth, 16) ||
720 !EVP_DigestUpdate(&mdctx, salt, 2) ||
721 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
722 pthread_mutex_unlock(&lock);
727 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
730 for (i = 0; i < 16; i++)
731 plain[i] = text[i] ^ hash[i];
733 for (offset = 16; offset < len; offset += 16) {
735 printf("text + offset - 16 c(%d): ", offset / 16);
736 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
738 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
739 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
740 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
741 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
743 pthread_mutex_unlock(&lock);
747 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
750 for (i = 0; i < 16; i++)
751 plain[offset + i] = text[offset + i] ^ hash[i];
754 memcpy(text, plain, len);
756 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
759 pthread_mutex_unlock(&lock);
763 struct realm *newrealmref(struct realm *r) {
769 /* returns with lock on realm */
770 struct realm *id2realm(struct list *realmlist, char *id) {
771 struct list_node *entry;
772 struct realm *realm, *subrealm;
774 /* need to do locking for subrealms and check subrealm timers */
775 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
776 realm = (struct realm *)entry->data;
777 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
778 pthread_mutex_lock(&realm->mutex);
779 if (realm->subrealms) {
780 subrealm = id2realm(realm->subrealms, id);
782 pthread_mutex_unlock(&realm->mutex);
786 return newrealmref(realm);
792 int hasdynamicserver(struct list *srvconfs) {
793 struct list_node *entry;
795 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
796 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
801 /* helper function, only used by removeserversubrealms() */
802 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
803 struct list_node *entry, *entry2;
806 for (entry = list_first(realmlist); entry;) {
807 realm = newrealmref((struct realm *)entry->data);
808 pthread_mutex_lock(&realm->mutex);
809 entry = list_next(entry);
811 if (realm->srvconfs) {
812 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
813 if (entry2->data == srv)
815 list_removedata(realm->srvconfs, srv);
817 if (realm->accsrvconfs) {
818 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
819 if (entry2->data == srv)
821 list_removedata(realm->accsrvconfs, srv);
824 /* remove subrealm if no dynamic servers left */
825 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
826 while (list_shift(realm->srvconfs))
828 list_destroy(realm->srvconfs);
829 realm->srvconfs = NULL;
830 while (list_shift(realm->accsrvconfs))
832 list_destroy(realm->accsrvconfs);
833 realm->accsrvconfs = NULL;
834 list_removedata(realmlist, realm);
836 pthread_mutex_unlock(&realm->mutex);
841 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
842 struct list_node *entry;
845 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
846 realm = (struct realm *)entry->data;
847 pthread_mutex_lock(&realm->mutex);
848 if (realm->subrealms) {
849 _internal_removeserversubrealms(realm->subrealms, srv);
850 if (!list_first(realm->subrealms)) {
851 list_destroy(realm->subrealms);
852 realm->subrealms = NULL;
855 pthread_mutex_unlock(&realm->mutex);
859 int attrvalidate(unsigned char *attrs, int length) {
861 if (ATTRLEN(attrs) < 2) {
862 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
865 length -= ATTRLEN(attrs);
867 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
870 attrs += ATTRLEN(attrs);
873 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
877 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
878 if (len < 16 || len > 128 || len % 16) {
879 debug(DBG_WARN, "pwdrecrypt: invalid password length");
883 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
884 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
888 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
890 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
891 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
897 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
900 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
901 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
904 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
905 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
911 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
912 char *oldsecret, char *newsecret) {
915 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
916 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
917 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
923 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
927 for (; attrs[0]; attrs += 2)
928 if (attrs[0] == vendor && attrs[1] == subattr)
933 /* returns 1 if entire element is to be removed, else 0 */
934 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
935 uint8_t alen, sublen;
939 if (!removevendorattrs)
942 memcpy(&vendor, attr->v, 4);
943 vendor = ntohl(vendor);
944 while (*removevendorattrs && *removevendorattrs != vendor)
945 removevendorattrs += 2;
946 if (!*removevendorattrs)
949 if (findvendorsubattr(removevendorattrs, vendor, 256))
950 return 1; /* remove entire vendor attribute */
952 sublen = attr->l - 4;
953 subattrs = attr->v + 4;
955 if (!attrvalidate(subattrs, sublen)) {
956 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
961 alen = ATTRLEN(subattrs);
963 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
964 memmove(subattrs, subattrs + alen, sublen);
972 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
973 struct list_node *n, *p;
977 n = list_first(msg->attrs);
979 attr = (struct tlv *)n->data;
980 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
981 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
982 list_removedata(msg->attrs, attr);
984 n = p ? list_next(p) : list_first(msg->attrs);
991 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
995 for (n = list_first(addattrs); n; n = list_next(n)) {
996 a = copytlv((struct tlv *)n->data);
999 if (!radmsg_add(msg, a)) {
1007 int resizeattr(struct tlv *attr, uint8_t newlen) {
1010 if (newlen != attr->l) {
1011 newv = realloc(attr->v, newlen);
1020 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1021 size_t nmatch = 10, reslen = 0, start = 0;
1022 regmatch_t pmatch[10], *pfield;
1026 in = stringcopy((char *)attr->v, attr->l);
1030 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1035 out = modattr->replacement;
1037 for (i = start; out[i]; i++) {
1038 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1039 pfield = &pmatch[out[i + 1] - '0'];
1040 if (pfield->rm_so >= 0) {
1041 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1047 reslen += i - start;
1049 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1054 if (!resizeattr(attr, reslen)) {
1061 for (i = start; out[i]; i++) {
1062 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1063 pfield = &pmatch[out[i + 1] - '0'];
1064 if (pfield->rm_so >= 0) {
1065 memcpy(attr->v + reslen, out + start, i - start);
1066 reslen += i - start;
1067 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1068 reslen += pfield->rm_eo - pfield->rm_so;
1075 memcpy(attr->v + reslen, out + start, i - start);
1079 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1080 struct list_node *n, *m;
1082 for (n = list_first(msg->attrs); n; n = list_next(n))
1083 for (m = list_first(modattrs); m; m = list_next(m))
1084 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1085 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1090 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1093 if (rewrite->removeattrs || rewrite->removevendorattrs)
1094 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1095 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1097 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1102 int rewriteusername(struct request *rq, struct tlv *attr) {
1103 char *orig = (char *)tlv2str(attr);
1104 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1108 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1109 rq->origusername = (char *)orig;
1115 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1122 vendor = htonl(vendor);
1123 memcpy(v, &vendor, 4);
1124 tlv2buf(v + 4, attr);
1126 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1127 if (vattr && radmsg_add(msg, vattr))
1134 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1141 if (attrtype[1] == 256) { /* not vendor */
1142 attr = maketlv(attrtype[0], 4, ttl);
1143 if (attr && !radmsg_add(msg, attr))
1146 attr = maketlv(attrtype[1], 4, ttl);
1148 addvendorattr(msg, attrtype[0], attr);
1154 int decttl(uint8_t l, uint8_t *v) {
1161 while (i >= 0 && !v[i])
1165 for (i--; i >= 0 && !v[i]; i--);
1174 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1175 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1176 uint8_t alen, *subattrs;
1178 struct list_node *node;
1182 if (attrtype[1] == 256) { /* not vendor */
1183 attr = radmsg_gettype(msg, attrtype[0]);
1185 return decttl(attr->l, attr->v);
1187 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1188 attr = (struct tlv *)node->data;
1189 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1191 memcpy(&vendor, attr->v, 4);
1192 if (ntohl(vendor) != attrtype[0])
1194 sublen = attr->l - 4;
1195 subattrs = attr->v + 4;
1196 if (!attrvalidate(subattrs, sublen))
1198 while (sublen > 1) {
1199 if (ATTRTYPE(subattrs) == attrtype[1])
1200 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1201 alen = ATTRLEN(subattrs);
1209 const char *radmsgtype2string(uint8_t code) {
1210 static const char *rad_msg_names[] = {
1211 "", "Access-Request", "Access-Accept", "Access-Reject",
1212 "Accounting-Request", "Accounting-Response", "", "",
1213 "", "", "", "Access-Challenge",
1214 "Status-Server", "Status-Client"
1216 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1219 void char2hex(char *h, unsigned char c) {
1220 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1221 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1222 h[0] = hexdigits[c / 16];
1223 h[1] = hexdigits[c % 16];
1227 uint8_t *radattr2ascii(struct tlv *attr) {
1235 for (i = 0; i < attr->l; i++)
1236 if (attr->v[i] < 32 || attr->v[i] > 126)
1239 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1246 for (i = 0; i < attr->l; i++)
1247 if (attr->v[i] < 32 || attr->v[i] > 126) {
1249 char2hex((char *)d, attr->v[i]);
1257 void acclog(struct radmsg *msg, struct client *from) {
1261 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1263 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1266 username = radattr2ascii(attr);
1268 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1274 void respond(struct request *rq, uint8_t code, char *message) {
1278 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1280 debug(DBG_ERR, "respond: malloc failed");
1283 if (message && *message) {
1284 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1285 if (!attr || !radmsg_add(msg, attr)) {
1288 debug(DBG_ERR, "respond: malloc failed");
1293 radmsg_free(rq->msg);
1295 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1296 sendreply(newrqref(rq));
1299 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1300 struct list_node *entry;
1301 struct clsrvconf *server, *best = NULL, *first = NULL;
1303 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1304 server = (struct clsrvconf *)entry->data;
1305 if (!server->servers)
1309 if (!server->servers->connectionok && !server->servers->dynstartup)
1311 if (!server->servers->lostrqs)
1317 if (server->servers->lostrqs < best->servers->lostrqs)
1320 return best ? best : first;
1323 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1324 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1325 struct clsrvconf *srvconf;
1326 struct realm *subrealm;
1327 struct server *server = NULL;
1328 char *id = (char *)tlv2str(username);
1332 /* returns with lock on realm */
1333 *realm = id2realm(realms, id);
1336 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1337 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1338 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1339 subrealm = adddynamicrealmserver(*realm, id);
1341 pthread_mutex_lock(&subrealm->mutex);
1342 pthread_mutex_unlock(&(*realm)->mutex);
1345 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1349 server = srvconf->servers;
1357 struct request *newrequest() {
1360 rq = malloc(sizeof(struct request));
1362 debug(DBG_ERR, "newrequest: malloc failed");
1365 memset(rq, 0, sizeof(struct request));
1367 gettimeofday(&rq->created, NULL);
1371 int addclientrq(struct request *rq) {
1375 r = rq->from->rqs[rq->rqid];
1377 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1378 gettimeofday(&now, NULL);
1379 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1381 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1382 sendreply(newrqref(r));
1384 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1390 rq->from->rqs[rq->rqid] = newrqref(rq);
1394 void rmclientrq(struct request *rq, uint8_t id) {
1397 r = rq->from->rqs[id];
1400 rq->from->rqs[id] = NULL;
1404 /* returns 0 if validation/authentication fails, else 1 */
1405 int radsrv(struct request *rq) {
1406 struct radmsg *msg = NULL;
1408 uint8_t *userascii = NULL;
1409 struct realm *realm = NULL;
1410 struct server *to = NULL;
1411 struct client *from = rq->from;
1414 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1419 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1426 memcpy(rq->rqauth, msg->auth, 16);
1428 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1429 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1430 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1434 if (!addclientrq(rq))
1437 if (msg->code == RAD_Status_Server) {
1438 respond(rq, RAD_Access_Accept, NULL);
1442 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1444 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1447 ttlres = checkttl(msg, options.ttlattrtype);
1449 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1453 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1455 if (msg->code == RAD_Accounting_Request) {
1457 respond(rq, RAD_Accounting_Response, NULL);
1459 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1463 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1464 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1468 userascii = radattr2ascii(attr);
1471 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1473 /* will return with lock on the realm */
1474 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1476 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1481 if (realm->message && msg->code == RAD_Access_Request) {
1482 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1483 respond(rq, RAD_Access_Reject, realm->message);
1484 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1486 respond(rq, RAD_Accounting_Response, NULL);
1491 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1492 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1493 from->conf->name, addr2string(from->addr), to->conf->name);
1497 if (msg->code == RAD_Accounting_Request)
1498 memset(msg->auth, 0, 16);
1499 else if (!RAND_bytes(msg->auth, 16)) {
1500 debug(DBG_WARN, "radsrv: failed to generate random auth");
1505 printfchars(NULL, "auth", "%02x ", auth, 16);
1508 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1510 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1511 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1515 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1517 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1518 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1522 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1525 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1526 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1531 pthread_mutex_unlock(&realm->mutex);
1536 rmclientrq(rq, msg->id);
1541 pthread_mutex_unlock(&realm->mutex);
1547 void replyh(struct server *server, unsigned char *buf) {
1548 struct client *from;
1549 struct rqout *rqout;
1551 unsigned char *subattrs;
1552 uint8_t *username, *stationid, *replymsg;
1553 struct radmsg *msg = NULL;
1555 struct list_node *node;
1557 server->connectionok = 1;
1558 server->lostrqs = 0;
1560 rqout = server->requests + buf[1];
1561 pthread_mutex_lock(rqout->lock);
1562 if (!rqout->tries) {
1565 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1569 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1573 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1576 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1577 && msg->code != RAD_Accounting_Response) {
1578 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1581 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1583 gettimeofday(&server->lastrcv, NULL);
1585 if (rqout->rq->msg->code == RAD_Status_Server) {
1586 freerqoutdata(rqout);
1587 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1591 gettimeofday(&server->lastreply, NULL);
1592 from = rqout->rq->from;
1594 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1595 debug(DBG_INFO, "replyh: rewritein failed");
1599 ttlres = checkttl(msg, options.ttlattrtype);
1601 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1606 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1607 attr = (struct tlv *)node->data;
1608 if (attr->t != RAD_Attr_Vendor_Specific)
1612 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1615 sublen = attr->l - 4;
1616 subattrs = attr->v + 4;
1617 if (!attrvalidate(subattrs, sublen) ||
1618 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1619 rqout->rq, server->conf->secret, from->conf->secret) ||
1620 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1621 rqout->rq, server->conf->secret, from->conf->secret))
1625 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1629 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1630 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1632 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1633 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1636 debug(DBG_WARN, "%s for user %s stationid %s from %s (%s) to %s (%s)",
1637 radmsgtype2string(msg->code), username, stationid, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1640 debug(DBG_WARN, "%s for user %s stationid %s from %s to %s (%s)",
1641 radmsgtype2string(msg->code), username, stationid, server->conf->name, from->conf->name, addr2string(from->addr));
1645 debug(DBG_WARN, "%s for user %s from %s (%s) to %s (%s)",
1646 radmsgtype2string(msg->code), username, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1649 debug(DBG_WARN, "%s for user %s from %s to %s (%s)",
1650 radmsgtype2string(msg->code), username, server->conf->name, from->conf->name, addr2string(from->addr));
1656 msg->id = (char)rqout->rq->rqid;
1657 memcpy(msg->auth, rqout->rq->rqauth, 16);
1660 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1663 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1664 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1665 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1668 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1671 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1672 debug(DBG_WARN, "replyh: rewriteout failed");
1676 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1677 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1679 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1680 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1682 radmsg_free(rqout->rq->msg);
1683 rqout->rq->msg = msg;
1684 sendreply(newrqref(rqout->rq));
1685 freerqoutdata(rqout);
1686 pthread_mutex_unlock(rqout->lock);
1691 pthread_mutex_unlock(rqout->lock);
1695 struct request *createstatsrvrq() {
1702 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1705 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1708 if (!radmsg_add(rq->msg, attr)) {
1719 /* code for removing state not finished */
1720 void *clientwr(void *arg) {
1721 struct server *server = (struct server *)arg;
1722 struct rqout *rqout = NULL;
1723 pthread_t clientrdth;
1724 int i, dynconffail = 0;
1727 struct timeval now, laststatsrv;
1728 struct timespec timeout;
1729 struct request *statsrvrq;
1730 struct clsrvconf *conf;
1732 conf = server->conf;
1734 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1736 server->dynstartup = 0;
1741 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1742 debug(DBG_WARN, "clientwr: resolve failed");
1743 server->dynstartup = 0;
1748 memset(&timeout, 0, sizeof(struct timespec));
1750 if (conf->statusserver) {
1751 gettimeofday(&server->lastrcv, NULL);
1752 gettimeofday(&laststatsrv, NULL);
1755 if (conf->pdef->connecter) {
1756 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1757 if (server->dynamiclookuparg) {
1758 server->dynstartup = 0;
1763 server->connectionok = 1;
1764 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1765 debug(DBG_ERR, "clientwr: pthread_create failed");
1769 server->connectionok = 1;
1770 server->dynstartup = 0;
1773 pthread_mutex_lock(&server->newrq_mutex);
1774 if (!server->newrq) {
1775 gettimeofday(&now, NULL);
1776 /* random 0-7 seconds */
1777 RAND_bytes(&rnd, 1);
1779 if (conf->statusserver) {
1780 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1781 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1783 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1784 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1786 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1787 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1790 if (timeout.tv_sec > now.tv_sec)
1791 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1793 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1796 if (server->newrq) {
1797 debug(DBG_DBG, "clientwr: got new request");
1802 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1804 pthread_mutex_unlock(&server->newrq_mutex);
1806 for (i = 0; i < MAX_REQUESTS; i++) {
1807 if (server->clientrdgone) {
1808 pthread_join(clientrdth, NULL);
1812 for (; i < MAX_REQUESTS; i++) {
1813 rqout = server->requests + i;
1815 pthread_mutex_lock(rqout->lock);
1818 pthread_mutex_unlock(rqout->lock);
1822 if (i == MAX_REQUESTS)
1825 gettimeofday(&now, NULL);
1826 if (now.tv_sec < rqout->expiry.tv_sec) {
1827 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1828 timeout.tv_sec = rqout->expiry.tv_sec;
1829 pthread_mutex_unlock(rqout->lock);
1833 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1834 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1835 if (conf->statusserver) {
1836 if (*rqout->rq->buf == RAD_Status_Server) {
1837 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1838 if (server->lostrqs < 255)
1842 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1843 if (server->lostrqs < 255)
1846 freerqoutdata(rqout);
1847 pthread_mutex_unlock(rqout->lock);
1851 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1852 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1853 timeout.tv_sec = rqout->expiry.tv_sec;
1855 conf->pdef->clientradput(server, rqout->rq->buf);
1856 pthread_mutex_unlock(rqout->lock);
1858 if (conf->statusserver && server->connectionok) {
1859 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1860 gettimeofday(&now, NULL);
1861 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1863 statsrvrq = createstatsrvrq();
1865 statsrvrq->to = server;
1866 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1873 conf->servers = NULL;
1874 if (server->dynamiclookuparg) {
1875 removeserversubrealms(realms, conf);
1879 freeclsrvconf(conf);
1881 freeserver(server, 1);
1882 ERR_remove_state(0);
1886 void createlistener(uint8_t type, char *arg) {
1888 struct addrinfo *res;
1889 int s = -1, on = 1, *sp = NULL;
1890 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1892 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1893 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1895 for (res = hp->addrinfo; res; res = res->ai_next) {
1896 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1898 debug(DBG_WARN, "createlistener: socket failed");
1901 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1903 if (res->ai_family == AF_INET6)
1904 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1906 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1907 debug(DBG_WARN, "createlistener: bind failed");
1913 sp = malloc(sizeof(int));
1915 debugx(1, DBG_ERR, "malloc failed");
1917 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1918 debugx(1, DBG_ERR, "pthread_create failed");
1922 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1924 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1928 void createlisteners(uint8_t type) {
1932 args = protodefs[type]->getlistenerargs();
1934 for (i = 0; args[i]; i++)
1935 createlistener(type, args[i]);
1937 createlistener(type, NULL);
1945 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1946 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1947 for (i = 0; i < CRYPTO_num_locks(); i++) {
1948 ssl_lock_count[i] = 0;
1949 pthread_mutex_init(&ssl_locks[i], NULL);
1951 CRYPTO_set_id_callback(ssl_thread_id);
1952 CRYPTO_set_locking_callback(ssl_locking_callback);
1954 SSL_load_error_strings();
1957 while (!RAND_status()) {
1960 RAND_seed((unsigned char *)&t, sizeof(time_t));
1961 RAND_seed((unsigned char *)&pid, sizeof(pid));
1965 struct list *addsrvconfs(char *value, char **names) {
1966 struct list *conflist;
1968 struct list_node *entry;
1969 struct clsrvconf *conf = NULL;
1971 if (!names || !*names)
1974 conflist = list_create();
1976 debug(DBG_ERR, "malloc failed");
1980 for (n = 0; names[n]; n++) {
1981 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1982 conf = (struct clsrvconf *)entry->data;
1983 if (!strcasecmp(names[n], conf->name))
1987 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
1988 list_destroy(conflist);
1991 if (!list_push(conflist, conf)) {
1992 debug(DBG_ERR, "malloc failed");
1993 list_destroy(conflist);
1996 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2001 void freerealm(struct realm *realm) {
2004 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2005 if (--realm->refcount)
2009 free(realm->message);
2010 regfree(&realm->regex);
2011 pthread_mutex_destroy(&realm->mutex);
2012 /* if refcount == 0, all subrealms gone */
2013 list_destroy(realm->subrealms);
2014 /* if refcount == 0, all srvconfs gone */
2015 list_destroy(realm->srvconfs);
2016 /* if refcount == 0, all accsrvconfs gone */
2017 list_destroy(realm->accsrvconfs);
2018 freerealm(realm->parent);
2022 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2024 struct realm *realm;
2025 char *s, *regex = NULL;
2027 if (*value == '/') {
2028 /* regexp, remove optional trailing / if present */
2029 if (value[strlen(value) - 1] == '/')
2030 value[strlen(value) - 1] = '\0';
2032 /* not a regexp, let us make it one */
2033 if (*value == '*' && !value[1])
2034 regex = stringcopy(".*", 0);
2036 for (n = 0, s = value; *s;)
2039 regex = malloc(strlen(value) + n + 3);
2042 for (n = 1, s = value; *s; s++) {
2052 debug(DBG_ERR, "malloc failed");
2056 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2059 realm = malloc(sizeof(struct realm));
2061 debug(DBG_ERR, "malloc failed");
2064 memset(realm, 0, sizeof(struct realm));
2066 if (pthread_mutex_init(&realm->mutex, NULL)) {
2067 debug(DBG_ERR, "mutex init failed");
2073 realm->name = stringcopy(value, 0);
2075 debug(DBG_ERR, "malloc failed");
2078 if (message && strlen(message) > 253) {
2079 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2082 realm->message = message;
2083 realm->accresp = accresp;
2085 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2086 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2090 if (servers && *servers) {
2091 realm->srvconfs = addsrvconfs(value, servers);
2092 if (!realm->srvconfs)
2096 if (accservers && *accservers) {
2097 realm->accsrvconfs = addsrvconfs(value, accservers);
2098 if (!realm->accsrvconfs)
2102 if (!list_push(realmlist, realm)) {
2103 debug(DBG_ERR, "malloc failed");
2104 pthread_mutex_destroy(&realm->mutex);
2108 debug(DBG_DBG, "addrealm: added realm %s", value);
2112 while (list_shift(realm->srvconfs));
2113 while (list_shift(realm->accsrvconfs));
2120 for (n = 0; servers[n]; n++)
2122 freegconfmstr(servers);
2126 for (n = 0; accservers[n]; n++)
2128 freegconfmstr(accservers);
2130 return newrealmref(realm);
2133 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2134 struct list_node *entry;
2135 struct clsrvconf *conf, *srvconf;
2136 struct list *subrealmservers = NULL;
2139 if (list_first(srvconfs)) {
2140 subrealmservers = list_create();
2141 if (!subrealmservers)
2145 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2146 conf = (struct clsrvconf *)entry->data;
2147 if (!conf->servers && conf->dynamiclookupcommand) {
2148 srvconf = malloc(sizeof(struct clsrvconf));
2150 debug(DBG_ERR, "malloc failed");
2154 if (addserver(srvconf)) {
2155 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2156 srvconf->servers->dynstartup = 1;
2157 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2158 debug(DBG_ERR, "pthread_create failed");
2159 freeserver(srvconf->servers, 1);
2160 srvconf->servers = NULL;
2162 pthread_detach(clientth);
2166 if (conf->servers) {
2167 if (list_push(subrealmservers, conf))
2170 debug(DBG_ERR, "malloc failed");
2173 return subrealmservers;
2176 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2177 struct realm *newrealm = NULL;
2178 char *realmname, *s;
2180 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2181 realmname = strrchr(id, '@');
2187 for (s = realmname; *s; s++)
2188 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2191 if (!realm->subrealms)
2192 realm->subrealms = list_create();
2193 if (!realm->subrealms)
2196 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2198 list_destroy(realm->subrealms);
2199 realm->subrealms = NULL;
2203 newrealm->parent = newrealmref(realm);
2204 /* add server and accserver to newrealm */
2205 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2206 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2210 int dynamicconfig(struct server *server) {
2211 int ok, fd[2], status;
2213 struct clsrvconf *conf = server->conf;
2214 struct gconffile *cf = NULL;
2216 /* for now we only learn hostname/address */
2217 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2220 debug(DBG_ERR, "dynamicconfig: pipe error");
2225 debug(DBG_ERR, "dynamicconfig: fork error");
2229 } else if (pid == 0) {
2232 if (fd[1] != STDOUT_FILENO) {
2233 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2234 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2237 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2238 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2242 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2243 ok = getgenericconfig(&cf, NULL,
2244 "Server", CONF_CBK, confserver_cb, (void *)conf,
2249 if (waitpid(pid, &status, 0) < 0) {
2250 debug(DBG_ERR, "dynamicconfig: wait error");
2255 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2263 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2267 /* should accept both names and numeric values, only numeric right now */
2268 uint8_t attrname2val(char *attrname) {
2271 val = atoi(attrname);
2272 return val > 0 && val < 256 ? val : 0;
2275 /* should accept both names and numeric values, only numeric right now */
2276 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2279 *vendor = atoi(attrname);
2280 s = strchr(attrname, ':');
2285 *type = atoi(s + 1);
2289 /* should accept both names and numeric values, only numeric right now */
2290 struct tlv *extractattr(char *nameval) {
2295 s = strchr(nameval, ':');
2296 name = atoi(nameval);
2297 if (!s || name < 1 || name > 255)
2299 len = strlen(s + 1);
2302 a = malloc(sizeof(struct tlv));
2305 a->v = (uint8_t *)stringcopy(s + 1, 0);
2315 /* should accept both names and numeric values, only numeric right now */
2316 struct modattr *extractmodattr(char *nameval) {
2321 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2325 s = strchr(nameval, ':');
2326 name = atoi(nameval);
2327 if (!s || name < 1 || name > 255 || s[1] != '/')
2331 /* regexp, remove optional trailing / if present */
2332 if (s[strlen(s) - 1] == '/')
2333 s[strlen(s) - 1] = '\0';
2341 m = malloc(sizeof(struct modattr));
2343 debug(DBG_ERR, "malloc failed");
2348 m->replacement = stringcopy(t, 0);
2349 if (!m->replacement) {
2351 debug(DBG_ERR, "malloc failed");
2355 m->regex = malloc(sizeof(regex_t));
2357 free(m->replacement);
2359 debug(DBG_ERR, "malloc failed");
2363 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2365 free(m->replacement);
2367 debug(DBG_ERR, "failed to compile regular expression %s", s);
2374 struct rewrite *getrewrite(char *alt1, char *alt2) {
2377 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2379 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2384 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2385 struct rewrite *rewrite = NULL;
2387 uint8_t *rma = NULL;
2388 uint32_t *p, *rmva = NULL;
2389 struct list *adda = NULL, *moda = NULL;
2394 for (n = 0; rmattrs[n]; n++);
2395 rma = calloc(n + 1, sizeof(uint8_t));
2397 debugx(1, DBG_ERR, "malloc failed");
2399 for (i = 0; i < n; i++)
2400 if (!(rma[i] = attrname2val(rmattrs[i])))
2401 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2402 freegconfmstr(rmattrs);
2407 for (n = 0; rmvattrs[n]; n++);
2408 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2410 debugx(1, DBG_ERR, "malloc failed");
2412 for (p = rmva, i = 0; i < n; i++, p += 2)
2413 if (!vattrname2val(rmvattrs[i], p, p + 1))
2414 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2415 freegconfmstr(rmvattrs);
2420 adda = list_create();
2422 debugx(1, DBG_ERR, "malloc failed");
2423 for (i = 0; addattrs[i]; i++) {
2424 a = extractattr(addattrs[i]);
2426 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2427 if (!list_push(adda, a))
2428 debugx(1, DBG_ERR, "malloc failed");
2430 freegconfmstr(addattrs);
2434 moda = list_create();
2436 debugx(1, DBG_ERR, "malloc failed");
2437 for (i = 0; modattrs[i]; i++) {
2438 m = extractmodattr(modattrs[i]);
2440 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2441 if (!list_push(moda, m))
2442 debugx(1, DBG_ERR, "malloc failed");
2444 freegconfmstr(modattrs);
2447 if (rma || rmva || adda || moda) {
2448 rewrite = malloc(sizeof(struct rewrite));
2450 debugx(1, DBG_ERR, "malloc failed");
2451 rewrite->removeattrs = rma;
2452 rewrite->removevendorattrs = rmva;
2453 rewrite->addattrs = adda;
2454 rewrite->modattrs = moda;
2457 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2458 debugx(1, DBG_ERR, "malloc failed");
2459 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2462 int setttlattr(struct options *opts, char *defaultattr) {
2463 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2465 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2466 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2468 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2472 void freeclsrvconf(struct clsrvconf *conf) {
2475 freegconfmstr(conf->hostsrc);
2476 free(conf->portsrc);
2479 free(conf->matchcertattr);
2480 if (conf->certcnregex)
2481 regfree(conf->certcnregex);
2482 if (conf->certuriregex)
2483 regfree(conf->certuriregex);
2484 free(conf->confrewritein);
2485 free(conf->confrewriteout);
2486 if (conf->rewriteusername) {
2487 if (conf->rewriteusername->regex)
2488 regfree(conf->rewriteusername->regex);
2489 free(conf->rewriteusername->replacement);
2490 free(conf->rewriteusername);
2492 free(conf->dynamiclookupcommand);
2493 free(conf->rewritein);
2494 free(conf->rewriteout);
2495 if (conf->hostports)
2496 freehostports(conf->hostports);
2498 pthread_mutex_destroy(conf->lock);
2501 /* not touching ssl_ctx, clients and servers */
2505 int mergeconfstring(char **dst, char **src) {
2514 t = stringcopy(*dst, 0);
2516 debug(DBG_ERR, "malloc failed");
2524 char **mstringcopy(char **in) {
2531 for (n = 0; in[n]; n++);
2532 out = malloc((n + 1) * sizeof(char *));
2535 for (n = 0; in[n]; n++) {
2536 out[n] = stringcopy(in[n], 0);
2546 int mergeconfmstring(char ***dst, char ***src) {
2555 t = mstringcopy(*dst);
2557 debug(DBG_ERR, "malloc failed");
2565 /* assumes dst is a shallow copy */
2566 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2567 if (!mergeconfstring(&dst->name, &src->name) ||
2568 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2569 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2570 !mergeconfstring(&dst->secret, &src->secret) ||
2571 !mergeconfstring(&dst->tls, &src->tls) ||
2572 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2573 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2574 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2575 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2578 dst->pdef = src->pdef;
2579 dst->statusserver = src->statusserver;
2580 dst->certnamecheck = src->certnamecheck;
2581 if (src->retryinterval != 255)
2582 dst->retryinterval = src->retryinterval;
2583 if (src->retrycount != 255)
2584 dst->retrycount = src->retrycount;
2588 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2589 struct clsrvconf *conf;
2590 char *conftype = NULL, *rewriteinalias = NULL;
2591 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2593 debug(DBG_DBG, "confclient_cb called for %s", block);
2595 conf = malloc(sizeof(struct clsrvconf));
2597 debugx(1, DBG_ERR, "malloc failed");
2598 memset(conf, 0, sizeof(struct clsrvconf));
2599 conf->certnamecheck = 1;
2601 if (!getgenericconfig(cf, block,
2602 "type", CONF_STR, &conftype,
2603 "host", CONF_MSTR, &conf->hostsrc,
2604 "secret", CONF_STR, &conf->secret,
2605 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2606 "tls", CONF_STR, &conf->tls,
2607 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2608 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2610 "DuplicateInterval", CONF_LINT, &dupinterval,
2611 "addTTL", CONF_LINT, &addttl,
2612 "rewrite", CONF_STR, &rewriteinalias,
2613 "rewriteIn", CONF_STR, &conf->confrewritein,
2614 "rewriteOut", CONF_STR, &conf->confrewriteout,
2615 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2618 debugx(1, DBG_ERR, "configuration error");
2620 conf->name = stringcopy(val, 0);
2621 if (conf->name && !conf->hostsrc) {
2622 conf->hostsrc = malloc(2 * sizeof(char *));
2623 if (conf->hostsrc) {
2624 conf->hostsrc[0] = stringcopy(val, 0);
2625 conf->hostsrc[1] = NULL;
2628 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2629 debugx(1, DBG_ERR, "malloc failed");
2632 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2633 conf->type = protoname2int(conftype);
2634 if (conf->type == 255)
2635 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2637 conf->pdef = protodefs[conf->type];
2639 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2640 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2641 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2643 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2644 if (conf->matchcertattr && !addmatchcertattr(conf))
2645 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2649 if (dupinterval != LONG_MIN) {
2650 if (dupinterval < 0 || dupinterval > 255)
2651 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2652 conf->dupinterval = (uint8_t)dupinterval;
2654 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2656 if (addttl != LONG_MIN) {
2657 if (addttl < 1 || addttl > 255)
2658 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2659 conf->addttl = (uint8_t)addttl;
2662 if (!conf->confrewritein)
2663 conf->confrewritein = rewriteinalias;
2665 free(rewriteinalias);
2666 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2667 if (conf->confrewriteout)
2668 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2670 if (conf->confrewriteusername) {
2671 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2672 if (!conf->rewriteusername)
2673 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2676 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2677 !resolvehostports(conf->hostports, conf->pdef->socktype))
2678 debugx(1, DBG_ERR, "resolve failed, exiting");
2680 if (!conf->secret) {
2681 if (!conf->pdef->secretdefault)
2682 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2683 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2685 debugx(1, DBG_ERR, "malloc failed");
2688 conf->lock = malloc(sizeof(pthread_mutex_t));
2690 debugx(1, DBG_ERR, "malloc failed");
2692 pthread_mutex_init(conf->lock, NULL);
2693 if (!list_push(clconfs, conf))
2694 debugx(1, DBG_ERR, "malloc failed");
2698 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2699 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2700 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2701 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2702 if (!conf->tlsconf) {
2703 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2706 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2707 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2713 if (!conf->portsrc) {
2714 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2715 if (!conf->portsrc) {
2716 debug(DBG_ERR, "malloc failed");
2721 if (conf->retryinterval == 255)
2722 conf->retryinterval = conf->pdef->retryintervaldefault;
2723 if (conf->retrycount == 255)
2724 conf->retrycount = conf->pdef->retrycountdefault;
2726 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2727 if (conf->confrewriteout)
2728 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2730 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2731 debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2735 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2736 debug(DBG_ERR, "resolve failed, exiting");
2742 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2743 struct clsrvconf *conf, *resconf;
2744 char *conftype = NULL, *rewriteinalias = NULL;
2745 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2747 debug(DBG_DBG, "confserver_cb called for %s", block);
2749 conf = malloc(sizeof(struct clsrvconf));
2751 debug(DBG_ERR, "malloc failed");
2754 memset(conf, 0, sizeof(struct clsrvconf));
2755 resconf = (struct clsrvconf *)arg;
2757 conf->statusserver = resconf->statusserver;
2758 conf->certnamecheck = resconf->certnamecheck;
2760 conf->certnamecheck = 1;
2762 if (!getgenericconfig(cf, block,
2763 "type", CONF_STR, &conftype,
2764 "host", CONF_MSTR, &conf->hostsrc,
2765 "port", CONF_STR, &conf->portsrc,
2766 "secret", CONF_STR, &conf->secret,
2767 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2768 "tls", CONF_STR, &conf->tls,
2769 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2770 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2772 "addTTL", CONF_LINT, &addttl,
2773 "rewrite", CONF_STR, &rewriteinalias,
2774 "rewriteIn", CONF_STR, &conf->confrewritein,
2775 "rewriteOut", CONF_STR, &conf->confrewriteout,
2776 "StatusServer", CONF_BLN, &conf->statusserver,
2777 "RetryInterval", CONF_LINT, &retryinterval,
2778 "RetryCount", CONF_LINT, &retrycount,
2779 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2782 debug(DBG_ERR, "configuration error");
2786 conf->name = stringcopy(val, 0);
2787 if (conf->name && !conf->hostsrc) {
2788 conf->hostsrc = malloc(2 * sizeof(char *));
2789 if (conf->hostsrc) {
2790 conf->hostsrc[0] = stringcopy(val, 0);
2791 conf->hostsrc[1] = NULL;
2794 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2795 debug(DBG_ERR, "malloc failed");
2800 debug(DBG_ERR, "error in block %s, option type missing", block);
2803 conf->type = protoname2int(conftype);
2804 if (conf->type == 255) {
2805 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2811 conf->pdef = protodefs[conf->type];
2813 if (!conf->confrewritein)
2814 conf->confrewritein = rewriteinalias;
2816 free(rewriteinalias);
2817 rewriteinalias = NULL;
2819 if (retryinterval != LONG_MIN) {
2820 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2821 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2824 conf->retryinterval = (uint8_t)retryinterval;
2826 conf->retryinterval = 255;
2828 if (retrycount != LONG_MIN) {
2829 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2830 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2833 conf->retrycount = (uint8_t)retrycount;
2835 conf->retrycount = 255;
2837 if (addttl != LONG_MIN) {
2838 if (addttl < 1 || addttl > 255) {
2839 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2842 conf->addttl = (uint8_t)addttl;
2846 if (!mergesrvconf(resconf, conf))
2850 if (conf->dynamiclookupcommand) {
2851 free(conf->dynamiclookupcommand);
2852 conf->dynamiclookupcommand = NULL;
2856 if (resconf || !conf->dynamiclookupcommand) {
2857 if (!compileserverconfig(conf, block))
2861 if (!conf->secret) {
2862 if (!conf->pdef->secretdefault) {
2863 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2866 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2867 if (!conf->secret) {
2868 debug(DBG_ERR, "malloc failed");
2876 if (!list_push(srvconfs, conf)) {
2877 debug(DBG_ERR, "malloc failed");
2884 free(rewriteinalias);
2885 freeclsrvconf(conf);
2889 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2890 char **servers = NULL, **accservers = NULL, *msg = NULL;
2891 uint8_t accresp = 0;
2893 debug(DBG_DBG, "confrealm_cb called for %s", block);
2895 if (!getgenericconfig(cf, block,
2896 "server", CONF_MSTR, &servers,
2897 "accountingServer", CONF_MSTR, &accservers,
2898 "ReplyMessage", CONF_STR, &msg,
2899 "AccountingResponse", CONF_BLN, &accresp,
2902 debugx(1, DBG_ERR, "configuration error");
2904 addrealm(realms, val, servers, accservers, msg, accresp);
2908 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2909 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
2911 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2913 if (!getgenericconfig(cf, block,
2914 "removeAttribute", CONF_MSTR, &rmattrs,
2915 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2916 "addAttribute", CONF_MSTR, &addattrs,
2917 "modifyAttribute", CONF_MSTR, &modattrs,
2920 debugx(1, DBG_ERR, "configuration error");
2921 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
2925 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2926 struct commonprotoopts *protoopts;
2928 protoopts = malloc(sizeof(struct commonprotoopts));
2931 memset(protoopts, 0, sizeof(struct commonprotoopts));
2932 protoopts->listenargs = listenargs;
2933 protoopts->sourcearg = sourcearg;
2934 protodefs[type]->setprotoopts(protoopts);
2938 void getmainconfig(const char *configfile) {
2939 long int addttl = LONG_MIN, loglevel = LONG_MIN;
2940 struct gconffile *cfs;
2941 char **listenargs[RAD_PROTOCOUNT];
2942 char *sourcearg[RAD_PROTOCOUNT];
2945 cfs = openconfigfile(configfile);
2946 memset(&options, 0, sizeof(options));
2947 memset(&listenargs, 0, sizeof(listenargs));
2948 memset(&sourcearg, 0, sizeof(sourcearg));
2950 clconfs = list_create();
2952 debugx(1, DBG_ERR, "malloc failed");
2954 srvconfs = list_create();
2956 debugx(1, DBG_ERR, "malloc failed");
2958 realms = list_create();
2960 debugx(1, DBG_ERR, "malloc failed");
2962 rewriteconfs = hash_create();
2964 debugx(1, DBG_ERR, "malloc failed");
2966 if (!getgenericconfig(&cfs, NULL,
2968 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
2969 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
2972 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
2973 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
2976 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
2977 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
2980 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
2981 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
2983 "TTLAttribute", CONF_STR, &options.ttlattr,
2984 "addTTL", CONF_LINT, &addttl,
2985 "LogLevel", CONF_LINT, &loglevel,
2986 "LogDestination", CONF_STR, &options.logdestination,
2987 "LoopPrevention", CONF_BLN, &options.loopprevention,
2988 "Client", CONF_CBK, confclient_cb, NULL,
2989 "Server", CONF_CBK, confserver_cb, NULL,
2990 "Realm", CONF_CBK, confrealm_cb, NULL,
2991 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2992 "TLS", CONF_CBK, conftls_cb, NULL,
2994 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
2997 debugx(1, DBG_ERR, "configuration error");
2999 if (loglevel != LONG_MIN) {
3000 if (loglevel < 1 || loglevel > 4)
3001 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3002 options.loglevel = (uint8_t)loglevel;
3004 if (addttl != LONG_MIN) {
3005 if (addttl < 1 || addttl > 255)
3006 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3007 options.addttl = (uint8_t)addttl;
3009 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3010 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3012 for (i = 0; i < RAD_PROTOCOUNT; i++)
3013 if (listenargs[i] || sourcearg[i])
3014 setprotoopts(i, listenargs[i], sourcearg[i]);
3017 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3020 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3023 *configfile = optarg;
3026 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3027 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3028 *loglevel = *optarg - '0';
3040 debug(DBG_ERR, "radsecproxy revision $Rev$");
3041 debug(DBG_ERR, "This binary was built with support for the following transports:");
3043 debug(DBG_ERR, " UDP");
3046 debug(DBG_ERR, " TCP");
3049 debug(DBG_ERR, " TLS");
3052 debug(DBG_ERR, " DTLS");
3059 if (!(argc - optind))
3063 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3067 int daemon(int a, int b) {
3075 for (i = 0; i < 3; i++) {
3077 open("/dev/null", O_RDWR);
3083 void *sighandler(void *arg) {
3088 sigemptyset(&sigset);
3089 sigaddset(&sigset, SIGHUP);
3090 sigaddset(&sigset, SIGPIPE);
3091 sigwait(&sigset, &sig);
3094 /* completely ignoring this */
3097 debug(DBG_INFO, "sighandler: got SIGHUP");
3101 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3104 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3109 int createpidfile(const char *pidfile) {
3111 FILE *f = fopen(pidfile, "w");
3113 r = fprintf(f, "%d\n", getpid());
3114 return f && !fclose(f) && r >= 0;
3117 int main(int argc, char **argv) {
3120 struct list_node *entry;
3121 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3122 char *configfile = NULL, *pidfile = NULL;
3123 struct clsrvconf *srvconf;
3126 debug_init("radsecproxy");
3127 debug_set_level(DEBUG_LEVEL);
3129 for (i = 0; i < RAD_PROTOCOUNT; i++)
3130 protodefs[i] = protoinits[i](i);
3132 /* needed even if no TLS/DTLS transport */
3135 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3137 debug_set_level(loglevel);
3138 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3140 options.loglevel = loglevel;
3141 else if (options.loglevel)
3142 debug_set_level(options.loglevel);
3144 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3145 free(options.logdestination);
3147 if (!list_first(clconfs))
3148 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3149 if (!list_first(realms))
3150 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3153 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3155 if (!foreground && (daemon(0, 0) < 0))
3156 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3158 debug_timestamp_on();
3159 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3160 if (pidfile && !createpidfile(pidfile))
3161 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3163 sigemptyset(&sigset);
3164 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3165 sigaddset(&sigset, SIGHUP);
3166 sigaddset(&sigset, SIGPIPE);
3167 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3168 pthread_create(&sigth, NULL, sighandler, NULL);
3170 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3171 srvconf = (struct clsrvconf *)entry->data;
3172 if (srvconf->dynamiclookupcommand)
3174 if (!addserver(srvconf))
3175 debugx(1, DBG_ERR, "failed to add server");
3176 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3177 (void *)(srvconf->servers)))
3178 debugx(1, DBG_ERR, "pthread_create failed");
3181 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3184 if (protodefs[i]->initextra)
3185 protodefs[i]->initextra();
3186 if (find_clconf_type(i, NULL))
3190 /* just hang around doing nothing, anything to do here? */