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>
76 #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 msg->id = (char)rqout->rq->rqid;
1669 memcpy(msg->auth, rqout->rq->rqauth, 16);
1672 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1675 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1676 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1677 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1680 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1683 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1684 debug(DBG_WARN, "replyh: rewriteout failed");
1688 if (ttlres == -1 && (options.addttl || from->conf->addttl))
1689 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
1691 debug(msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response ? DBG_WARN : DBG_INFO,
1692 "replyh: passing %s to client %s (%s)", radmsgtype2string(msg->code), from->conf->name, addr2string(from->addr));
1694 radmsg_free(rqout->rq->msg);
1695 rqout->rq->msg = msg;
1696 sendreply(newrqref(rqout->rq));
1697 freerqoutdata(rqout);
1698 pthread_mutex_unlock(rqout->lock);
1703 pthread_mutex_unlock(rqout->lock);
1707 struct request *createstatsrvrq() {
1714 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
1717 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1720 if (!radmsg_add(rq->msg, attr)) {
1731 /* code for removing state not finished */
1732 void *clientwr(void *arg) {
1733 struct server *server = (struct server *)arg;
1734 struct rqout *rqout = NULL;
1735 pthread_t clientrdth;
1736 int i, dynconffail = 0;
1739 struct timeval now, laststatsrv;
1740 struct timespec timeout;
1741 struct request *statsrvrq;
1742 struct clsrvconf *conf;
1744 conf = server->conf;
1746 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1748 server->dynstartup = 0;
1753 if (!resolvehostports(conf->hostports, conf->pdef->socktype)) {
1754 debug(DBG_WARN, "clientwr: resolve failed");
1755 server->dynstartup = 0;
1760 memset(&timeout, 0, sizeof(struct timespec));
1762 if (conf->statusserver) {
1763 gettimeofday(&server->lastrcv, NULL);
1764 gettimeofday(&laststatsrv, NULL);
1767 if (conf->pdef->connecter) {
1768 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 5 : 0, "clientwr")) {
1769 if (server->dynamiclookuparg) {
1770 server->dynstartup = 0;
1775 server->connectionok = 1;
1776 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1777 debugerrno(errno, DBG_ERR, "clientwr: pthread_create failed");
1781 server->connectionok = 1;
1782 server->dynstartup = 0;
1785 pthread_mutex_lock(&server->newrq_mutex);
1786 if (!server->newrq) {
1787 gettimeofday(&now, NULL);
1788 /* random 0-7 seconds */
1789 RAND_bytes(&rnd, 1);
1791 if (conf->statusserver) {
1792 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1793 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
1795 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
1796 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
1798 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
1799 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
1802 if (timeout.tv_sec > now.tv_sec)
1803 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
1805 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
1808 if (server->newrq) {
1809 debug(DBG_DBG, "clientwr: got new request");
1814 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
1816 pthread_mutex_unlock(&server->newrq_mutex);
1818 for (i = 0; i < MAX_REQUESTS; i++) {
1819 if (server->clientrdgone) {
1820 pthread_join(clientrdth, NULL);
1824 for (; i < MAX_REQUESTS; i++) {
1825 rqout = server->requests + i;
1827 pthread_mutex_lock(rqout->lock);
1830 pthread_mutex_unlock(rqout->lock);
1834 if (i == MAX_REQUESTS)
1837 gettimeofday(&now, NULL);
1838 if (now.tv_sec < rqout->expiry.tv_sec) {
1839 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1840 timeout.tv_sec = rqout->expiry.tv_sec;
1841 pthread_mutex_unlock(rqout->lock);
1845 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
1846 debug(DBG_DBG, "clientwr: removing expired packet from queue");
1847 if (conf->statusserver) {
1848 if (*rqout->rq->buf == RAD_Status_Server) {
1849 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->name);
1850 if (server->lostrqs < 255)
1854 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->name);
1855 if (server->lostrqs < 255)
1858 freerqoutdata(rqout);
1859 pthread_mutex_unlock(rqout->lock);
1863 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
1864 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
1865 timeout.tv_sec = rqout->expiry.tv_sec;
1867 conf->pdef->clientradput(server, rqout->rq->buf);
1868 pthread_mutex_unlock(rqout->lock);
1870 if (conf->statusserver && server->connectionok) {
1871 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
1872 gettimeofday(&now, NULL);
1873 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
1875 statsrvrq = createstatsrvrq();
1877 statsrvrq->to = server;
1878 debug(DBG_DBG, "clientwr: sending status server to %s", conf->name);
1885 conf->servers = NULL;
1886 if (server->dynamiclookuparg) {
1887 removeserversubrealms(realms, conf);
1891 freeclsrvconf(conf);
1893 freeserver(server, 1);
1894 ERR_remove_state(0);
1898 void createlistener(uint8_t type, char *arg) {
1900 struct addrinfo *res;
1901 int s = -1, on = 1, *sp = NULL;
1902 struct hostportres *hp = newhostport(arg, protodefs[type]->portdefault, 0);
1904 if (!hp || !resolvehostport(hp, protodefs[type]->socktype, 1))
1905 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
1907 for (res = hp->addrinfo; res; res = res->ai_next) {
1908 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1910 debugerrno(errno, DBG_WARN, "createlistener: socket failed");
1913 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1915 disable_DF_bit(s, res);
1918 if (res->ai_family == AF_INET6)
1919 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
1921 if (bind(s, res->ai_addr, res->ai_addrlen)) {
1922 debugerrno(errno, DBG_WARN, "createlistener: bind failed");
1928 sp = malloc(sizeof(int));
1930 debugx(1, DBG_ERR, "malloc failed");
1932 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
1933 debugerrnox(errno, DBG_ERR, "pthread_create failed");
1937 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
1939 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name, hp->host ? hp->host : "*", hp->port);
1943 void createlisteners(uint8_t type) {
1947 args = protodefs[type]->getlistenerargs();
1949 for (i = 0; args[i]; i++)
1950 createlistener(type, args[i]);
1952 createlistener(type, NULL);
1960 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
1961 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
1962 for (i = 0; i < CRYPTO_num_locks(); i++) {
1963 ssl_lock_count[i] = 0;
1964 pthread_mutex_init(&ssl_locks[i], NULL);
1966 CRYPTO_set_id_callback(ssl_thread_id);
1967 CRYPTO_set_locking_callback(ssl_locking_callback);
1969 SSL_load_error_strings();
1972 while (!RAND_status()) {
1975 RAND_seed((unsigned char *)&t, sizeof(time_t));
1976 RAND_seed((unsigned char *)&pid, sizeof(pid));
1980 struct list *addsrvconfs(char *value, char **names) {
1981 struct list *conflist;
1983 struct list_node *entry;
1984 struct clsrvconf *conf = NULL;
1986 if (!names || !*names)
1989 conflist = list_create();
1991 debug(DBG_ERR, "malloc failed");
1995 for (n = 0; names[n]; n++) {
1996 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1997 conf = (struct clsrvconf *)entry->data;
1998 if (!strcasecmp(names[n], conf->name))
2002 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2003 list_destroy(conflist);
2006 if (!list_push(conflist, conf)) {
2007 debug(DBG_ERR, "malloc failed");
2008 list_destroy(conflist);
2011 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2016 void freerealm(struct realm *realm) {
2019 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2020 if (--realm->refcount)
2024 free(realm->message);
2025 regfree(&realm->regex);
2026 pthread_mutex_destroy(&realm->mutex);
2027 /* if refcount == 0, all subrealms gone */
2028 list_destroy(realm->subrealms);
2029 /* if refcount == 0, all srvconfs gone */
2030 list_destroy(realm->srvconfs);
2031 /* if refcount == 0, all accsrvconfs gone */
2032 list_destroy(realm->accsrvconfs);
2033 freerealm(realm->parent);
2037 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2039 struct realm *realm;
2040 char *s, *regex = NULL;
2042 if (*value == '/') {
2043 /* regexp, remove optional trailing / if present */
2044 if (value[strlen(value) - 1] == '/')
2045 value[strlen(value) - 1] = '\0';
2047 /* not a regexp, let us make it one */
2048 if (*value == '*' && !value[1])
2049 regex = stringcopy(".*", 0);
2051 for (n = 0, s = value; *s;)
2054 regex = malloc(strlen(value) + n + 3);
2057 for (n = 1, s = value; *s; s++) {
2067 debug(DBG_ERR, "malloc failed");
2071 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2074 realm = malloc(sizeof(struct realm));
2076 debug(DBG_ERR, "malloc failed");
2079 memset(realm, 0, sizeof(struct realm));
2081 if (pthread_mutex_init(&realm->mutex, NULL)) {
2082 debugerrno(errno, DBG_ERR, "mutex init failed");
2088 realm->name = stringcopy(value, 0);
2090 debug(DBG_ERR, "malloc failed");
2093 if (message && strlen(message) > 253) {
2094 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2097 realm->message = message;
2098 realm->accresp = accresp;
2100 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2101 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2105 if (servers && *servers) {
2106 realm->srvconfs = addsrvconfs(value, servers);
2107 if (!realm->srvconfs)
2111 if (accservers && *accservers) {
2112 realm->accsrvconfs = addsrvconfs(value, accservers);
2113 if (!realm->accsrvconfs)
2117 if (!list_push(realmlist, realm)) {
2118 debug(DBG_ERR, "malloc failed");
2119 pthread_mutex_destroy(&realm->mutex);
2123 debug(DBG_DBG, "addrealm: added realm %s", value);
2127 while (list_shift(realm->srvconfs));
2128 while (list_shift(realm->accsrvconfs));
2135 for (n = 0; servers[n]; n++)
2137 freegconfmstr(servers);
2141 for (n = 0; accservers[n]; n++)
2143 freegconfmstr(accservers);
2145 return newrealmref(realm);
2148 struct list *createsubrealmservers(struct realm *realm, struct list *srvconfs) {
2149 struct list_node *entry;
2150 struct clsrvconf *conf, *srvconf;
2151 struct list *subrealmservers = NULL;
2154 if (list_first(srvconfs)) {
2155 subrealmservers = list_create();
2156 if (!subrealmservers)
2160 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2161 conf = (struct clsrvconf *)entry->data;
2162 if (!conf->servers && conf->dynamiclookupcommand) {
2163 srvconf = malloc(sizeof(struct clsrvconf));
2165 debug(DBG_ERR, "malloc failed");
2169 if (addserver(srvconf)) {
2170 srvconf->servers->dynamiclookuparg = stringcopy(realm->name, 0);
2171 srvconf->servers->dynstartup = 1;
2172 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2173 debugerrno(errno, DBG_ERR, "pthread_create failed");
2174 freeserver(srvconf->servers, 1);
2175 srvconf->servers = NULL;
2177 pthread_detach(clientth);
2181 if (conf->servers) {
2182 if (list_push(subrealmservers, conf))
2185 debug(DBG_ERR, "malloc failed");
2188 return subrealmservers;
2191 struct realm *adddynamicrealmserver(struct realm *realm, char *id) {
2192 struct realm *newrealm = NULL;
2193 char *realmname, *s;
2195 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2196 realmname = strrchr(id, '@');
2202 for (s = realmname; *s; s++)
2203 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2206 if (!realm->subrealms)
2207 realm->subrealms = list_create();
2208 if (!realm->subrealms)
2211 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, stringcopy(realm->message, 0), realm->accresp);
2213 list_destroy(realm->subrealms);
2214 realm->subrealms = NULL;
2218 newrealm->parent = newrealmref(realm);
2219 /* add server and accserver to newrealm */
2220 newrealm->srvconfs = createsubrealmservers(newrealm, realm->srvconfs);
2221 newrealm->accsrvconfs = createsubrealmservers(newrealm, realm->accsrvconfs);
2225 int dynamicconfig(struct server *server) {
2226 int ok, fd[2], status;
2228 struct clsrvconf *conf = server->conf;
2229 struct gconffile *cf = NULL;
2231 /* for now we only learn hostname/address */
2232 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2235 debugerrno(errno, DBG_ERR, "dynamicconfig: pipe error");
2240 debugerrno(errno, DBG_ERR, "dynamicconfig: fork error");
2244 } else if (pid == 0) {
2247 if (fd[1] != STDOUT_FILENO) {
2248 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2249 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2252 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2253 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2257 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2258 ok = getgenericconfig(&cf, NULL,
2259 "Server", CONF_CBK, confserver_cb, (void *)conf,
2264 if (waitpid(pid, &status, 0) < 0) {
2265 debugerrno(errno, DBG_ERR, "dynamicconfig: wait error");
2270 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2278 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2282 /* should accept both names and numeric values, only numeric right now */
2283 uint8_t attrname2val(char *attrname) {
2286 val = atoi(attrname);
2287 return val > 0 && val < 256 ? val : 0;
2290 /* ATTRNAME is on the form vendor[:type].
2291 If only vendor is found, TYPE is set to 256 and 1 is returned.
2292 If type is >= 256, 1 is returned.
2293 Otherwise, 0 is returned.
2295 /* should accept both names and numeric values, only numeric right now */
2296 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2299 *vendor = atoi(attrname);
2300 s = strchr(attrname, ':');
2301 if (!s) { /* Only vendor was found. */
2305 *type = atoi(s + 1);
2309 /** Extract attributes from string NAMEVAL, create a struct tlv and
2310 * return the tlv. If VENDOR_FLAG, NAMEVAL is on the form
2311 * "<vendor>:<name>:<val>" and otherwise it's "<name>:<val>". Return
2312 * NULL if fields are missing or if conversion fails.
2314 * FIXME: Should accept both names and numeric values, only numeric
2316 struct tlv *extractattr(char *nameval, char vendor_flag) {
2318 int vendor = 0; /* Vendor 0 is reserved, see RFC 1700. */
2322 s = strchr(nameval, ':');
2325 name = atoi(nameval);
2328 s2 = strchr(s + 1, ':');
2335 len = strlen(s + 1);
2339 if (name < 1 || name > 255)
2341 a = malloc(sizeof(struct tlv));
2345 a->v = (uint8_t *)stringcopy(s + 1, 0);
2354 a = makevendortlv(vendor, a);
2359 /* should accept both names and numeric values, only numeric right now */
2360 struct modattr *extractmodattr(char *nameval) {
2365 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2369 s = strchr(nameval, ':');
2370 name = atoi(nameval);
2371 if (!s || name < 1 || name > 255 || s[1] != '/')
2375 /* regexp, remove optional trailing / if present */
2376 if (s[strlen(s) - 1] == '/')
2377 s[strlen(s) - 1] = '\0';
2385 m = malloc(sizeof(struct modattr));
2387 debug(DBG_ERR, "malloc failed");
2392 m->replacement = stringcopy(t, 0);
2393 if (!m->replacement) {
2395 debug(DBG_ERR, "malloc failed");
2399 m->regex = malloc(sizeof(regex_t));
2401 free(m->replacement);
2403 debug(DBG_ERR, "malloc failed");
2407 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2409 free(m->replacement);
2411 debug(DBG_ERR, "failed to compile regular expression %s", s);
2418 struct rewrite *getrewrite(char *alt1, char *alt2) {
2422 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2425 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2430 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **addvattrs, char **modattrs)
2432 struct rewrite *rewrite = NULL;
2434 uint8_t *rma = NULL;
2435 uint32_t *p, *rmva = NULL;
2436 struct list *adda = NULL, *moda = NULL;
2441 for (n = 0; rmattrs[n]; n++);
2442 rma = calloc(n + 1, sizeof(uint8_t));
2444 debugx(1, DBG_ERR, "malloc failed");
2446 for (i = 0; i < n; i++)
2447 if (!(rma[i] = attrname2val(rmattrs[i])))
2448 debugx(1, DBG_ERR, "addrewrite: removing invalid attribute %s", rmattrs[i]);
2449 freegconfmstr(rmattrs);
2454 for (n = 0; rmvattrs[n]; n++);
2455 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2457 debugx(1, DBG_ERR, "malloc failed");
2459 for (p = rmva, i = 0; i < n; i++, p += 2)
2460 if (!vattrname2val(rmvattrs[i], p, p + 1))
2461 debugx(1, DBG_ERR, "addrewrite: removing invalid vendor attribute %s", rmvattrs[i]);
2462 freegconfmstr(rmvattrs);
2467 adda = list_create();
2469 debugx(1, DBG_ERR, "malloc failed");
2470 for (i = 0; addattrs[i]; i++) {
2471 a = extractattr(addattrs[i], 0);
2473 debugx(1, DBG_ERR, "addrewrite: adding invalid attribute %s", addattrs[i]);
2474 if (!list_push(adda, a))
2475 debugx(1, DBG_ERR, "malloc failed");
2477 freegconfmstr(addattrs);
2482 adda = list_create();
2484 debugx(1, DBG_ERR, "malloc failed");
2485 for (i = 0; addvattrs[i]; i++) {
2486 a = extractattr(addvattrs[i], 1);
2488 debugx(1, DBG_ERR, "addrewrite: adding invalid vendor attribute %s", addvattrs[i]);
2489 if (!list_push(adda, a))
2490 debugx(1, DBG_ERR, "malloc failed");
2492 freegconfmstr(addvattrs);
2496 moda = list_create();
2498 debugx(1, DBG_ERR, "malloc failed");
2499 for (i = 0; modattrs[i]; i++) {
2500 m = extractmodattr(modattrs[i]);
2502 debugx(1, DBG_ERR, "addrewrite: modifying invalid attribute %s", modattrs[i]);
2503 if (!list_push(moda, m))
2504 debugx(1, DBG_ERR, "malloc failed");
2506 freegconfmstr(modattrs);
2509 if (rma || rmva || adda || moda) {
2510 rewrite = malloc(sizeof(struct rewrite));
2512 debugx(1, DBG_ERR, "malloc failed");
2513 rewrite->removeattrs = rma;
2514 rewrite->removevendorattrs = rmva;
2515 rewrite->addattrs = adda;
2516 rewrite->modattrs = moda;
2519 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2520 debugx(1, DBG_ERR, "malloc failed");
2521 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2524 int setttlattr(struct options *opts, char *defaultattr) {
2525 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
2527 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
2528 (opts->ttlattrtype[1] != 256 || opts->ttlattrtype[0] < 256))
2530 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
2534 void freeclsrvconf(struct clsrvconf *conf) {
2537 freegconfmstr(conf->hostsrc);
2538 free(conf->portsrc);
2541 free(conf->matchcertattr);
2542 if (conf->certcnregex)
2543 regfree(conf->certcnregex);
2544 if (conf->certuriregex)
2545 regfree(conf->certuriregex);
2546 free(conf->confrewritein);
2547 free(conf->confrewriteout);
2548 if (conf->rewriteusername) {
2549 if (conf->rewriteusername->regex)
2550 regfree(conf->rewriteusername->regex);
2551 free(conf->rewriteusername->replacement);
2552 free(conf->rewriteusername);
2554 free(conf->dynamiclookupcommand);
2555 free(conf->rewritein);
2556 free(conf->rewriteout);
2557 if (conf->hostports)
2558 freehostports(conf->hostports);
2560 pthread_mutex_destroy(conf->lock);
2563 /* not touching ssl_ctx, clients and servers */
2567 int mergeconfstring(char **dst, char **src) {
2576 t = stringcopy(*dst, 0);
2578 debug(DBG_ERR, "malloc failed");
2586 char **mstringcopy(char **in) {
2593 for (n = 0; in[n]; n++);
2594 out = malloc((n + 1) * sizeof(char *));
2597 for (n = 0; in[n]; n++) {
2598 out[n] = stringcopy(in[n], 0);
2608 int mergeconfmstring(char ***dst, char ***src) {
2617 t = mstringcopy(*dst);
2619 debug(DBG_ERR, "malloc failed");
2627 /* assumes dst is a shallow copy */
2628 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2629 if (!mergeconfstring(&dst->name, &src->name) ||
2630 !mergeconfmstring(&dst->hostsrc, &src->hostsrc) ||
2631 !mergeconfstring(&dst->portsrc, &src->portsrc) ||
2632 !mergeconfstring(&dst->secret, &src->secret) ||
2633 !mergeconfstring(&dst->tls, &src->tls) ||
2634 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2635 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2636 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2637 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2640 dst->pdef = src->pdef;
2641 dst->statusserver = src->statusserver;
2642 dst->certnamecheck = src->certnamecheck;
2643 if (src->retryinterval != 255)
2644 dst->retryinterval = src->retryinterval;
2645 if (src->retrycount != 255)
2646 dst->retrycount = src->retrycount;
2650 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2651 struct clsrvconf *conf;
2652 char *conftype = NULL, *rewriteinalias = NULL;
2653 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
2655 debug(DBG_DBG, "confclient_cb called for %s", block);
2657 conf = malloc(sizeof(struct clsrvconf));
2659 debugx(1, DBG_ERR, "malloc failed");
2660 memset(conf, 0, sizeof(struct clsrvconf));
2661 conf->certnamecheck = 1;
2663 if (!getgenericconfig(cf, block,
2664 "type", CONF_STR, &conftype,
2665 "host", CONF_MSTR, &conf->hostsrc,
2666 "secret", CONF_STR, &conf->secret,
2667 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2668 "tls", CONF_STR, &conf->tls,
2669 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2670 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2672 "DuplicateInterval", CONF_LINT, &dupinterval,
2673 "addTTL", CONF_LINT, &addttl,
2674 "rewrite", CONF_STR, &rewriteinalias,
2675 "rewriteIn", CONF_STR, &conf->confrewritein,
2676 "rewriteOut", CONF_STR, &conf->confrewriteout,
2677 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2680 debugx(1, DBG_ERR, "configuration error");
2682 conf->name = stringcopy(val, 0);
2683 if (conf->name && !conf->hostsrc) {
2684 conf->hostsrc = malloc(2 * sizeof(char *));
2685 if (conf->hostsrc) {
2686 conf->hostsrc[0] = stringcopy(val, 0);
2687 conf->hostsrc[1] = NULL;
2690 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0])
2691 debugx(1, DBG_ERR, "malloc failed");
2694 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2695 conf->type = protoname2int(conftype);
2696 if (conf->type == 255)
2697 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2699 conf->pdef = protodefs[conf->type];
2701 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2702 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2703 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
2705 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2706 if (conf->matchcertattr && !addmatchcertattr(conf))
2707 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2711 if (dupinterval != LONG_MIN) {
2712 if (dupinterval < 0 || dupinterval > 255)
2713 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
2714 conf->dupinterval = (uint8_t)dupinterval;
2716 conf->dupinterval = conf->pdef->duplicateintervaldefault;
2718 if (addttl != LONG_MIN) {
2719 if (addttl < 1 || addttl > 255)
2720 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2721 conf->addttl = (uint8_t)addttl;
2724 if (!conf->confrewritein)
2725 conf->confrewritein = rewriteinalias;
2727 free(rewriteinalias);
2728 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2729 if (conf->confrewriteout)
2730 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2732 if (conf->confrewriteusername) {
2733 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2734 if (!conf->rewriteusername)
2735 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2738 if (!addhostport(&conf->hostports, conf->hostsrc, conf->pdef->portdefault, 1) ||
2739 !resolvehostports(conf->hostports, conf->pdef->socktype))
2740 debugx(1, DBG_ERR, "resolve failed, exiting");
2742 if (!conf->secret) {
2743 if (!conf->pdef->secretdefault)
2744 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2745 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2747 debugx(1, DBG_ERR, "malloc failed");
2750 conf->lock = malloc(sizeof(pthread_mutex_t));
2752 debugx(1, DBG_ERR, "malloc failed");
2754 pthread_mutex_init(conf->lock, NULL);
2755 if (!list_push(clconfs, conf))
2756 debugx(1, DBG_ERR, "malloc failed");
2760 int compileserverconfig(struct clsrvconf *conf, const char *block) {
2761 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2762 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2763 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
2764 if (!conf->tlsconf) {
2765 debug(DBG_ERR, "error in block %s, no tls context defined", block);
2768 if (conf->matchcertattr && !addmatchcertattr(conf)) {
2769 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2775 if (!conf->portsrc) {
2776 conf->portsrc = stringcopy(conf->pdef->portdefault, 0);
2777 if (!conf->portsrc) {
2778 debug(DBG_ERR, "malloc failed");
2783 if (conf->retryinterval == 255)
2784 conf->retryinterval = conf->pdef->retryintervaldefault;
2785 if (conf->retrycount == 255)
2786 conf->retrycount = conf->pdef->retrycountdefault;
2788 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
2789 if (conf->confrewriteout)
2790 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2792 if (!addhostport(&conf->hostports, conf->hostsrc, conf->portsrc, 0)) {
2793 debug(DBG_ERR, "error in block %s, failed to parse %s", block, conf->hostsrc);
2797 if (!conf->dynamiclookupcommand && !resolvehostports(conf->hostports, conf->pdef->socktype)) {
2798 debug(DBG_ERR, "resolve failed, exiting");
2804 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2805 struct clsrvconf *conf, *resconf;
2806 char *conftype = NULL, *rewriteinalias = NULL;
2807 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
2809 debug(DBG_DBG, "confserver_cb called for %s", block);
2811 conf = malloc(sizeof(struct clsrvconf));
2813 debug(DBG_ERR, "malloc failed");
2816 memset(conf, 0, sizeof(struct clsrvconf));
2817 conf->loopprevention = UCHAR_MAX; /* Uninitialized. */
2818 resconf = (struct clsrvconf *)arg;
2820 conf->statusserver = resconf->statusserver;
2821 conf->certnamecheck = resconf->certnamecheck;
2823 conf->certnamecheck = 1;
2825 if (!getgenericconfig(cf, block,
2826 "type", CONF_STR, &conftype,
2827 "host", CONF_MSTR, &conf->hostsrc,
2828 "port", CONF_STR, &conf->portsrc,
2829 "secret", CONF_STR, &conf->secret,
2830 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
2831 "tls", CONF_STR, &conf->tls,
2832 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
2833 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2835 "addTTL", CONF_LINT, &addttl,
2836 "rewrite", CONF_STR, &rewriteinalias,
2837 "rewriteIn", CONF_STR, &conf->confrewritein,
2838 "rewriteOut", CONF_STR, &conf->confrewriteout,
2839 "StatusServer", CONF_BLN, &conf->statusserver,
2840 "RetryInterval", CONF_LINT, &retryinterval,
2841 "RetryCount", CONF_LINT, &retrycount,
2842 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
2843 "LoopPrevention", CONF_BLN, &conf->loopprevention,
2846 debug(DBG_ERR, "configuration error");
2850 conf->name = stringcopy(val, 0);
2851 if (conf->name && !conf->hostsrc) {
2852 conf->hostsrc = malloc(2 * sizeof(char *));
2853 if (conf->hostsrc) {
2854 conf->hostsrc[0] = stringcopy(val, 0);
2855 conf->hostsrc[1] = NULL;
2858 if (!conf->name || !conf->hostsrc || !conf->hostsrc[0]) {
2859 debug(DBG_ERR, "malloc failed");
2864 debug(DBG_ERR, "error in block %s, option type missing", block);
2867 conf->type = protoname2int(conftype);
2868 if (conf->type == 255) {
2869 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2875 conf->pdef = protodefs[conf->type];
2877 if (!conf->confrewritein)
2878 conf->confrewritein = rewriteinalias;
2880 free(rewriteinalias);
2881 rewriteinalias = NULL;
2883 if (retryinterval != LONG_MIN) {
2884 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
2885 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
2888 conf->retryinterval = (uint8_t)retryinterval;
2890 conf->retryinterval = 255;
2892 if (retrycount != LONG_MIN) {
2893 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
2894 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
2897 conf->retrycount = (uint8_t)retrycount;
2899 conf->retrycount = 255;
2901 if (addttl != LONG_MIN) {
2902 if (addttl < 1 || addttl > 255) {
2903 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
2906 conf->addttl = (uint8_t)addttl;
2910 if (!mergesrvconf(resconf, conf))
2914 if (conf->dynamiclookupcommand) {
2915 free(conf->dynamiclookupcommand);
2916 conf->dynamiclookupcommand = NULL;
2920 if (resconf || !conf->dynamiclookupcommand) {
2921 if (!compileserverconfig(conf, block))
2925 if (!conf->secret) {
2926 if (!conf->pdef->secretdefault) {
2927 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
2930 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
2931 if (!conf->secret) {
2932 debug(DBG_ERR, "malloc failed");
2940 if (!list_push(srvconfs, conf)) {
2941 debug(DBG_ERR, "malloc failed");
2948 free(rewriteinalias);
2949 freeclsrvconf(conf);
2953 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2954 char **servers = NULL, **accservers = NULL, *msg = NULL;
2955 uint8_t accresp = 0;
2957 debug(DBG_DBG, "confrealm_cb called for %s", block);
2959 if (!getgenericconfig(cf, block,
2960 "server", CONF_MSTR, &servers,
2961 "accountingServer", CONF_MSTR, &accservers,
2962 "ReplyMessage", CONF_STR, &msg,
2963 "AccountingResponse", CONF_BLN, &accresp,
2966 debugx(1, DBG_ERR, "configuration error");
2968 addrealm(realms, val, servers, accservers, msg, accresp);
2972 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2973 char **rmattrs = NULL, **rmvattrs = NULL;
2974 char **addattrs = NULL, **addvattrs = NULL;
2975 char **modattrs = NULL;
2977 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2979 if (!getgenericconfig(cf, block,
2980 "removeAttribute", CONF_MSTR, &rmattrs,
2981 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
2982 "addAttribute", CONF_MSTR, &addattrs,
2983 "addVendorAttribute", CONF_MSTR, &addvattrs,
2984 "modifyAttribute", CONF_MSTR, &modattrs,
2987 debugx(1, DBG_ERR, "configuration error");
2988 addrewrite(val, rmattrs, rmvattrs, addattrs, addvattrs, modattrs);
2992 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
2993 struct commonprotoopts *protoopts;
2995 protoopts = malloc(sizeof(struct commonprotoopts));
2998 memset(protoopts, 0, sizeof(struct commonprotoopts));
2999 protoopts->listenargs = listenargs;
3000 protoopts->sourcearg = sourcearg;
3001 protodefs[type]->setprotoopts(protoopts);
3005 void getmainconfig(const char *configfile) {
3006 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3007 struct gconffile *cfs;
3008 char **listenargs[RAD_PROTOCOUNT];
3009 char *sourcearg[RAD_PROTOCOUNT];
3012 cfs = openconfigfile(configfile);
3013 memset(&options, 0, sizeof(options));
3014 memset(&listenargs, 0, sizeof(listenargs));
3015 memset(&sourcearg, 0, sizeof(sourcearg));
3017 clconfs = list_create();
3019 debugx(1, DBG_ERR, "malloc failed");
3021 srvconfs = list_create();
3023 debugx(1, DBG_ERR, "malloc failed");
3025 realms = list_create();
3027 debugx(1, DBG_ERR, "malloc failed");
3029 rewriteconfs = hash_create();
3031 debugx(1, DBG_ERR, "malloc failed");
3033 if (!getgenericconfig(
3036 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3037 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3040 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3041 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3044 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3045 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3048 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3049 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3051 "TTLAttribute", CONF_STR, &options.ttlattr,
3052 "addTTL", CONF_LINT, &addttl,
3053 "LogLevel", CONF_LINT, &loglevel,
3054 "LogDestination", CONF_STR, &options.logdestination,
3055 "LoopPrevention", CONF_BLN, &options.loopprevention,
3056 "Client", CONF_CBK, confclient_cb, NULL,
3057 "Server", CONF_CBK, confserver_cb, NULL,
3058 "Realm", CONF_CBK, confrealm_cb, NULL,
3059 #if defined(RADPROT_TLS) || defined(RADPROT_DTLS)
3060 "TLS", CONF_CBK, conftls_cb, NULL,
3062 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3065 debugx(1, DBG_ERR, "configuration error");
3067 if (loglevel != LONG_MIN) {
3068 if (loglevel < 1 || loglevel > 5)
3069 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3, 4 or 5", configfile, loglevel);
3070 options.loglevel = (uint8_t)loglevel;
3072 if (addttl != LONG_MIN) {
3073 if (addttl < 1 || addttl > 255)
3074 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3075 options.addttl = (uint8_t)addttl;
3077 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3078 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3080 for (i = 0; i < RAD_PROTOCOUNT; i++)
3081 if (listenargs[i] || sourcearg[i])
3082 setprotoopts(i, listenargs[i], sourcearg[i]);
3085 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile, char **pidfile) {
3088 while ((c = getopt(argc, argv, "c:d:i:fpv")) != -1) {
3091 *configfile = optarg;
3094 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '5')
3095 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3, 4 or 5, not %s", optarg);
3096 *loglevel = *optarg - '0';
3108 debug(DBG_ERR, "radsecproxy revision %s", PACKAGE_VERSION);
3109 debug(DBG_ERR, "This binary was built with support for the following transports:");
3111 debug(DBG_ERR, " UDP");
3114 debug(DBG_ERR, " TCP");
3117 debug(DBG_ERR, " TLS");
3120 debug(DBG_ERR, " DTLS");
3127 if (!(argc - optind))
3131 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -i pidfile ] [ -p ] [ -v ]", argv[0]);
3135 int daemon(int a, int b) {
3143 for (i = 0; i < 3; i++) {
3145 open("/dev/null", O_RDWR);
3151 void *sighandler(void *arg) {
3156 sigemptyset(&sigset);
3157 sigaddset(&sigset, SIGHUP);
3158 sigaddset(&sigset, SIGPIPE);
3159 sigwait(&sigset, &sig);
3162 /* completely ignoring this */
3165 debug(DBG_INFO, "sighandler: got SIGHUP");
3169 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3172 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3177 int createpidfile(const char *pidfile) {
3179 FILE *f = fopen(pidfile, "w");
3181 r = fprintf(f, "%ld\n", (long) getpid());
3182 return f && !fclose(f) && r >= 0;
3185 int main(int argc, char **argv) {
3188 struct list_node *entry;
3189 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3190 char *configfile = NULL, *pidfile = NULL;
3191 struct clsrvconf *srvconf;
3194 debug_init("radsecproxy");
3195 debug_set_level(DEBUG_LEVEL);
3197 for (i = 0; i < RAD_PROTOCOUNT; i++)
3198 protodefs[i] = protoinits[i](i);
3200 /* needed even if no TLS/DTLS transport */
3203 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile, &pidfile);
3205 debug_set_level(loglevel);
3206 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3208 options.loglevel = loglevel;
3209 else if (options.loglevel)
3210 debug_set_level(options.loglevel);
3212 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3213 free(options.logdestination);
3215 if (!list_first(clconfs))
3216 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3217 if (!list_first(realms))
3218 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3221 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3223 if (!foreground && (daemon(0, 0) < 0))
3224 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3226 debug_timestamp_on();
3227 debug(DBG_INFO, "radsecproxy revision %s starting", PACKAGE_VERSION);
3228 if (pidfile && !createpidfile(pidfile))
3229 debugx(1, DBG_ERR, "failed to create pidfile %s: %s", pidfile, strerror(errno));
3231 sigemptyset(&sigset);
3232 /* exit on all but SIGHUP|SIGPIPE, ignore more? */
3233 sigaddset(&sigset, SIGHUP);
3234 sigaddset(&sigset, SIGPIPE);
3235 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3236 pthread_create(&sigth, NULL, sighandler, NULL);
3238 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3239 srvconf = (struct clsrvconf *)entry->data;
3240 if (srvconf->dynamiclookupcommand)
3242 if (!addserver(srvconf))
3243 debugx(1, DBG_ERR, "failed to add server");
3244 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3245 (void *)(srvconf->servers)))
3246 debugx(1, DBG_ERR, "pthread_create failed");
3249 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3252 if (protodefs[i]->initextra)
3253 protodefs[i]->initextra();
3254 if (find_clconf_type(i, NULL))
3258 /* just hang around doing nothing, anything to do here? */
3263 /* Local Variables: */
3264 /* c-file-style: "stroustrup" */