2 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
3 * Copyright (C) 2010, 2011 NORDUnet A/S
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
10 /* Code contributions from:
12 * Arne Schwabe <schwabe at uni-paderborn.de>
13 * Maja Wolniewicz <mgw@umk.pl>
14 * Simon Leinen <simon.leinen@switch.ch>
15 * Stefan Winter <stefan.winter@restena.lu>
18 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
19 * rd is responsible for init and launching wr
20 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
21 * each tlsserverrd launches tlsserverwr
22 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
23 * for init and launching rd
25 * serverrd will receive a request, processes it and puts it in the requestq of
26 * the appropriate clientwr
27 * clientwr monitors its requestq and sends requests
28 * clientrd looks for responses, processes them and puts them in the replyq of
29 * the peer the request came from
30 * serverwr monitors its reply and sends replies
32 * In addition to the main thread, we have:
33 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
34 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
35 * For each TLS peer connecting to us there will be 2 more TLS threads
36 * This is only for connected peers
37 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
38 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
42 * May segfault when dtls connections go down? More testing needed
43 * Remove expired stuff from clients request list?
44 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
45 * Useful for TCP accounting? Now we require separate server config for alt port
49 #include <sys/socket.h>
50 #include <netinet/in.h>
59 #include <sys/types.h>
62 #include <arpa/inet.h>
67 #include <openssl/ssl.h>
68 #include <openssl/rand.h>
69 #include <openssl/err.h>
70 #include <openssl/md5.h>
75 #include "radsecproxy.h"
80 #if defined(WANT_FTICKS)
84 static struct options options;
85 static struct list *clconfs, *srvconfs;
86 static struct list *realms;
87 static struct hash *rewriteconfs;
89 static pthread_mutex_t *ssl_locks = NULL;
90 static long *ssl_lock_count;
93 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
95 /* minimum required declarations to avoid reordering code */
96 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
97 int dynamicconfig(struct server *server);
98 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
99 void freerealm(struct realm *realm);
100 void freeclsrvconf(struct clsrvconf *conf);
101 void freerq(struct request *rq);
102 void freerqoutdata(struct rqout *rqout);
103 void rmclientrq(struct request *rq, uint8_t id);
105 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
107 uint8_t protoname2int(const char *name) {
110 for (i = 0; i < RAD_PROTOCOUNT; i++)
111 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
116 /* callbacks for making OpenSSL thread safe */
117 unsigned long ssl_thread_id() {
118 return (unsigned long)pthread_self();
121 void ssl_locking_callback(int mode, int type, const char *file, int line) {
122 if (mode & CRYPTO_LOCK) {
123 pthread_mutex_lock(&ssl_locks[type]);
124 ssl_lock_count[type]++;
126 pthread_mutex_unlock(&ssl_locks[type]);
129 /* returns 1 if the len first bits are equal, else 0 */
130 int prefixmatch(void *a1, void *a2, uint8_t len) {
131 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
132 uint8_t r, l = len / 8;
133 if (l && memcmp(a1, a2, l))
138 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
141 /* returns next config with matching address, or NULL */
142 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
143 struct list_node *entry;
144 struct clsrvconf *conf;
146 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
147 conf = (struct clsrvconf *)entry->data;
148 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
157 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
158 return find_conf(type, addr, clconfs, cur, 0);
161 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
162 return find_conf(type, addr, srvconfs, cur, 1);
165 /* returns next config of given type, or NULL */
166 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
167 struct list_node *entry;
168 struct clsrvconf *conf;
170 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
171 conf = (struct clsrvconf *)entry->data;
172 if (conf->type == type) {
181 struct gqueue *newqueue() {
184 q = malloc(sizeof(struct gqueue));
186 debugx(1, DBG_ERR, "malloc failed");
187 q->entries = list_create();
189 debugx(1, DBG_ERR, "malloc failed");
190 pthread_mutex_init(&q->mutex, NULL);
191 pthread_cond_init(&q->cond, NULL);
195 void removequeue(struct gqueue *q) {
196 struct list_node *entry;
200 pthread_mutex_lock(&q->mutex);
201 for (entry = list_first(q->entries); entry; entry = list_next(entry))
202 freerq((struct request *)entry);
203 list_destroy(q->entries);
204 pthread_cond_destroy(&q->cond);
205 pthread_mutex_unlock(&q->mutex);
206 pthread_mutex_destroy(&q->mutex);
210 void freebios(struct gqueue *q) {
213 pthread_mutex_lock(&q->mutex);
214 while ((bio = (BIO *)list_shift(q->entries)))
216 pthread_mutex_unlock(&q->mutex);
220 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
221 struct client *new = malloc(sizeof(struct client));
224 debug(DBG_ERR, "malloc failed");
229 pthread_mutex_lock(conf->lock);
230 if (!conf->clients) {
231 conf->clients = list_create();
232 if (!conf->clients) {
234 pthread_mutex_unlock(conf->lock);
235 debug(DBG_ERR, "malloc failed");
240 memset(new, 0, sizeof(struct client));
242 if (conf->pdef->addclient)
243 conf->pdef->addclient(new);
245 new->replyq = newqueue();
246 list_push(conf->clients, new);
248 pthread_mutex_unlock(conf->lock);
252 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
253 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
256 pthread_mutex_lock(&lock);
258 pthread_mutex_unlock(&lock);
261 void removeclientrqs(struct client *client) {
266 removeclientrqs_sendrq_freeserver_lock(1);
267 for (i = 0; i < MAX_REQUESTS; i++) {
272 rqout = rq->to->requests + rq->newid;
273 pthread_mutex_lock(rqout->lock);
274 if (rqout->rq == rq) /* still pointing to our request */
275 freerqoutdata(rqout);
276 pthread_mutex_unlock(rqout->lock);
280 removeclientrqs_sendrq_freeserver_lock(0);
283 void removelockedclient(struct client *client) {
284 struct clsrvconf *conf;
288 removeclientrqs(client);
289 removequeue(client->replyq);
290 list_removedata(conf->clients, client);
296 void removeclient(struct client *client) {
297 struct clsrvconf *conf;
303 pthread_mutex_lock(conf->lock);
304 removelockedclient(client);
305 pthread_mutex_unlock(conf->lock);
308 void freeserver(struct server *server, uint8_t destroymutex) {
309 struct rqout *rqout, *end;
314 removeclientrqs_sendrq_freeserver_lock(1);
315 if (server->requests) {
316 rqout = server->requests;
317 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
319 rqout->rq->to = NULL;
320 freerqoutdata(rqout);
321 pthread_mutex_destroy(rqout->lock);
324 free(server->requests);
327 freebios(server->rbios);
328 free(server->dynamiclookuparg);
330 SSL_free(server->ssl);
332 pthread_mutex_destroy(&server->lock);
333 pthread_cond_destroy(&server->newrq_cond);
334 pthread_mutex_destroy(&server->newrq_mutex);
336 removeclientrqs_sendrq_freeserver_lock(0);
340 int addserver(struct clsrvconf *conf) {
344 debug(DBG_ERR, "addserver: currently works with just one server per conf");
347 conf->servers = malloc(sizeof(struct server));
348 if (!conf->servers) {
349 debug(DBG_ERR, "malloc failed");
352 memset(conf->servers, 0, sizeof(struct server));
353 conf->servers->conf = conf;
356 if (conf->type == RAD_DTLS)
357 conf->servers->rbios = newqueue();
359 conf->pdef->setsrcres();
361 conf->servers->sock = -1;
362 if (conf->pdef->addserverextra)
363 conf->pdef->addserverextra(conf);
365 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
366 if (!conf->servers->requests) {
367 debug(DBG_ERR, "malloc failed");
370 for (i = 0; i < MAX_REQUESTS; i++) {
371 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
372 if (!conf->servers->requests[i].lock) {
373 debug(DBG_ERR, "malloc failed");
376 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
377 debugerrno(errno, DBG_ERR, "mutex init failed");
378 free(conf->servers->requests[i].lock);
379 conf->servers->requests[i].lock = NULL;
383 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
384 debugerrno(errno, DBG_ERR, "mutex init failed");
387 conf->servers->newrq = 0;
388 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
389 debugerrno(errno, DBG_ERR, "mutex init failed");
390 pthread_mutex_destroy(&conf->servers->lock);
393 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
394 debugerrno(errno, DBG_ERR, "mutex init failed");
395 pthread_mutex_destroy(&conf->servers->newrq_mutex);
396 pthread_mutex_destroy(&conf->servers->lock);
403 freeserver(conf->servers, 0);
404 conf->servers = NULL;
408 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
410 if (ATTRTYPE(attrs) == type)
412 length -= ATTRLEN(attrs);
413 attrs += ATTRLEN(attrs);
418 struct request *newrqref(struct request *rq) {
424 void freerq(struct request *rq) {
427 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
430 if (rq->origusername)
431 free(rq->origusername);
437 radmsg_free(rq->msg);
441 void freerqoutdata(struct rqout *rqout) {
445 if (rqout->rq->buf) {
446 free(rqout->rq->buf);
447 rqout->rq->buf = NULL;
453 memset(&rqout->expiry, 0, sizeof(struct timeval));
456 void sendrq(struct request *rq) {
460 removeclientrqs_sendrq_freeserver_lock(1);
465 start = to->conf->statusserver ? 1 : 0;
466 pthread_mutex_lock(&to->newrq_mutex);
467 if (start && rq->msg->code == RAD_Status_Server) {
468 pthread_mutex_lock(to->requests[0].lock);
469 if (to->requests[0].rq) {
470 pthread_mutex_unlock(to->requests[0].lock);
471 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
478 /* might simplify if only try nextid, might be ok */
479 for (i = to->nextid; i < MAX_REQUESTS; i++) {
480 if (!to->requests[i].rq) {
481 pthread_mutex_lock(to->requests[i].lock);
482 if (!to->requests[i].rq)
484 pthread_mutex_unlock(to->requests[i].lock);
487 if (i == MAX_REQUESTS) {
488 for (i = start; i < to->nextid; i++) {
489 if (!to->requests[i].rq) {
490 pthread_mutex_lock(to->requests[i].lock);
491 if (!to->requests[i].rq)
493 pthread_mutex_unlock(to->requests[i].lock);
496 if (i == to->nextid) {
497 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
502 rq->newid = (uint8_t)i;
503 rq->msg->id = (uint8_t)i;
504 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
506 pthread_mutex_unlock(to->requests[i].lock);
507 debug(DBG_ERR, "sendrq: radmsg2buf failed");
511 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
512 to->requests[i].rq = rq;
513 pthread_mutex_unlock(to->requests[i].lock);
514 if (i >= start) /* i is not reserved for statusserver */
519 debug(DBG_DBG, "sendrq: signalling client writer");
520 pthread_cond_signal(&to->newrq_cond);
523 pthread_mutex_unlock(&to->newrq_mutex);
524 removeclientrqs_sendrq_freeserver_lock(0);
529 rmclientrq(rq, rq->msg->id);
531 pthread_mutex_unlock(&to->newrq_mutex);
532 removeclientrqs_sendrq_freeserver_lock(0);
535 void sendreply(struct request *rq) {
537 struct client *to = rq->from;
540 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
541 radmsg_free(rq->msg);
545 debug(DBG_ERR, "sendreply: radmsg2buf failed");
549 pthread_mutex_lock(&to->replyq->mutex);
550 first = list_first(to->replyq->entries) == NULL;
552 if (!list_push(to->replyq->entries, rq)) {
553 pthread_mutex_unlock(&to->replyq->mutex);
555 debug(DBG_ERR, "sendreply: malloc failed");
560 debug(DBG_DBG, "signalling server writer");
561 pthread_cond_signal(&to->replyq->cond);
563 pthread_mutex_unlock(&to->replyq->mutex);
566 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
567 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
568 static unsigned char first = 1;
569 static EVP_MD_CTX mdctx;
570 unsigned char hash[EVP_MAX_MD_SIZE], *input;
572 uint8_t i, offset = 0, out[128];
574 pthread_mutex_lock(&lock);
576 EVP_MD_CTX_init(&mdctx);
582 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
583 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
584 !EVP_DigestUpdate(&mdctx, input, 16) ||
585 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
587 pthread_mutex_unlock(&lock);
590 for (i = 0; i < 16; i++)
591 out[offset + i] = hash[i] ^ in[offset + i];
593 input = out + offset;
600 memcpy(in, out, len);
601 pthread_mutex_unlock(&lock);
605 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
606 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
607 static unsigned char first = 1;
608 static EVP_MD_CTX mdctx;
609 unsigned char hash[EVP_MAX_MD_SIZE];
613 pthread_mutex_lock(&lock);
615 EVP_MD_CTX_init(&mdctx);
620 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
621 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
622 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
625 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
626 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
627 !EVP_DigestUpdate(&mdctx, auth, 16) ||
628 !EVP_DigestUpdate(&mdctx, salt, 2) ||
629 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
630 pthread_mutex_unlock(&lock);
635 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
638 for (i = 0; i < 16; i++)
641 for (offset = 16; offset < len; offset += 16) {
643 printf("text + offset - 16 c(%d): ", offset / 16);
644 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
646 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
647 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
648 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
649 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
651 pthread_mutex_unlock(&lock);
655 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
658 for (i = 0; i < 16; i++)
659 text[offset + i] ^= hash[i];
663 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
666 pthread_mutex_unlock(&lock);
670 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
671 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
672 static unsigned char first = 1;
673 static EVP_MD_CTX mdctx;
674 unsigned char hash[EVP_MAX_MD_SIZE];
679 pthread_mutex_lock(&lock);
681 EVP_MD_CTX_init(&mdctx);
686 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
687 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
688 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
691 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
692 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
693 !EVP_DigestUpdate(&mdctx, auth, 16) ||
694 !EVP_DigestUpdate(&mdctx, salt, 2) ||
695 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
696 pthread_mutex_unlock(&lock);
701 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
704 for (i = 0; i < 16; i++)
705 plain[i] = text[i] ^ hash[i];
707 for (offset = 16; offset < len; offset += 16) {
709 printf("text + offset - 16 c(%d): ", offset / 16);
710 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
712 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
713 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
714 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
715 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
717 pthread_mutex_unlock(&lock);
721 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
724 for (i = 0; i < 16; i++)
725 plain[offset + i] = text[offset + i] ^ hash[i];
728 memcpy(text, plain, len);
730 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
733 pthread_mutex_unlock(&lock);
737 struct realm *newrealmref(struct realm *r) {
743 /* returns with lock on realm */
744 struct realm *id2realm(struct list *realmlist, char *id) {
745 struct list_node *entry;
746 struct realm *realm, *subrealm;
748 /* need to do locking for subrealms and check subrealm timers */
749 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
750 realm = (struct realm *)entry->data;
751 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
752 pthread_mutex_lock(&realm->mutex);
753 if (realm->subrealms) {
754 subrealm = id2realm(realm->subrealms, id);
756 pthread_mutex_unlock(&realm->mutex);
760 return newrealmref(realm);
766 int hasdynamicserver(struct list *srvconfs) {
767 struct list_node *entry;
769 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
770 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
775 /* helper function, only used by removeserversubrealms() */
776 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
777 struct list_node *entry, *entry2;
780 for (entry = list_first(realmlist); entry;) {
781 realm = newrealmref((struct realm *)entry->data);
782 pthread_mutex_lock(&realm->mutex);
783 entry = list_next(entry);
785 if (realm->srvconfs) {
786 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
787 if (entry2->data == srv)
789 list_removedata(realm->srvconfs, srv);
791 if (realm->accsrvconfs) {
792 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
793 if (entry2->data == srv)
795 list_removedata(realm->accsrvconfs, srv);
798 /* remove subrealm if no dynamic servers left */
799 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
800 while (list_shift(realm->srvconfs))
802 list_destroy(realm->srvconfs);
803 realm->srvconfs = NULL;
804 while (list_shift(realm->accsrvconfs))
806 list_destroy(realm->accsrvconfs);
807 realm->accsrvconfs = NULL;
808 list_removedata(realmlist, realm);
810 pthread_mutex_unlock(&realm->mutex);
815 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
816 struct list_node *entry;
819 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
820 realm = (struct realm *)entry->data;
821 pthread_mutex_lock(&realm->mutex);
822 if (realm->subrealms) {
823 _internal_removeserversubrealms(realm->subrealms, srv);
824 if (!list_first(realm->subrealms)) {
825 list_destroy(realm->subrealms);
826 realm->subrealms = NULL;
829 pthread_mutex_unlock(&realm->mutex);
833 int attrvalidate(unsigned char *attrs, int length) {
835 if (ATTRLEN(attrs) < 2) {
836 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
839 length -= ATTRLEN(attrs);
841 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
844 attrs += ATTRLEN(attrs);
847 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
851 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
852 if (len < 16 || len > 128 || len % 16) {
853 debug(DBG_WARN, "pwdrecrypt: invalid password length");
857 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
858 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
862 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
864 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
865 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
871 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
874 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
875 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
878 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
879 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
885 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
886 char *oldsecret, char *newsecret) {
889 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
890 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
891 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
897 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
901 for (; attrs[0]; attrs += 2)
902 if (attrs[0] == vendor && attrs[1] == subattr)
907 /* returns 1 if entire element is to be removed, else 0 */
908 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
909 uint8_t alen, sublen;
913 if (!removevendorattrs)
916 memcpy(&vendor, attr->v, 4);
917 vendor = ntohl(vendor);
918 while (*removevendorattrs && *removevendorattrs != vendor)
919 removevendorattrs += 2;
920 if (!*removevendorattrs)
923 if (findvendorsubattr(removevendorattrs, vendor, 256))
924 return 1; /* remove entire vendor attribute */
926 sublen = attr->l - 4;
927 subattrs = attr->v + 4;
929 if (!attrvalidate(subattrs, sublen)) {
930 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
935 alen = ATTRLEN(subattrs);
937 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
938 memmove(subattrs, subattrs + alen, sublen);
946 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
947 struct list_node *n, *p;
951 n = list_first(msg->attrs);
953 attr = (struct tlv *)n->data;
954 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
955 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
956 list_removedata(msg->attrs, attr);
958 n = p ? list_next(p) : list_first(msg->attrs);
966 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
970 for (n = list_first(addattrs); n; n = list_next(n)) {
971 a = copytlv((struct tlv *)n->data);
974 if (!radmsg_add(msg, a)) {
982 int resizeattr(struct tlv *attr, uint8_t newlen) {
985 if (newlen != attr->l) {
986 newv = realloc(attr->v, newlen);
995 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
996 size_t nmatch = 10, reslen = 0, start = 0;
997 regmatch_t pmatch[10], *pfield;
1001 in = stringcopy((char *)attr->v, attr->l);
1005 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1010 out = modattr->replacement;
1012 for (i = start; out[i]; i++) {
1013 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1014 pfield = &pmatch[out[i + 1] - '0'];
1015 if (pfield->rm_so >= 0) {
1016 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1022 reslen += i - start;
1024 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1029 if (!resizeattr(attr, reslen)) {
1036 for (i = start; out[i]; i++) {
1037 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1038 pfield = &pmatch[out[i + 1] - '0'];
1039 if (pfield->rm_so >= 0) {
1040 memcpy(attr->v + reslen, out + start, i - start);
1041 reslen += i - start;
1042 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1043 reslen += pfield->rm_eo - pfield->rm_so;
1050 memcpy(attr->v + reslen, out + start, i - start);
1054 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1055 struct list_node *n, *m;
1057 for (n = list_first(msg->attrs); n; n = list_next(n))
1058 for (m = list_first(modattrs); m; m = list_next(m))
1059 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1060 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1065 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1066 int rv = 1; /* Success. */
1069 if (rewrite->removeattrs || rewrite->removevendorattrs)
1070 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1071 if (rewrite->modattrs)
1072 if (!dorewritemod(msg, rewrite->modattrs))
1074 if (rewrite->addattrs)
1075 if (!dorewriteadd(msg, rewrite->addattrs))
1081 int rewriteusername(struct request *rq, struct tlv *attr) {
1082 char *orig = (char *)tlv2str(attr);
1083 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1087 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1088 rq->origusername = (char *)orig;
1094 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1095 * all is well with the new tlv, i.e. if the function returns
1098 makevendortlv(uint32_t vendor, struct tlv *attr)
1100 struct tlv *newtlv = NULL;
1108 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1109 memcpy(v, &vendor, 4);
1110 tlv2buf(v + 4, attr);
1111 v[5] += 2; /* Vendor length increased for type and length fields. */
1112 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1121 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1123 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1126 vattr = makevendortlv(vendor, attr);
1131 if (!radmsg_add(msg, vattr)) {
1138 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1145 if (attrtype[1] == 256) { /* not vendor */
1146 attr = maketlv(attrtype[0], 4, ttl);
1147 if (attr && !radmsg_add(msg, attr))
1150 attr = maketlv(attrtype[1], 4, ttl);
1152 addvendorattr(msg, attrtype[0], attr);
1156 int decttl(uint8_t l, uint8_t *v) {
1163 while (i >= 0 && !v[i])
1167 for (i--; i >= 0 && !v[i]; i--);
1176 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1177 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1178 uint8_t alen, *subattrs;
1180 struct list_node *node;
1184 if (attrtype[1] == 256) { /* not vendor */
1185 attr = radmsg_gettype(msg, attrtype[0]);
1187 return decttl(attr->l, attr->v);
1189 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1190 attr = (struct tlv *)node->data;
1191 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1193 memcpy(&vendor, attr->v, 4);
1194 if (ntohl(vendor) != attrtype[0])
1196 sublen = attr->l - 4;
1197 subattrs = attr->v + 4;
1198 if (!attrvalidate(subattrs, sublen))
1200 while (sublen > 1) {
1201 if (ATTRTYPE(subattrs) == attrtype[1])
1202 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1203 alen = ATTRLEN(subattrs);
1211 const char *radmsgtype2string(uint8_t code) {
1212 static const char *rad_msg_names[] = {
1213 "", "Access-Request", "Access-Accept", "Access-Reject",
1214 "Accounting-Request", "Accounting-Response", "", "",
1215 "", "", "", "Access-Challenge",
1216 "Status-Server", "Status-Client"
1218 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1221 void char2hex(char *h, unsigned char c) {
1222 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1223 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1224 h[0] = hexdigits[c / 16];
1225 h[1] = hexdigits[c % 16];
1229 uint8_t *radattr2ascii(struct tlv *attr) {
1237 for (i = 0; i < attr->l; i++)
1238 if (attr->v[i] < 32 || attr->v[i] > 126)
1241 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1248 for (i = 0; i < attr->l; i++)
1249 if (attr->v[i] < 32 || attr->v[i] > 126) {
1251 char2hex((char *)d, attr->v[i]);
1259 void acclog(struct radmsg *msg, struct client *from) {
1263 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1265 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1268 username = radattr2ascii(attr);
1270 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1276 void respond(struct request *rq, uint8_t code, char *message) {
1280 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1282 debug(DBG_ERR, "respond: malloc failed");
1285 if (message && *message) {
1286 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1287 if (!attr || !radmsg_add(msg, attr)) {
1290 debug(DBG_ERR, "respond: malloc failed");
1295 radmsg_free(rq->msg);
1297 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1298 sendreply(newrqref(rq));
1301 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1302 struct list_node *entry;
1303 struct clsrvconf *server, *best = NULL, *first = NULL;
1305 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1306 server = (struct clsrvconf *)entry->data;
1307 if (!server->servers)
1311 if (!server->servers->connectionok && !server->servers->dynstartup)
1313 if (!server->servers->lostrqs)
1319 if (server->servers->lostrqs < best->servers->lostrqs)
1322 return best ? best : first;
1325 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1326 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1327 struct clsrvconf *srvconf;
1328 struct realm *subrealm;
1329 struct server *server = NULL;
1330 char *id = (char *)tlv2str(username);
1334 /* returns with lock on realm */
1335 *realm = id2realm(realms, id);
1338 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1339 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1340 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1341 subrealm = adddynamicrealmserver(*realm, id);
1343 pthread_mutex_lock(&subrealm->mutex);
1344 pthread_mutex_unlock(&(*realm)->mutex);
1347 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1351 server = srvconf->servers;
1359 struct request *newrequest() {
1362 rq = malloc(sizeof(struct request));
1364 debug(DBG_ERR, "newrequest: malloc failed");
1367 memset(rq, 0, sizeof(struct request));
1369 gettimeofday(&rq->created, NULL);
1373 int addclientrq(struct request *rq) {
1377 r = rq->from->rqs[rq->rqid];
1379 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1380 gettimeofday(&now, NULL);
1381 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1383 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1384 sendreply(newrqref(r));
1386 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1392 rq->from->rqs[rq->rqid] = newrqref(rq);
1396 void rmclientrq(struct request *rq, uint8_t id) {
1399 r = rq->from->rqs[id];
1402 rq->from->rqs[id] = NULL;
1406 /* returns 0 if validation/authentication fails, else 1 */
1407 int radsrv(struct request *rq) {
1408 struct radmsg *msg = NULL;
1410 uint8_t *userascii = NULL;
1411 struct realm *realm = NULL;
1412 struct server *to = NULL;
1413 struct client *from = rq->from;
1416 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1421 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1428 memcpy(rq->rqauth, msg->auth, 16);
1430 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1431 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1432 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1436 if (!addclientrq(rq))
1439 if (msg->code == RAD_Status_Server) {
1440 respond(rq, RAD_Access_Accept, NULL);
1444 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1446 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1449 ttlres = checkttl(msg, options.ttlattrtype);
1451 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1455 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1457 if (msg->code == RAD_Accounting_Request) {
1459 respond(rq, RAD_Accounting_Response, NULL);
1461 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1465 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1466 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1470 userascii = radattr2ascii(attr);
1473 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1475 /* will return with lock on the realm */
1476 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1478 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1483 if (realm->message && msg->code == RAD_Access_Request) {
1484 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1485 respond(rq, RAD_Access_Reject, realm->message);
1486 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1488 respond(rq, RAD_Accounting_Response, NULL);
1493 if ((to->conf->loopprevention == 1
1494 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1495 && !strcmp(from->conf->name, to->conf->name)) {
1496 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1497 from->conf->name, addr2string(from->addr), to->conf->name);
1501 if (msg->code == RAD_Accounting_Request)
1502 memset(msg->auth, 0, 16);
1503 else if (!RAND_bytes(msg->auth, 16)) {
1504 debug(DBG_WARN, "radsrv: failed to generate random auth");
1509 printfchars(NULL, "auth", "%02x ", auth, 16);
1512 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1514 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1515 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1519 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1521 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1522 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1526 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1529 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1530 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1535 pthread_mutex_unlock(&realm->mutex);
1540 rmclientrq(rq, msg->id);
1545 pthread_mutex_unlock(&realm->mutex);
1551 void replyh(struct server *server, unsigned char *buf) {
1552 struct client *from;
1553 struct rqout *rqout;
1555 unsigned char *subattrs;
1556 uint8_t *username, *stationid, *replymsg;
1557 struct radmsg *msg = NULL;
1559 struct list_node *node;
1561 server->connectionok = 1;
1562 server->lostrqs = 0;
1564 rqout = server->requests + buf[1];
1565 pthread_mutex_lock(rqout->lock);
1566 if (!rqout->tries) {
1569 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1573 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1577 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1580 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1581 && msg->code != RAD_Accounting_Response) {
1582 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1585 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1587 gettimeofday(&server->lastrcv, NULL);
1589 if (rqout->rq->msg->code == RAD_Status_Server) {
1590 freerqoutdata(rqout);
1591 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1595 gettimeofday(&server->lastreply, NULL);
1596 from = rqout->rq->from;
1598 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1599 debug(DBG_INFO, "replyh: rewritein failed");
1603 ttlres = checkttl(msg, options.ttlattrtype);
1605 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1610 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1611 attr = (struct tlv *)node->data;
1612 if (attr->t != RAD_Attr_Vendor_Specific)
1616 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1619 sublen = attr->l - 4;
1620 subattrs = attr->v + 4;
1621 if (!attrvalidate(subattrs, sublen) ||
1622 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1623 rqout->rq, server->conf->secret, from->conf->secret) ||
1624 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1625 rqout->rq, server->conf->secret, from->conf->secret))
1629 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1633 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1634 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1636 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1637 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1641 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1642 radmsgtype2string(msg->code), username, stationid,
1643 server->conf->name, replymsg, from->conf->name,
1644 addr2string(from->addr));
1648 "%s for user %s stationid %s from %s to %s (%s)",
1649 radmsgtype2string(msg->code), username, stationid,
1650 server->conf->name, from->conf->name,
1651 addr2string(from->addr));
1655 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1656 radmsgtype2string(msg->code), username,
1657 server->conf->name, replymsg, from->conf->name,
1658 addr2string(from->addr));
1661 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1662 radmsgtype2string(msg->code), username,
1663 server->conf->name, from->conf->name,
1664 addr2string(from->addr));
1670 #if defined(WANT_FTICKS)
1671 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1672 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1673 fticks_log(&options, from, msg, rqout);
1676 msg->id = (char)rqout->rq->rqid;
1677 memcpy(msg->auth, rqout->rq->rqauth, 16);
1680 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1683 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1684 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1685 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1688 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1691 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1692 debug(DBG_WARN, "replyh: rewriteout failed");
1696 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1697 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1699 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1700 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1702 radmsg_free(rqout->rq->msg);
1703 rqout->rq->msg = msg;
1704 sendreply(newrqref(rqout->rq));
1705 freerqoutdata(rqout);
1706 pthread_mutex_unlock(rqout->lock);
1711 pthread_mutex_unlock(rqout->lock);
1715 struct request *createstatsrvrq() {
1722 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1725 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1728 if (!radmsg_add(rq->msg, attr)) {
1739 /* code for removing state not finished */
1740 void *clientwr(void *arg) {
1741 struct server *server = (struct server *)arg;
1742 struct rqout *rqout = NULL;
1743 pthread_t clientrdth;
1744 int i, dynconffail = 0;
1747 struct timeval now, laststatsrv;
1748 struct timespec timeout;
1749 struct request *statsrvrq;
1750 struct clsrvconf *conf;
1752 conf = server->conf;
1754 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1756 server->dynstartup = 0;
1761 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1762 debug(DBG_WARN, "clientwr: resolve failed");
1763 server->dynstartup = 0;
1768 memset(&timeout, 0, sizeof(struct timespec));
1770 if (conf->statusserver) {
1771 gettimeofday(&server->lastrcv, NULL);
1772 gettimeofday(&laststatsrv, NULL);
1775 if (conf->pdef->connecter) {
1776 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1777 if (server->dynamiclookuparg) {
1778 server->dynstartup = 0;
1783 server->connectionok = 1;
1784 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1785 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1789 server->connectionok = 1;
1790 server->dynstartup = 0;
1793 pthread_mutex_lock(&server->newrq_mutex);
1794 if (!server->newrq) {
1795 gettimeofday(&now, NULL);
1796 /* random 0-7 seconds */
1797 RAND_bytes(&rnd, 1);
1799 if (conf->statusserver) {
1800 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1801 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1803 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1804 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1806 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1807 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1810 if (timeout.tv_sec > now.tv_sec)
1811 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1813 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1816 if (server->newrq) {
1817 debug(DBG_DBG, "clientwr: got new request");
1822 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1824 pthread_mutex_unlock(&server->newrq_mutex);
1826 for (i = 0; i < MAX_REQUESTS; i++) {
1827 if (server->clientrdgone) {
1828 pthread_join(clientrdth, NULL);
1832 for (; i < MAX_REQUESTS; i++) {
1833 rqout = server->requests + i;
1835 pthread_mutex_lock(rqout->lock);
1838 pthread_mutex_unlock(rqout->lock);
1842 if (i == MAX_REQUESTS)
1845 gettimeofday(&now, NULL);
1846 if (now.tv_sec < rqout->expiry.tv_sec) {
1847 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1848 timeout.tv_sec = rqout->expiry.tv_sec;
1849 pthread_mutex_unlock(rqout->lock);
1853 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1854 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1855 if (conf->statusserver) {
1856 if (*rqout->rq->buf == RAD_Status_Server) {
1857 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1858 if (server->lostrqs < 255)
1862 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1863 if (server->lostrqs < 255)
1866 freerqoutdata(rqout);
1867 pthread_mutex_unlock(rqout->lock);
1871 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1872 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1873 timeout.tv_sec = rqout->expiry.tv_sec;
1875 conf->pdef->clientradput(server, rqout->rq->buf);
1876 pthread_mutex_unlock(rqout->lock);
1878 if (conf->statusserver && server->connectionok) {
1879 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1880 gettimeofday(&now, NULL);
1881 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1883 statsrvrq = createstatsrvrq();
1885 statsrvrq->to = server;
1886 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1893 conf->servers = NULL;
1894 if (server->dynamiclookuparg) {
1895 removeserversubrealms(realms, conf);
1899 freeclsrvconf(conf);
1901 freeserver(server, 1);
1902 ERR_remove_state(0);
1906 void createlistener(uint8_t type, char *arg) {
1908 struct addrinfo *res;
1909 int s = -1, on = 1, *sp = NULL;
1910 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1912 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1913 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1915 for (res = hp->addrinfo; res; res = res->ai_next) {
1916 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1918 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1921 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1923 disable_DF_bit(s, res);
1926 if (res->ai_family == AF_INET6)
1927 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1929 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1930 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1936 sp = malloc(sizeof(int));
1938 debugx(1, DBG_ERR, "malloc failed");
1940 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1941 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1945 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1947 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1951 void createlisteners(uint8_t type) {
1955 args = protodefs[type]->getlistenerargs();
1957 for (i = 0; args[i]; i++)
1958 createlistener(type, args[i]);
1960 createlistener(type, NULL);
1968 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1969 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1970 for (i = 0; i < CRYPTO_num_locks(); i++) {
1971 ssl_lock_count[i] = 0;
1972 pthread_mutex_init(&ssl_locks[i], NULL);
1974 CRYPTO_set_id_callback(ssl_thread_id);
1975 CRYPTO_set_locking_callback(ssl_locking_callback);
1977 SSL_load_error_strings();
1980 while (!RAND_status()) {
1983 RAND_seed((unsigned char *)&t, sizeof(time_t));
1984 RAND_seed((unsigned char *)&pid, sizeof(pid));
1988 struct list *addsrvconfs(char *value, char **names) {
1989 struct list *conflist;
1991 struct list_node *entry;
1992 struct clsrvconf *conf = NULL;
1994 if (!names || !*names)
1997 conflist = list_create();
1999 debug(DBG_ERR, "malloc failed");
2003 for (n = 0; names[n]; n++) {
2004 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2005 conf = (struct clsrvconf *)entry->data;
2006 if (!strcasecmp(names[n], conf->name))
2010 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2011 list_destroy(conflist);
2014 if (!list_push(conflist, conf)) {
2015 debug(DBG_ERR, "malloc failed");
2016 list_destroy(conflist);
2019 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2024 void freerealm(struct realm *realm) {
2027 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2028 if (--realm->refcount)
2032 free(realm->message);
2033 regfree(&realm->regex);
2034 pthread_mutex_destroy(&realm->mutex);
2035 /* if refcount == 0, all subrealms gone */
2036 list_destroy(realm->subrealms);
2037 /* if refcount == 0, all srvconfs gone */
2038 list_destroy(realm->srvconfs);
2039 /* if refcount == 0, all accsrvconfs gone */
2040 list_destroy(realm->accsrvconfs);
2041 freerealm(realm->parent);
2045 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2047 struct realm *realm;
2048 char *s, *regex = NULL;
2050 if (*value == '/') {
2051 /* regexp, remove optional trailing / if present */
2052 if (value[strlen(value) - 1] == '/')
2053 value[strlen(value) - 1] = '\0';
2055 /* not a regexp, let us make it one */
2056 if (*value == '*' && !value[1])
2057 regex = stringcopy(".*", 0);
2059 for (n = 0, s = value; *s;)
2062 regex = malloc(strlen(value) + n + 3);
2065 for (n = 1, s = value; *s; s++) {
2075 debug(DBG_ERR, "malloc failed");
2079 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2082 realm = malloc(sizeof(struct realm));
2084 debug(DBG_ERR, "malloc failed");
2087 memset(realm, 0, sizeof(struct realm));
2089 if (pthread_mutex_init(&realm->mutex, NULL)) {
2090 debugerrno(errno, DBG_ERR, "mutex init failed");
2096 realm->name = stringcopy(value, 0);
2098 debug(DBG_ERR, "malloc failed");
2101 if (message && strlen(message) > 253) {
2102 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2105 realm->message = message;
2106 realm->accresp = accresp;
2108 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2109 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2113 if (servers && *servers) {
2114 realm->srvconfs = addsrvconfs(value, servers);
2115 if (!realm->srvconfs)
2119 if (accservers && *accservers) {
2120 realm->accsrvconfs = addsrvconfs(value, accservers);
2121 if (!realm->accsrvconfs)
2125 if (!list_push(realmlist, realm)) {
2126 debug(DBG_ERR, "malloc failed");
2127 pthread_mutex_destroy(&realm->mutex);
2131 debug(DBG_DBG, "addrealm: added realm %s", value);
2135 while (list_shift(realm->srvconfs));
2136 while (list_shift(realm->accsrvconfs));
2143 for (n = 0; servers[n]; n++)
2145 freegconfmstr(servers);
2149 for (n = 0; accservers[n]; n++)
2151 freegconfmstr(accservers);
2153 return newrealmref(realm);
2156 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2157 struct list_node *entry;
2158 struct clsrvconf *conf, *srvconf;
2159 struct list *subrealmservers = NULL;
2162 if (list_first(srvconfs)) {
2163 subrealmservers = list_create();
2164 if (!subrealmservers)
2168 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2169 conf = (struct clsrvconf *)entry->data;
2170 if (!conf->servers && conf->dynamiclookupcommand) {
2171 srvconf = malloc(sizeof(struct clsrvconf));
2173 debug(DBG_ERR, "malloc failed");
2177 if (addserver(srvconf)) {
2178 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2179 srvconf->servers->dynstartup = 1;
2180 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2181 debugerrno(errno, DBG_ERR, "pthread_create failed");
2182 freeserver(srvconf->servers, 1);
2183 srvconf->servers = NULL;
2185 pthread_detach(clientth);
2189 if (conf->servers) {
2190 if (list_push(subrealmservers, conf))
2193 debug(DBG_ERR, "malloc failed");
2196 return subrealmservers;
2199 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2200 struct realm *newrealm = NULL;
2201 char *realmname, *s;
2203 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2204 realmname = strrchr(id, '@');
2210 for (s = realmname; *s; s++)
2211 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2214 if (!realm->subrealms)
2215 realm->subrealms = list_create();
2216 if (!realm->subrealms)
2219 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2221 list_destroy(realm->subrealms);
2222 realm->subrealms = NULL;
2226 newrealm->parent = newrealmref(realm);
2227 /* add server and accserver to newrealm */
2228 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2229 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2233 int dynamicconfig(struct server *server) {
2234 int ok, fd[2], status;
2236 struct clsrvconf *conf = server->conf;
2237 struct gconffile *cf = NULL;
2239 /* for now we only learn hostname/address */
2240 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2243 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2248 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2252 } else if (pid == 0) {
2255 if (fd[1] != STDOUT_FILENO) {
2256 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2257 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2260 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2261 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2265 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2266 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2267 (void *) conf, NULL);
2270 if (waitpid(pid, &status, 0) < 0) {
2271 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2276 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2284 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2288 /* should accept both names and numeric values, only numeric right now */
2289 uint8_t attrname2val(char *attrname) {
2292 val = atoi(attrname);
2293 return val > 0 && val < 256 ? val : 0;
2296 /* ATTRNAME is on the form vendor[:type].
2297 If only vendor is found, TYPE is set to 256 and 1 is returned.
2298 If type is >= 256, 1 is returned.
2299 Otherwise, 0 is returned.
2301 /* should accept both names and numeric values, only numeric right now */
2302 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2305 *vendor = atoi(attrname);
2306 s = strchr(attrname, ':');
2307 if (!s) { /* Only vendor was found. */
2311 *type = atoi(s + 1);
2315 /** Extract attributes from string NAMEVAL, create a struct tlv and
2316 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2317 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2318 * NULL if fields are missing or if conversion fails.
2320 * FIXME: Should accept both names and numeric values, only numeric
2322 struct tlv *extractattr(char *nameval, char vendor_flag) {
2324 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2328 s = strchr(nameval, ':');
2331 name = atoi(nameval);
2334 s2 = strchr(s + 1, ':');
2341 len = strlen(s + 1);
2345 if (name < 1 || name > 255)
2347 a = malloc(sizeof(struct tlv));
2351 a->v = (uint8_t *)stringcopy(s + 1, 0);
2360 a = makevendortlv(vendor, a);
2365 /* should accept both names and numeric values, only numeric right now */
2366 struct modattr *extractmodattr(char *nameval) {
2371 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2375 s = strchr(nameval, ':');
2376 name = atoi(nameval);
2377 if (!s || name < 1 || name > 255 || s[1] != '/')
2381 /* regexp, remove optional trailing / if present */
2382 if (s[strlen(s) - 1] == '/')
2383 s[strlen(s) - 1] = '\0';
2391 m = malloc(sizeof(struct modattr));
2393 debug(DBG_ERR, "malloc failed");
2398 m->replacement = stringcopy(t, 0);
2399 if (!m->replacement) {
2401 debug(DBG_ERR, "malloc failed");
2405 m->regex = malloc(sizeof(regex_t));
2407 free(m->replacement);
2409 debug(DBG_ERR, "malloc failed");
2413 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2415 free(m->replacement);
2417 debug(DBG_ERR, "failed to compile regular expression %s", s);
2424 struct rewrite *getrewrite(char *alt1, char *alt2) {
2428 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2431 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2436 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2438 struct rewrite *rewrite = NULL;
2440 uint8_t *rma = NULL;
2441 uint32_t *p, *rmva = NULL;
2442 struct list *adda = NULL, *moda = NULL;
2447 for (n = 0; rmattrs[n]; n++);
2448 rma = calloc(n + 1, sizeof(uint8_t));
2450 debugx(1, DBG_ERR, "malloc failed");
2452 for (i = 0; i < n; i++)
2453 if (!(rma[i] = attrname2val(rmattrs[i])))
2454 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2455 freegconfmstr(rmattrs);
2460 for (n = 0; rmvattrs[n]; n++);
2461 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2463 debugx(1, DBG_ERR, "malloc failed");
2465 for (p = rmva, i = 0; i < n; i++, p += 2)
2466 if (!vattrname2val(rmvattrs[i], p, p + 1))
2467 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2468 freegconfmstr(rmvattrs);
2473 adda = list_create();
2475 debugx(1, DBG_ERR, "malloc failed");
2476 for (i = 0; addattrs[i]; i++) {
2477 a = extractattr(addattrs[i], 0);
2479 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2480 if (!list_push(adda, a))
2481 debugx(1, DBG_ERR, "malloc failed");
2483 freegconfmstr(addattrs);
2488 adda = list_create();
2490 debugx(1, DBG_ERR, "malloc failed");
2491 for (i = 0; addvattrs[i]; i++) {
2492 a = extractattr(addvattrs[i], 1);
2494 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2495 if (!list_push(adda, a))
2496 debugx(1, DBG_ERR, "malloc failed");
2498 freegconfmstr(addvattrs);
2502 moda = list_create();
2504 debugx(1, DBG_ERR, "malloc failed");
2505 for (i = 0; modattrs[i]; i++) {
2506 m = extractmodattr(modattrs[i]);
2508 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2509 if (!list_push(moda, m))
2510 debugx(1, DBG_ERR, "malloc failed");
2512 freegconfmstr(modattrs);
2515 if (rma || rmva || adda || moda) {
2516 rewrite = malloc(sizeof(struct rewrite));
2518 debugx(1, DBG_ERR, "malloc failed");
2519 rewrite->removeattrs = rma;
2520 rewrite->removevendorattrs = rmva;
2521 rewrite->addattrs = adda;
2522 rewrite->modattrs = moda;
2525 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2526 debugx(1, DBG_ERR, "malloc failed");
2527 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2530 int setttlattr(struct options *opts, char *defaultattr) {
2531 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2533 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2534 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2536 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2540 void freeclsrvconf(struct clsrvconf *conf) {
2543 freegconfmstr(conf->hostsrc);
2544 free(conf->portsrc);
2547 free(conf->matchcertattr);
2548 if (conf->certcnregex)
2549 regfree(conf->certcnregex);
2550 if (conf->certuriregex)
2551 regfree(conf->certuriregex);
2552 free(conf->confrewritein);
2553 free(conf->confrewriteout);
2554 if (conf->rewriteusername) {
2555 if (conf->rewriteusername->regex)
2556 regfree(conf->rewriteusername->regex);
2557 free(conf->rewriteusername->replacement);
2558 free(conf->rewriteusername);
2560 free(conf->dynamiclookupcommand);
2561 free(conf->rewritein);
2562 free(conf->rewriteout);
2563 if (conf->hostports)
2564 freehostports(conf->hostports);
2566 pthread_mutex_destroy(conf->lock);
2569 /* not touching ssl_ctx, clients and servers */
2573 int mergeconfstring(char **dst, char **src) {
2582 t = stringcopy(*dst, 0);
2584 debug(DBG_ERR, "malloc failed");
2592 char **mstringcopy(char **in) {
2599 for (n = 0; in[n]; n++);
2600 out = malloc((n + 1) * sizeof(char *));
2603 for (n = 0; in[n]; n++) {
2604 out[n] = stringcopy(in[n], 0);
2614 int mergeconfmstring(char ***dst, char ***src) {
2623 t = mstringcopy(*dst);
2625 debug(DBG_ERR, "malloc failed");
2633 /* assumes dst is a shallow copy */
2634 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2635 if (!mergeconfstring(&dst->name, &src->name) ||
2636 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2637 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2638 !mergeconfstring(&dst->secret, &src->secret) ||
2639 !mergeconfstring(&dst->tls, &src->tls) ||
2640 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2641 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2642 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2643 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2646 dst->pdef = src->pdef;
2647 dst->statusserver = src->statusserver;
2648 dst->certnamecheck = src->certnamecheck;
2649 if (src->retryinterval != 255)
2650 dst->retryinterval = src->retryinterval;
2651 if (src->retrycount != 255)
2652 dst->retrycount = src->retrycount;
2656 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2657 struct clsrvconf *conf;
2658 char *conftype = NULL, *rewriteinalias = NULL;
2659 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2661 debug(DBG_DBG, "confclient_cb called for %s", block);
2663 conf = malloc(sizeof(struct clsrvconf));
2665 debugx(1, DBG_ERR, "malloc failed");
2666 memset(conf, 0, sizeof(struct clsrvconf));
2667 conf->certnamecheck = 1;
2669 if (!getgenericconfig(
2671 "type", CONF_STR, &conftype,
2672 "host", CONF_MSTR, &conf->hostsrc,
2673 "secret", CONF_STR, &conf->secret,
2674 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2675 "tls", CONF_STR, &conf->tls,
2676 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2677 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2679 "DuplicateInterval", CONF_LINT, &dupinterval,
2680 "addTTL", CONF_LINT, &addttl,
2681 "rewrite", CONF_STR, &rewriteinalias,
2682 "rewriteIn", CONF_STR, &conf->confrewritein,
2683 "rewriteOut", CONF_STR, &conf->confrewriteout,
2684 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2685 #if defined(WANT_FTICKS)
2686 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2690 debugx(1, DBG_ERR, "configuration error");
2692 conf->name = stringcopy(val, 0);
2693 if (conf->name && !conf->hostsrc) {
2694 conf->hostsrc = malloc(2 * sizeof(char *));
2695 if (conf->hostsrc) {
2696 conf->hostsrc[0] = stringcopy(val, 0);
2697 conf->hostsrc[1] = NULL;
2700 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2701 debugx(1, DBG_ERR, "malloc failed");
2704 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2705 conf->type = protoname2int(conftype);
2706 if (conf->type == 255)
2707 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2709 conf->pdef = protodefs[conf->type];
2711 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2712 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2713 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2715 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2716 if (conf->matchcertattr && !addmatchcertattr(conf))
2717 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2721 if (dupinterval != LONG_MIN) {
2722 if (dupinterval < 0 || dupinterval > 255)
2723 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2724 conf->dupinterval = (uint8_t)dupinterval;
2726 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2728 if (addttl != LONG_MIN) {
2729 if (addttl < 1 || addttl > 255)
2730 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2731 conf->addttl = (uint8_t)addttl;
2734 if (!conf->confrewritein)
2735 conf->confrewritein = rewriteinalias;
2737 free(rewriteinalias);
2738 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2739 if (conf->confrewriteout)
2740 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2742 if (conf->confrewriteusername) {
2743 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2744 if (!conf->rewriteusername)
2745 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2748 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2749 !resolvehostports(conf->hostports, conf->pdef->socktype))
2750 debugx(1, DBG_ERR, "resolve failed, exiting");
2752 if (!conf->secret) {
2753 if (!conf->pdef->secretdefault)
2754 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2755 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2757 debugx(1, DBG_ERR, "malloc failed");
2760 conf->lock = malloc(sizeof(pthread_mutex_t));
2762 debugx(1, DBG_ERR, "malloc failed");
2764 pthread_mutex_init(conf->lock, NULL);
2765 if (!list_push(clconfs, conf))
2766 debugx(1, DBG_ERR, "malloc failed");
2770 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2771 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2772 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2773 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2774 if (!conf->tlsconf) {
2775 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2778 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2779 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2785 if (!conf->portsrc) {
2786 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2787 if (!conf->portsrc) {
2788 debug(DBG_ERR, "malloc failed");
2793 if (conf->retryinterval == 255)
2794 conf->retryinterval = conf->pdef->retryintervaldefault;
2795 if (conf->retrycount == 255)
2796 conf->retrycount = conf->pdef->retrycountdefault;
2798 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2799 if (conf->confrewriteout)
2800 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2802 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2803 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2807 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2808 debug(DBG_ERR, "resolve failed, exiting");
2814 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2815 struct clsrvconf *conf, *resconf;
2816 char *conftype = NULL, *rewriteinalias = NULL;
2817 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2819 debug(DBG_DBG, "confserver_cb called for %s", block);
2821 conf = malloc(sizeof(struct clsrvconf));
2823 debug(DBG_ERR, "malloc failed");
2826 memset(conf, 0, sizeof(struct clsrvconf));
2827 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2828 resconf = (struct clsrvconf *)arg;
2830 conf->statusserver = resconf->statusserver;
2831 conf->certnamecheck = resconf->certnamecheck;
2833 conf->certnamecheck = 1;
2835 if (!getgenericconfig(cf, block,
2836 "type", CONF_STR, &conftype,
2837 "host", CONF_MSTR, &conf->hostsrc,
2838 "port", CONF_STR, &conf->portsrc,
2839 "secret", CONF_STR, &conf->secret,
2840 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2841 "tls", CONF_STR, &conf->tls,
2842 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2843 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2845 "addTTL", CONF_LINT, &addttl,
2846 "rewrite", CONF_STR, &rewriteinalias,
2847 "rewriteIn", CONF_STR, &conf->confrewritein,
2848 "rewriteOut", CONF_STR, &conf->confrewriteout,
2849 "StatusServer", CONF_BLN, &conf->statusserver,
2850 "RetryInterval", CONF_LINT, &retryinterval,
2851 "RetryCount", CONF_LINT, &retrycount,
2852 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2853 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2856 debug(DBG_ERR, "configuration error");
2860 conf->name = stringcopy(val, 0);
2861 if (conf->name && !conf->hostsrc) {
2862 conf->hostsrc = malloc(2 * sizeof(char *));
2863 if (conf->hostsrc) {
2864 conf->hostsrc[0] = stringcopy(val, 0);
2865 conf->hostsrc[1] = NULL;
2868 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2869 debug(DBG_ERR, "malloc failed");
2874 debug(DBG_ERR, "error in block %s, option type missing", block);
2877 conf->type = protoname2int(conftype);
2878 if (conf->type == 255) {
2879 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2885 conf->pdef = protodefs[conf->type];
2887 if (!conf->confrewritein)
2888 conf->confrewritein = rewriteinalias;
2890 free(rewriteinalias);
2891 rewriteinalias = NULL;
2893 if (retryinterval != LONG_MIN) {
2894 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2895 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2898 conf->retryinterval = (uint8_t)retryinterval;
2900 conf->retryinterval = 255;
2902 if (retrycount != LONG_MIN) {
2903 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2904 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2907 conf->retrycount = (uint8_t)retrycount;
2909 conf->retrycount = 255;
2911 if (addttl != LONG_MIN) {
2912 if (addttl < 1 || addttl > 255) {
2913 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2916 conf->addttl = (uint8_t)addttl;
2920 if (!mergesrvconf(resconf, conf))
2924 if (conf->dynamiclookupcommand) {
2925 free(conf->dynamiclookupcommand);
2926 conf->dynamiclookupcommand = NULL;
2930 if (resconf || !conf->dynamiclookupcommand) {
2931 if (!compileserverconfig(conf, block))
2935 if (!conf->secret) {
2936 if (!conf->pdef->secretdefault) {
2937 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2940 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2941 if (!conf->secret) {
2942 debug(DBG_ERR, "malloc failed");
2950 if (!list_push(srvconfs, conf)) {
2951 debug(DBG_ERR, "malloc failed");
2958 free(rewriteinalias);
2959 freeclsrvconf(conf);
2963 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2964 char **servers = NULL, **accservers = NULL, *msg = NULL;
2965 uint8_t accresp = 0;
2967 debug(DBG_DBG, "confrealm_cb called for %s", block);
2969 if (!getgenericconfig(cf, block,
2970 "server", CONF_MSTR, &servers,
2971 "accountingServer", CONF_MSTR, &accservers,
2972 "ReplyMessage", CONF_STR, &msg,
2973 "AccountingResponse", CONF_BLN, &accresp,
2976 debugx(1, DBG_ERR, "configuration error");
2978 addrealm(realms, val, servers, accservers, msg, accresp);
2982 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2983 char **rmattrs = NULL, **rmvattrs = NULL;
2984 char **addattrs = NULL, **addvattrs = NULL;
2985 char **modattrs = NULL;
2987 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2989 if (!getgenericconfig(cf, block,
2990 "removeAttribute", CONF_MSTR, &rmattrs,
2991 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2992 "addAttribute", CONF_MSTR, &addattrs,
2993 "addVendorAttribute", CONF_MSTR, &addvattrs,
2994 "modifyAttribute", CONF_MSTR, &modattrs,
2997 debugx(1, DBG_ERR, "configuration error");
2998 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
3002 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3003 struct commonprotoopts *protoopts;
3005 protoopts = malloc(sizeof(struct commonprotoopts));
3008 memset(protoopts, 0, sizeof(struct commonprotoopts));
3009 protoopts->listenargs = listenargs;
3010 protoopts->sourcearg = sourcearg;
3011 protodefs[type]->setprotoopts(protoopts);
3015 void getmainconfig(const char *configfile) {
3016 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3017 struct gconffile *cfs;
3018 char **listenargs[RAD_PROTOCOUNT];
3019 char *sourcearg[RAD_PROTOCOUNT];
3020 #if defined(WANT_FTICKS)
3021 uint8_t *fticks_reporting_str = NULL;
3022 uint8_t *fticks_mac_str = NULL;
3023 uint8_t *fticks_key_str = NULL;
3027 cfs = openconfigfile(configfile);
3028 memset(&options, 0, sizeof(options));
3029 memset(&listenargs, 0, sizeof(listenargs));
3030 memset(&sourcearg, 0, sizeof(sourcearg));
3032 clconfs = list_create();
3034 debugx(1, DBG_ERR, "malloc failed");
3036 srvconfs = list_create();
3038 debugx(1, DBG_ERR, "malloc failed");
3040 realms = list_create();
3042 debugx(1, DBG_ERR, "malloc failed");
3044 rewriteconfs = hash_create();
3046 debugx(1, DBG_ERR, "malloc failed");
3048 if (!getgenericconfig(
3051 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3052 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3055 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3056 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3059 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3060 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3063 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3064 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3066 "TTLAttribute", CONF_STR, &options.ttlattr,
3067 "addTTL", CONF_LINT, &addttl,
3068 "LogLevel", CONF_LINT, &loglevel,
3069 "LogDestination", CONF_STR, &options.logdestination,
3070 "LoopPrevention", CONF_BLN, &options.loopprevention,
3071 "Client", CONF_CBK, confclient_cb, NULL,
3072 "Server", CONF_CBK, confserver_cb, NULL,
3073 "Realm", CONF_CBK, confrealm_cb, NULL,
3074 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3075 "TLS", CONF_CBK, conftls_cb, NULL,
3077 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3078 #if defined(WANT_FTICKS)
3079 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3080 "FTicksMAC", CONF_STR, &fticks_mac_str,
3081 "FTicksKey", CONF_STR, &fticks_key_str,
3085 debugx(1, DBG_ERR, "configuration error");
3087 if (loglevel != LONG_MIN) {
3088 if (loglevel < 1 || loglevel > 5)
3089 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3090 options.loglevel = (uint8_t)loglevel;
3092 if (addttl != LONG_MIN) {
3093 if (addttl < 1 || addttl > 255)
3094 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3095 options.addttl = (uint8_t)addttl;
3097 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3098 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3100 #if defined(WANT_FTICKS)
3101 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3105 for (i = 0; i < RAD_PROTOCOUNT; i++)
3106 if (listenargs[i] || sourcearg[i])
3107 setprotoopts(i, listenargs[i], sourcearg[i]);
3110 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3113 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3116 *configfile = optarg;
3119 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3120 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3121 *loglevel = *optarg - '0';
3133 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3134 debug(DBG_ERR, "This binary was built with support for the following transports:");
3136 debug(DBG_ERR, " UDP");
3139 debug(DBG_ERR, " TCP");
3142 debug(DBG_ERR, " TLS");
3145 debug(DBG_ERR, " DTLS");
3152 if (!(argc - optind))
3156 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3160 int daemon(int a, int b) {
3168 for (i = 0; i < 3; i++) {
3170 open("/dev/null", O_RDWR);
3176 void *sighandler(void *arg) {
3181 sigemptyset(&sigset);
3182 sigaddset(&sigset, SIGHUP);
3183 sigaddset(&sigset, SIGPIPE);
3184 sigwait(&sigset, &sig);
3187 /* completely ignoring this */
3190 debug(DBG_INFO, "sighandler: got SIGHUP");
3194 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3197 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3202 int createpidfile(const char *pidfile) {
3204 FILE *f = fopen(pidfile, "w");
3206 r = fprintf(f, "%ld\n", (long) getpid());
3207 return f && !fclose(f) && r >= 0;
3210 int radsecproxy_main(int argc, char **argv) {
3213 struct list_node *entry;
3214 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3215 char *configfile = NULL, *pidfile = NULL;
3216 struct clsrvconf *srvconf;
3219 debug_init("radsecproxy");
3220 debug_set_level(DEBUG_LEVEL);
3222 for (i = 0; i < RAD_PROTOCOUNT; i++)
3223 protodefs[i] = protoinits[i](i);
3225 /* needed even if no TLS/DTLS transport */
3228 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3230 debug_set_level(loglevel);
3231 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3233 options.loglevel = loglevel;
3234 else if (options.loglevel)
3235 debug_set_level(options.loglevel);
3237 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3238 free(options.logdestination);
3240 if (!list_first(clconfs))
3241 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3242 if (!list_first(realms))
3243 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3246 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3248 if (!foreground && (daemon(0, 0) < 0))
3249 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3251 debug_timestamp_on();
3252 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3253 if (pidfile && !createpidfile(pidfile))
3254 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3256 sigemptyset(&sigset);
3257 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3258 sigaddset(&sigset, SIGHUP);
3259 sigaddset(&sigset, SIGPIPE);
3260 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3261 pthread_create(&sigth, NULL, sighandler, NULL);
3263 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3264 srvconf = (struct clsrvconf *)entry->data;
3265 if (srvconf->dynamiclookupcommand)
3267 if (!addserver(srvconf))
3268 debugx(1, DBG_ERR, "failed to add server");
3269 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3270 (void *)(srvconf->servers)))
3271 debugx(1, DBG_ERR, "pthread_create failed");
3274 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3277 if (protodefs[i]->initextra)
3278 protodefs[i]->initextra();
3279 if (find_clconf_type(i, NULL))
3283 /* just hang around doing nothing, anything to do here? */
3288 /* Local Variables: */
3289 /* c-file-style: "stroustrup" */