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>
12 * Maja Wolniewicz <mgw@umk.pl>
13 * Simon Leinen <simon.leinen@switch.ch>
14 * Stefan Winter <stefan.winter@restena.lu>
17 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
18 * rd is responsible for init and launching wr
19 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
20 * each tlsserverrd launches tlsserverwr
21 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
22 * for init and launching rd
24 * serverrd will receive a request, processes it and puts it in the requestq of
25 * the appropriate clientwr
26 * clientwr monitors its requestq and sends requests
27 * clientrd looks for responses, processes them and puts them in the replyq of
28 * the peer the request came from
29 * serverwr monitors its reply and sends replies
31 * In addition to the main thread, we have:
32 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
33 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
34 * For each TLS peer connecting to us there will be 2 more TLS threads
35 * This is only for connected peers
36 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
37 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
41 * May segfault when dtls connections go down? More testing needed
42 * Remove expired stuff from clients request list?
43 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
44 * Useful for TCP accounting? Now we require separate server config for alt port
48 #include <sys/socket.h>
49 #include <netinet/in.h>
58 #include <sys/types.h>
61 #include <arpa/inet.h>
66 #include <openssl/ssl.h>
67 #include <openssl/rand.h>
68 #include <openssl/err.h>
69 #include <openssl/md5.h>
75 #include "radsecproxy.h"
81 static struct options options;
82 static struct list *clconfs, *srvconfs;
83 static struct list *realms;
84 static struct hash *rewriteconfs;
86 static pthread_mutex_t *ssl_locks = NULL;
87 static long *ssl_lock_count;
90 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
102 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
104 uint8_t protoname2int(const char *name) {
107 for (i = 0; i < RAD_PROTOCOUNT; i++)
108 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
113 /* callbacks for making OpenSSL thread safe */
114 unsigned long ssl_thread_id() {
115 return (unsigned long)pthread_self();
118 void ssl_locking_callback(int mode, int type, const char *file, int line) {
119 if (mode & CRYPTO_LOCK) {
120 pthread_mutex_lock(&ssl_locks[type]);
121 ssl_lock_count[type]++;
123 pthread_mutex_unlock(&ssl_locks[type]);
126 /* returns 1 if the len first bits are equal, else 0 */
127 int prefixmatch(void *a1, void *a2, uint8_t len) {
128 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
129 uint8_t r, l = len / 8;
130 if (l && memcmp(a1, a2, l))
135 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
138 /* returns next config with matching address, or NULL */
139 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
140 struct list_node *entry;
141 struct clsrvconf *conf;
143 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
144 conf = (struct clsrvconf *)entry->data;
145 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
154 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
155 return find_conf(type, addr, clconfs, cur, 0);
158 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
159 return find_conf(type, addr, srvconfs, cur, 1);
162 /* returns next config of given type, or NULL */
163 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
164 struct list_node *entry;
165 struct clsrvconf *conf;
167 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
168 conf = (struct clsrvconf *)entry->data;
169 if (conf->type == type) {
178 struct gqueue *newqueue() {
181 q = malloc(sizeof(struct gqueue));
183 debugx(1, DBG_ERR, "malloc failed");
184 q->entries = list_create();
186 debugx(1, DBG_ERR, "malloc failed");
187 pthread_mutex_init(&q->mutex, NULL);
188 pthread_cond_init(&q->cond, NULL);
192 void removequeue(struct gqueue *q) {
193 struct list_node *entry;
197 pthread_mutex_lock(&q->mutex);
198 for (entry = list_first(q->entries); entry; entry = list_next(entry))
199 freerq((struct request *)entry);
200 list_destroy(q->entries);
201 pthread_cond_destroy(&q->cond);
202 pthread_mutex_unlock(&q->mutex);
203 pthread_mutex_destroy(&q->mutex);
207 void freebios(struct gqueue *q) {
210 pthread_mutex_lock(&q->mutex);
211 while ((bio = (BIO *)list_shift(q->entries)))
213 pthread_mutex_unlock(&q->mutex);
217 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
218 struct client *new = malloc(sizeof(struct client));
221 debug(DBG_ERR, "malloc failed");
226 pthread_mutex_lock(conf->lock);
227 if (!conf->clients) {
228 conf->clients = list_create();
229 if (!conf->clients) {
231 pthread_mutex_unlock(conf->lock);
232 debug(DBG_ERR, "malloc failed");
237 memset(new, 0, sizeof(struct client));
239 if (conf->pdef->addclient)
240 conf->pdef->addclient(new);
242 new->replyq = newqueue();
243 list_push(conf->clients, new);
245 pthread_mutex_unlock(conf->lock);
249 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
250 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
253 pthread_mutex_lock(&lock);
255 pthread_mutex_unlock(&lock);
258 void removeclientrqs(struct client *client) {
263 removeclientrqs_sendrq_freeserver_lock(1);
264 for (i = 0; i < MAX_REQUESTS; i++) {
269 rqout = rq->to->requests + rq->newid;
270 pthread_mutex_lock(rqout->lock);
271 if (rqout->rq == rq) /* still pointing to our request */
272 freerqoutdata(rqout);
273 pthread_mutex_unlock(rqout->lock);
277 removeclientrqs_sendrq_freeserver_lock(0);
280 void removelockedclient(struct client *client) {
281 struct clsrvconf *conf;
285 removeclientrqs(client);
286 removequeue(client->replyq);
287 list_removedata(conf->clients, client);
293 void removeclient(struct client *client) {
294 struct clsrvconf *conf;
300 pthread_mutex_lock(conf->lock);
301 removelockedclient(client);
302 pthread_mutex_unlock(conf->lock);
305 void freeserver(struct server *server, uint8_t destroymutex) {
306 struct rqout *rqout, *end;
311 removeclientrqs_sendrq_freeserver_lock(1);
312 if (server->requests) {
313 rqout = server->requests;
314 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
316 rqout->rq->to = NULL;
317 freerqoutdata(rqout);
318 pthread_mutex_destroy(rqout->lock);
321 free(server->requests);
324 freebios(server->rbios);
325 free(server->dynamiclookuparg);
327 SSL_free(server->ssl);
329 pthread_mutex_destroy(&server->lock);
330 pthread_cond_destroy(&server->newrq_cond);
331 pthread_mutex_destroy(&server->newrq_mutex);
333 removeclientrqs_sendrq_freeserver_lock(0);
337 int addserver(struct clsrvconf *conf) {
341 debug(DBG_ERR, "addserver: currently works with just one server per conf");
344 conf->servers = malloc(sizeof(struct server));
345 if (!conf->servers) {
346 debug(DBG_ERR, "malloc failed");
349 memset(conf->servers, 0, sizeof(struct server));
350 conf->servers->conf = conf;
353 if (conf->type == RAD_DTLS)
354 conf->servers->rbios = newqueue();
356 conf->pdef->setsrcres();
358 conf->servers->sock = -1;
359 if (conf->pdef->addserverextra)
360 conf->pdef->addserverextra(conf);
362 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
363 if (!conf->servers->requests) {
364 debug(DBG_ERR, "malloc failed");
367 for (i = 0; i < MAX_REQUESTS; i++) {
368 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
369 if (!conf->servers->requests[i].lock) {
370 debug(DBG_ERR, "malloc failed");
373 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
374 debugerrno(errno, DBG_ERR, "mutex init failed");
375 free(conf->servers->requests[i].lock);
376 conf->servers->requests[i].lock = NULL;
380 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
381 debugerrno(errno, DBG_ERR, "mutex init failed");
384 conf->servers->newrq = 0;
385 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
386 debugerrno(errno, DBG_ERR, "mutex init failed");
387 pthread_mutex_destroy(&conf->servers->lock);
390 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
391 debugerrno(errno, DBG_ERR, "mutex init failed");
392 pthread_mutex_destroy(&conf->servers->newrq_mutex);
393 pthread_mutex_destroy(&conf->servers->lock);
400 freeserver(conf->servers, 0);
401 conf->servers = NULL;
405 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
407 if (ATTRTYPE(attrs) == type)
409 length -= ATTRLEN(attrs);
410 attrs += ATTRLEN(attrs);
415 struct request *newrqref(struct request *rq) {
421 void freerq(struct request *rq) {
424 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
427 if (rq->origusername)
428 free(rq->origusername);
434 radmsg_free(rq->msg);
438 void freerqoutdata(struct rqout *rqout) {
442 if (rqout->rq->buf) {
443 free(rqout->rq->buf);
444 rqout->rq->buf = NULL;
450 memset(&rqout->expiry, 0, sizeof(struct timeval));
453 void sendrq(struct request *rq) {
457 removeclientrqs_sendrq_freeserver_lock(1);
462 start = to->conf->statusserver ? 1 : 0;
463 pthread_mutex_lock(&to->newrq_mutex);
464 if (start && rq->msg->code == RAD_Status_Server) {
465 pthread_mutex_lock(to->requests[0].lock);
466 if (to->requests[0].rq) {
467 pthread_mutex_unlock(to->requests[0].lock);
468 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
475 /* might simplify if only try nextid, might be ok */
476 for (i = to->nextid; i < MAX_REQUESTS; i++) {
477 if (!to->requests[i].rq) {
478 pthread_mutex_lock(to->requests[i].lock);
479 if (!to->requests[i].rq)
481 pthread_mutex_unlock(to->requests[i].lock);
484 if (i == MAX_REQUESTS) {
485 for (i = start; i < to->nextid; i++) {
486 if (!to->requests[i].rq) {
487 pthread_mutex_lock(to->requests[i].lock);
488 if (!to->requests[i].rq)
490 pthread_mutex_unlock(to->requests[i].lock);
493 if (i == to->nextid) {
494 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
499 rq->newid = (uint8_t)i;
500 rq->msg->id = (uint8_t)i;
501 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
503 pthread_mutex_unlock(to->requests[i].lock);
504 debug(DBG_ERR, "sendrq: radmsg2buf failed");
508 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
509 to->requests[i].rq = rq;
510 pthread_mutex_unlock(to->requests[i].lock);
511 if (i >= start) /* i is not reserved for statusserver */
516 debug(DBG_DBG, "sendrq: signalling client writer");
517 pthread_cond_signal(&to->newrq_cond);
520 pthread_mutex_unlock(&to->newrq_mutex);
521 removeclientrqs_sendrq_freeserver_lock(0);
526 rmclientrq(rq, rq->msg->id);
528 pthread_mutex_unlock(&to->newrq_mutex);
529 removeclientrqs_sendrq_freeserver_lock(0);
532 void sendreply(struct request *rq) {
534 struct client *to = rq->from;
537 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
538 radmsg_free(rq->msg);
542 debug(DBG_ERR, "sendreply: radmsg2buf failed");
546 pthread_mutex_lock(&to->replyq->mutex);
547 first = list_first(to->replyq->entries) == NULL;
549 if (!list_push(to->replyq->entries, rq)) {
550 pthread_mutex_unlock(&to->replyq->mutex);
552 debug(DBG_ERR, "sendreply: malloc failed");
557 debug(DBG_DBG, "signalling server writer");
558 pthread_cond_signal(&to->replyq->cond);
560 pthread_mutex_unlock(&to->replyq->mutex);
563 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
564 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
565 static unsigned char first = 1;
566 static EVP_MD_CTX mdctx;
567 unsigned char hash[EVP_MAX_MD_SIZE], *input;
569 uint8_t i, offset = 0, out[128];
571 pthread_mutex_lock(&lock);
573 EVP_MD_CTX_init(&mdctx);
579 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
580 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
581 !EVP_DigestUpdate(&mdctx, input, 16) ||
582 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
584 pthread_mutex_unlock(&lock);
587 for (i = 0; i < 16; i++)
588 out[offset + i] = hash[i] ^ in[offset + i];
590 input = out + offset;
597 memcpy(in, out, len);
598 pthread_mutex_unlock(&lock);
602 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
603 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
604 static unsigned char first = 1;
605 static EVP_MD_CTX mdctx;
606 unsigned char hash[EVP_MAX_MD_SIZE];
610 pthread_mutex_lock(&lock);
612 EVP_MD_CTX_init(&mdctx);
617 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
618 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
619 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
622 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
623 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
624 !EVP_DigestUpdate(&mdctx, auth, 16) ||
625 !EVP_DigestUpdate(&mdctx, salt, 2) ||
626 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
627 pthread_mutex_unlock(&lock);
632 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
635 for (i = 0; i < 16; i++)
638 for (offset = 16; offset < len; offset += 16) {
640 printf("text + offset - 16 c(%d): ", offset / 16);
641 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
643 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
644 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
645 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
646 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
648 pthread_mutex_unlock(&lock);
652 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
655 for (i = 0; i < 16; i++)
656 text[offset + i] ^= hash[i];
660 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
663 pthread_mutex_unlock(&lock);
667 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
668 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
669 static unsigned char first = 1;
670 static EVP_MD_CTX mdctx;
671 unsigned char hash[EVP_MAX_MD_SIZE];
676 pthread_mutex_lock(&lock);
678 EVP_MD_CTX_init(&mdctx);
683 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
684 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
685 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
688 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
689 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
690 !EVP_DigestUpdate(&mdctx, auth, 16) ||
691 !EVP_DigestUpdate(&mdctx, salt, 2) ||
692 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
693 pthread_mutex_unlock(&lock);
698 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
701 for (i = 0; i < 16; i++)
702 plain[i] = text[i] ^ hash[i];
704 for (offset = 16; offset < len; offset += 16) {
706 printf("text + offset - 16 c(%d): ", offset / 16);
707 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
709 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
710 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
711 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
712 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
714 pthread_mutex_unlock(&lock);
718 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
721 for (i = 0; i < 16; i++)
722 plain[offset + i] = text[offset + i] ^ hash[i];
725 memcpy(text, plain, len);
727 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
730 pthread_mutex_unlock(&lock);
734 struct realm *newrealmref(struct realm *r) {
740 /* returns with lock on realm */
741 struct realm *id2realm(struct list *realmlist, char *id) {
742 struct list_node *entry;
743 struct realm *realm, *subrealm;
745 /* need to do locking for subrealms and check subrealm timers */
746 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
747 realm = (struct realm *)entry->data;
748 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
749 pthread_mutex_lock(&realm->mutex);
750 if (realm->subrealms) {
751 subrealm = id2realm(realm->subrealms, id);
753 pthread_mutex_unlock(&realm->mutex);
757 return newrealmref(realm);
763 int hasdynamicserver(struct list *srvconfs) {
764 struct list_node *entry;
766 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
767 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
772 /* helper function, only used by removeserversubrealms() */
773 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
774 struct list_node *entry, *entry2;
777 for (entry = list_first(realmlist); entry;) {
778 realm = newrealmref((struct realm *)entry->data);
779 pthread_mutex_lock(&realm->mutex);
780 entry = list_next(entry);
782 if (realm->srvconfs) {
783 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
784 if (entry2->data == srv)
786 list_removedata(realm->srvconfs, srv);
788 if (realm->accsrvconfs) {
789 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
790 if (entry2->data == srv)
792 list_removedata(realm->accsrvconfs, srv);
795 /* remove subrealm if no dynamic servers left */
796 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
797 while (list_shift(realm->srvconfs))
799 list_destroy(realm->srvconfs);
800 realm->srvconfs = NULL;
801 while (list_shift(realm->accsrvconfs))
803 list_destroy(realm->accsrvconfs);
804 realm->accsrvconfs = NULL;
805 list_removedata(realmlist, realm);
807 pthread_mutex_unlock(&realm->mutex);
812 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
813 struct list_node *entry;
816 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
817 realm = (struct realm *)entry->data;
818 pthread_mutex_lock(&realm->mutex);
819 if (realm->subrealms) {
820 _internal_removeserversubrealms(realm->subrealms, srv);
821 if (!list_first(realm->subrealms)) {
822 list_destroy(realm->subrealms);
823 realm->subrealms = NULL;
826 pthread_mutex_unlock(&realm->mutex);
830 int attrvalidate(unsigned char *attrs, int length) {
832 if (ATTRLEN(attrs) < 2) {
833 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
836 length -= ATTRLEN(attrs);
838 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
841 attrs += ATTRLEN(attrs);
844 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
848 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
849 if (len < 16 || len > 128 || len % 16) {
850 debug(DBG_WARN, "pwdrecrypt: invalid password length");
854 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
855 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
859 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
861 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
862 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
868 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
871 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
872 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
875 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
876 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
882 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
883 char *oldsecret, char *newsecret) {
886 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
887 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
888 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
894 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
898 for (; attrs[0]; attrs += 2)
899 if (attrs[0] == vendor && attrs[1] == subattr)
904 /* returns 1 if entire element is to be removed, else 0 */
905 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
906 uint8_t alen, sublen;
910 if (!removevendorattrs)
913 memcpy(&vendor, attr->v, 4);
914 vendor = ntohl(vendor);
915 while (*removevendorattrs && *removevendorattrs != vendor)
916 removevendorattrs += 2;
917 if (!*removevendorattrs)
920 if (findvendorsubattr(removevendorattrs, vendor, 256))
921 return 1; /* remove entire vendor attribute */
923 sublen = attr->l - 4;
924 subattrs = attr->v + 4;
926 if (!attrvalidate(subattrs, sublen)) {
927 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
932 alen = ATTRLEN(subattrs);
934 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
935 memmove(subattrs, subattrs + alen, sublen);
943 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
944 struct list_node *n, *p;
948 n = list_first(msg->attrs);
950 attr = (struct tlv *)n->data;
951 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
952 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
953 list_removedata(msg->attrs, attr);
955 n = p ? list_next(p) : list_first(msg->attrs);
963 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
967 for (n = list_first(addattrs); n; n = list_next(n)) {
968 a = copytlv((struct tlv *)n->data);
971 if (!radmsg_add(msg, a)) {
979 int resizeattr(struct tlv *attr, uint8_t newlen) {
982 if (newlen != attr->l) {
983 newv = realloc(attr->v, newlen);
992 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
993 size_t nmatch = 10, reslen = 0, start = 0;
994 regmatch_t pmatch[10], *pfield;
998 in = stringcopy((char *)attr->v, attr->l);
1002 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1007 out = modattr->replacement;
1009 for (i = start; out[i]; i++) {
1010 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1011 pfield = &pmatch[out[i + 1] - '0'];
1012 if (pfield->rm_so >= 0) {
1013 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1019 reslen += i - start;
1021 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1026 if (!resizeattr(attr, reslen)) {
1033 for (i = start; out[i]; i++) {
1034 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1035 pfield = &pmatch[out[i + 1] - '0'];
1036 if (pfield->rm_so >= 0) {
1037 memcpy(attr->v + reslen, out + start, i - start);
1038 reslen += i - start;
1039 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1040 reslen += pfield->rm_eo - pfield->rm_so;
1047 memcpy(attr->v + reslen, out + start, i - start);
1051 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1052 struct list_node *n, *m;
1054 for (n = list_first(msg->attrs); n; n = list_next(n))
1055 for (m = list_first(modattrs); m; m = list_next(m))
1056 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1057 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1062 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1063 int rv = 1; /* Success. */
1066 if (rewrite->removeattrs || rewrite->removevendorattrs)
1067 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1068 if (rewrite->modattrs)
1069 if (!dorewritemod(msg, rewrite->modattrs))
1071 if (rewrite->addattrs)
1072 if (!dorewriteadd(msg, rewrite->addattrs))
1078 int rewriteusername(struct request *rq, struct tlv *attr) {
1079 char *orig = (char *)tlv2str(attr);
1080 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1084 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1085 rq->origusername = (char *)orig;
1091 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1092 * all is well with the new tlv, i.e. if the function returns
1095 makevendortlv(uint32_t vendor, struct tlv *attr)
1097 struct tlv *newtlv = NULL;
1105 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1106 memcpy(v, &vendor, 4);
1107 tlv2buf(v + 4, attr);
1108 v[5] += 2; /* Vendor length increased for type and length fields. */
1109 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1118 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1120 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1123 vattr = makevendortlv(vendor, attr);
1128 if (!radmsg_add(msg, vattr)) {
1135 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1142 if (attrtype[1] == 256) { /* not vendor */
1143 attr = maketlv(attrtype[0], 4, ttl);
1144 if (attr && !radmsg_add(msg, attr))
1147 attr = maketlv(attrtype[1], 4, ttl);
1149 addvendorattr(msg, attrtype[0], attr);
1153 int decttl(uint8_t l, uint8_t *v) {
1160 while (i >= 0 && !v[i])
1164 for (i--; i >= 0 && !v[i]; i--);
1173 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1174 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1175 uint8_t alen, *subattrs;
1177 struct list_node *node;
1181 if (attrtype[1] == 256) { /* not vendor */
1182 attr = radmsg_gettype(msg, attrtype[0]);
1184 return decttl(attr->l, attr->v);
1186 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1187 attr = (struct tlv *)node->data;
1188 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1190 memcpy(&vendor, attr->v, 4);
1191 if (ntohl(vendor) != attrtype[0])
1193 sublen = attr->l - 4;
1194 subattrs = attr->v + 4;
1195 if (!attrvalidate(subattrs, sublen))
1197 while (sublen > 1) {
1198 if (ATTRTYPE(subattrs) == attrtype[1])
1199 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1200 alen = ATTRLEN(subattrs);
1208 const char *radmsgtype2string(uint8_t code) {
1209 static const char *rad_msg_names[] = {
1210 "", "Access-Request", "Access-Accept", "Access-Reject",
1211 "Accounting-Request", "Accounting-Response", "", "",
1212 "", "", "", "Access-Challenge",
1213 "Status-Server", "Status-Client"
1215 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1218 void char2hex(char *h, unsigned char c) {
1219 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1220 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1221 h[0] = hexdigits[c / 16];
1222 h[1] = hexdigits[c % 16];
1226 uint8_t *radattr2ascii(struct tlv *attr) {
1234 for (i = 0; i < attr->l; i++)
1235 if (attr->v[i] < 32 || attr->v[i] > 126)
1238 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1245 for (i = 0; i < attr->l; i++)
1246 if (attr->v[i] < 32 || attr->v[i] > 126) {
1248 char2hex((char *)d, attr->v[i]);
1256 void acclog(struct radmsg *msg, struct client *from) {
1260 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1262 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1265 username = radattr2ascii(attr);
1267 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1273 void respond(struct request *rq, uint8_t code, char *message) {
1277 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1279 debug(DBG_ERR, "respond: malloc failed");
1282 if (message && *message) {
1283 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1284 if (!attr || !radmsg_add(msg, attr)) {
1287 debug(DBG_ERR, "respond: malloc failed");
1292 radmsg_free(rq->msg);
1294 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1295 sendreply(newrqref(rq));
1298 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1299 struct list_node *entry;
1300 struct clsrvconf *server, *best = NULL, *first = NULL;
1302 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1303 server = (struct clsrvconf *)entry->data;
1304 if (!server->servers)
1308 if (!server->servers->connectionok && !server->servers->dynstartup)
1310 if (!server->servers->lostrqs)
1316 if (server->servers->lostrqs < best->servers->lostrqs)
1319 return best ? best : first;
1322 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1323 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1324 struct clsrvconf *srvconf;
1325 struct realm *subrealm;
1326 struct server *server = NULL;
1327 char *id = (char *)tlv2str(username);
1331 /* returns with lock on realm */
1332 *realm = id2realm(realms, id);
1335 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1336 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1337 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1338 subrealm = adddynamicrealmserver(*realm, id);
1340 pthread_mutex_lock(&subrealm->mutex);
1341 pthread_mutex_unlock(&(*realm)->mutex);
1344 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1348 server = srvconf->servers;
1356 struct request *newrequest() {
1359 rq = malloc(sizeof(struct request));
1361 debug(DBG_ERR, "newrequest: malloc failed");
1364 memset(rq, 0, sizeof(struct request));
1366 gettimeofday(&rq->created, NULL);
1370 int addclientrq(struct request *rq) {
1374 r = rq->from->rqs[rq->rqid];
1376 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1377 gettimeofday(&now, NULL);
1378 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1380 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1381 sendreply(newrqref(r));
1383 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1389 rq->from->rqs[rq->rqid] = newrqref(rq);
1393 void rmclientrq(struct request *rq, uint8_t id) {
1396 r = rq->from->rqs[id];
1399 rq->from->rqs[id] = NULL;
1403 /* returns 0 if validation/authentication fails, else 1 */
1404 int radsrv(struct request *rq) {
1405 struct radmsg *msg = NULL;
1407 uint8_t *userascii = NULL;
1408 struct realm *realm = NULL;
1409 struct server *to = NULL;
1410 struct client *from = rq->from;
1413 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1418 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1425 memcpy(rq->rqauth, msg->auth, 16);
1427 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1428 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1429 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1433 if (!addclientrq(rq))
1436 if (msg->code == RAD_Status_Server) {
1437 respond(rq, RAD_Access_Accept, NULL);
1441 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1443 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1446 ttlres = checkttl(msg, options.ttlattrtype);
1448 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1452 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1454 if (msg->code == RAD_Accounting_Request) {
1456 respond(rq, RAD_Accounting_Response, NULL);
1458 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1462 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1463 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1467 userascii = radattr2ascii(attr);
1470 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1472 /* will return with lock on the realm */
1473 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1475 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1480 if (realm->message && msg->code == RAD_Access_Request) {
1481 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1482 respond(rq, RAD_Access_Reject, realm->message);
1483 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1485 respond(rq, RAD_Accounting_Response, NULL);
1490 if ((to->conf->loopprevention == 1
1491 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1492 && !strcmp(from->conf->name, to->conf->name)) {
1493 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1494 from->conf->name, addr2string(from->addr), to->conf->name);
1498 if (msg->code == RAD_Accounting_Request)
1499 memset(msg->auth, 0, 16);
1500 else if (!RAND_bytes(msg->auth, 16)) {
1501 debug(DBG_WARN, "radsrv: failed to generate random auth");
1506 printfchars(NULL, "auth", "%02x ", auth, 16);
1509 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1511 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1512 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1516 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1518 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1519 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1523 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1526 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1527 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1532 pthread_mutex_unlock(&realm->mutex);
1537 rmclientrq(rq, msg->id);
1542 pthread_mutex_unlock(&realm->mutex);
1548 void replyh(struct server *server, unsigned char *buf) {
1549 struct client *from;
1550 struct rqout *rqout;
1552 unsigned char *subattrs;
1553 uint8_t *username, *stationid, *replymsg;
1554 struct radmsg *msg = NULL;
1556 struct list_node *node;
1558 server->connectionok = 1;
1559 server->lostrqs = 0;
1561 rqout = server->requests + buf[1];
1562 pthread_mutex_lock(rqout->lock);
1563 if (!rqout->tries) {
1566 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1570 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1574 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1577 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1578 && msg->code != RAD_Accounting_Response) {
1579 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1582 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1584 gettimeofday(&server->lastrcv, NULL);
1586 if (rqout->rq->msg->code == RAD_Status_Server) {
1587 freerqoutdata(rqout);
1588 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1592 gettimeofday(&server->lastreply, NULL);
1593 from = rqout->rq->from;
1595 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1596 debug(DBG_INFO, "replyh: rewritein failed");
1600 ttlres = checkttl(msg, options.ttlattrtype);
1602 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1607 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1608 attr = (struct tlv *)node->data;
1609 if (attr->t != RAD_Attr_Vendor_Specific)
1613 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1616 sublen = attr->l - 4;
1617 subattrs = attr->v + 4;
1618 if (!attrvalidate(subattrs, sublen) ||
1619 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1620 rqout->rq, server->conf->secret, from->conf->secret) ||
1621 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1622 rqout->rq, server->conf->secret, from->conf->secret))
1626 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1630 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1631 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1633 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1634 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1638 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1639 radmsgtype2string(msg->code), username, stationid,
1640 server->conf->name, replymsg, from->conf->name,
1641 addr2string(from->addr));
1645 "%s for user %s stationid %s from %s to %s (%s)",
1646 radmsgtype2string(msg->code), username, stationid,
1647 server->conf->name, from->conf->name,
1648 addr2string(from->addr));
1652 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1653 radmsgtype2string(msg->code), username,
1654 server->conf->name, replymsg, from->conf->name,
1655 addr2string(from->addr));
1658 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1659 radmsgtype2string(msg->code), username,
1660 server->conf->name, from->conf->name,
1661 addr2string(from->addr));
1667 msg->id = (char)rqout->rq->rqid;
1668 memcpy(msg->auth, rqout->rq->rqauth, 16);
1671 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1674 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1675 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1676 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1679 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1682 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1683 debug(DBG_WARN, "replyh: rewriteout failed");
1687 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1688 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1690 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1691 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1693 radmsg_free(rqout->rq->msg);
1694 rqout->rq->msg = msg;
1695 sendreply(newrqref(rqout->rq));
1696 freerqoutdata(rqout);
1697 pthread_mutex_unlock(rqout->lock);
1702 pthread_mutex_unlock(rqout->lock);
1706 struct request *createstatsrvrq() {
1713 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1716 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1719 if (!radmsg_add(rq->msg, attr)) {
1730 /* code for removing state not finished */
1731 void *clientwr(void *arg) {
1732 struct server *server = (struct server *)arg;
1733 struct rqout *rqout = NULL;
1734 pthread_t clientrdth;
1735 int i, dynconffail = 0;
1738 struct timeval now, laststatsrv;
1739 struct timespec timeout;
1740 struct request *statsrvrq;
1741 struct clsrvconf *conf;
1743 conf = server->conf;
1745 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1747 server->dynstartup = 0;
1752 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1753 debug(DBG_WARN, "clientwr: resolve failed");
1754 server->dynstartup = 0;
1759 memset(&timeout, 0, sizeof(struct timespec));
1761 if (conf->statusserver) {
1762 gettimeofday(&server->lastrcv, NULL);
1763 gettimeofday(&laststatsrv, NULL);
1766 if (conf->pdef->connecter) {
1767 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1768 if (server->dynamiclookuparg) {
1769 server->dynstartup = 0;
1774 server->connectionok = 1;
1775 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1776 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1780 server->connectionok = 1;
1781 server->dynstartup = 0;
1784 pthread_mutex_lock(&server->newrq_mutex);
1785 if (!server->newrq) {
1786 gettimeofday(&now, NULL);
1787 /* random 0-7 seconds */
1788 RAND_bytes(&rnd, 1);
1790 if (conf->statusserver) {
1791 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1792 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1794 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1795 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1797 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1798 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1801 if (timeout.tv_sec > now.tv_sec)
1802 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1804 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1807 if (server->newrq) {
1808 debug(DBG_DBG, "clientwr: got new request");
1813 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1815 pthread_mutex_unlock(&server->newrq_mutex);
1817 for (i = 0; i < MAX_REQUESTS; i++) {
1818 if (server->clientrdgone) {
1819 pthread_join(clientrdth, NULL);
1823 for (; i < MAX_REQUESTS; i++) {
1824 rqout = server->requests + i;
1826 pthread_mutex_lock(rqout->lock);
1829 pthread_mutex_unlock(rqout->lock);
1833 if (i == MAX_REQUESTS)
1836 gettimeofday(&now, NULL);
1837 if (now.tv_sec < rqout->expiry.tv_sec) {
1838 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1839 timeout.tv_sec = rqout->expiry.tv_sec;
1840 pthread_mutex_unlock(rqout->lock);
1844 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1845 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1846 if (conf->statusserver) {
1847 if (*rqout->rq->buf == RAD_Status_Server) {
1848 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1849 if (server->lostrqs < 255)
1853 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1854 if (server->lostrqs < 255)
1857 freerqoutdata(rqout);
1858 pthread_mutex_unlock(rqout->lock);
1862 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1863 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1864 timeout.tv_sec = rqout->expiry.tv_sec;
1866 conf->pdef->clientradput(server, rqout->rq->buf);
1867 pthread_mutex_unlock(rqout->lock);
1869 if (conf->statusserver && server->connectionok) {
1870 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1871 gettimeofday(&now, NULL);
1872 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1874 statsrvrq = createstatsrvrq();
1876 statsrvrq->to = server;
1877 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1884 conf->servers = NULL;
1885 if (server->dynamiclookuparg) {
1886 removeserversubrealms(realms, conf);
1890 freeclsrvconf(conf);
1892 freeserver(server, 1);
1893 ERR_remove_state(0);
1897 void createlistener(uint8_t type, char *arg) {
1899 struct addrinfo *res;
1900 int s = -1, on = 1, *sp = NULL;
1901 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1903 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1904 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1906 for (res = hp->addrinfo; res; res = res->ai_next) {
1907 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1909 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1912 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1914 disable_DF_bit(s, res);
1917 if (res->ai_family == AF_INET6)
1918 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1920 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1921 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1927 sp = malloc(sizeof(int));
1929 debugx(1, DBG_ERR, "malloc failed");
1931 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1932 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1936 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1938 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1942 void createlisteners(uint8_t type) {
1946 args = protodefs[type]->getlistenerargs();
1948 for (i = 0; args[i]; i++)
1949 createlistener(type, args[i]);
1951 createlistener(type, NULL);
1959 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1960 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1961 for (i = 0; i < CRYPTO_num_locks(); i++) {
1962 ssl_lock_count[i] = 0;
1963 pthread_mutex_init(&ssl_locks[i], NULL);
1965 CRYPTO_set_id_callback(ssl_thread_id);
1966 CRYPTO_set_locking_callback(ssl_locking_callback);
1968 SSL_load_error_strings();
1971 while (!RAND_status()) {
1974 RAND_seed((unsigned char *)&t, sizeof(time_t));
1975 RAND_seed((unsigned char *)&pid, sizeof(pid));
1979 struct list *addsrvconfs(char *value, char **names) {
1980 struct list *conflist;
1982 struct list_node *entry;
1983 struct clsrvconf *conf = NULL;
1985 if (!names || !*names)
1988 conflist = list_create();
1990 debug(DBG_ERR, "malloc failed");
1994 for (n = 0; names[n]; n++) {
1995 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1996 conf = (struct clsrvconf *)entry->data;
1997 if (!strcasecmp(names[n], conf->name))
2001 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2002 list_destroy(conflist);
2005 if (!list_push(conflist, conf)) {
2006 debug(DBG_ERR, "malloc failed");
2007 list_destroy(conflist);
2010 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2015 void freerealm(struct realm *realm) {
2018 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2019 if (--realm->refcount)
2023 free(realm->message);
2024 regfree(&realm->regex);
2025 pthread_mutex_destroy(&realm->mutex);
2026 /* if refcount == 0, all subrealms gone */
2027 list_destroy(realm->subrealms);
2028 /* if refcount == 0, all srvconfs gone */
2029 list_destroy(realm->srvconfs);
2030 /* if refcount == 0, all accsrvconfs gone */
2031 list_destroy(realm->accsrvconfs);
2032 freerealm(realm->parent);
2036 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2038 struct realm *realm;
2039 char *s, *regex = NULL;
2041 if (*value == '/') {
2042 /* regexp, remove optional trailing / if present */
2043 if (value[strlen(value) - 1] == '/')
2044 value[strlen(value) - 1] = '\0';
2046 /* not a regexp, let us make it one */
2047 if (*value == '*' && !value[1])
2048 regex = stringcopy(".*", 0);
2050 for (n = 0, s = value; *s;)
2053 regex = malloc(strlen(value) + n + 3);
2056 for (n = 1, s = value; *s; s++) {
2066 debug(DBG_ERR, "malloc failed");
2070 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2073 realm = malloc(sizeof(struct realm));
2075 debug(DBG_ERR, "malloc failed");
2078 memset(realm, 0, sizeof(struct realm));
2080 if (pthread_mutex_init(&realm->mutex, NULL)) {
2081 debugerrno(errno, DBG_ERR, "mutex init failed");
2087 realm->name = stringcopy(value, 0);
2089 debug(DBG_ERR, "malloc failed");
2092 if (message && strlen(message) > 253) {
2093 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2096 realm->message = message;
2097 realm->accresp = accresp;
2099 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2100 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2104 if (servers && *servers) {
2105 realm->srvconfs = addsrvconfs(value, servers);
2106 if (!realm->srvconfs)
2110 if (accservers && *accservers) {
2111 realm->accsrvconfs = addsrvconfs(value, accservers);
2112 if (!realm->accsrvconfs)
2116 if (!list_push(realmlist, realm)) {
2117 debug(DBG_ERR, "malloc failed");
2118 pthread_mutex_destroy(&realm->mutex);
2122 debug(DBG_DBG, "addrealm: added realm %s", value);
2126 while (list_shift(realm->srvconfs));
2127 while (list_shift(realm->accsrvconfs));
2134 for (n = 0; servers[n]; n++)
2136 freegconfmstr(servers);
2140 for (n = 0; accservers[n]; n++)
2142 freegconfmstr(accservers);
2144 return newrealmref(realm);
2147 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2148 struct list_node *entry;
2149 struct clsrvconf *conf, *srvconf;
2150 struct list *subrealmservers = NULL;
2153 if (list_first(srvconfs)) {
2154 subrealmservers = list_create();
2155 if (!subrealmservers)
2159 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2160 conf = (struct clsrvconf *)entry->data;
2161 if (!conf->servers && conf->dynamiclookupcommand) {
2162 srvconf = malloc(sizeof(struct clsrvconf));
2164 debug(DBG_ERR, "malloc failed");
2168 if (addserver(srvconf)) {
2169 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2170 srvconf->servers->dynstartup = 1;
2171 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2172 debugerrno(errno, DBG_ERR, "pthread_create failed");
2173 freeserver(srvconf->servers, 1);
2174 srvconf->servers = NULL;
2176 pthread_detach(clientth);
2180 if (conf->servers) {
2181 if (list_push(subrealmservers, conf))
2184 debug(DBG_ERR, "malloc failed");
2187 return subrealmservers;
2190 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2191 struct realm *newrealm = NULL;
2192 char *realmname, *s;
2194 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2195 realmname = strrchr(id, '@');
2201 for (s = realmname; *s; s++)
2202 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2205 if (!realm->subrealms)
2206 realm->subrealms = list_create();
2207 if (!realm->subrealms)
2210 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2212 list_destroy(realm->subrealms);
2213 realm->subrealms = NULL;
2217 newrealm->parent = newrealmref(realm);
2218 /* add server and accserver to newrealm */
2219 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2220 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2224 int dynamicconfig(struct server *server) {
2225 int ok, fd[2], status;
2227 struct clsrvconf *conf = server->conf;
2228 struct gconffile *cf = NULL;
2230 /* for now we only learn hostname/address */
2231 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2234 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2239 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2243 } else if (pid == 0) {
2246 if (fd[1] != STDOUT_FILENO) {
2247 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2248 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2251 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2252 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2256 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2257 ok = getgenericconfig(&cf, NULL,
2258 "Server", CONF_CBK, confserver_cb, (void *)conf,
2263 if (waitpid(pid, &status, 0) < 0) {
2264 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2269 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2277 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2281 /* should accept both names and numeric values, only numeric right now */
2282 uint8_t attrname2val(char *attrname) {
2285 val = atoi(attrname);
2286 return val > 0 && val < 256 ? val : 0;
2289 /* ATTRNAME is on the form vendor[:type].
2290 If only vendor is found, TYPE is set to 256 and 1 is returned.
2291 If type is >= 256, 1 is returned.
2292 Otherwise, 0 is returned.
2294 /* should accept both names and numeric values, only numeric right now */
2295 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2298 *vendor = atoi(attrname);
2299 s = strchr(attrname, ':');
2300 if (!s) { /* Only vendor was found. */
2304 *type = atoi(s + 1);
2308 /** Extract attributes from string NAMEVAL, create a struct tlv and
2309 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2310 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2311 * NULL if fields are missing or if conversion fails.
2313 * FIXME: Should accept both names and numeric values, only numeric
2315 struct tlv *extractattr(char *nameval, char vendor_flag) {
2317 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2321 s = strchr(nameval, ':');
2324 name = atoi(nameval);
2327 s2 = strchr(s + 1, ':');
2334 len = strlen(s + 1);
2338 if (name < 1 || name > 255)
2340 a = malloc(sizeof(struct tlv));
2344 a->v = (uint8_t *)stringcopy(s + 1, 0);
2353 a = makevendortlv(vendor, a);
2358 /* should accept both names and numeric values, only numeric right now */
2359 struct modattr *extractmodattr(char *nameval) {
2364 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2368 s = strchr(nameval, ':');
2369 name = atoi(nameval);
2370 if (!s || name < 1 || name > 255 || s[1] != '/')
2374 /* regexp, remove optional trailing / if present */
2375 if (s[strlen(s) - 1] == '/')
2376 s[strlen(s) - 1] = '\0';
2384 m = malloc(sizeof(struct modattr));
2386 debug(DBG_ERR, "malloc failed");
2391 m->replacement = stringcopy(t, 0);
2392 if (!m->replacement) {
2394 debug(DBG_ERR, "malloc failed");
2398 m->regex = malloc(sizeof(regex_t));
2400 free(m->replacement);
2402 debug(DBG_ERR, "malloc failed");
2406 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2408 free(m->replacement);
2410 debug(DBG_ERR, "failed to compile regular expression %s", s);
2417 struct rewrite *getrewrite(char *alt1, char *alt2) {
2420 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2422 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2427 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2429 struct rewrite *rewrite = NULL;
2431 uint8_t *rma = NULL;
2432 uint32_t *p, *rmva = NULL;
2433 struct list *adda = NULL, *moda = NULL;
2438 for (n = 0; rmattrs[n]; n++);
2439 rma = calloc(n + 1, sizeof(uint8_t));
2441 debugx(1, DBG_ERR, "malloc failed");
2443 for (i = 0; i < n; i++)
2444 if (!(rma[i] = attrname2val(rmattrs[i])))
2445 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2446 freegconfmstr(rmattrs);
2451 for (n = 0; rmvattrs[n]; n++);
2452 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2454 debugx(1, DBG_ERR, "malloc failed");
2456 for (p = rmva, i = 0; i < n; i++, p += 2)
2457 if (!vattrname2val(rmvattrs[i], p, p + 1))
2458 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2459 freegconfmstr(rmvattrs);
2464 adda = list_create();
2466 debugx(1, DBG_ERR, "malloc failed");
2467 for (i = 0; addattrs[i]; i++) {
2468 a = extractattr(addattrs[i], 0);
2470 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2471 if (!list_push(adda, a))
2472 debugx(1, DBG_ERR, "malloc failed");
2474 freegconfmstr(addattrs);
2479 adda = list_create();
2481 debugx(1, DBG_ERR, "malloc failed");
2482 for (i = 0; addvattrs[i]; i++) {
2483 a = extractattr(addvattrs[i], 1);
2485 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2486 if (!list_push(adda, a))
2487 debugx(1, DBG_ERR, "malloc failed");
2489 freegconfmstr(addvattrs);
2493 moda = list_create();
2495 debugx(1, DBG_ERR, "malloc failed");
2496 for (i = 0; modattrs[i]; i++) {
2497 m = extractmodattr(modattrs[i]);
2499 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2500 if (!list_push(moda, m))
2501 debugx(1, DBG_ERR, "malloc failed");
2503 freegconfmstr(modattrs);
2506 if (rma || rmva || adda || moda) {
2507 rewrite = malloc(sizeof(struct rewrite));
2509 debugx(1, DBG_ERR, "malloc failed");
2510 rewrite->removeattrs = rma;
2511 rewrite->removevendorattrs = rmva;
2512 rewrite->addattrs = adda;
2513 rewrite->modattrs = moda;
2516 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2517 debugx(1, DBG_ERR, "malloc failed");
2518 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2521 int setttlattr(struct options *opts, char *defaultattr) {
2522 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2524 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2525 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2527 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2531 void freeclsrvconf(struct clsrvconf *conf) {
2534 freegconfmstr(conf->hostsrc);
2535 free(conf->portsrc);
2538 free(conf->matchcertattr);
2539 if (conf->certcnregex)
2540 regfree(conf->certcnregex);
2541 if (conf->certuriregex)
2542 regfree(conf->certuriregex);
2543 free(conf->confrewritein);
2544 free(conf->confrewriteout);
2545 if (conf->rewriteusername) {
2546 if (conf->rewriteusername->regex)
2547 regfree(conf->rewriteusername->regex);
2548 free(conf->rewriteusername->replacement);
2549 free(conf->rewriteusername);
2551 free(conf->dynamiclookupcommand);
2552 free(conf->rewritein);
2553 free(conf->rewriteout);
2554 if (conf->hostports)
2555 freehostports(conf->hostports);
2557 pthread_mutex_destroy(conf->lock);
2560 /* not touching ssl_ctx, clients and servers */
2564 int mergeconfstring(char **dst, char **src) {
2573 t = stringcopy(*dst, 0);
2575 debug(DBG_ERR, "malloc failed");
2583 char **mstringcopy(char **in) {
2590 for (n = 0; in[n]; n++);
2591 out = malloc((n + 1) * sizeof(char *));
2594 for (n = 0; in[n]; n++) {
2595 out[n] = stringcopy(in[n], 0);
2605 int mergeconfmstring(char ***dst, char ***src) {
2614 t = mstringcopy(*dst);
2616 debug(DBG_ERR, "malloc failed");
2624 /* assumes dst is a shallow copy */
2625 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2626 if (!mergeconfstring(&dst->name, &src->name) ||
2627 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2628 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2629 !mergeconfstring(&dst->secret, &src->secret) ||
2630 !mergeconfstring(&dst->tls, &src->tls) ||
2631 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2632 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2633 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2634 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2637 dst->pdef = src->pdef;
2638 dst->statusserver = src->statusserver;
2639 dst->certnamecheck = src->certnamecheck;
2640 if (src->retryinterval != 255)
2641 dst->retryinterval = src->retryinterval;
2642 if (src->retrycount != 255)
2643 dst->retrycount = src->retrycount;
2647 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2648 struct clsrvconf *conf;
2649 char *conftype = NULL, *rewriteinalias = NULL;
2650 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2652 debug(DBG_DBG, "confclient_cb called for %s", block);
2654 conf = malloc(sizeof(struct clsrvconf));
2656 debugx(1, DBG_ERR, "malloc failed");
2657 memset(conf, 0, sizeof(struct clsrvconf));
2658 conf->certnamecheck = 1;
2660 if (!getgenericconfig(cf, block,
2661 "type", CONF_STR, &conftype,
2662 "host", CONF_MSTR, &conf->hostsrc,
2663 "secret", CONF_STR, &conf->secret,
2664 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2665 "tls", CONF_STR, &conf->tls,
2666 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2667 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2669 "DuplicateInterval", CONF_LINT, &dupinterval,
2670 "addTTL", CONF_LINT, &addttl,
2671 "rewrite", CONF_STR, &rewriteinalias,
2672 "rewriteIn", CONF_STR, &conf->confrewritein,
2673 "rewriteOut", CONF_STR, &conf->confrewriteout,
2674 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2677 debugx(1, DBG_ERR, "configuration error");
2679 conf->name = stringcopy(val, 0);
2680 if (conf->name && !conf->hostsrc) {
2681 conf->hostsrc = malloc(2 * sizeof(char *));
2682 if (conf->hostsrc) {
2683 conf->hostsrc[0] = stringcopy(val, 0);
2684 conf->hostsrc[1] = NULL;
2687 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2688 debugx(1, DBG_ERR, "malloc failed");
2691 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2692 conf->type = protoname2int(conftype);
2693 if (conf->type == 255)
2694 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2696 conf->pdef = protodefs[conf->type];
2698 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2699 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2700 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2702 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2703 if (conf->matchcertattr && !addmatchcertattr(conf))
2704 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2708 if (dupinterval != LONG_MIN) {
2709 if (dupinterval < 0 || dupinterval > 255)
2710 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2711 conf->dupinterval = (uint8_t)dupinterval;
2713 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2715 if (addttl != LONG_MIN) {
2716 if (addttl < 1 || addttl > 255)
2717 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2718 conf->addttl = (uint8_t)addttl;
2721 if (!conf->confrewritein)
2722 conf->confrewritein = rewriteinalias;
2724 free(rewriteinalias);
2725 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2726 if (conf->confrewriteout)
2727 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2729 if (conf->confrewriteusername) {
2730 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2731 if (!conf->rewriteusername)
2732 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2735 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2736 !resolvehostports(conf->hostports, conf->pdef->socktype))
2737 debugx(1, DBG_ERR, "resolve failed, exiting");
2739 if (!conf->secret) {
2740 if (!conf->pdef->secretdefault)
2741 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2742 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2744 debugx(1, DBG_ERR, "malloc failed");
2747 conf->lock = malloc(sizeof(pthread_mutex_t));
2749 debugx(1, DBG_ERR, "malloc failed");
2751 pthread_mutex_init(conf->lock, NULL);
2752 if (!list_push(clconfs, conf))
2753 debugx(1, DBG_ERR, "malloc failed");
2757 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2758 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2759 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2760 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2761 if (!conf->tlsconf) {
2762 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2765 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2766 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2772 if (!conf->portsrc) {
2773 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2774 if (!conf->portsrc) {
2775 debug(DBG_ERR, "malloc failed");
2780 if (conf->retryinterval == 255)
2781 conf->retryinterval = conf->pdef->retryintervaldefault;
2782 if (conf->retrycount == 255)
2783 conf->retrycount = conf->pdef->retrycountdefault;
2785 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2786 if (conf->confrewriteout)
2787 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2789 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2790 debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2794 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2795 debug(DBG_ERR, "resolve failed, exiting");
2801 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2802 struct clsrvconf *conf, *resconf;
2803 char *conftype = NULL, *rewriteinalias = NULL;
2804 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2806 debug(DBG_DBG, "confserver_cb called for %s", block);
2808 conf = malloc(sizeof(struct clsrvconf));
2810 debug(DBG_ERR, "malloc failed");
2813 memset(conf, 0, sizeof(struct clsrvconf));
2814 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2815 resconf = (struct clsrvconf *)arg;
2817 conf->statusserver = resconf->statusserver;
2818 conf->certnamecheck = resconf->certnamecheck;
2820 conf->certnamecheck = 1;
2822 if (!getgenericconfig(cf, block,
2823 "type", CONF_STR, &conftype,
2824 "host", CONF_MSTR, &conf->hostsrc,
2825 "port", CONF_STR, &conf->portsrc,
2826 "secret", CONF_STR, &conf->secret,
2827 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2828 "tls", CONF_STR, &conf->tls,
2829 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2830 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2832 "addTTL", CONF_LINT, &addttl,
2833 "rewrite", CONF_STR, &rewriteinalias,
2834 "rewriteIn", CONF_STR, &conf->confrewritein,
2835 "rewriteOut", CONF_STR, &conf->confrewriteout,
2836 "StatusServer", CONF_BLN, &conf->statusserver,
2837 "RetryInterval", CONF_LINT, &retryinterval,
2838 "RetryCount", CONF_LINT, &retrycount,
2839 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2840 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2843 debug(DBG_ERR, "configuration error");
2847 conf->name = stringcopy(val, 0);
2848 if (conf->name && !conf->hostsrc) {
2849 conf->hostsrc = malloc(2 * sizeof(char *));
2850 if (conf->hostsrc) {
2851 conf->hostsrc[0] = stringcopy(val, 0);
2852 conf->hostsrc[1] = NULL;
2855 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2856 debug(DBG_ERR, "malloc failed");
2861 debug(DBG_ERR, "error in block %s, option type missing", block);
2864 conf->type = protoname2int(conftype);
2865 if (conf->type == 255) {
2866 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2872 conf->pdef = protodefs[conf->type];
2874 if (!conf->confrewritein)
2875 conf->confrewritein = rewriteinalias;
2877 free(rewriteinalias);
2878 rewriteinalias = NULL;
2880 if (retryinterval != LONG_MIN) {
2881 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2882 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2885 conf->retryinterval = (uint8_t)retryinterval;
2887 conf->retryinterval = 255;
2889 if (retrycount != LONG_MIN) {
2890 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2891 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2894 conf->retrycount = (uint8_t)retrycount;
2896 conf->retrycount = 255;
2898 if (addttl != LONG_MIN) {
2899 if (addttl < 1 || addttl > 255) {
2900 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2903 conf->addttl = (uint8_t)addttl;
2907 if (!mergesrvconf(resconf, conf))
2911 if (conf->dynamiclookupcommand) {
2912 free(conf->dynamiclookupcommand);
2913 conf->dynamiclookupcommand = NULL;
2917 if (resconf || !conf->dynamiclookupcommand) {
2918 if (!compileserverconfig(conf, block))
2922 if (!conf->secret) {
2923 if (!conf->pdef->secretdefault) {
2924 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2927 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2928 if (!conf->secret) {
2929 debug(DBG_ERR, "malloc failed");
2937 if (!list_push(srvconfs, conf)) {
2938 debug(DBG_ERR, "malloc failed");
2945 free(rewriteinalias);
2946 freeclsrvconf(conf);
2950 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2951 char **servers = NULL, **accservers = NULL, *msg = NULL;
2952 uint8_t accresp = 0;
2954 debug(DBG_DBG, "confrealm_cb called for %s", block);
2956 if (!getgenericconfig(cf, block,
2957 "server", CONF_MSTR, &servers,
2958 "accountingServer", CONF_MSTR, &accservers,
2959 "ReplyMessage", CONF_STR, &msg,
2960 "AccountingResponse", CONF_BLN, &accresp,
2963 debugx(1, DBG_ERR, "configuration error");
2965 addrealm(realms, val, servers, accservers, msg, accresp);
2969 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2970 char **rmattrs = NULL, **rmvattrs = NULL;
2971 char **addattrs = NULL, **addvattrs = NULL;
2972 char **modattrs = NULL;
2974 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2976 if (!getgenericconfig(cf, block,
2977 "removeAttribute", CONF_MSTR, &rmattrs,
2978 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2979 "addAttribute", CONF_MSTR, &addattrs,
2980 "addVendorAttribute", CONF_MSTR, &addvattrs,
2981 "modifyAttribute", CONF_MSTR, &modattrs,
2984 debugx(1, DBG_ERR, "configuration error");
2985 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2989 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2990 struct commonprotoopts *protoopts;
2992 protoopts = malloc(sizeof(struct commonprotoopts));
2995 memset(protoopts, 0, sizeof(struct commonprotoopts));
2996 protoopts->listenargs = listenargs;
2997 protoopts->sourcearg = sourcearg;
2998 protodefs[type]->setprotoopts(protoopts);
3002 void getmainconfig(const char *configfile) {
3003 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3004 struct gconffile *cfs;
3005 char **listenargs[RAD_PROTOCOUNT];
3006 char *sourcearg[RAD_PROTOCOUNT];
3009 cfs = openconfigfile(configfile);
3010 memset(&options, 0, sizeof(options));
3011 memset(&listenargs, 0, sizeof(listenargs));
3012 memset(&sourcearg, 0, sizeof(sourcearg));
3014 clconfs = list_create();
3016 debugx(1, DBG_ERR, "malloc failed");
3018 srvconfs = list_create();
3020 debugx(1, DBG_ERR, "malloc failed");
3022 realms = list_create();
3024 debugx(1, DBG_ERR, "malloc failed");
3026 rewriteconfs = hash_create();
3028 debugx(1, DBG_ERR, "malloc failed");
3030 if (!getgenericconfig(&cfs, NULL,
3032 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3033 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3036 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3037 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3040 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3041 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3044 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3045 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3047 "TTLAttribute", CONF_STR, &options.ttlattr,
3048 "addTTL", CONF_LINT, &addttl,
3049 "LogLevel", CONF_LINT, &loglevel,
3050 "LogDestination", CONF_STR, &options.logdestination,
3051 "LoopPrevention", CONF_BLN, &options.loopprevention,
3052 "Client", CONF_CBK, confclient_cb, NULL,
3053 "Server", CONF_CBK, confserver_cb, NULL,
3054 "Realm", CONF_CBK, confrealm_cb, NULL,
3055 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3056 "TLS", CONF_CBK, conftls_cb, NULL,
3058 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3061 debugx(1, DBG_ERR, "configuration error");
3063 if (loglevel != LONG_MIN) {
3064 if (loglevel < 1 || loglevel > 5)
3065 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3066 options.loglevel = (uint8_t)loglevel;
3068 if (addttl != LONG_MIN) {
3069 if (addttl < 1 || addttl > 255)
3070 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3071 options.addttl = (uint8_t)addttl;
3073 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3074 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3076 for (i = 0; i < RAD_PROTOCOUNT; i++)
3077 if (listenargs[i] || sourcearg[i])
3078 setprotoopts(i, listenargs[i], sourcearg[i]);
3081 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3084 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3087 *configfile = optarg;
3090 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3091 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3092 *loglevel = *optarg - '0';
3104 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3105 debug(DBG_ERR, "This binary was built with support for the following transports:");
3107 debug(DBG_ERR, " UDP");
3110 debug(DBG_ERR, " TCP");
3113 debug(DBG_ERR, " TLS");
3116 debug(DBG_ERR, " DTLS");
3123 if (!(argc - optind))
3127 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3131 int daemon(int a, int b) {
3139 for (i = 0; i < 3; i++) {
3141 open("/dev/null", O_RDWR);
3147 void *sighandler(void *arg) {
3152 sigemptyset(&sigset);
3153 sigaddset(&sigset, SIGHUP);
3154 sigaddset(&sigset, SIGPIPE);
3155 sigwait(&sigset, &sig);
3158 /* completely ignoring this */
3161 debug(DBG_INFO, "sighandler: got SIGHUP");
3165 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3168 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3173 int createpidfile(const char *pidfile) {
3175 FILE *f = fopen(pidfile, "w");
3177 r = fprintf(f, "%ld\n", (long) getpid());
3178 return f && !fclose(f) && r >= 0;
3181 int main(int argc, char **argv) {
3184 struct list_node *entry;
3185 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3186 char *configfile = NULL, *pidfile = NULL;
3187 struct clsrvconf *srvconf;
3190 debug_init("radsecproxy");
3191 debug_set_level(DEBUG_LEVEL);
3193 for (i = 0; i < RAD_PROTOCOUNT; i++)
3194 protodefs[i] = protoinits[i](i);
3196 /* needed even if no TLS/DTLS transport */
3199 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3201 debug_set_level(loglevel);
3202 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3204 options.loglevel = loglevel;
3205 else if (options.loglevel)
3206 debug_set_level(options.loglevel);
3208 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3209 free(options.logdestination);
3211 if (!list_first(clconfs))
3212 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3213 if (!list_first(realms))
3214 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3217 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3219 if (!foreground && (daemon(0, 0) < 0))
3220 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3222 debug_timestamp_on();
3223 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3224 if (pidfile && !createpidfile(pidfile))
3225 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3227 sigemptyset(&sigset);
3228 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3229 sigaddset(&sigset, SIGHUP);
3230 sigaddset(&sigset, SIGPIPE);
3231 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3232 pthread_create(&sigth, NULL, sighandler, NULL);
3234 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3235 srvconf = (struct clsrvconf *)entry->data;
3236 if (srvconf->dynamiclookupcommand)
3238 if (!addserver(srvconf))
3239 debugx(1, DBG_ERR, "failed to add server");
3240 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3241 (void *)(srvconf->servers)))
3242 debugx(1, DBG_ERR, "pthread_create failed");
3245 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3248 if (protodefs[i]->initextra)
3249 protodefs[i]->initextra();
3250 if (find_clconf_type(i, NULL))
3254 /* just hang around doing nothing, anything to do here? */
3259 /* Local Variables: */
3260 /* c-file-style: "stroustrup" */