2 * Copyright (C) 2006-2009 Stig Venaas <venaas@uninett.no>
3 * Copyright (C) 2010, 2011 NORDUnet A/S
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
10 /* Code contributions from:
12 * Arne Schwabe <schwabe at uni-paderborn.de>
13 * Maja Wolniewicz <mgw@umk.pl>
14 * Simon Leinen <simon.leinen@switch.ch>
15 * Stefan Winter <stefan.winter@restena.lu>
18 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
19 * rd is responsible for init and launching wr
20 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
21 * each tlsserverrd launches tlsserverwr
22 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
23 * for init and launching rd
25 * serverrd will receive a request, processes it and puts it in the requestq of
26 * the appropriate clientwr
27 * clientwr monitors its requestq and sends requests
28 * clientrd looks for responses, processes them and puts them in the replyq of
29 * the peer the request came from
30 * serverwr monitors its reply and sends replies
32 * In addition to the main thread, we have:
33 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
34 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
35 * For each TLS peer connecting to us there will be 2 more TLS threads
36 * This is only for connected peers
37 * Example: With 3 UDP peers and 30 TLS peers, there will be a max of
38 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
42 * May segfault when dtls connections go down? More testing needed
43 * Remove expired stuff from clients request list?
44 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
45 * Useful for TCP accounting? Now we require separate server config for alt port
49 #include <sys/socket.h>
50 #include <netinet/in.h>
59 #include <sys/types.h>
62 #include <arpa/inet.h>
67 #include <openssl/ssl.h>
68 #include <openssl/rand.h>
69 #include <openssl/err.h>
70 #include <openssl/md5.h>
75 #include "radsecproxy.h"
82 static struct options options;
83 static struct list *clconfs, *srvconfs;
84 static struct list *realms;
85 static struct hash *rewriteconfs;
87 static pthread_mutex_t *ssl_locks = NULL;
88 static long *ssl_lock_count;
91 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
93 /* minimum required declarations to avoid reordering code */
94 struct realm *adddynamicrealmserver(struct realm *realm, char *id);
95 int dynamicconfig(struct server *server);
96 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
97 void freerealm(struct realm *realm);
98 void freeclsrvconf(struct clsrvconf *conf);
99 void freerq(struct request *rq);
100 void freerqoutdata(struct rqout *rqout);
101 void rmclientrq(struct request *rq, uint8_t id);
103 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
105 uint8_t protoname2int(const char *name) {
108 for (i = 0; i < RAD_PROTOCOUNT; i++)
109 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
114 /* callbacks for making OpenSSL thread safe */
115 unsigned long ssl_thread_id() {
116 return (unsigned long)pthread_self();
119 void ssl_locking_callback(int mode, int type, const char *file, int line) {
120 if (mode & CRYPTO_LOCK) {
121 pthread_mutex_lock(&ssl_locks[type]);
122 ssl_lock_count[type]++;
124 pthread_mutex_unlock(&ssl_locks[type]);
127 /* returns 1 if the len first bits are equal, else 0 */
128 int prefixmatch(void *a1, void *a2, uint8_t len) {
129 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
130 uint8_t r, l = len / 8;
131 if (l && memcmp(a1, a2, l))
136 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
139 /* returns next config with matching address, or NULL */
140 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur, uint8_t server_p) {
141 struct list_node *entry;
142 struct clsrvconf *conf;
144 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
145 conf = (struct clsrvconf *)entry->data;
146 if (conf->type == type && addressmatches(conf->hostports, addr, server_p)) {
155 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
156 return find_conf(type, addr, clconfs, cur, 0);
159 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
160 return find_conf(type, addr, srvconfs, cur, 1);
163 /* returns next config of given type, or NULL */
164 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
165 struct list_node *entry;
166 struct clsrvconf *conf;
168 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
169 conf = (struct clsrvconf *)entry->data;
170 if (conf->type == type) {
179 struct gqueue *newqueue() {
182 q = malloc(sizeof(struct gqueue));
184 debugx(1, DBG_ERR, "malloc failed");
185 q->entries = list_create();
187 debugx(1, DBG_ERR, "malloc failed");
188 pthread_mutex_init(&q->mutex, NULL);
189 pthread_cond_init(&q->cond, NULL);
193 void removequeue(struct gqueue *q) {
194 struct list_node *entry;
198 pthread_mutex_lock(&q->mutex);
199 for (entry = list_first(q->entries); entry; entry = list_next(entry))
200 freerq((struct request *)entry);
201 list_destroy(q->entries);
202 pthread_cond_destroy(&q->cond);
203 pthread_mutex_unlock(&q->mutex);
204 pthread_mutex_destroy(&q->mutex);
208 void freebios(struct gqueue *q) {
211 pthread_mutex_lock(&q->mutex);
212 while ((bio = (BIO *)list_shift(q->entries)))
214 pthread_mutex_unlock(&q->mutex);
218 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
219 struct client *new = malloc(sizeof(struct client));
222 debug(DBG_ERR, "malloc failed");
227 pthread_mutex_lock(conf->lock);
228 if (!conf->clients) {
229 conf->clients = list_create();
230 if (!conf->clients) {
232 pthread_mutex_unlock(conf->lock);
233 debug(DBG_ERR, "malloc failed");
238 memset(new, 0, sizeof(struct client));
240 if (conf->pdef->addclient)
241 conf->pdef->addclient(new);
243 new->replyq = newqueue();
244 list_push(conf->clients, new);
246 pthread_mutex_unlock(conf->lock);
250 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
251 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
254 pthread_mutex_lock(&lock);
256 pthread_mutex_unlock(&lock);
259 void removeclientrqs(struct client *client) {
264 removeclientrqs_sendrq_freeserver_lock(1);
265 for (i = 0; i < MAX_REQUESTS; i++) {
270 rqout = rq->to->requests + rq->newid;
271 pthread_mutex_lock(rqout->lock);
272 if (rqout->rq == rq) /* still pointing to our request */
273 freerqoutdata(rqout);
274 pthread_mutex_unlock(rqout->lock);
278 removeclientrqs_sendrq_freeserver_lock(0);
281 void removelockedclient(struct client *client) {
282 struct clsrvconf *conf;
286 removeclientrqs(client);
287 removequeue(client->replyq);
288 list_removedata(conf->clients, client);
294 void removeclient(struct client *client) {
295 struct clsrvconf *conf;
301 pthread_mutex_lock(conf->lock);
302 removelockedclient(client);
303 pthread_mutex_unlock(conf->lock);
306 void freeserver(struct server *server, uint8_t destroymutex) {
307 struct rqout *rqout, *end;
312 removeclientrqs_sendrq_freeserver_lock(1);
313 if (server->requests) {
314 rqout = server->requests;
315 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
317 rqout->rq->to = NULL;
318 freerqoutdata(rqout);
319 pthread_mutex_destroy(rqout->lock);
322 free(server->requests);
325 freebios(server->rbios);
326 free(server->dynamiclookuparg);
328 SSL_free(server->ssl);
330 pthread_mutex_destroy(&server->lock);
331 pthread_cond_destroy(&server->newrq_cond);
332 pthread_mutex_destroy(&server->newrq_mutex);
334 removeclientrqs_sendrq_freeserver_lock(0);
338 int addserver(struct clsrvconf *conf) {
342 debug(DBG_ERR, "addserver: currently works with just one server per conf");
345 conf->servers = malloc(sizeof(struct server));
346 if (!conf->servers) {
347 debug(DBG_ERR, "malloc failed");
350 memset(conf->servers, 0, sizeof(struct server));
351 conf->servers->conf = conf;
354 if (conf->type == RAD_DTLS)
355 conf->servers->rbios = newqueue();
357 conf->pdef->setsrcres();
359 conf->servers->sock = -1;
360 if (conf->pdef->addserverextra)
361 conf->pdef->addserverextra(conf);
363 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
364 if (!conf->servers->requests) {
365 debug(DBG_ERR, "malloc failed");
368 for (i = 0; i < MAX_REQUESTS; i++) {
369 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
370 if (!conf->servers->requests[i].lock) {
371 debug(DBG_ERR, "malloc failed");
374 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
375 debugerrno(errno, DBG_ERR, "mutex init failed");
376 free(conf->servers->requests[i].lock);
377 conf->servers->requests[i].lock = NULL;
381 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
382 debugerrno(errno, DBG_ERR, "mutex init failed");
385 conf->servers->newrq = 0;
386 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
387 debugerrno(errno, DBG_ERR, "mutex init failed");
388 pthread_mutex_destroy(&conf->servers->lock);
391 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
392 debugerrno(errno, DBG_ERR, "mutex init failed");
393 pthread_mutex_destroy(&conf->servers->newrq_mutex);
394 pthread_mutex_destroy(&conf->servers->lock);
401 freeserver(conf->servers, 0);
402 conf->servers = NULL;
406 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
408 if (ATTRTYPE(attrs) == type)
410 length -= ATTRLEN(attrs);
411 attrs += ATTRLEN(attrs);
416 struct request *newrqref(struct request *rq) {
422 void freerq(struct request *rq) {
425 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
428 if (rq->origusername)
429 free(rq->origusername);
435 radmsg_free(rq->msg);
439 void freerqoutdata(struct rqout *rqout) {
443 if (rqout->rq->buf) {
444 free(rqout->rq->buf);
445 rqout->rq->buf = NULL;
451 memset(&rqout->expiry, 0, sizeof(struct timeval));
454 void sendrq(struct request *rq) {
458 removeclientrqs_sendrq_freeserver_lock(1);
463 start = to->conf->statusserver ? 1 : 0;
464 pthread_mutex_lock(&to->newrq_mutex);
465 if (start && rq->msg->code == RAD_Status_Server) {
466 pthread_mutex_lock(to->requests[0].lock);
467 if (to->requests[0].rq) {
468 pthread_mutex_unlock(to->requests[0].lock);
469 debug(DBG_INFO, "sendrq: status server already in queue, dropping request");
476 /* might simplify if only try nextid, might be ok */
477 for (i = to->nextid; i < MAX_REQUESTS; i++) {
478 if (!to->requests[i].rq) {
479 pthread_mutex_lock(to->requests[i].lock);
480 if (!to->requests[i].rq)
482 pthread_mutex_unlock(to->requests[i].lock);
485 if (i == MAX_REQUESTS) {
486 for (i = start; i < to->nextid; i++) {
487 if (!to->requests[i].rq) {
488 pthread_mutex_lock(to->requests[i].lock);
489 if (!to->requests[i].rq)
491 pthread_mutex_unlock(to->requests[i].lock);
494 if (i == to->nextid) {
495 debug(DBG_INFO, "sendrq: no room in queue, dropping request");
500 rq->newid = (uint8_t)i;
501 rq->msg->id = (uint8_t)i;
502 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
504 pthread_mutex_unlock(to->requests[i].lock);
505 debug(DBG_ERR, "sendrq: radmsg2buf failed");
509 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->name);
510 to->requests[i].rq = rq;
511 pthread_mutex_unlock(to->requests[i].lock);
512 if (i >= start) /* i is not reserved for statusserver */
517 debug(DBG_DBG, "sendrq: signalling client writer");
518 pthread_cond_signal(&to->newrq_cond);
521 pthread_mutex_unlock(&to->newrq_mutex);
522 removeclientrqs_sendrq_freeserver_lock(0);
527 rmclientrq(rq, rq->msg->id);
529 pthread_mutex_unlock(&to->newrq_mutex);
530 removeclientrqs_sendrq_freeserver_lock(0);
533 void sendreply(struct request *rq) {
535 struct client *to = rq->from;
538 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
539 radmsg_free(rq->msg);
543 debug(DBG_ERR, "sendreply: radmsg2buf failed");
547 pthread_mutex_lock(&to->replyq->mutex);
548 first = list_first(to->replyq->entries) == NULL;
550 if (!list_push(to->replyq->entries, rq)) {
551 pthread_mutex_unlock(&to->replyq->mutex);
553 debug(DBG_ERR, "sendreply: malloc failed");
558 debug(DBG_DBG, "signalling server writer");
559 pthread_cond_signal(&to->replyq->cond);
561 pthread_mutex_unlock(&to->replyq->mutex);
564 int pwdcrypt(char encrypt_flag, uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
565 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
566 static unsigned char first = 1;
567 static EVP_MD_CTX mdctx;
568 unsigned char hash[EVP_MAX_MD_SIZE], *input;
570 uint8_t i, offset = 0, out[128];
572 pthread_mutex_lock(&lock);
574 EVP_MD_CTX_init(&mdctx);
580 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
581 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
582 !EVP_DigestUpdate(&mdctx, input, 16) ||
583 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
585 pthread_mutex_unlock(&lock);
588 for (i = 0; i < 16; i++)
589 out[offset + i] = hash[i] ^ in[offset + i];
591 input = out + offset;
598 memcpy(in, out, len);
599 pthread_mutex_unlock(&lock);
603 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
604 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
605 static unsigned char first = 1;
606 static EVP_MD_CTX mdctx;
607 unsigned char hash[EVP_MAX_MD_SIZE];
611 pthread_mutex_lock(&lock);
613 EVP_MD_CTX_init(&mdctx);
618 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
619 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
620 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
623 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
624 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
625 !EVP_DigestUpdate(&mdctx, auth, 16) ||
626 !EVP_DigestUpdate(&mdctx, salt, 2) ||
627 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
628 pthread_mutex_unlock(&lock);
633 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
636 for (i = 0; i < 16; i++)
639 for (offset = 16; offset < len; offset += 16) {
641 printf("text + offset - 16 c(%d): ", offset / 16);
642 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
644 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
645 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
646 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
647 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
649 pthread_mutex_unlock(&lock);
653 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
656 for (i = 0; i < 16; i++)
657 text[offset + i] ^= hash[i];
661 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
664 pthread_mutex_unlock(&lock);
668 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
669 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
670 static unsigned char first = 1;
671 static EVP_MD_CTX mdctx;
672 unsigned char hash[EVP_MAX_MD_SIZE];
677 pthread_mutex_lock(&lock);
679 EVP_MD_CTX_init(&mdctx);
684 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
685 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
686 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
689 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
690 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
691 !EVP_DigestUpdate(&mdctx, auth, 16) ||
692 !EVP_DigestUpdate(&mdctx, salt, 2) ||
693 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
694 pthread_mutex_unlock(&lock);
699 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
702 for (i = 0; i < 16; i++)
703 plain[i] = text[i] ^ hash[i];
705 for (offset = 16; offset < len; offset += 16) {
707 printf("text + offset - 16 c(%d): ", offset / 16);
708 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
710 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
711 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
712 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
713 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
715 pthread_mutex_unlock(&lock);
719 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
722 for (i = 0; i < 16; i++)
723 plain[offset + i] = text[offset + i] ^ hash[i];
726 memcpy(text, plain, len);
728 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
731 pthread_mutex_unlock(&lock);
735 struct realm *newrealmref(struct realm *r) {
741 /* returns with lock on realm */
742 struct realm *id2realm(struct list *realmlist, char *id) {
743 struct list_node *entry;
744 struct realm *realm, *subrealm;
746 /* need to do locking for subrealms and check subrealm timers */
747 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
748 realm = (struct realm *)entry->data;
749 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
750 pthread_mutex_lock(&realm->mutex);
751 if (realm->subrealms) {
752 subrealm = id2realm(realm->subrealms, id);
754 pthread_mutex_unlock(&realm->mutex);
758 return newrealmref(realm);
764 int hasdynamicserver(struct list *srvconfs) {
765 struct list_node *entry;
767 for (entry = list_first(srvconfs); entry; entry = list_next(entry))
768 if (((struct clsrvconf *)entry->data)->dynamiclookupcommand)
773 /* helper function, only used by removeserversubrealms() */
774 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
775 struct list_node *entry, *entry2;
778 for (entry = list_first(realmlist); entry;) {
779 realm = newrealmref((struct realm *)entry->data);
780 pthread_mutex_lock(&realm->mutex);
781 entry = list_next(entry);
783 if (realm->srvconfs) {
784 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
785 if (entry2->data == srv)
787 list_removedata(realm->srvconfs, srv);
789 if (realm->accsrvconfs) {
790 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
791 if (entry2->data == srv)
793 list_removedata(realm->accsrvconfs, srv);
796 /* remove subrealm if no dynamic servers left */
797 if (!hasdynamicserver(realm->srvconfs) && !hasdynamicserver(realm->accsrvconfs)) {
798 while (list_shift(realm->srvconfs))
800 list_destroy(realm->srvconfs);
801 realm->srvconfs = NULL;
802 while (list_shift(realm->accsrvconfs))
804 list_destroy(realm->accsrvconfs);
805 realm->accsrvconfs = NULL;
806 list_removedata(realmlist, realm);
808 pthread_mutex_unlock(&realm->mutex);
813 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
814 struct list_node *entry;
817 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
818 realm = (struct realm *)entry->data;
819 pthread_mutex_lock(&realm->mutex);
820 if (realm->subrealms) {
821 _internal_removeserversubrealms(realm->subrealms, srv);
822 if (!list_first(realm->subrealms)) {
823 list_destroy(realm->subrealms);
824 realm->subrealms = NULL;
827 pthread_mutex_unlock(&realm->mutex);
831 int attrvalidate(unsigned char *attrs, int length) {
833 if (ATTRLEN(attrs) < 2) {
834 debug(DBG_INFO, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
837 length -= ATTRLEN(attrs);
839 debug(DBG_INFO, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
842 attrs += ATTRLEN(attrs);
845 debug(DBG_INFO, "attrvalidate: malformed packet? remaining byte after last attribute");
849 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
850 if (len < 16 || len > 128 || len % 16) {
851 debug(DBG_WARN, "pwdrecrypt: invalid password length");
855 if (!pwdcrypt(0, pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
856 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
860 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
862 if (!pwdcrypt(1, pwd, len, newsecret, strlen(newsecret), newauth)) {
863 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
869 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
872 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
873 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
876 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
877 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
883 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
884 char *oldsecret, char *newsecret) {
887 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
888 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
889 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
895 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint32_t subattr) {
899 for (; attrs[0]; attrs += 2)
900 if (attrs[0] == vendor && attrs[1] == subattr)
905 /* returns 1 if entire element is to be removed, else 0 */
906 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
907 uint8_t alen, sublen;
911 if (!removevendorattrs)
914 memcpy(&vendor, attr->v, 4);
915 vendor = ntohl(vendor);
916 while (*removevendorattrs && *removevendorattrs != vendor)
917 removevendorattrs += 2;
918 if (!*removevendorattrs)
921 if (findvendorsubattr(removevendorattrs, vendor, 256))
922 return 1; /* remove entire vendor attribute */
924 sublen = attr->l - 4;
925 subattrs = attr->v + 4;
927 if (!attrvalidate(subattrs, sublen)) {
928 debug(DBG_INFO, "dovendorrewrite: vendor attribute validation failed, no rewrite");
933 alen = ATTRLEN(subattrs);
935 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
936 memmove(subattrs, subattrs + alen, sublen);
944 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
945 struct list_node *n, *p;
949 n = list_first(msg->attrs);
951 attr = (struct tlv *)n->data;
952 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
953 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
954 list_removedata(msg->attrs, attr);
956 n = p ? list_next(p) : list_first(msg->attrs);
964 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
968 for (n = list_first(addattrs); n; n = list_next(n)) {
969 a = copytlv((struct tlv *)n->data);
972 if (!radmsg_add(msg, a)) {
980 int resizeattr(struct tlv *attr, uint8_t newlen) {
983 if (newlen != attr->l) {
984 newv = realloc(attr->v, newlen);
993 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
994 size_t nmatch = 10, reslen = 0, start = 0;
995 regmatch_t pmatch[10], *pfield;
999 in = stringcopy((char *)attr->v, attr->l);
1003 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1008 out = modattr->replacement;
1010 for (i = start; out[i]; i++) {
1011 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1012 pfield = &pmatch[out[i + 1] - '0'];
1013 if (pfield->rm_so >= 0) {
1014 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1020 reslen += i - start;
1022 debug(DBG_INFO, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1027 if (!resizeattr(attr, reslen)) {
1034 for (i = start; out[i]; i++) {
1035 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1036 pfield = &pmatch[out[i + 1] - '0'];
1037 if (pfield->rm_so >= 0) {
1038 memcpy(attr->v + reslen, out + start, i - start);
1039 reslen += i - start;
1040 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1041 reslen += pfield->rm_eo - pfield->rm_so;
1048 memcpy(attr->v + reslen, out + start, i - start);
1052 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1053 struct list_node *n, *m;
1055 for (n = list_first(msg->attrs); n; n = list_next(n))
1056 for (m = list_first(modattrs); m; m = list_next(m))
1057 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1058 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1063 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1064 int rv = 1; /* Success. */
1067 if (rewrite->removeattrs || rewrite->removevendorattrs)
1068 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1069 if (rewrite->modattrs)
1070 if (!dorewritemod(msg, rewrite->modattrs))
1072 if (rewrite->addattrs)
1073 if (!dorewriteadd(msg, rewrite->addattrs))
1079 int rewriteusername(struct request *rq, struct tlv *attr) {
1080 char *orig = (char *)tlv2str(attr);
1081 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1085 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1086 rq->origusername = (char *)orig;
1092 /** Create vendor specific tlv with ATTR. ATTR is consumed (freed) if
1093 * all is well with the new tlv, i.e. if the function returns
1096 makevendortlv(uint32_t vendor, struct tlv *attr)
1098 struct tlv *newtlv = NULL;
1106 vendor = htonl(vendor & 0x00ffffff); /* MSB=0 according to RFC 2865. */
1107 memcpy(v, &vendor, 4);
1108 tlv2buf(v + 4, attr);
1109 v[5] += 2; /* Vendor length increased for type and length fields. */
1110 newtlv = maketlv(RAD_Attr_Vendor_Specific, l, v);
1119 /** Ad vendor attribute with VENDOR + ATTR and push it on MSG. ATTR
1121 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1124 vattr = makevendortlv(vendor, attr);
1129 if (!radmsg_add(msg, vattr)) {
1136 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1143 if (attrtype[1] == 256) { /* not vendor */
1144 attr = maketlv(attrtype[0], 4, ttl);
1145 if (attr && !radmsg_add(msg, attr))
1148 attr = maketlv(attrtype[1], 4, ttl);
1150 addvendorattr(msg, attrtype[0], attr);
1154 int decttl(uint8_t l, uint8_t *v) {
1161 while (i >= 0 && !v[i])
1165 for (i--; i >= 0 && !v[i]; i--);
1174 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1175 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1176 uint8_t alen, *subattrs;
1178 struct list_node *node;
1182 if (attrtype[1] == 256) { /* not vendor */
1183 attr = radmsg_gettype(msg, attrtype[0]);
1185 return decttl(attr->l, attr->v);
1187 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1188 attr = (struct tlv *)node->data;
1189 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1191 memcpy(&vendor, attr->v, 4);
1192 if (ntohl(vendor) != attrtype[0])
1194 sublen = attr->l - 4;
1195 subattrs = attr->v + 4;
1196 if (!attrvalidate(subattrs, sublen))
1198 while (sublen > 1) {
1199 if (ATTRTYPE(subattrs) == attrtype[1])
1200 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1201 alen = ATTRLEN(subattrs);
1209 const char *radmsgtype2string(uint8_t code) {
1210 static const char *rad_msg_names[] = {
1211 "", "Access-Request", "Access-Accept", "Access-Reject",
1212 "Accounting-Request", "Accounting-Response", "", "",
1213 "", "", "", "Access-Challenge",
1214 "Status-Server", "Status-Client"
1216 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1219 void char2hex(char *h, unsigned char c) {
1220 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1221 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1222 h[0] = hexdigits[c / 16];
1223 h[1] = hexdigits[c % 16];
1227 uint8_t *radattr2ascii(struct tlv *attr) {
1235 for (i = 0; i < attr->l; i++)
1236 if (attr->v[i] < 32 || attr->v[i] > 126)
1239 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1246 for (i = 0; i < attr->l; i++)
1247 if (attr->v[i] < 32 || attr->v[i] > 126) {
1249 char2hex((char *)d, attr->v[i]);
1257 void acclog(struct radmsg *msg, struct client *from) {
1261 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1263 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) without username attribute", from->conf->name, addr2string(from->addr));
1266 username = radattr2ascii(attr);
1268 debug(DBG_INFO, "acclog: accounting-request from client %s (%s) with username: %s", from->conf->name, addr2string(from->addr), username);
1274 void respond(struct request *rq, uint8_t code, char *message) {
1278 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1280 debug(DBG_ERR, "respond: malloc failed");
1283 if (message && *message) {
1284 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1285 if (!attr || !radmsg_add(msg, attr)) {
1288 debug(DBG_ERR, "respond: malloc failed");
1293 radmsg_free(rq->msg);
1295 debug(DBG_DBG, "respond: sending %s to %s (%s)", radmsgtype2string(msg->code), rq->from->conf->name, addr2string(rq->from->addr));
1296 sendreply(newrqref(rq));
1299 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1300 struct list_node *entry;
1301 struct clsrvconf *server, *best = NULL, *first = NULL;
1303 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1304 server = (struct clsrvconf *)entry->data;
1305 if (!server->servers)
1309 if (!server->servers->connectionok && !server->servers->dynstartup)
1311 if (!server->servers->lostrqs)
1317 if (server->servers->lostrqs < best->servers->lostrqs)
1320 return best ? best : first;
1323 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1324 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1325 struct clsrvconf *srvconf;
1326 struct realm *subrealm;
1327 struct server *server = NULL;
1328 char *id = (char *)tlv2str(username);
1332 /* returns with lock on realm */
1333 *realm = id2realm(realms, id);
1336 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1337 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1338 if (srvconf && !(*realm)->parent && !srvconf->servers && srvconf->dynamiclookupcommand) {
1339 subrealm = adddynamicrealmserver(*realm, id);
1341 pthread_mutex_lock(&subrealm->mutex);
1342 pthread_mutex_unlock(&(*realm)->mutex);
1345 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1349 server = srvconf->servers;
1357 struct request *newrequest() {
1360 rq = malloc(sizeof(struct request));
1362 debug(DBG_ERR, "newrequest: malloc failed");
1365 memset(rq, 0, sizeof(struct request));
1367 gettimeofday(&rq->created, NULL);
1371 int addclientrq(struct request *rq) {
1375 r = rq->from->rqs[rq->rqid];
1377 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1378 gettimeofday(&now, NULL);
1379 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1381 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1382 sendreply(newrqref(r));
1384 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1390 rq->from->rqs[rq->rqid] = newrqref(rq);
1394 void rmclientrq(struct request *rq, uint8_t id) {
1397 r = rq->from->rqs[id];
1400 rq->from->rqs[id] = NULL;
1404 /* returns 0 if validation/authentication fails, else 1 */
1405 int radsrv(struct request *rq) {
1406 struct radmsg *msg = NULL;
1408 uint8_t *userascii = NULL;
1409 struct realm *realm = NULL;
1410 struct server *to = NULL;
1411 struct client *from = rq->from;
1414 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1419 debug(DBG_INFO, "radsrv: message validation failed, ignoring packet");
1426 memcpy(rq->rqauth, msg->auth, 16);
1428 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1429 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1430 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1434 if (!addclientrq(rq))
1437 if (msg->code == RAD_Status_Server) {
1438 respond(rq, RAD_Access_Accept, NULL);
1442 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1444 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1447 ttlres = checkttl(msg, options.ttlattrtype);
1449 debug(DBG_INFO, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1453 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1455 if (msg->code == RAD_Accounting_Request) {
1457 respond(rq, RAD_Accounting_Response, NULL);
1459 debug(DBG_INFO, "radsrv: ignoring access request, no username attribute");
1463 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1464 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1468 userascii = radattr2ascii(attr);
1471 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1473 /* will return with lock on the realm */
1474 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1476 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1481 if (realm->message && msg->code == RAD_Access_Request) {
1482 debug(DBG_INFO, "radsrv: sending reject to %s (%s) for %s", from->conf->name, addr2string(from->addr), userascii);
1483 respond(rq, RAD_Access_Reject, realm->message);
1484 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1486 respond(rq, RAD_Accounting_Response, NULL);
1491 if ((to->conf->loopprevention == 1
1492 || (to->conf->loopprevention == UCHAR_MAX && options.loopprevention == 1))
1493 && !strcmp(from->conf->name, to->conf->name)) {
1494 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1495 from->conf->name, addr2string(from->addr), to->conf->name);
1499 if (msg->code == RAD_Accounting_Request)
1500 memset(msg->auth, 0, 16);
1501 else if (!RAND_bytes(msg->auth, 16)) {
1502 debug(DBG_WARN, "radsrv: failed to generate random auth");
1507 printfchars(NULL, "auth", "%02x ", auth, 16);
1510 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1512 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1513 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1517 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1519 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1520 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1524 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1527 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1528 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1533 pthread_mutex_unlock(&realm->mutex);
1538 rmclientrq(rq, msg->id);
1543 pthread_mutex_unlock(&realm->mutex);
1549 void replyh(struct server *server, unsigned char *buf) {
1550 struct client *from;
1551 struct rqout *rqout;
1553 unsigned char *subattrs;
1554 uint8_t *username, *stationid, *replymsg;
1555 struct radmsg *msg = NULL;
1557 struct list_node *node;
1559 server->connectionok = 1;
1560 server->lostrqs = 0;
1562 rqout = server->requests + buf[1];
1563 pthread_mutex_lock(rqout->lock);
1564 if (!rqout->tries) {
1567 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1571 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1575 debug(DBG_INFO, "replyh: message validation failed, ignoring packet");
1578 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1579 && msg->code != RAD_Accounting_Response) {
1580 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1583 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1585 gettimeofday(&server->lastrcv, NULL);
1587 if (rqout->rq->msg->code == RAD_Status_Server) {
1588 freerqoutdata(rqout);
1589 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->name);
1593 gettimeofday(&server->lastreply, NULL);
1594 from = rqout->rq->from;
1596 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1597 debug(DBG_INFO, "replyh: rewritein failed");
1601 ttlres = checkttl(msg, options.ttlattrtype);
1603 debug(DBG_INFO, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->name);
1608 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1609 attr = (struct tlv *)node->data;
1610 if (attr->t != RAD_Attr_Vendor_Specific)
1614 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1617 sublen = attr->l - 4;
1618 subattrs = attr->v + 4;
1619 if (!attrvalidate(subattrs, sublen) ||
1620 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1621 rqout->rq, server->conf->secret, from->conf->secret) ||
1622 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1623 rqout->rq, server->conf->secret, from->conf->secret))
1627 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1631 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1632 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1634 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1635 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1639 "%s for user %s stationid %s from %s (%s) to %s (%s)",
1640 radmsgtype2string(msg->code), username, stationid,
1641 server->conf->name, replymsg, from->conf->name,
1642 addr2string(from->addr));
1646 "%s for user %s stationid %s from %s to %s (%s)",
1647 radmsgtype2string(msg->code), username, stationid,
1648 server->conf->name, from->conf->name,
1649 addr2string(from->addr));
1653 debug(DBG_NOTICE, "%s for user %s from %s (%s) to %s (%s)",
1654 radmsgtype2string(msg->code), username,
1655 server->conf->name, replymsg, from->conf->name,
1656 addr2string(from->addr));
1659 debug(DBG_NOTICE, "%s for user %s from %s to %s (%s)",
1660 radmsgtype2string(msg->code), username,
1661 server->conf->name, from->conf->name,
1662 addr2string(from->addr));
1668 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject)
1669 if (options.fticks_reporting && from->conf->fticks_viscountry != NULL)
1670 fticks_log(&options, from, msg, rqout);
1672 msg->id = (char)rqout->rq->rqid;
1673 memcpy(msg->auth, rqout->rq->rqauth, 16);
1676 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1679 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1680 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1681 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1684 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1687 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1688 debug(DBG_WARN, "replyh: rewriteout failed");
1692 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1693 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1695 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1696 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1698 radmsg_free(rqout->rq->msg);
1699 rqout->rq->msg = msg;
1700 sendreply(newrqref(rqout->rq));
1701 freerqoutdata(rqout);
1702 pthread_mutex_unlock(rqout->lock);
1707 pthread_mutex_unlock(rqout->lock);
1711 struct request *createstatsrvrq() {
1718 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1721 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1724 if (!radmsg_add(rq->msg, attr)) {
1735 /* code for removing state not finished */
1736 void *clientwr(void *arg) {
1737 struct server *server = (struct server *)arg;
1738 struct rqout *rqout = NULL;
1739 pthread_t clientrdth;
1740 int i, dynconffail = 0;
1743 struct timeval now, laststatsrv;
1744 struct timespec timeout;
1745 struct request *statsrvrq;
1746 struct clsrvconf *conf;
1748 conf = server->conf;
1750 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1752 server->dynstartup = 0;
1757 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1758 debug(DBG_WARN, "clientwr: resolve failed");
1759 server->dynstartup = 0;
1764 memset(&timeout, 0, sizeof(struct timespec));
1766 if (conf->statusserver) {
1767 gettimeofday(&server->lastrcv, NULL);
1768 gettimeofday(&laststatsrv, NULL);
1771 if (conf->pdef->connecter) {
1772 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1773 if (server->dynamiclookuparg) {
1774 server->dynstartup = 0;
1779 server->connectionok = 1;
1780 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1781 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1785 server->connectionok = 1;
1786 server->dynstartup = 0;
1789 pthread_mutex_lock(&server->newrq_mutex);
1790 if (!server->newrq) {
1791 gettimeofday(&now, NULL);
1792 /* random 0-7 seconds */
1793 RAND_bytes(&rnd, 1);
1795 if (conf->statusserver) {
1796 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1797 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1799 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1800 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1802 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1803 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1806 if (timeout.tv_sec > now.tv_sec)
1807 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1809 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1812 if (server->newrq) {
1813 debug(DBG_DBG, "clientwr: got new request");
1818 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1820 pthread_mutex_unlock(&server->newrq_mutex);
1822 for (i = 0; i < MAX_REQUESTS; i++) {
1823 if (server->clientrdgone) {
1824 pthread_join(clientrdth, NULL);
1828 for (; i < MAX_REQUESTS; i++) {
1829 rqout = server->requests + i;
1831 pthread_mutex_lock(rqout->lock);
1834 pthread_mutex_unlock(rqout->lock);
1838 if (i == MAX_REQUESTS)
1841 gettimeofday(&now, NULL);
1842 if (now.tv_sec < rqout->expiry.tv_sec) {
1843 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1844 timeout.tv_sec = rqout->expiry.tv_sec;
1845 pthread_mutex_unlock(rqout->lock);
1849 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1850 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1851 if (conf->statusserver) {
1852 if (*rqout->rq->buf == RAD_Status_Server) {
1853 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1854 if (server->lostrqs < 255)
1858 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1859 if (server->lostrqs < 255)
1862 freerqoutdata(rqout);
1863 pthread_mutex_unlock(rqout->lock);
1867 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1868 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1869 timeout.tv_sec = rqout->expiry.tv_sec;
1871 conf->pdef->clientradput(server, rqout->rq->buf);
1872 pthread_mutex_unlock(rqout->lock);
1874 if (conf->statusserver && server->connectionok) {
1875 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1876 gettimeofday(&now, NULL);
1877 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1879 statsrvrq = createstatsrvrq();
1881 statsrvrq->to = server;
1882 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1889 conf->servers = NULL;
1890 if (server->dynamiclookuparg) {
1891 removeserversubrealms(realms, conf);
1895 freeclsrvconf(conf);
1897 freeserver(server, 1);
1898 ERR_remove_state(0);
1902 void createlistener(uint8_t type, char *arg) {
1904 struct addrinfo *res;
1905 int s = -1, on = 1, *sp = NULL;
1906 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1908 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1909 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1911 for (res = hp->addrinfo; res; res = res->ai_next) {
1912 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1914 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1917 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1919 disable_DF_bit(s, res);
1922 if (res->ai_family == AF_INET6)
1923 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1925 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1926 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1932 sp = malloc(sizeof(int));
1934 debugx(1, DBG_ERR, "malloc failed");
1936 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1937 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1941 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1943 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1947 void createlisteners(uint8_t type) {
1951 args = protodefs[type]->getlistenerargs();
1953 for (i = 0; args[i]; i++)
1954 createlistener(type, args[i]);
1956 createlistener(type, NULL);
1964 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1965 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1966 for (i = 0; i < CRYPTO_num_locks(); i++) {
1967 ssl_lock_count[i] = 0;
1968 pthread_mutex_init(&ssl_locks[i], NULL);
1970 CRYPTO_set_id_callback(ssl_thread_id);
1971 CRYPTO_set_locking_callback(ssl_locking_callback);
1973 SSL_load_error_strings();
1976 while (!RAND_status()) {
1979 RAND_seed((unsigned char *)&t, sizeof(time_t));
1980 RAND_seed((unsigned char *)&pid, sizeof(pid));
1984 struct list *addsrvconfs(char *value, char **names) {
1985 struct list *conflist;
1987 struct list_node *entry;
1988 struct clsrvconf *conf = NULL;
1990 if (!names || !*names)
1993 conflist = list_create();
1995 debug(DBG_ERR, "malloc failed");
1999 for (n = 0; names[n]; n++) {
2000 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2001 conf = (struct clsrvconf *)entry->data;
2002 if (!strcasecmp(names[n], conf->name))
2006 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2007 list_destroy(conflist);
2010 if (!list_push(conflist, conf)) {
2011 debug(DBG_ERR, "malloc failed");
2012 list_destroy(conflist);
2015 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2020 void freerealm(struct realm *realm) {
2023 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2024 if (--realm->refcount)
2028 free(realm->message);
2029 regfree(&realm->regex);
2030 pthread_mutex_destroy(&realm->mutex);
2031 /* if refcount == 0, all subrealms gone */
2032 list_destroy(realm->subrealms);
2033 /* if refcount == 0, all srvconfs gone */
2034 list_destroy(realm->srvconfs);
2035 /* if refcount == 0, all accsrvconfs gone */
2036 list_destroy(realm->accsrvconfs);
2037 freerealm(realm->parent);
2041 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2043 struct realm *realm;
2044 char *s, *regex = NULL;
2046 if (*value == '/') {
2047 /* regexp, remove optional trailing / if present */
2048 if (value[strlen(value) - 1] == '/')
2049 value[strlen(value) - 1] = '\0';
2051 /* not a regexp, let us make it one */
2052 if (*value == '*' && !value[1])
2053 regex = stringcopy(".*", 0);
2055 for (n = 0, s = value; *s;)
2058 regex = malloc(strlen(value) + n + 3);
2061 for (n = 1, s = value; *s; s++) {
2071 debug(DBG_ERR, "malloc failed");
2075 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2078 realm = malloc(sizeof(struct realm));
2080 debug(DBG_ERR, "malloc failed");
2083 memset(realm, 0, sizeof(struct realm));
2085 if (pthread_mutex_init(&realm->mutex, NULL)) {
2086 debugerrno(errno, DBG_ERR, "mutex init failed");
2092 realm->name = stringcopy(value, 0);
2094 debug(DBG_ERR, "malloc failed");
2097 if (message && strlen(message) > 253) {
2098 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2101 realm->message = message;
2102 realm->accresp = accresp;
2104 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2105 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2109 if (servers && *servers) {
2110 realm->srvconfs = addsrvconfs(value, servers);
2111 if (!realm->srvconfs)
2115 if (accservers && *accservers) {
2116 realm->accsrvconfs = addsrvconfs(value, accservers);
2117 if (!realm->accsrvconfs)
2121 if (!list_push(realmlist, realm)) {
2122 debug(DBG_ERR, "malloc failed");
2123 pthread_mutex_destroy(&realm->mutex);
2127 debug(DBG_DBG, "addrealm: added realm %s", value);
2131 while (list_shift(realm->srvconfs));
2132 while (list_shift(realm->accsrvconfs));
2139 for (n = 0; servers[n]; n++)
2141 freegconfmstr(servers);
2145 for (n = 0; accservers[n]; n++)
2147 freegconfmstr(accservers);
2149 return newrealmref(realm);
2152 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2153 struct list_node *entry;
2154 struct clsrvconf *conf, *srvconf;
2155 struct list *subrealmservers = NULL;
2158 if (list_first(srvconfs)) {
2159 subrealmservers = list_create();
2160 if (!subrealmservers)
2164 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2165 conf = (struct clsrvconf *)entry->data;
2166 if (!conf->servers && conf->dynamiclookupcommand) {
2167 srvconf = malloc(sizeof(struct clsrvconf));
2169 debug(DBG_ERR, "malloc failed");
2173 if (addserver(srvconf)) {
2174 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2175 srvconf->servers->dynstartup = 1;
2176 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2177 debugerrno(errno, DBG_ERR, "pthread_create failed");
2178 freeserver(srvconf->servers, 1);
2179 srvconf->servers = NULL;
2181 pthread_detach(clientth);
2185 if (conf->servers) {
2186 if (list_push(subrealmservers, conf))
2189 debug(DBG_ERR, "malloc failed");
2192 return subrealmservers;
2195 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2196 struct realm *newrealm = NULL;
2197 char *realmname, *s;
2199 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2200 realmname = strrchr(id, '@');
2206 for (s = realmname; *s; s++)
2207 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2210 if (!realm->subrealms)
2211 realm->subrealms = list_create();
2212 if (!realm->subrealms)
2215 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2217 list_destroy(realm->subrealms);
2218 realm->subrealms = NULL;
2222 newrealm->parent = newrealmref(realm);
2223 /* add server and accserver to newrealm */
2224 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2225 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2229 int dynamicconfig(struct server *server) {
2230 int ok, fd[2], status;
2232 struct clsrvconf *conf = server->conf;
2233 struct gconffile *cf = NULL;
2235 /* for now we only learn hostname/address */
2236 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2239 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2244 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2248 } else if (pid == 0) {
2251 if (fd[1] != STDOUT_FILENO) {
2252 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2253 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2256 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2257 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2261 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2262 ok = getgenericconfig(&cf, NULL, "Server", CONF_CBK, confserver_cb,
2263 (void *) conf, NULL);
2266 if (waitpid(pid, &status, 0) < 0) {
2267 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2272 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2280 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2284 /* should accept both names and numeric values, only numeric right now */
2285 uint8_t attrname2val(char *attrname) {
2288 val = atoi(attrname);
2289 return val > 0 && val < 256 ? val : 0;
2292 /* ATTRNAME is on the form vendor[:type].
2293 If only vendor is found, TYPE is set to 256 and 1 is returned.
2294 If type is >= 256, 1 is returned.
2295 Otherwise, 0 is returned.
2297 /* should accept both names and numeric values, only numeric right now */
2298 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2301 *vendor = atoi(attrname);
2302 s = strchr(attrname, ':');
2303 if (!s) { /* Only vendor was found. */
2307 *type = atoi(s + 1);
2311 /** Extract attributes from string NAMEVAL, create a struct tlv and
2312 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2313 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2314 * NULL if fields are missing or if conversion fails.
2316 * FIXME: Should accept both names and numeric values, only numeric
2318 struct tlv *extractattr(char *nameval, char vendor_flag) {
2320 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2324 s = strchr(nameval, ':');
2327 name = atoi(nameval);
2330 s2 = strchr(s + 1, ':');
2337 len = strlen(s + 1);
2341 if (name < 1 || name > 255)
2343 a = malloc(sizeof(struct tlv));
2347 a->v = (uint8_t *)stringcopy(s + 1, 0);
2356 a = makevendortlv(vendor, a);
2361 /* should accept both names and numeric values, only numeric right now */
2362 struct modattr *extractmodattr(char *nameval) {
2367 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2371 s = strchr(nameval, ':');
2372 name = atoi(nameval);
2373 if (!s || name < 1 || name > 255 || s[1] != '/')
2377 /* regexp, remove optional trailing / if present */
2378 if (s[strlen(s) - 1] == '/')
2379 s[strlen(s) - 1] = '\0';
2387 m = malloc(sizeof(struct modattr));
2389 debug(DBG_ERR, "malloc failed");
2394 m->replacement = stringcopy(t, 0);
2395 if (!m->replacement) {
2397 debug(DBG_ERR, "malloc failed");
2401 m->regex = malloc(sizeof(regex_t));
2403 free(m->replacement);
2405 debug(DBG_ERR, "malloc failed");
2409 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2411 free(m->replacement);
2413 debug(DBG_ERR, "failed to compile regular expression %s", s);
2420 struct rewrite *getrewrite(char *alt1, char *alt2) {
2424 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2427 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2432 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2434 struct rewrite *rewrite = NULL;
2436 uint8_t *rma = NULL;
2437 uint32_t *p, *rmva = NULL;
2438 struct list *adda = NULL, *moda = NULL;
2443 for (n = 0; rmattrs[n]; n++);
2444 rma = calloc(n + 1, sizeof(uint8_t));
2446 debugx(1, DBG_ERR, "malloc failed");
2448 for (i = 0; i < n; i++)
2449 if (!(rma[i] = attrname2val(rmattrs[i])))
2450 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2451 freegconfmstr(rmattrs);
2456 for (n = 0; rmvattrs[n]; n++);
2457 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2459 debugx(1, DBG_ERR, "malloc failed");
2461 for (p = rmva, i = 0; i < n; i++, p += 2)
2462 if (!vattrname2val(rmvattrs[i], p, p + 1))
2463 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2464 freegconfmstr(rmvattrs);
2469 adda = list_create();
2471 debugx(1, DBG_ERR, "malloc failed");
2472 for (i = 0; addattrs[i]; i++) {
2473 a = extractattr(addattrs[i], 0);
2475 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2476 if (!list_push(adda, a))
2477 debugx(1, DBG_ERR, "malloc failed");
2479 freegconfmstr(addattrs);
2484 adda = list_create();
2486 debugx(1, DBG_ERR, "malloc failed");
2487 for (i = 0; addvattrs[i]; i++) {
2488 a = extractattr(addvattrs[i], 1);
2490 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2491 if (!list_push(adda, a))
2492 debugx(1, DBG_ERR, "malloc failed");
2494 freegconfmstr(addvattrs);
2498 moda = list_create();
2500 debugx(1, DBG_ERR, "malloc failed");
2501 for (i = 0; modattrs[i]; i++) {
2502 m = extractmodattr(modattrs[i]);
2504 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2505 if (!list_push(moda, m))
2506 debugx(1, DBG_ERR, "malloc failed");
2508 freegconfmstr(modattrs);
2511 if (rma || rmva || adda || moda) {
2512 rewrite = malloc(sizeof(struct rewrite));
2514 debugx(1, DBG_ERR, "malloc failed");
2515 rewrite->removeattrs = rma;
2516 rewrite->removevendorattrs = rmva;
2517 rewrite->addattrs = adda;
2518 rewrite->modattrs = moda;
2521 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2522 debugx(1, DBG_ERR, "malloc failed");
2523 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2526 int setttlattr(struct options *opts, char *defaultattr) {
2527 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2529 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2530 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2532 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2536 void freeclsrvconf(struct clsrvconf *conf) {
2539 freegconfmstr(conf->hostsrc);
2540 free(conf->portsrc);
2543 free(conf->matchcertattr);
2544 if (conf->certcnregex)
2545 regfree(conf->certcnregex);
2546 if (conf->certuriregex)
2547 regfree(conf->certuriregex);
2548 free(conf->confrewritein);
2549 free(conf->confrewriteout);
2550 if (conf->rewriteusername) {
2551 if (conf->rewriteusername->regex)
2552 regfree(conf->rewriteusername->regex);
2553 free(conf->rewriteusername->replacement);
2554 free(conf->rewriteusername);
2556 free(conf->dynamiclookupcommand);
2557 free(conf->rewritein);
2558 free(conf->rewriteout);
2559 if (conf->hostports)
2560 freehostports(conf->hostports);
2562 pthread_mutex_destroy(conf->lock);
2565 /* not touching ssl_ctx, clients and servers */
2569 int mergeconfstring(char **dst, char **src) {
2578 t = stringcopy(*dst, 0);
2580 debug(DBG_ERR, "malloc failed");
2588 char **mstringcopy(char **in) {
2595 for (n = 0; in[n]; n++);
2596 out = malloc((n + 1) * sizeof(char *));
2599 for (n = 0; in[n]; n++) {
2600 out[n] = stringcopy(in[n], 0);
2610 int mergeconfmstring(char ***dst, char ***src) {
2619 t = mstringcopy(*dst);
2621 debug(DBG_ERR, "malloc failed");
2629 /* assumes dst is a shallow copy */
2630 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2631 if (!mergeconfstring(&dst->name, &src->name) ||
2632 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2633 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2634 !mergeconfstring(&dst->secret, &src->secret) ||
2635 !mergeconfstring(&dst->tls, &src->tls) ||
2636 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2637 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2638 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2639 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2642 dst->pdef = src->pdef;
2643 dst->statusserver = src->statusserver;
2644 dst->certnamecheck = src->certnamecheck;
2645 if (src->retryinterval != 255)
2646 dst->retryinterval = src->retryinterval;
2647 if (src->retrycount != 255)
2648 dst->retrycount = src->retrycount;
2652 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2653 struct clsrvconf *conf;
2654 char *conftype = NULL, *rewriteinalias = NULL;
2655 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2657 debug(DBG_DBG, "confclient_cb called for %s", block);
2659 conf = malloc(sizeof(struct clsrvconf));
2661 debugx(1, DBG_ERR, "malloc failed");
2662 memset(conf, 0, sizeof(struct clsrvconf));
2663 conf->certnamecheck = 1;
2665 if (!getgenericconfig(
2667 "type", CONF_STR, &conftype,
2668 "host", CONF_MSTR, &conf->hostsrc,
2669 "secret", CONF_STR, &conf->secret,
2670 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2671 "tls", CONF_STR, &conf->tls,
2672 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2673 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2675 "DuplicateInterval", CONF_LINT, &dupinterval,
2676 "addTTL", CONF_LINT, &addttl,
2677 "rewrite", CONF_STR, &rewriteinalias,
2678 "rewriteIn", CONF_STR, &conf->confrewritein,
2679 "rewriteOut", CONF_STR, &conf->confrewriteout,
2680 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2681 "fticksVISCOUNTRY", CONF_STR, &conf->fticks_viscountry,
2684 debugx(1, DBG_ERR, "configuration error");
2686 conf->name = stringcopy(val, 0);
2687 if (conf->name && !conf->hostsrc) {
2688 conf->hostsrc = malloc(2 * sizeof(char *));
2689 if (conf->hostsrc) {
2690 conf->hostsrc[0] = stringcopy(val, 0);
2691 conf->hostsrc[1] = NULL;
2694 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2695 debugx(1, DBG_ERR, "malloc failed");
2698 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2699 conf->type = protoname2int(conftype);
2700 if (conf->type == 255)
2701 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2703 conf->pdef = protodefs[conf->type];
2705 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2706 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2707 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2709 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2710 if (conf->matchcertattr && !addmatchcertattr(conf))
2711 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2715 if (dupinterval != LONG_MIN) {
2716 if (dupinterval < 0 || dupinterval > 255)
2717 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2718 conf->dupinterval = (uint8_t)dupinterval;
2720 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2722 if (addttl != LONG_MIN) {
2723 if (addttl < 1 || addttl > 255)
2724 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2725 conf->addttl = (uint8_t)addttl;
2728 if (!conf->confrewritein)
2729 conf->confrewritein = rewriteinalias;
2731 free(rewriteinalias);
2732 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2733 if (conf->confrewriteout)
2734 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2736 if (conf->confrewriteusername) {
2737 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2738 if (!conf->rewriteusername)
2739 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2742 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2743 !resolvehostports(conf->hostports, conf->pdef->socktype))
2744 debugx(1, DBG_ERR, "resolve failed, exiting");
2746 if (!conf->secret) {
2747 if (!conf->pdef->secretdefault)
2748 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2749 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2751 debugx(1, DBG_ERR, "malloc failed");
2754 conf->lock = malloc(sizeof(pthread_mutex_t));
2756 debugx(1, DBG_ERR, "malloc failed");
2758 pthread_mutex_init(conf->lock, NULL);
2759 if (!list_push(clconfs, conf))
2760 debugx(1, DBG_ERR, "malloc failed");
2764 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2765 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2766 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2767 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2768 if (!conf->tlsconf) {
2769 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2772 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2773 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2779 if (!conf->portsrc) {
2780 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2781 if (!conf->portsrc) {
2782 debug(DBG_ERR, "malloc failed");
2787 if (conf->retryinterval == 255)
2788 conf->retryinterval = conf->pdef->retryintervaldefault;
2789 if (conf->retrycount == 255)
2790 conf->retrycount = conf->pdef->retrycountdefault;
2792 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2793 if (conf->confrewriteout)
2794 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2796 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2797 debug(DBG_ERR, "error in block %s, failed to parse %s", block, *conf->hostsrc);
2801 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2802 debug(DBG_ERR, "resolve failed, exiting");
2808 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2809 struct clsrvconf *conf, *resconf;
2810 char *conftype = NULL, *rewriteinalias = NULL;
2811 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2813 debug(DBG_DBG, "confserver_cb called for %s", block);
2815 conf = malloc(sizeof(struct clsrvconf));
2817 debug(DBG_ERR, "malloc failed");
2820 memset(conf, 0, sizeof(struct clsrvconf));
2821 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2822 resconf = (struct clsrvconf *)arg;
2824 conf->statusserver = resconf->statusserver;
2825 conf->certnamecheck = resconf->certnamecheck;
2827 conf->certnamecheck = 1;
2829 if (!getgenericconfig(cf, block,
2830 "type", CONF_STR, &conftype,
2831 "host", CONF_MSTR, &conf->hostsrc,
2832 "port", CONF_STR, &conf->portsrc,
2833 "secret", CONF_STR, &conf->secret,
2834 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2835 "tls", CONF_STR, &conf->tls,
2836 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2837 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2839 "addTTL", CONF_LINT, &addttl,
2840 "rewrite", CONF_STR, &rewriteinalias,
2841 "rewriteIn", CONF_STR, &conf->confrewritein,
2842 "rewriteOut", CONF_STR, &conf->confrewriteout,
2843 "StatusServer", CONF_BLN, &conf->statusserver,
2844 "RetryInterval", CONF_LINT, &retryinterval,
2845 "RetryCount", CONF_LINT, &retrycount,
2846 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2847 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2850 debug(DBG_ERR, "configuration error");
2854 conf->name = stringcopy(val, 0);
2855 if (conf->name && !conf->hostsrc) {
2856 conf->hostsrc = malloc(2 * sizeof(char *));
2857 if (conf->hostsrc) {
2858 conf->hostsrc[0] = stringcopy(val, 0);
2859 conf->hostsrc[1] = NULL;
2862 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2863 debug(DBG_ERR, "malloc failed");
2868 debug(DBG_ERR, "error in block %s, option type missing", block);
2871 conf->type = protoname2int(conftype);
2872 if (conf->type == 255) {
2873 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2879 conf->pdef = protodefs[conf->type];
2881 if (!conf->confrewritein)
2882 conf->confrewritein = rewriteinalias;
2884 free(rewriteinalias);
2885 rewriteinalias = NULL;
2887 if (retryinterval != LONG_MIN) {
2888 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2889 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2892 conf->retryinterval = (uint8_t)retryinterval;
2894 conf->retryinterval = 255;
2896 if (retrycount != LONG_MIN) {
2897 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2898 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2901 conf->retrycount = (uint8_t)retrycount;
2903 conf->retrycount = 255;
2905 if (addttl != LONG_MIN) {
2906 if (addttl < 1 || addttl > 255) {
2907 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2910 conf->addttl = (uint8_t)addttl;
2914 if (!mergesrvconf(resconf, conf))
2918 if (conf->dynamiclookupcommand) {
2919 free(conf->dynamiclookupcommand);
2920 conf->dynamiclookupcommand = NULL;
2924 if (resconf || !conf->dynamiclookupcommand) {
2925 if (!compileserverconfig(conf, block))
2929 if (!conf->secret) {
2930 if (!conf->pdef->secretdefault) {
2931 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2934 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2935 if (!conf->secret) {
2936 debug(DBG_ERR, "malloc failed");
2944 if (!list_push(srvconfs, conf)) {
2945 debug(DBG_ERR, "malloc failed");
2952 free(rewriteinalias);
2953 freeclsrvconf(conf);
2957 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2958 char **servers = NULL, **accservers = NULL, *msg = NULL;
2959 uint8_t accresp = 0;
2961 debug(DBG_DBG, "confrealm_cb called for %s", block);
2963 if (!getgenericconfig(cf, block,
2964 "server", CONF_MSTR, &servers,
2965 "accountingServer", CONF_MSTR, &accservers,
2966 "ReplyMessage", CONF_STR, &msg,
2967 "AccountingResponse", CONF_BLN, &accresp,
2970 debugx(1, DBG_ERR, "configuration error");
2972 addrealm(realms, val, servers, accservers, msg, accresp);
2976 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2977 char **rmattrs = NULL, **rmvattrs = NULL;
2978 char **addattrs = NULL, **addvattrs = NULL;
2979 char **modattrs = NULL;
2981 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2983 if (!getgenericconfig(cf, block,
2984 "removeAttribute", CONF_MSTR, &rmattrs,
2985 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2986 "addAttribute", CONF_MSTR, &addattrs,
2987 "addVendorAttribute", CONF_MSTR, &addvattrs,
2988 "modifyAttribute", CONF_MSTR, &modattrs,
2991 debugx(1, DBG_ERR, "configuration error");
2992 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2996 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2997 struct commonprotoopts *protoopts;
2999 protoopts = malloc(sizeof(struct commonprotoopts));
3002 memset(protoopts, 0, sizeof(struct commonprotoopts));
3003 protoopts->listenargs = listenargs;
3004 protoopts->sourcearg = sourcearg;
3005 protodefs[type]->setprotoopts(protoopts);
3009 void getmainconfig(const char *configfile) {
3010 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3011 struct gconffile *cfs;
3012 char **listenargs[RAD_PROTOCOUNT];
3013 char *sourcearg[RAD_PROTOCOUNT];
3014 uint8_t *fticks_reporting_str = NULL;
3015 uint8_t *fticks_mac_str = NULL;
3016 uint8_t *fticks_key_str = NULL;
3019 cfs = openconfigfile(configfile);
3020 memset(&options, 0, sizeof(options));
3021 memset(&listenargs, 0, sizeof(listenargs));
3022 memset(&sourcearg, 0, sizeof(sourcearg));
3024 clconfs = list_create();
3026 debugx(1, DBG_ERR, "malloc failed");
3028 srvconfs = list_create();
3030 debugx(1, DBG_ERR, "malloc failed");
3032 realms = list_create();
3034 debugx(1, DBG_ERR, "malloc failed");
3036 rewriteconfs = hash_create();
3038 debugx(1, DBG_ERR, "malloc failed");
3040 if (!getgenericconfig(
3043 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3044 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3047 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3048 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3051 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3052 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3055 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3056 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3058 "TTLAttribute", CONF_STR, &options.ttlattr,
3059 "addTTL", CONF_LINT, &addttl,
3060 "LogLevel", CONF_LINT, &loglevel,
3061 "LogDestination", CONF_STR, &options.logdestination,
3062 "LoopPrevention", CONF_BLN, &options.loopprevention,
3063 "Client", CONF_CBK, confclient_cb, NULL,
3064 "Server", CONF_CBK, confserver_cb, NULL,
3065 "Realm", CONF_CBK, confrealm_cb, NULL,
3066 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3067 "TLS", CONF_CBK, conftls_cb, NULL,
3069 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3070 "FTicksReporting", CONF_STR, &fticks_reporting_str,
3071 "FTicksMAC", CONF_STR, &fticks_mac_str,
3072 "FTicksKey", CONF_STR, &fticks_key_str,
3075 debugx(1, DBG_ERR, "configuration error");
3077 if (loglevel != LONG_MIN) {
3078 if (loglevel < 1 || loglevel > 5)
3079 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3080 options.loglevel = (uint8_t)loglevel;
3082 if (addttl != LONG_MIN) {
3083 if (addttl < 1 || addttl > 255)
3084 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3085 options.addttl = (uint8_t)addttl;
3087 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3088 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3090 fticks_configure(&options, &fticks_reporting_str, &fticks_mac_str,
3093 for (i = 0; i < RAD_PROTOCOUNT; i++)
3094 if (listenargs[i] || sourcearg[i])
3095 setprotoopts(i, listenargs[i], sourcearg[i]);
3098 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3101 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3104 *configfile = optarg;
3107 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3108 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3109 *loglevel = *optarg - '0';
3121 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3122 debug(DBG_ERR, "This binary was built with support for the following transports:");
3124 debug(DBG_ERR, " UDP");
3127 debug(DBG_ERR, " TCP");
3130 debug(DBG_ERR, " TLS");
3133 debug(DBG_ERR, " DTLS");
3140 if (!(argc - optind))
3144 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3148 int daemon(int a, int b) {
3156 for (i = 0; i < 3; i++) {
3158 open("/dev/null", O_RDWR);
3164 void *sighandler(void *arg) {
3169 sigemptyset(&sigset);
3170 sigaddset(&sigset, SIGHUP);
3171 sigaddset(&sigset, SIGPIPE);
3172 sigwait(&sigset, &sig);
3175 /* completely ignoring this */
3178 debug(DBG_INFO, "sighandler: got SIGHUP");
3182 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3185 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3190 int createpidfile(const char *pidfile) {
3192 FILE *f = fopen(pidfile, "w");
3194 r = fprintf(f, "%ld\n", (long) getpid());
3195 return f && !fclose(f) && r >= 0;
3198 int main(int argc, char **argv) {
3201 struct list_node *entry;
3202 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3203 char *configfile = NULL, *pidfile = NULL;
3204 struct clsrvconf *srvconf;
3207 debug_init("radsecproxy");
3208 debug_set_level(DEBUG_LEVEL);
3210 for (i = 0; i < RAD_PROTOCOUNT; i++)
3211 protodefs[i] = protoinits[i](i);
3213 /* needed even if no TLS/DTLS transport */
3216 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3218 debug_set_level(loglevel);
3219 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3221 options.loglevel = loglevel;
3222 else if (options.loglevel)
3223 debug_set_level(options.loglevel);
3225 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3226 free(options.logdestination);
3228 if (!list_first(clconfs))
3229 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3230 if (!list_first(realms))
3231 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3234 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3236 if (!foreground && (daemon(0, 0) < 0))
3237 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3239 debug_timestamp_on();
3240 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3241 if (pidfile && !createpidfile(pidfile))
3242 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3244 sigemptyset(&sigset);
3245 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3246 sigaddset(&sigset, SIGHUP);
3247 sigaddset(&sigset, SIGPIPE);
3248 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3249 pthread_create(&sigth, NULL, sighandler, NULL);
3251 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3252 srvconf = (struct clsrvconf *)entry->data;
3253 if (srvconf->dynamiclookupcommand)
3255 if (!addserver(srvconf))
3256 debugx(1, DBG_ERR, "failed to add server");
3257 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3258 (void *)(srvconf->servers)))
3259 debugx(1, DBG_ERR, "pthread_create failed");
3262 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3265 if (protodefs[i]->initextra)
3266 protodefs[i]->initextra();
3267 if (find_clconf_type(i, NULL))
3271 /* just hang around doing nothing, anything to do here? */
3276 /* Local Variables: */
3277 /* c-file-style: "stroustrup" */