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>
65 #include <openssl/ssl.h>
66 #include <openssl/rand.h>
67 #include <openssl/err.h>
68 #include <openssl/md5.h>
74 #include "radsecproxy.h"
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
82 static struct list *realms;
83 static struct hash *rewriteconfs;
85 static pthread_mutex_t *ssl_locks = NULL;
86 static long *ssl_lock_count;
89 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
91 /* minimum required declarations to avoid reordering code */
92 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
93 int dynamicconfig(struct server *server);
94 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
95 void freerealm(struct realm *realm);
96 void freeclsrvconf(struct clsrvconf *conf);
97 void freerq(struct request *rq);
98 void freerqoutdata(struct rqout *rqout);
99 void rmclientrq(struct request *rq, uint8_t id);
101 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
103 uint8_t protoname2int(const char *name) {
106 for (i = 0; i < RAD_PROTOCOUNT; i++)
107 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
112 /* callbacks for making OpenSSL thread safe */
113 unsigned long ssl_thread_id() {
114 return (unsigned long)pthread_self();
117 void ssl_locking_callback(int mode, int type, const char *file, int line) {
118 if (mode & CRYPTO_LOCK) {
119 pthread_mutex_lock(&ssl_locks[type]);
120 ssl_lock_count[type]++;
122 pthread_mutex_unlock(&ssl_locks[type]);
125 /* returns 1 if the len first bits are equal, else 0 */
126 int prefixmatch(void *a1, void *a2, uint8_t len) {
127 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
128 uint8_t r, l = len / 8;
129 if (l && memcmp(a1, a2, l))
134 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
137 /* returns next config with matching address, or NULL */
138 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
139 struct list_node *entry;
140 struct clsrvconf *conf;
142 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
143 conf = (struct clsrvconf *)entry->data;
144 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
153 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
154 return find_conf(type, addr, clconfs, cur, 0);
157 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
158 return find_conf(type, addr, srvconfs, cur, 1);
161 /* returns next config of given type, or NULL */
162 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
163 struct list_node *entry;
164 struct clsrvconf *conf;
166 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
167 conf = (struct clsrvconf *)entry->data;
168 if (conf->type == type) {
177 struct gqueue *newqueue() {
180 q = malloc(sizeof(struct gqueue));
182 debugx(1, DBG_ERR, "malloc failed");
183 q->entries = list_create();
185 debugx(1, DBG_ERR, "malloc failed");
186 pthread_mutex_init(&q->mutex, NULL);
187 pthread_cond_init(&q->cond, NULL);
191 void removequeue(struct gqueue *q) {
192 struct list_node *entry;
196 pthread_mutex_lock(&q->mutex);
197 for (entry = list_first(q->entries); entry; entry = list_next(entry))
198 freerq((struct request *)entry);
199 list_destroy(q->entries);
200 pthread_cond_destroy(&q->cond);
201 pthread_mutex_unlock(&q->mutex);
202 pthread_mutex_destroy(&q->mutex);
206 void freebios(struct gqueue *q) {
209 pthread_mutex_lock(&q->mutex);
210 while ((bio = (BIO *)list_shift(q->entries)))
212 pthread_mutex_unlock(&q->mutex);
216 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
217 struct client *new = malloc(sizeof(struct client));
220 debug(DBG_ERR, "malloc failed");
225 pthread_mutex_lock(conf->lock);
226 if (!conf->clients) {
227 conf->clients = list_create();
228 if (!conf->clients) {
230 pthread_mutex_unlock(conf->lock);
231 debug(DBG_ERR, "malloc failed");
236 memset(new, 0, sizeof(struct client));
238 if (conf->pdef->addclient)
239 conf->pdef->addclient(new);
241 new->replyq = newqueue();
242 list_push(conf->clients, new);
244 pthread_mutex_unlock(conf->lock);
248 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
249 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
252 pthread_mutex_lock(&lock);
254 pthread_mutex_unlock(&lock);
257 void removeclientrqs(struct client *client) {
262 removeclientrqs_sendrq_freeserver_lock(1);
263 for (i = 0; i < MAX_REQUESTS; i++) {
268 rqout = rq->to->requests + rq->newid;
269 pthread_mutex_lock(rqout->lock);
270 if (rqout->rq == rq) /* still pointing to our request */
271 freerqoutdata(rqout);
272 pthread_mutex_unlock(rqout->lock);
276 removeclientrqs_sendrq_freeserver_lock(0);
279 void removelockedclient(struct client *client) {
280 struct clsrvconf *conf;
284 removeclientrqs(client);
285 removequeue(client->replyq);
286 list_removedata(conf->clients, client);
292 void removeclient(struct client *client) {
293 struct clsrvconf *conf;
299 pthread_mutex_lock(conf->lock);
300 removelockedclient(client);
301 pthread_mutex_unlock(conf->lock);
304 void freeserver(struct server *server, uint8_t destroymutex) {
305 struct rqout *rqout, *end;
310 removeclientrqs_sendrq_freeserver_lock(1);
311 if (server->requests) {
312 rqout = server->requests;
313 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
315 rqout->rq->to = NULL;
316 freerqoutdata(rqout);
317 pthread_mutex_destroy(rqout->lock);
320 free(server->requests);
323 freebios(server->rbios);
324 free(server->dynamiclookuparg);
326 SSL_free(server->ssl);
328 pthread_mutex_destroy(&server->lock);
329 pthread_cond_destroy(&server->newrq_cond);
330 pthread_mutex_destroy(&server->newrq_mutex);
332 removeclientrqs_sendrq_freeserver_lock(0);
336 int addserver(struct clsrvconf *conf) {
340 debug(DBG_ERR, "addserver: currently works with just one server per conf");
343 conf->servers = malloc(sizeof(struct server));
344 if (!conf->servers) {
345 debug(DBG_ERR, "malloc failed");
348 memset(conf->servers, 0, sizeof(struct server));
349 conf->servers->conf = conf;
352 if (conf->type == RAD_DTLS)
353 conf->servers->rbios = newqueue();
355 conf->pdef->setsrcres();
357 conf->servers->sock = -1;
358 if (conf->pdef->addserverextra)
359 conf->pdef->addserverextra(conf);
361 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
362 if (!conf->servers->requests) {
363 debug(DBG_ERR, "malloc failed");
366 for (i = 0; i < MAX_REQUESTS; i++) {
367 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
368 if (!conf->servers->requests[i].lock) {
369 debug(DBG_ERR, "malloc failed");
372 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
373 debug(DBG_ERR, "mutex init failed");
374 free(conf->servers->requests[i].lock);
375 conf->servers->requests[i].lock = NULL;
379 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
380 debug(DBG_ERR, "mutex init failed");
383 conf->servers->newrq = 0;
384 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
385 debug(DBG_ERR, "mutex init failed");
386 pthread_mutex_destroy(&conf->servers->lock);
389 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
390 debug(DBG_ERR, "mutex init failed");
391 pthread_mutex_destroy(&conf->servers->newrq_mutex);
392 pthread_mutex_destroy(&conf->servers->lock);
399 freeserver(conf->servers, 0);
400 conf->servers = NULL;
404 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
406 if (ATTRTYPE(attrs) == type)
408 length -= ATTRLEN(attrs);
409 attrs += ATTRLEN(attrs);
414 struct request *newrqref(struct request *rq) {
420 void freerq(struct request *rq) {
423 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
426 if (rq->origusername)
427 free(rq->origusername);
433 radmsg_free(rq->msg);
437 void freerqoutdata(struct rqout *rqout) {
441 if (rqout->rq->buf) {
442 free(rqout->rq->buf);
443 rqout->rq->buf = NULL;
449 memset(&rqout->expiry, 0, sizeof(struct timeval));
452 void sendrq(struct request *rq) {
456 removeclientrqs_sendrq_freeserver_lock(1);
461 start = to->conf->statusserver ? 1 : 0;
462 pthread_mutex_lock(&to->newrq_mutex);
463 if (start && rq->msg->code == RAD_Status_Server) {
464 pthread_mutex_lock(to->requests[0].lock);
465 if (to->requests[0].rq) {
466 pthread_mutex_unlock(to->requests[0].lock);
467 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
474 /* might simplify if only try nextid, might be ok */
475 for (i = to->nextid; i < MAX_REQUESTS; i++) {
476 if (!to->requests[i].rq) {
477 pthread_mutex_lock(to->requests[i].lock);
478 if (!to->requests[i].rq)
480 pthread_mutex_unlock(to->requests[i].lock);
483 if (i == MAX_REQUESTS) {
484 for (i = start; i < to->nextid; i++) {
485 if (!to->requests[i].rq) {
486 pthread_mutex_lock(to->requests[i].lock);
487 if (!to->requests[i].rq)
489 pthread_mutex_unlock(to->requests[i].lock);
492 if (i == to->nextid) {
493 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
498 rq->newid = (uint8_t)i;
499 rq->msg->id = (uint8_t)i;
500 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
502 pthread_mutex_unlock(to->requests[i].lock);
503 debug(DBG_ERR, "sendrq: radmsg2buf failed");
507 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
508 to->requests[i].rq = rq;
509 pthread_mutex_unlock(to->requests[i].lock);
510 if (i >= start) /* i is not reserved for statusserver */
515 debug(DBG_DBG, "sendrq: signalling client writer");
516 pthread_cond_signal(&to->newrq_cond);
519 pthread_mutex_unlock(&to->newrq_mutex);
520 removeclientrqs_sendrq_freeserver_lock(0);
525 rmclientrq(rq, rq->msg->id);
527 pthread_mutex_unlock(&to->newrq_mutex);
528 removeclientrqs_sendrq_freeserver_lock(0);
531 void sendreply(struct request *rq) {
533 struct client *to = rq->from;
536 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
537 radmsg_free(rq->msg);
541 debug(DBG_ERR, "sendreply: radmsg2buf failed");
545 pthread_mutex_lock(&to->replyq->mutex);
546 first = list_first(to->replyq->entries) == NULL;
548 if (!list_push(to->replyq->entries, rq)) {
549 pthread_mutex_unlock(&to->replyq->mutex);
551 debug(DBG_ERR, "sendreply: malloc failed");
556 debug(DBG_DBG, "signalling server writer");
557 pthread_cond_signal(&to->replyq->cond);
559 pthread_mutex_unlock(&to->replyq->mutex);
562 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
563 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
564 static unsigned char first = 1;
565 static EVP_MD_CTX mdctx;
566 unsigned char hash[EVP_MAX_MD_SIZE], *input;
568 uint8_t i, offset = 0, out[128];
570 pthread_mutex_lock(&lock);
572 EVP_MD_CTX_init(&mdctx);
578 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
579 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
580 !EVP_DigestUpdate(&mdctx, input, 16) ||
581 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
583 pthread_mutex_unlock(&lock);
586 for (i = 0; i < 16; i++)
587 out[offset + i] = hash[i] ^ in[offset + i];
589 input = out + offset;
596 memcpy(in, out, len);
597 pthread_mutex_unlock(&lock);
601 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
602 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
603 static unsigned char first = 1;
604 static EVP_MD_CTX mdctx;
605 unsigned char hash[EVP_MAX_MD_SIZE];
609 pthread_mutex_lock(&lock);
611 EVP_MD_CTX_init(&mdctx);
616 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
617 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
618 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
621 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
622 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
623 !EVP_DigestUpdate(&mdctx, auth, 16) ||
624 !EVP_DigestUpdate(&mdctx, salt, 2) ||
625 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
626 pthread_mutex_unlock(&lock);
631 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
634 for (i = 0; i < 16; i++)
637 for (offset = 16; offset < len; offset += 16) {
639 printf("text + offset - 16 c(%d): ", offset / 16);
640 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
642 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
643 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
644 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
645 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
647 pthread_mutex_unlock(&lock);
651 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
654 for (i = 0; i < 16; i++)
655 text[offset + i] ^= hash[i];
659 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
662 pthread_mutex_unlock(&lock);
666 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
667 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
668 static unsigned char first = 1;
669 static EVP_MD_CTX mdctx;
670 unsigned char hash[EVP_MAX_MD_SIZE];
675 pthread_mutex_lock(&lock);
677 EVP_MD_CTX_init(&mdctx);
682 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
683 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
684 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
687 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
688 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
689 !EVP_DigestUpdate(&mdctx, auth, 16) ||
690 !EVP_DigestUpdate(&mdctx, salt, 2) ||
691 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
692 pthread_mutex_unlock(&lock);
697 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
700 for (i = 0; i < 16; i++)
701 plain[i] = text[i] ^ hash[i];
703 for (offset = 16; offset < len; offset += 16) {
705 printf("text + offset - 16 c(%d): ", offset / 16);
706 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
708 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
709 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
710 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
711 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
713 pthread_mutex_unlock(&lock);
717 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
720 for (i = 0; i < 16; i++)
721 plain[offset + i] = text[offset + i] ^ hash[i];
724 memcpy(text, plain, len);
726 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
729 pthread_mutex_unlock(&lock);
733 struct realm *newrealmref(struct realm *r) {
739 /* returns with lock on realm */
740 struct realm *id2realm(struct list *realmlist, char *id) {
741 struct list_node *entry;
742 struct realm *realm, *subrealm;
744 /* need to do locking for subrealms and check subrealm timers */
745 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
746 realm = (struct realm *)entry->data;
747 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
748 pthread_mutex_lock(&realm->mutex);
749 if (realm->subrealms) {
750 subrealm = id2realm(realm->subrealms, id);
752 pthread_mutex_unlock(&realm->mutex);
756 return newrealmref(realm);
762 int hasdynamicserver(struct list *srvconfs) {
763 struct list_node *entry;
765 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
766 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
771 /* helper function, only used by removeserversubrealms() */
772 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
773 struct list_node *entry, *entry2;
776 for (entry = list_first(realmlist); entry;) {
777 realm = newrealmref((struct realm *)entry->data);
778 pthread_mutex_lock(&realm->mutex);
779 entry = list_next(entry);
781 if (realm->srvconfs) {
782 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
783 if (entry2->data == srv)
785 list_removedata(realm->srvconfs, srv);
787 if (realm->accsrvconfs) {
788 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
789 if (entry2->data == srv)
791 list_removedata(realm->accsrvconfs, srv);
794 /* remove subrealm if no dynamic servers left */
795 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
796 while (list_shift(realm->srvconfs))
798 list_destroy(realm->srvconfs);
799 realm->srvconfs = NULL;
800 while (list_shift(realm->accsrvconfs))
802 list_destroy(realm->accsrvconfs);
803 realm->accsrvconfs = NULL;
804 list_removedata(realmlist, realm);
806 pthread_mutex_unlock(&realm->mutex);
811 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
812 struct list_node *entry;
815 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
816 realm = (struct realm *)entry->data;
817 pthread_mutex_lock(&realm->mutex);
818 if (realm->subrealms) {
819 _internal_removeserversubrealms(realm->subrealms, srv);
820 if (!list_first(realm->subrealms)) {
821 list_destroy(realm->subrealms);
822 realm->subrealms = NULL;
825 pthread_mutex_unlock(&realm->mutex);
829 int attrvalidate(unsigned char *attrs, int length) {
831 if (ATTRLEN(attrs) < 2) {
832 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
835 length -= ATTRLEN(attrs);
837 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
840 attrs += ATTRLEN(attrs);
843 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
847 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
848 if (len < 16 || len > 128 || len % 16) {
849 debug(DBG_WARN, "pwdrecrypt: invalid password length");
853 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
854 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
858 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
860 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
861 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
867 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
870 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
871 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
874 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
875 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
881 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
882 char *oldsecret, char *newsecret) {
885 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
886 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
887 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
893 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
897 for (; attrs[0]; attrs += 2)
898 if (attrs[0] == vendor && attrs[1] == subattr)
903 /* returns 1 if entire element is to be removed, else 0 */
904 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
905 uint8_t alen, sublen;
909 if (!removevendorattrs)
912 memcpy(&vendor, attr->v, 4);
913 vendor = ntohl(vendor);
914 while (*removevendorattrs && *removevendorattrs != vendor)
915 removevendorattrs += 2;
916 if (!*removevendorattrs)
919 if (findvendorsubattr(removevendorattrs, vendor, 256))
920 return 1; /* remove entire vendor attribute */
922 sublen = attr->l - 4;
923 subattrs = attr->v + 4;
925 if (!attrvalidate(subattrs, sublen)) {
926 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
931 alen = ATTRLEN(subattrs);
933 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
934 memmove(subattrs, subattrs + alen, sublen);
942 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
943 struct list_node *n, *p;
947 n = list_first(msg->attrs);
949 attr = (struct tlv *)n->data;
950 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
951 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
952 list_removedata(msg->attrs, attr);
954 n = p ? list_next(p) : list_first(msg->attrs);
962 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
966 for (n = list_first(addattrs); n; n = list_next(n)) {
967 a = copytlv((struct tlv *)n->data);
970 if (!radmsg_add(msg, a)) {
978 int resizeattr(struct tlv *attr, uint8_t newlen) {
981 if (newlen != attr->l) {
982 newv = realloc(attr->v, newlen);
991 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
992 size_t nmatch = 10, reslen = 0, start = 0;
993 regmatch_t pmatch[10], *pfield;
997 in = stringcopy((char *)attr->v, attr->l);
1001 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1006 out = modattr->replacement;
1008 for (i = start; out[i]; i++) {
1009 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1010 pfield = &pmatch[out[i + 1] - '0'];
1011 if (pfield->rm_so >= 0) {
1012 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1018 reslen += i - start;
1020 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1025 if (!resizeattr(attr, reslen)) {
1032 for (i = start; out[i]; i++) {
1033 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1034 pfield = &pmatch[out[i + 1] - '0'];
1035 if (pfield->rm_so >= 0) {
1036 memcpy(attr->v + reslen, out + start, i - start);
1037 reslen += i - start;
1038 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1039 reslen += pfield->rm_eo - pfield->rm_so;
1046 memcpy(attr->v + reslen, out + start, i - start);
1050 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1051 struct list_node *n, *m;
1053 for (n = list_first(msg->attrs); n; n = list_next(n))
1054 for (m = list_first(modattrs); m; m = list_next(m))
1055 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1056 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1061 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1062 int rv = 1; /* Success. */
1065 if (rewrite->removeattrs || rewrite->removevendorattrs)
1066 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1067 if (rewrite->modattrs)
1068 if (!dorewritemod(msg, rewrite->modattrs))
1070 if (rewrite->addattrs)
1071 if (!dorewriteadd(msg, rewrite->addattrs))
1077 int rewriteusername(struct request *rq, struct tlv *attr) {
1078 char *orig = (char *)tlv2str(attr);
1079 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1083 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1084 rq->origusername = (char *)orig;
1090 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1091 * all is well with the new tlv, i.e. if the function returns
1094 makevendortlv(uint32_t vendor, struct tlv *attr)
1096 struct tlv *newtlv = NULL;
1104 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1105 memcpy(v, &vendor, 4);
1106 tlv2buf(v + 4, attr);
1107 v[5] += 2; /* Vendor length increased for type and length fields. */
1108 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1117 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1119 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1122 vattr = makevendortlv(vendor, attr);
1127 if (!radmsg_add(msg, vattr)) {
1134 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1141 if (attrtype[1] == 256) { /* not vendor */
1142 attr = maketlv(attrtype[0], 4, ttl);
1143 if (attr && !radmsg_add(msg, attr))
1146 attr = maketlv(attrtype[1], 4, ttl);
1148 addvendorattr(msg, attrtype[0], attr);
1152 int decttl(uint8_t l, uint8_t *v) {
1159 while (i >= 0 && !v[i])
1163 for (i--; i >= 0 && !v[i]; i--);
1172 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1173 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1174 uint8_t alen, *subattrs;
1176 struct list_node *node;
1180 if (attrtype[1] == 256) { /* not vendor */
1181 attr = radmsg_gettype(msg, attrtype[0]);
1183 return decttl(attr->l, attr->v);
1185 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1186 attr = (struct tlv *)node->data;
1187 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1189 memcpy(&vendor, attr->v, 4);
1190 if (ntohl(vendor) != attrtype[0])
1192 sublen = attr->l - 4;
1193 subattrs = attr->v + 4;
1194 if (!attrvalidate(subattrs, sublen))
1196 while (sublen > 1) {
1197 if (ATTRTYPE(subattrs) == attrtype[1])
1198 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1199 alen = ATTRLEN(subattrs);
1207 const char *radmsgtype2string(uint8_t code) {
1208 static const char *rad_msg_names[] = {
1209 "", "Access-Request", "Access-Accept", "Access-Reject",
1210 "Accounting-Request", "Accounting-Response", "", "",
1211 "", "", "", "Access-Challenge",
1212 "Status-Server", "Status-Client"
1214 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1217 void char2hex(char *h, unsigned char c) {
1218 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1219 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1220 h[0] = hexdigits[c / 16];
1221 h[1] = hexdigits[c % 16];
1225 uint8_t *radattr2ascii(struct tlv *attr) {
1233 for (i = 0; i < attr->l; i++)
1234 if (attr->v[i] < 32 || attr->v[i] > 126)
1237 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1244 for (i = 0; i < attr->l; i++)
1245 if (attr->v[i] < 32 || attr->v[i] > 126) {
1247 char2hex((char *)d, attr->v[i]);
1255 void acclog(struct radmsg *msg, struct client *from) {
1259 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1261 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1264 username = radattr2ascii(attr);
1266 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1272 void respond(struct request *rq, uint8_t code, char *message) {
1276 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1278 debug(DBG_ERR, "respond: malloc failed");
1281 if (message && *message) {
1282 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1283 if (!attr || !radmsg_add(msg, attr)) {
1286 debug(DBG_ERR, "respond: malloc failed");
1291 radmsg_free(rq->msg);
1293 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1294 sendreply(newrqref(rq));
1297 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1298 struct list_node *entry;
1299 struct clsrvconf *server, *best = NULL, *first = NULL;
1301 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1302 server = (struct clsrvconf *)entry->data;
1303 if (!server->servers)
1307 if (!server->servers->connectionok && !server->servers->dynstartup)
1309 if (!server->servers->lostrqs)
1315 if (server->servers->lostrqs < best->servers->lostrqs)
1318 return best ? best : first;
1321 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1322 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1323 struct clsrvconf *srvconf;
1324 struct realm *subrealm;
1325 struct server *server = NULL;
1326 char *id = (char *)tlv2str(username);
1330 /* returns with lock on realm */
1331 *realm = id2realm(realms, id);
1334 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1335 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1336 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1337 subrealm = adddynamicrealmserver(*realm, id);
1339 pthread_mutex_lock(&subrealm->mutex);
1340 pthread_mutex_unlock(&(*realm)->mutex);
1343 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1347 server = srvconf->servers;
1355 struct request *newrequest() {
1358 rq = malloc(sizeof(struct request));
1360 debug(DBG_ERR, "newrequest: malloc failed");
1363 memset(rq, 0, sizeof(struct request));
1365 gettimeofday(&rq->created, NULL);
1369 int addclientrq(struct request *rq) {
1373 r = rq->from->rqs[rq->rqid];
1375 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1376 gettimeofday(&now, NULL);
1377 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1379 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1380 sendreply(newrqref(r));
1382 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1388 rq->from->rqs[rq->rqid] = newrqref(rq);
1392 void rmclientrq(struct request *rq, uint8_t id) {
1395 r = rq->from->rqs[id];
1398 rq->from->rqs[id] = NULL;
1402 /* returns 0 if validation/authentication fails, else 1 */
1403 int radsrv(struct request *rq) {
1404 struct radmsg *msg = NULL;
1406 uint8_t *userascii = NULL;
1407 struct realm *realm = NULL;
1408 struct server *to = NULL;
1409 struct client *from = rq->from;
1412 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1417 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1424 memcpy(rq->rqauth, msg->auth, 16);
1426 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1427 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1428 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1432 if (!addclientrq(rq))
1435 if (msg->code == RAD_Status_Server) {
1436 respond(rq, RAD_Access_Accept, NULL);
1440 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1442 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1445 ttlres = checkttl(msg, options.ttlattrtype);
1447 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1451 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1453 if (msg->code == RAD_Accounting_Request) {
1455 respond(rq, RAD_Accounting_Response, NULL);
1457 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1461 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1462 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1466 userascii = radattr2ascii(attr);
1469 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1471 /* will return with lock on the realm */
1472 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1474 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1479 if (realm->message && msg->code == RAD_Access_Request) {
1480 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1481 respond(rq, RAD_Access_Reject, realm->message);
1482 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1484 respond(rq, RAD_Accounting_Response, NULL);
1489 if ((to->conf->loopprevention == 1
1490 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1491 && !strcmp(from->conf->name, to->conf->name)) {
1492 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1493 from->conf->name, addr2string(from->addr), to->conf->name);
1497 if (msg->code == RAD_Accounting_Request)
1498 memset(msg->auth, 0, 16);
1499 else if (!RAND_bytes(msg->auth, 16)) {
1500 debug(DBG_WARN, "radsrv: failed to generate random auth");
1505 printfchars(NULL, "auth", "%02x ", auth, 16);
1508 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1510 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1511 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1515 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1517 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1518 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1522 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1525 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1526 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1531 pthread_mutex_unlock(&realm->mutex);
1536 rmclientrq(rq, msg->id);
1541 pthread_mutex_unlock(&realm->mutex);
1547 void replyh(struct server *server, unsigned char *buf) {
1548 struct client *from;
1549 struct rqout *rqout;
1551 unsigned char *subattrs;
1552 uint8_t *username, *stationid, *replymsg;
1553 struct radmsg *msg = NULL;
1555 struct list_node *node;
1557 server->connectionok = 1;
1558 server->lostrqs = 0;
1560 rqout = server->requests + buf[1];
1561 pthread_mutex_lock(rqout->lock);
1562 if (!rqout->tries) {
1565 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1569 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1573 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1576 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1577 && msg->code != RAD_Accounting_Response) {
1578 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1581 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1583 gettimeofday(&server->lastrcv, NULL);
1585 if (rqout->rq->msg->code == RAD_Status_Server) {
1586 freerqoutdata(rqout);
1587 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1591 gettimeofday(&server->lastreply, NULL);
1592 from = rqout->rq->from;
1594 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1595 debug(DBG_INFO, "replyh: rewritein failed");
1599 ttlres = checkttl(msg, options.ttlattrtype);
1601 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1606 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1607 attr = (struct tlv *)node->data;
1608 if (attr->t != RAD_Attr_Vendor_Specific)
1612 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1615 sublen = attr->l - 4;
1616 subattrs = attr->v + 4;
1617 if (!attrvalidate(subattrs, sublen) ||
1618 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1619 rqout->rq, server->conf->secret, from->conf->secret) ||
1620 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1621 rqout->rq, server->conf->secret, from->conf->secret))
1625 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1629 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1630 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1632 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1633 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1636 debug(DBG_WARN, "%s for user %s stationid %s from %s (%s) to %s (%s)",
1637 radmsgtype2string(msg->code), username, stationid, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1640 debug(DBG_WARN, "%s for user %s stationid %s from %s to %s (%s)",
1641 radmsgtype2string(msg->code), username, stationid, server->conf->name, from->conf->name, addr2string(from->addr));
1645 debug(DBG_WARN, "%s for user %s from %s (%s) to %s (%s)",
1646 radmsgtype2string(msg->code), username, server->conf->name, replymsg, from->conf->name, addr2string(from->addr));
1649 debug(DBG_WARN, "%s for user %s from %s to %s (%s)",
1650 radmsgtype2string(msg->code), username, server->conf->name, from->conf->name, addr2string(from->addr));
1656 msg->id = (char)rqout->rq->rqid;
1657 memcpy(msg->auth, rqout->rq->rqauth, 16);
1660 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1663 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1664 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1665 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1668 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1671 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1672 debug(DBG_WARN, "replyh: rewriteout failed");
1676 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1677 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1679 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1680 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1682 radmsg_free(rqout->rq->msg);
1683 rqout->rq->msg = msg;
1684 sendreply(newrqref(rqout->rq));
1685 freerqoutdata(rqout);
1686 pthread_mutex_unlock(rqout->lock);
1691 pthread_mutex_unlock(rqout->lock);
1695 struct request *createstatsrvrq() {
1702 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1705 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1708 if (!radmsg_add(rq->msg, attr)) {
1719 /* code for removing state not finished */
1720 void *clientwr(void *arg) {
1721 struct server *server = (struct server *)arg;
1722 struct rqout *rqout = NULL;
1723 pthread_t clientrdth;
1724 int i, dynconffail = 0;
1727 struct timeval now, laststatsrv;
1728 struct timespec timeout;
1729 struct request *statsrvrq;
1730 struct clsrvconf *conf;
1732 conf = server->conf;
1734 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1736 server->dynstartup = 0;
1741 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1742 debug(DBG_WARN, "clientwr: resolve failed");
1743 server->dynstartup = 0;
1748 memset(&timeout, 0, sizeof(struct timespec));
1750 if (conf->statusserver) {
1751 gettimeofday(&server->lastrcv, NULL);
1752 gettimeofday(&laststatsrv, NULL);
1755 if (conf->pdef->connecter) {
1756 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1757 if (server->dynamiclookuparg) {
1758 server->dynstartup = 0;
1763 server->connectionok = 1;
1764 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1765 debug(DBG_ERR, "clientwr: pthread_create failed");
1769 server->connectionok = 1;
1770 server->dynstartup = 0;
1773 pthread_mutex_lock(&server->newrq_mutex);
1774 if (!server->newrq) {
1775 gettimeofday(&now, NULL);
1776 /* random 0-7 seconds */
1777 RAND_bytes(&rnd, 1);
1779 if (conf->statusserver) {
1780 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1781 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1783 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1784 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1786 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1787 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1790 if (timeout.tv_sec > now.tv_sec)
1791 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1793 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1796 if (server->newrq) {
1797 debug(DBG_DBG, "clientwr: got new request");
1802 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1804 pthread_mutex_unlock(&server->newrq_mutex);
1806 for (i = 0; i < MAX_REQUESTS; i++) {
1807 if (server->clientrdgone) {
1808 pthread_join(clientrdth, NULL);
1812 for (; i < MAX_REQUESTS; i++) {
1813 rqout = server->requests + i;
1815 pthread_mutex_lock(rqout->lock);
1818 pthread_mutex_unlock(rqout->lock);
1822 if (i == MAX_REQUESTS)
1825 gettimeofday(&now, NULL);
1826 if (now.tv_sec < rqout->expiry.tv_sec) {
1827 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1828 timeout.tv_sec = rqout->expiry.tv_sec;
1829 pthread_mutex_unlock(rqout->lock);
1833 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1834 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1835 if (conf->statusserver) {
1836 if (*rqout->rq->buf == RAD_Status_Server) {
1837 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1838 if (server->lostrqs < 255)
1842 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1843 if (server->lostrqs < 255)
1846 freerqoutdata(rqout);
1847 pthread_mutex_unlock(rqout->lock);
1851 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1852 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1853 timeout.tv_sec = rqout->expiry.tv_sec;
1855 conf->pdef->clientradput(server, rqout->rq->buf);
1856 pthread_mutex_unlock(rqout->lock);
1858 if (conf->statusserver && server->connectionok) {
1859 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1860 gettimeofday(&now, NULL);
1861 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1863 statsrvrq = createstatsrvrq();
1865 statsrvrq->to = server;
1866 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1873 conf->servers = NULL;
1874 if (server->dynamiclookuparg) {
1875 removeserversubrealms(realms, conf);
1879 freeclsrvconf(conf);
1881 freeserver(server, 1);
1882 ERR_remove_state(0);
1886 void createlistener(uint8_t type, char *arg) {
1888 struct addrinfo *res;
1889 int s = -1, on = 1, *sp = NULL;
1890 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1892 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1893 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1895 for (res = hp->addrinfo; res; res = res->ai_next) {
1896 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1898 debug(DBG_WARN, "createlistener: socket failed");
1901 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1903 disable_DF_bit(s, res);
1906 if (res->ai_family == AF_INET6)
1907 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1909 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1910 debug(DBG_WARN, "createlistener: bind failed");
1916 sp = malloc(sizeof(int));
1918 debugx(1, DBG_ERR, "malloc failed");
1920 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1921 debugx(1, DBG_ERR, "pthread_create failed");
1925 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1927 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1931 void createlisteners(uint8_t type) {
1935 args = protodefs[type]->getlistenerargs();
1937 for (i = 0; args[i]; i++)
1938 createlistener(type, args[i]);
1940 createlistener(type, NULL);
1948 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1949 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1950 for (i = 0; i < CRYPTO_num_locks(); i++) {
1951 ssl_lock_count[i] = 0;
1952 pthread_mutex_init(&ssl_locks[i], NULL);
1954 CRYPTO_set_id_callback(ssl_thread_id);
1955 CRYPTO_set_locking_callback(ssl_locking_callback);
1957 SSL_load_error_strings();
1960 while (!RAND_status()) {
1963 RAND_seed((unsigned char *)&t, sizeof(time_t));
1964 RAND_seed((unsigned char *)&pid, sizeof(pid));
1968 struct list *addsrvconfs(char *value, char **names) {
1969 struct list *conflist;
1971 struct list_node *entry;
1972 struct clsrvconf *conf = NULL;
1974 if (!names || !*names)
1977 conflist = list_create();
1979 debug(DBG_ERR, "malloc failed");
1983 for (n = 0; names[n]; n++) {
1984 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1985 conf = (struct clsrvconf *)entry->data;
1986 if (!strcasecmp(names[n], conf->name))
1990 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
1991 list_destroy(conflist);
1994 if (!list_push(conflist, conf)) {
1995 debug(DBG_ERR, "malloc failed");
1996 list_destroy(conflist);
1999 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2004 void freerealm(struct realm *realm) {
2007 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2008 if (--realm->refcount)
2012 free(realm->message);
2013 regfree(&realm->regex);
2014 pthread_mutex_destroy(&realm->mutex);
2015 /* if refcount == 0, all subrealms gone */
2016 list_destroy(realm->subrealms);
2017 /* if refcount == 0, all srvconfs gone */
2018 list_destroy(realm->srvconfs);
2019 /* if refcount == 0, all accsrvconfs gone */
2020 list_destroy(realm->accsrvconfs);
2021 freerealm(realm->parent);
2025 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2027 struct realm *realm;
2028 char *s, *regex = NULL;
2030 if (*value == '/') {
2031 /* regexp, remove optional trailing / if present */
2032 if (value[strlen(value) - 1] == '/')
2033 value[strlen(value) - 1] = '\0';
2035 /* not a regexp, let us make it one */
2036 if (*value == '*' && !value[1])
2037 regex = stringcopy(".*", 0);
2039 for (n = 0, s = value; *s;)
2042 regex = malloc(strlen(value) + n + 3);
2045 for (n = 1, s = value; *s; s++) {
2055 debug(DBG_ERR, "malloc failed");
2059 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2062 realm = malloc(sizeof(struct realm));
2064 debug(DBG_ERR, "malloc failed");
2067 memset(realm, 0, sizeof(struct realm));
2069 if (pthread_mutex_init(&realm->mutex, NULL)) {
2070 debug(DBG_ERR, "mutex init failed");
2076 realm->name = stringcopy(value, 0);
2078 debug(DBG_ERR, "malloc failed");
2081 if (message && strlen(message) > 253) {
2082 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2085 realm->message = message;
2086 realm->accresp = accresp;
2088 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2089 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2093 if (servers && *servers) {
2094 realm->srvconfs = addsrvconfs(value, servers);
2095 if (!realm->srvconfs)
2099 if (accservers && *accservers) {
2100 realm->accsrvconfs = addsrvconfs(value, accservers);
2101 if (!realm->accsrvconfs)
2105 if (!list_push(realmlist, realm)) {
2106 debug(DBG_ERR, "malloc failed");
2107 pthread_mutex_destroy(&realm->mutex);
2111 debug(DBG_DBG, "addrealm: added realm %s", value);
2115 while (list_shift(realm->srvconfs));
2116 while (list_shift(realm->accsrvconfs));
2123 for (n = 0; servers[n]; n++)
2125 freegconfmstr(servers);
2129 for (n = 0; accservers[n]; n++)
2131 freegconfmstr(accservers);
2133 return newrealmref(realm);
2136 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2137 struct list_node *entry;
2138 struct clsrvconf *conf, *srvconf;
2139 struct list *subrealmservers = NULL;
2142 if (list_first(srvconfs)) {
2143 subrealmservers = list_create();
2144 if (!subrealmservers)
2148 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2149 conf = (struct clsrvconf *)entry->data;
2150 if (!conf->servers && conf->dynamiclookupcommand) {
2151 srvconf = malloc(sizeof(struct clsrvconf));
2153 debug(DBG_ERR, "malloc failed");
2157 if (addserver(srvconf)) {
2158 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2159 srvconf->servers->dynstartup = 1;
2160 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2161 debug(DBG_ERR, "pthread_create failed");
2162 freeserver(srvconf->servers, 1);
2163 srvconf->servers = NULL;
2165 pthread_detach(clientth);
2169 if (conf->servers) {
2170 if (list_push(subrealmservers, conf))
2173 debug(DBG_ERR, "malloc failed");
2176 return subrealmservers;
2179 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2180 struct realm *newrealm = NULL;
2181 char *realmname, *s;
2183 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2184 realmname = strrchr(id, '@');
2190 for (s = realmname; *s; s++)
2191 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2194 if (!realm->subrealms)
2195 realm->subrealms = list_create();
2196 if (!realm->subrealms)
2199 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2201 list_destroy(realm->subrealms);
2202 realm->subrealms = NULL;
2206 newrealm->parent = newrealmref(realm);
2207 /* add server and accserver to newrealm */
2208 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2209 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2213 int dynamicconfig(struct server *server) {
2214 int ok, fd[2], status;
2216 struct clsrvconf *conf = server->conf;
2217 struct gconffile *cf = NULL;
2219 /* for now we only learn hostname/address */
2220 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2223 debug(DBG_ERR, "dynamicconfig: pipe error");
2228 debug(DBG_ERR, "dynamicconfig: fork error");
2232 } else if (pid == 0) {
2235 if (fd[1] != STDOUT_FILENO) {
2236 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2237 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2240 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2241 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2245 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2246 ok = getgenericconfig(&cf, NULL,
2247 "Server", CONF_CBK, confserver_cb, (void *)conf,
2252 if (waitpid(pid, &status, 0) < 0) {
2253 debug(DBG_ERR, "dynamicconfig: wait error");
2258 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2266 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2270 /* should accept both names and numeric values, only numeric right now */
2271 uint8_t attrname2val(char *attrname) {
2274 val = atoi(attrname);
2275 return val > 0 && val < 256 ? val : 0;
2278 /* ATTRNAME is on the form vendor[:type].
2279 If only vendor is found, TYPE is set to 256 and 1 is returned.
2280 If type is >= 256, 1 is returned.
2281 Otherwise, 0 is returned.
2283 /* should accept both names and numeric values, only numeric right now */
2284 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2287 *vendor = atoi(attrname);
2288 s = strchr(attrname, ':');
2289 if (!s) { /* Only vendor was found. */
2293 *type = atoi(s + 1);
2297 /** Extract attributes from string NAMEVAL, create a struct tlv and
2298 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2299 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2300 * NULL if fields are missing or if conversion fails.
2302 * FIXME: Should accept both names and numeric values, only numeric
2304 struct tlv *extractattr(char *nameval, char vendor_flag) {
2306 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2310 s = strchr(nameval, ':');
2313 name = atoi(nameval);
2316 s2 = strchr(s + 1, ':');
2323 len = strlen(s + 1);
2327 if (name < 1 || name > 255)
2329 a = malloc(sizeof(struct tlv));
2333 a->v = (uint8_t *)stringcopy(s + 1, 0);
2342 a = makevendortlv(vendor, a);
2347 /* should accept both names and numeric values, only numeric right now */
2348 struct modattr *extractmodattr(char *nameval) {
2353 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2357 s = strchr(nameval, ':');
2358 name = atoi(nameval);
2359 if (!s || name < 1 || name > 255 || s[1] != '/')
2363 /* regexp, remove optional trailing / if present */
2364 if (s[strlen(s) - 1] == '/')
2365 s[strlen(s) - 1] = '\0';
2373 m = malloc(sizeof(struct modattr));
2375 debug(DBG_ERR, "malloc failed");
2380 m->replacement = stringcopy(t, 0);
2381 if (!m->replacement) {
2383 debug(DBG_ERR, "malloc failed");
2387 m->regex = malloc(sizeof(regex_t));
2389 free(m->replacement);
2391 debug(DBG_ERR, "malloc failed");
2395 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2397 free(m->replacement);
2399 debug(DBG_ERR, "failed to compile regular expression %s", s);
2406 struct rewrite *getrewrite(char *alt1, char *alt2) {
2409 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2411 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2416 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2418 struct rewrite *rewrite = NULL;
2420 uint8_t *rma = NULL;
2421 uint32_t *p, *rmva = NULL;
2422 struct list *adda = NULL, *moda = NULL;
2427 for (n = 0; rmattrs[n]; n++);
2428 rma = calloc(n + 1, sizeof(uint8_t));
2430 debugx(1, DBG_ERR, "malloc failed");
2432 for (i = 0; i < n; i++)
2433 if (!(rma[i] = attrname2val(rmattrs[i])))
2434 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2435 freegconfmstr(rmattrs);
2440 for (n = 0; rmvattrs[n]; n++);
2441 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2443 debugx(1, DBG_ERR, "malloc failed");
2445 for (p = rmva, i = 0; i < n; i++, p += 2)
2446 if (!vattrname2val(rmvattrs[i], p, p + 1))
2447 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2448 freegconfmstr(rmvattrs);
2453 adda = list_create();
2455 debugx(1, DBG_ERR, "malloc failed");
2456 for (i = 0; addattrs[i]; i++) {
2457 a = extractattr(addattrs[i], 0);
2459 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2460 if (!list_push(adda, a))
2461 debugx(1, DBG_ERR, "malloc failed");
2463 freegconfmstr(addattrs);
2468 adda = list_create();
2470 debugx(1, DBG_ERR, "malloc failed");
2471 for (i = 0; addvattrs[i]; i++) {
2472 a = extractattr(addvattrs[i], 1);
2474 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2475 if (!list_push(adda, a))
2476 debugx(1, DBG_ERR, "malloc failed");
2478 freegconfmstr(addvattrs);
2482 moda = list_create();
2484 debugx(1, DBG_ERR, "malloc failed");
2485 for (i = 0; modattrs[i]; i++) {
2486 m = extractmodattr(modattrs[i]);
2488 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2489 if (!list_push(moda, m))
2490 debugx(1, DBG_ERR, "malloc failed");
2492 freegconfmstr(modattrs);
2495 if (rma || rmva || adda || moda) {
2496 rewrite = malloc(sizeof(struct rewrite));
2498 debugx(1, DBG_ERR, "malloc failed");
2499 rewrite->removeattrs = rma;
2500 rewrite->removevendorattrs = rmva;
2501 rewrite->addattrs = adda;
2502 rewrite->modattrs = moda;
2505 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2506 debugx(1, DBG_ERR, "malloc failed");
2507 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2510 int setttlattr(struct options *opts, char *defaultattr) {
2511 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2513 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2514 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2516 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2520 void freeclsrvconf(struct clsrvconf *conf) {
2523 freegconfmstr(conf->hostsrc);
2524 free(conf->portsrc);
2527 free(conf->matchcertattr);
2528 if (conf->certcnregex)
2529 regfree(conf->certcnregex);
2530 if (conf->certuriregex)
2531 regfree(conf->certuriregex);
2532 free(conf->confrewritein);
2533 free(conf->confrewriteout);
2534 if (conf->rewriteusername) {
2535 if (conf->rewriteusername->regex)
2536 regfree(conf->rewriteusername->regex);
2537 free(conf->rewriteusername->replacement);
2538 free(conf->rewriteusername);
2540 free(conf->dynamiclookupcommand);
2541 free(conf->rewritein);
2542 free(conf->rewriteout);
2543 if (conf->hostports)
2544 freehostports(conf->hostports);
2546 pthread_mutex_destroy(conf->lock);
2549 /* not touching ssl_ctx, clients and servers */
2553 int mergeconfstring(char **dst, char **src) {
2562 t = stringcopy(*dst, 0);
2564 debug(DBG_ERR, "malloc failed");
2572 char **mstringcopy(char **in) {
2579 for (n = 0; in[n]; n++);
2580 out = malloc((n + 1) * sizeof(char *));
2583 for (n = 0; in[n]; n++) {
2584 out[n] = stringcopy(in[n], 0);
2594 int mergeconfmstring(char ***dst, char ***src) {
2603 t = mstringcopy(*dst);
2605 debug(DBG_ERR, "malloc failed");
2613 /* assumes dst is a shallow copy */
2614 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2615 if (!mergeconfstring(&dst->name, &src->name) ||
2616 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2617 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2618 !mergeconfstring(&dst->secret, &src->secret) ||
2619 !mergeconfstring(&dst->tls, &src->tls) ||
2620 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2621 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2622 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2623 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2626 dst->pdef = src->pdef;
2627 dst->statusserver = src->statusserver;
2628 dst->certnamecheck = src->certnamecheck;
2629 if (src->retryinterval != 255)
2630 dst->retryinterval = src->retryinterval;
2631 if (src->retrycount != 255)
2632 dst->retrycount = src->retrycount;
2636 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2637 struct clsrvconf *conf;
2638 char *conftype = NULL, *rewriteinalias = NULL;
2639 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2641 debug(DBG_DBG, "confclient_cb called for %s", block);
2643 conf = malloc(sizeof(struct clsrvconf));
2645 debugx(1, DBG_ERR, "malloc failed");
2646 memset(conf, 0, sizeof(struct clsrvconf));
2647 conf->certnamecheck = 1;
2649 if (!getgenericconfig(cf, block,
2650 "type", CONF_STR, &conftype,
2651 "host", CONF_MSTR, &conf->hostsrc,
2652 "secret", CONF_STR, &conf->secret,
2653 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2654 "tls", CONF_STR, &conf->tls,
2655 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2656 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2658 "DuplicateInterval", CONF_LINT, &dupinterval,
2659 "addTTL", CONF_LINT, &addttl,
2660 "rewrite", CONF_STR, &rewriteinalias,
2661 "rewriteIn", CONF_STR, &conf->confrewritein,
2662 "rewriteOut", CONF_STR, &conf->confrewriteout,
2663 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2666 debugx(1, DBG_ERR, "configuration error");
2668 conf->name = stringcopy(val, 0);
2669 if (conf->name && !conf->hostsrc) {
2670 conf->hostsrc = malloc(2 * sizeof(char *));
2671 if (conf->hostsrc) {
2672 conf->hostsrc[0] = stringcopy(val, 0);
2673 conf->hostsrc[1] = NULL;
2676 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2677 debugx(1, DBG_ERR, "malloc failed");
2680 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2681 conf->type = protoname2int(conftype);
2682 if (conf->type == 255)
2683 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2685 conf->pdef = protodefs[conf->type];
2687 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2688 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2689 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2691 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2692 if (conf->matchcertattr && !addmatchcertattr(conf))
2693 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2697 if (dupinterval != LONG_MIN) {
2698 if (dupinterval < 0 || dupinterval > 255)
2699 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2700 conf->dupinterval = (uint8_t)dupinterval;
2702 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2704 if (addttl != LONG_MIN) {
2705 if (addttl < 1 || addttl > 255)
2706 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2707 conf->addttl = (uint8_t)addttl;
2710 if (!conf->confrewritein)
2711 conf->confrewritein = rewriteinalias;
2713 free(rewriteinalias);
2714 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2715 if (conf->confrewriteout)
2716 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2718 if (conf->confrewriteusername) {
2719 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2720 if (!conf->rewriteusername)
2721 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2724 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2725 !resolvehostports(conf->hostports, conf->pdef->socktype))
2726 debugx(1, DBG_ERR, "resolve failed, exiting");
2728 if (!conf->secret) {
2729 if (!conf->pdef->secretdefault)
2730 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2731 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2733 debugx(1, DBG_ERR, "malloc failed");
2736 conf->lock = malloc(sizeof(pthread_mutex_t));
2738 debugx(1, DBG_ERR, "malloc failed");
2740 pthread_mutex_init(conf->lock, NULL);
2741 if (!list_push(clconfs, conf))
2742 debugx(1, DBG_ERR, "malloc failed");
2746 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2747 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2748 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2749 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2750 if (!conf->tlsconf) {
2751 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2754 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2755 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2761 if (!conf->portsrc) {
2762 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2763 if (!conf->portsrc) {
2764 debug(DBG_ERR, "malloc failed");
2769 if (conf->retryinterval == 255)
2770 conf->retryinterval = conf->pdef->retryintervaldefault;
2771 if (conf->retrycount == 255)
2772 conf->retrycount = conf->pdef->retrycountdefault;
2774 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2775 if (conf->confrewriteout)
2776 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2778 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2779 debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2783 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2784 debug(DBG_ERR, "resolve failed, exiting");
2790 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2791 struct clsrvconf *conf, *resconf;
2792 char *conftype = NULL, *rewriteinalias = NULL;
2793 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2795 debug(DBG_DBG, "confserver_cb called for %s", block);
2797 conf = malloc(sizeof(struct clsrvconf));
2799 debug(DBG_ERR, "malloc failed");
2802 memset(conf, 0, sizeof(struct clsrvconf));
2803 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2804 resconf = (struct clsrvconf *)arg;
2806 conf->statusserver = resconf->statusserver;
2807 conf->certnamecheck = resconf->certnamecheck;
2809 conf->certnamecheck = 1;
2811 if (!getgenericconfig(cf, block,
2812 "type", CONF_STR, &conftype,
2813 "host", CONF_MSTR, &conf->hostsrc,
2814 "port", CONF_STR, &conf->portsrc,
2815 "secret", CONF_STR, &conf->secret,
2816 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2817 "tls", CONF_STR, &conf->tls,
2818 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2819 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2821 "addTTL", CONF_LINT, &addttl,
2822 "rewrite", CONF_STR, &rewriteinalias,
2823 "rewriteIn", CONF_STR, &conf->confrewritein,
2824 "rewriteOut", CONF_STR, &conf->confrewriteout,
2825 "StatusServer", CONF_BLN, &conf->statusserver,
2826 "RetryInterval", CONF_LINT, &retryinterval,
2827 "RetryCount", CONF_LINT, &retrycount,
2828 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2829 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2832 debug(DBG_ERR, "configuration error");
2836 conf->name = stringcopy(val, 0);
2837 if (conf->name && !conf->hostsrc) {
2838 conf->hostsrc = malloc(2 * sizeof(char *));
2839 if (conf->hostsrc) {
2840 conf->hostsrc[0] = stringcopy(val, 0);
2841 conf->hostsrc[1] = NULL;
2844 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2845 debug(DBG_ERR, "malloc failed");
2850 debug(DBG_ERR, "error in block %s, option type missing", block);
2853 conf->type = protoname2int(conftype);
2854 if (conf->type == 255) {
2855 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2861 conf->pdef = protodefs[conf->type];
2863 if (!conf->confrewritein)
2864 conf->confrewritein = rewriteinalias;
2866 free(rewriteinalias);
2867 rewriteinalias = NULL;
2869 if (retryinterval != LONG_MIN) {
2870 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2871 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2874 conf->retryinterval = (uint8_t)retryinterval;
2876 conf->retryinterval = 255;
2878 if (retrycount != LONG_MIN) {
2879 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2880 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2883 conf->retrycount = (uint8_t)retrycount;
2885 conf->retrycount = 255;
2887 if (addttl != LONG_MIN) {
2888 if (addttl < 1 || addttl > 255) {
2889 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2892 conf->addttl = (uint8_t)addttl;
2896 if (!mergesrvconf(resconf, conf))
2900 if (conf->dynamiclookupcommand) {
2901 free(conf->dynamiclookupcommand);
2902 conf->dynamiclookupcommand = NULL;
2906 if (resconf || !conf->dynamiclookupcommand) {
2907 if (!compileserverconfig(conf, block))
2911 if (!conf->secret) {
2912 if (!conf->pdef->secretdefault) {
2913 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2916 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2917 if (!conf->secret) {
2918 debug(DBG_ERR, "malloc failed");
2926 if (!list_push(srvconfs, conf)) {
2927 debug(DBG_ERR, "malloc failed");
2934 free(rewriteinalias);
2935 freeclsrvconf(conf);
2939 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2940 char **servers = NULL, **accservers = NULL, *msg = NULL;
2941 uint8_t accresp = 0;
2943 debug(DBG_DBG, "confrealm_cb called for %s", block);
2945 if (!getgenericconfig(cf, block,
2946 "server", CONF_MSTR, &servers,
2947 "accountingServer", CONF_MSTR, &accservers,
2948 "ReplyMessage", CONF_STR, &msg,
2949 "AccountingResponse", CONF_BLN, &accresp,
2952 debugx(1, DBG_ERR, "configuration error");
2954 addrealm(realms, val, servers, accservers, msg, accresp);
2958 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2959 char **rmattrs = NULL, **rmvattrs = NULL;
2960 char **addattrs = NULL, **addvattrs = NULL;
2961 char **modattrs = NULL;
2963 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2965 if (!getgenericconfig(cf, block,
2966 "removeAttribute", CONF_MSTR, &rmattrs,
2967 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2968 "addAttribute", CONF_MSTR, &addattrs,
2969 "addVendorAttribute", CONF_MSTR, &addvattrs,
2970 "modifyAttribute", CONF_MSTR, &modattrs,
2973 debugx(1, DBG_ERR, "configuration error");
2974 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2978 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2979 struct commonprotoopts *protoopts;
2981 protoopts = malloc(sizeof(struct commonprotoopts));
2984 memset(protoopts, 0, sizeof(struct commonprotoopts));
2985 protoopts->listenargs = listenargs;
2986 protoopts->sourcearg = sourcearg;
2987 protodefs[type]->setprotoopts(protoopts);
2991 void getmainconfig(const char *configfile) {
2992 long int addttl = LONG_MIN, loglevel = LONG_MIN;
2993 struct gconffile *cfs;
2994 char **listenargs[RAD_PROTOCOUNT];
2995 char *sourcearg[RAD_PROTOCOUNT];
2998 cfs = openconfigfile(configfile);
2999 memset(&options, 0, sizeof(options));
3000 memset(&listenargs, 0, sizeof(listenargs));
3001 memset(&sourcearg, 0, sizeof(sourcearg));
3003 clconfs = list_create();
3005 debugx(1, DBG_ERR, "malloc failed");
3007 srvconfs = list_create();
3009 debugx(1, DBG_ERR, "malloc failed");
3011 realms = list_create();
3013 debugx(1, DBG_ERR, "malloc failed");
3015 rewriteconfs = hash_create();
3017 debugx(1, DBG_ERR, "malloc failed");
3019 if (!getgenericconfig(&cfs, NULL,
3021 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3022 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3025 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3026 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3029 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3030 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3033 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3034 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3036 "TTLAttribute", CONF_STR, &options.ttlattr,
3037 "addTTL", CONF_LINT, &addttl,
3038 "LogLevel", CONF_LINT, &loglevel,
3039 "LogDestination", CONF_STR, &options.logdestination,
3040 "LoopPrevention", CONF_BLN, &options.loopprevention,
3041 "Client", CONF_CBK, confclient_cb, NULL,
3042 "Server", CONF_CBK, confserver_cb, NULL,
3043 "Realm", CONF_CBK, confrealm_cb, NULL,
3044 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3045 "TLS", CONF_CBK, conftls_cb, NULL,
3047 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3050 debugx(1, DBG_ERR, "configuration error");
3052 if (loglevel != LONG_MIN) {
3053 if (loglevel < 1 || loglevel > 4)
3054 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3055 options.loglevel = (uint8_t)loglevel;
3057 if (addttl != LONG_MIN) {
3058 if (addttl < 1 || addttl > 255)
3059 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3060 options.addttl = (uint8_t)addttl;
3062 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3063 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3065 for (i = 0; i < RAD_PROTOCOUNT; i++)
3066 if (listenargs[i] || sourcearg[i])
3067 setprotoopts(i, listenargs[i], sourcearg[i]);
3070 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3073 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3076 *configfile = optarg;
3079 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3080 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3081 *loglevel = *optarg - '0';
3093 debug(DBG_ERR, "radsecproxy revision $Rev$");
3094 debug(DBG_ERR, "This binary was built with support for the following transports:");
3096 debug(DBG_ERR, " UDP");
3099 debug(DBG_ERR, " TCP");
3102 debug(DBG_ERR, " TLS");
3105 debug(DBG_ERR, " DTLS");
3112 if (!(argc - optind))
3116 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3120 int daemon(int a, int b) {
3128 for (i = 0; i < 3; i++) {
3130 open("/dev/null", O_RDWR);
3136 void *sighandler(void *arg) {
3141 sigemptyset(&sigset);
3142 sigaddset(&sigset, SIGHUP);
3143 sigaddset(&sigset, SIGPIPE);
3144 sigwait(&sigset, &sig);
3147 /* completely ignoring this */
3150 debug(DBG_INFO, "sighandler: got SIGHUP");
3154 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3157 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3162 int createpidfile(const char *pidfile) {
3164 FILE *f = fopen(pidfile, "w");
3166 r = fprintf(f, "%d\n", getpid());
3167 return f && !fclose(f) && r >= 0;
3170 int main(int argc, char **argv) {
3173 struct list_node *entry;
3174 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3175 char *configfile = NULL, *pidfile = NULL;
3176 struct clsrvconf *srvconf;
3179 debug_init("radsecproxy");
3180 debug_set_level(DEBUG_LEVEL);
3182 for (i = 0; i < RAD_PROTOCOUNT; i++)
3183 protodefs[i] = protoinits[i](i);
3185 /* needed even if no TLS/DTLS transport */
3188 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3190 debug_set_level(loglevel);
3191 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3193 options.loglevel = loglevel;
3194 else if (options.loglevel)
3195 debug_set_level(options.loglevel);
3197 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3198 free(options.logdestination);
3200 if (!list_first(clconfs))
3201 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3202 if (!list_first(realms))
3203 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3206 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3208 if (!foreground && (daemon(0, 0) < 0))
3209 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3211 debug_timestamp_on();
3212 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3213 if (pidfile && !createpidfile(pidfile))
3214 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3216 sigemptyset(&sigset);
3217 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3218 sigaddset(&sigset, SIGHUP);
3219 sigaddset(&sigset, SIGPIPE);
3220 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3221 pthread_create(&sigth, NULL, sighandler, NULL);
3223 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3224 srvconf = (struct clsrvconf *)entry->data;
3225 if (srvconf->dynamiclookupcommand)
3227 if (!addserver(srvconf))
3228 debugx(1, DBG_ERR, "failed to add server");
3229 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3230 (void *)(srvconf->servers)))
3231 debugx(1, DBG_ERR, "pthread_create failed");
3234 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3237 if (protodefs[i]->initextra)
3238 protodefs[i]->initextra();
3239 if (find_clconf_type(i, NULL))
3243 /* just hang around doing nothing, anything to do here? */
3248 /* Local Variables: */
3249 /* c-file-style: "stroustrup" */