2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * May segfault when dtls connections go down? More testing needed
39 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
59 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
74 #include "radsecproxy.h"
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
83 struct hash *tlsconfs, *rewriteconfs;
85 static pthread_mutex_t *ssl_locks = NULL;
86 static long *ssl_lock_count;
89 static const struct protodefs *protodefs[RAD_PROTOCOUNT];
91 /* minimum required declarations to avoid reordering code */
92 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
93 int dynamicconfig(struct server *server);
94 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
95 void freerealm(struct realm *realm);
96 void freeclsrvconf(struct clsrvconf *conf);
97 void freerq(struct request *rq);
98 void freerqoutdata(struct rqout *rqout);
99 void rmclientrq(struct request *rq, uint8_t id);
101 static const struct protodefs *(*protoinits[])(uint8_t) = { udpinit, tlsinit, tcpinit, dtlsinit };
103 uint8_t protoname2int(const char *name) {
106 for (i = 0; i < RAD_PROTOCOUNT; i++)
107 if (protodefs[i] && protodefs[i]->name && !strcasecmp(protodefs[i]->name, name))
112 /* callbacks for making OpenSSL thread safe */
113 unsigned long ssl_thread_id() {
114 return (unsigned long)pthread_self();
117 void ssl_locking_callback(int mode, int type, const char *file, int line) {
118 if (mode & CRYPTO_LOCK) {
119 pthread_mutex_lock(&ssl_locks[type]);
120 ssl_lock_count[type]++;
122 pthread_mutex_unlock(&ssl_locks[type]);
125 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
126 int pwdlen = strlen(userdata);
127 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
129 memcpy(buf, userdata, pwdlen);
133 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
138 err_cert = X509_STORE_CTX_get_current_cert(ctx);
139 err = X509_STORE_CTX_get_error(ctx);
140 depth = X509_STORE_CTX_get_error_depth(ctx);
142 if (depth > MAX_CERT_DEPTH) {
144 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
145 X509_STORE_CTX_set_error(ctx, err);
150 buf = X509_NAME_oneline(X509_get_subject_name(err_cert), NULL, 0);
151 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf ? buf : "");
156 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
158 buf = X509_NAME_oneline(X509_get_issuer_name(err_cert), NULL, 0);
160 debug(DBG_WARN, "\tIssuer=%s", buf);
166 case X509_V_ERR_CERT_NOT_YET_VALID:
167 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
168 debug(DBG_WARN, "\tCertificate not yet valid");
170 case X509_V_ERR_CERT_HAS_EXPIRED:
171 debug(DBG_WARN, "Certificate has expired");
173 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
174 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
176 case X509_V_ERR_NO_EXPLICIT_POLICY:
177 debug(DBG_WARN, "No Explicit Certificate Policy");
182 printf("certificate verify returns %d\n", ok);
187 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
188 struct addrinfo hints, *addrinfo, *res;
192 slash = conf->host ? strchr(conf->host, '/') : NULL;
196 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
200 if (*s < '0' || *s > '9') {
201 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
204 plen = atoi(slash + 1);
205 if (plen < 0 || plen > 128) {
206 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
211 memset(&hints, 0, sizeof(hints));
212 hints.ai_socktype = conf->pdef->socktype;
213 hints.ai_family = AF_UNSPEC;
214 hints.ai_flags = ai_flags;
215 if (!conf->host && !conf->port) {
216 /* getaddrinfo() doesn't like host and port to be NULL */
217 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
218 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
221 for (res = addrinfo; res; res = res->ai_next)
222 port_set(res->ai_addr, 0);
225 hints.ai_flags |= AI_NUMERICHOST;
226 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
227 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
232 switch (addrinfo->ai_family) {
235 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
236 freeaddrinfo(addrinfo);
243 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
244 freeaddrinfo(addrinfo);
247 conf->prefixlen = (uint8_t)plen;
249 conf->prefixlen = 255;
252 freeaddrinfo(conf->addrinfo);
253 conf->addrinfo = addrinfo;
257 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
262 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
266 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
268 debugx(1, DBG_ERR, "no ] matching initial [");
272 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
275 debugx(1, DBG_ERR, "missing host/address");
277 conf->host = stringcopy(field, p - field);
280 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
281 debugx(1, DBG_ERR, "unexpected character after ]");
284 /* port number or service name is specified */;
286 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
288 debugx(1, DBG_ERR, "syntax error, : but no following port");
289 conf->port = stringcopy(field, p - field);
291 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
295 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
296 struct clsrvconf *conf;
298 conf = malloc(sizeof(struct clsrvconf));
300 debugx(1, DBG_ERR, "malloc failed");
301 memset(conf, 0, sizeof(struct clsrvconf));
303 conf->pdef = protodefs[conf->type];
305 parsehostport(lconf, conf, default_port);
306 if (!strcmp(conf->host, "*")) {
311 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
312 if (!resolvepeer(conf, AI_PASSIVE))
313 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
317 void freeclsrvres(struct clsrvconf *res) {
321 freeaddrinfo(res->addrinfo);
325 struct addrinfo *resolve_hostport_addrinfo(uint8_t type, char *hostport) {
327 struct clsrvconf *res;
329 res = resolve_hostport(type, hostport, NULL);
331 res->addrinfo = NULL;
336 /* returns 1 if the len first bits are equal, else 0 */
337 int prefixmatch(void *a1, void *a2, uint8_t len) {
338 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
339 uint8_t r, l = len / 8;
340 if (l && memcmp(a1, a2, l))
345 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
348 /* returns next config with matching address, or NULL */
349 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
350 struct sockaddr_in6 *sa6 = NULL;
351 struct in_addr *a4 = NULL;
352 struct addrinfo *res;
353 struct list_node *entry;
354 struct clsrvconf *conf;
356 if (addr->sa_family == AF_INET6) {
357 sa6 = (struct sockaddr_in6 *)addr;
358 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
359 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
363 a4 = &((struct sockaddr_in *)addr)->sin_addr;
365 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
366 conf = (struct clsrvconf *)entry->data;
367 if (conf->type == type) {
368 if (conf->prefixlen == 255) {
369 for (res = conf->addrinfo; res; res = res->ai_next)
370 if ((a4 && res->ai_family == AF_INET &&
371 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
372 (sa6 && res->ai_family == AF_INET6 &&
373 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
379 res = conf->addrinfo;
381 ((a4 && res->ai_family == AF_INET &&
382 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
383 (sa6 && res->ai_family == AF_INET6 &&
384 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
395 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
396 return find_conf(type, addr, clconfs, cur);
399 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
400 return find_conf(type, addr, srvconfs, cur);
403 /* returns next config of given type, or NULL */
404 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
405 struct list_node *entry;
406 struct clsrvconf *conf;
408 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
409 conf = (struct clsrvconf *)entry->data;
410 if (conf->type == type) {
419 struct queue *newqueue() {
422 q = malloc(sizeof(struct queue));
424 debugx(1, DBG_ERR, "malloc failed");
425 q->entries = list_create();
427 debugx(1, DBG_ERR, "malloc failed");
428 pthread_mutex_init(&q->mutex, NULL);
429 pthread_cond_init(&q->cond, NULL);
433 void removequeue(struct queue *q) {
434 struct list_node *entry;
438 pthread_mutex_lock(&q->mutex);
439 for (entry = list_first(q->entries); entry; entry = list_next(entry))
440 freerq((struct request *)entry);
441 list_destroy(q->entries);
442 pthread_cond_destroy(&q->cond);
443 pthread_mutex_unlock(&q->mutex);
444 pthread_mutex_destroy(&q->mutex);
448 void freebios(struct queue *q) {
451 pthread_mutex_lock(&q->mutex);
452 while ((bio = (BIO *)list_shift(q->entries)))
454 pthread_mutex_unlock(&q->mutex);
458 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
459 struct client *new = malloc(sizeof(struct client));
462 debug(DBG_ERR, "malloc failed");
467 pthread_mutex_lock(conf->lock);
468 if (!conf->clients) {
469 conf->clients = list_create();
470 if (!conf->clients) {
472 pthread_mutex_unlock(conf->lock);
473 debug(DBG_ERR, "malloc failed");
478 memset(new, 0, sizeof(struct client));
480 if (conf->pdef->addclient)
481 conf->pdef->addclient(new);
483 new->replyq = newqueue();
484 list_push(conf->clients, new);
486 pthread_mutex_unlock(conf->lock);
490 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
491 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
494 pthread_mutex_lock(&lock);
496 pthread_mutex_unlock(&lock);
499 void removeclientrqs(struct client *client) {
504 removeclientrqs_sendrq_freeserver_lock(1);
505 for (i = 0; i < MAX_REQUESTS; i++) {
510 rqout = rq->to->requests + rq->newid;
511 pthread_mutex_lock(rqout->lock);
512 if (rqout->rq == rq) /* still pointing to our request */
513 freerqoutdata(rqout);
514 pthread_mutex_unlock(rqout->lock);
518 removeclientrqs_sendrq_freeserver_lock(0);
521 void removelockedclient(struct client *client) {
522 struct clsrvconf *conf;
526 removeclientrqs(client);
527 removequeue(client->replyq);
528 list_removedata(conf->clients, client);
534 void removeclient(struct client *client) {
535 struct clsrvconf *conf;
541 pthread_mutex_lock(conf->lock);
542 removelockedclient(client);
543 pthread_mutex_unlock(conf->lock);
546 void freeserver(struct server *server, uint8_t destroymutex) {
547 struct rqout *rqout, *end;
552 removeclientrqs_sendrq_freeserver_lock(1);
553 if (server->requests) {
554 rqout = server->requests;
555 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
557 rqout->rq->to = NULL;
558 freerqoutdata(rqout);
559 pthread_mutex_destroy(rqout->lock);
562 free(server->requests);
565 freebios(server->rbios);
566 free(server->dynamiclookuparg);
568 SSL_free(server->ssl);
570 pthread_mutex_destroy(&server->lock);
571 pthread_cond_destroy(&server->newrq_cond);
572 pthread_mutex_destroy(&server->newrq_mutex);
574 removeclientrqs_sendrq_freeserver_lock(0);
578 int addserver(struct clsrvconf *conf) {
583 debug(DBG_ERR, "addserver: currently works with just one server per conf");
586 conf->servers = malloc(sizeof(struct server));
587 if (!conf->servers) {
588 debug(DBG_ERR, "malloc failed");
591 memset(conf->servers, 0, sizeof(struct server));
592 conf->servers->conf = conf;
595 if (type == RAD_DTLS)
596 conf->servers->rbios = newqueue();
598 conf->pdef->setsrcres();
600 conf->servers->sock = -1;
601 if (conf->pdef->addserverextra)
602 conf->pdef->addserverextra(conf);
604 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
605 if (!conf->servers->requests) {
606 debug(DBG_ERR, "malloc failed");
609 for (i = 0; i < MAX_REQUESTS; i++) {
610 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
611 if (!conf->servers->requests[i].lock) {
612 debug(DBG_ERR, "malloc failed");
615 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
616 debug(DBG_ERR, "mutex init failed");
617 free(conf->servers->requests[i].lock);
618 conf->servers->requests[i].lock = NULL;
622 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
623 debug(DBG_ERR, "mutex init failed");
626 conf->servers->newrq = 0;
627 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
628 debug(DBG_ERR, "mutex init failed");
629 pthread_mutex_destroy(&conf->servers->lock);
632 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
633 debug(DBG_ERR, "mutex init failed");
634 pthread_mutex_destroy(&conf->servers->newrq_mutex);
635 pthread_mutex_destroy(&conf->servers->lock);
642 freeserver(conf->servers, 0);
643 conf->servers = NULL;
647 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
648 int loc, i, l, n, r = 0;
651 STACK_OF(GENERAL_NAME) *alt;
654 debug(DBG_DBG, "subjectaltnameaddr");
656 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
660 ex = X509_get_ext(cert, loc);
661 alt = X509V3_EXT_d2i(ex);
665 n = sk_GENERAL_NAME_num(alt);
666 for (i = 0; i < n; i++) {
667 gn = sk_GENERAL_NAME_value(alt, i);
668 if (gn->type != GEN_IPADD)
671 v = (char *)ASN1_STRING_data(gn->d.ia5);
672 l = ASN1_STRING_length(gn->d.ia5);
673 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
674 && !memcmp(v, &addr, l)) {
679 GENERAL_NAMES_free(alt);
683 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
690 nm = X509_get_subject_name(cert);
693 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
696 e = X509_NAME_get_entry(nm, loc);
697 t = X509_NAME_ENTRY_get_data(e);
698 v = (char *) ASN1_STRING_data(t);
699 l = ASN1_STRING_length(t);
703 if (l == strlen(exact) && !strncasecmp(exact, v, l))
706 s = stringcopy((char *)v, l);
708 debug(DBG_ERR, "malloc failed");
711 if (regexec(regex, s, 0, NULL, 0)) {
722 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
723 int loc, i, l, n, r = 0;
726 STACK_OF(GENERAL_NAME) *alt;
729 debug(DBG_DBG, "subjectaltnameregexp");
731 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
735 ex = X509_get_ext(cert, loc);
736 alt = X509V3_EXT_d2i(ex);
740 n = sk_GENERAL_NAME_num(alt);
741 for (i = 0; i < n; i++) {
742 gn = sk_GENERAL_NAME_value(alt, i);
743 if (gn->type != type)
746 v = (char *)ASN1_STRING_data(gn->d.ia5);
747 l = ASN1_STRING_length(gn->d.ia5);
751 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
754 if (memcmp(v, exact, l))
757 s = stringcopy((char *)v, l);
759 debug(DBG_ERR, "malloc failed");
762 if (regexec(regex, s, 0, NULL, 0)) {
771 GENERAL_NAMES_free(alt);
775 X509 *verifytlscert(SSL *ssl) {
779 if (SSL_get_verify_result(ssl) != X509_V_OK) {
780 debug(DBG_ERR, "verifytlscert: basic validation failed");
781 while ((error = ERR_get_error()))
782 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
786 cert = SSL_get_peer_certificate(ssl);
788 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
792 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
794 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
795 struct in6_addr addr;
797 if (conf->certnamecheck && conf->prefixlen == 255) {
798 if (inet_pton(AF_INET, conf->host, &addr))
800 else if (inet_pton(AF_INET6, conf->host, &addr))
803 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
806 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
809 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
811 if (!cnregexp(cert, conf->host, NULL)) {
812 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
815 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
818 if (conf->certcnregex) {
819 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
820 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
823 debug(DBG_DBG, "verifyconfcert: CN matching regex");
825 if (conf->certuriregex) {
826 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
827 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
830 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
835 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
837 if (ATTRTYPE(attrs) == type)
839 length -= ATTRLEN(attrs);
840 attrs += ATTRLEN(attrs);
845 struct request *newrqref(struct request *rq) {
851 void freerq(struct request *rq) {
854 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
857 if (rq->origusername)
858 free(rq->origusername);
864 radmsg_free(rq->msg);
868 void freerqoutdata(struct rqout *rqout) {
872 if (rqout->rq->buf) {
873 free(rqout->rq->buf);
874 rqout->rq->buf = NULL;
880 memset(&rqout->expiry, 0, sizeof(struct timeval));
883 void sendrq(struct request *rq) {
887 removeclientrqs_sendrq_freeserver_lock(1);
892 start = to->conf->statusserver ? 1 : 0;
893 pthread_mutex_lock(&to->newrq_mutex);
894 if (start && rq->msg->code == RAD_Status_Server) {
895 pthread_mutex_lock(to->requests[0].lock);
896 if (to->requests[0].rq) {
897 pthread_mutex_unlock(to->requests[0].lock);
898 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
905 /* might simplify if only try nextid, might be ok */
906 for (i = to->nextid; i < MAX_REQUESTS; i++) {
907 if (!to->requests[i].rq) {
908 pthread_mutex_lock(to->requests[i].lock);
909 if (!to->requests[i].rq)
911 pthread_mutex_unlock(to->requests[i].lock);
914 if (i == MAX_REQUESTS) {
915 for (i = start; i < to->nextid; i++) {
916 if (!to->requests[i].rq) {
917 pthread_mutex_lock(to->requests[i].lock);
918 if (!to->requests[i].rq)
920 pthread_mutex_unlock(to->requests[i].lock);
923 if (i == to->nextid) {
924 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
929 rq->newid = (uint8_t)i;
930 rq->msg->id = (uint8_t)i;
931 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
933 pthread_mutex_unlock(to->requests[i].lock);
934 debug(DBG_ERR, "sendrq: radmsg2buf failed");
938 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
939 to->requests[i].rq = rq;
940 pthread_mutex_unlock(to->requests[i].lock);
941 if (i >= start) /* i is not reserved for statusserver */
946 debug(DBG_DBG, "sendrq: signalling client writer");
947 pthread_cond_signal(&to->newrq_cond);
950 pthread_mutex_unlock(&to->newrq_mutex);
951 removeclientrqs_sendrq_freeserver_lock(0);
956 rmclientrq(rq, rq->msg->id);
958 pthread_mutex_unlock(&to->newrq_mutex);
959 removeclientrqs_sendrq_freeserver_lock(0);
962 void sendreply(struct request *rq) {
964 struct client *to = rq->from;
967 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
968 radmsg_free(rq->msg);
972 debug(DBG_ERR, "sendreply: radmsg2buf failed");
976 pthread_mutex_lock(&to->replyq->mutex);
977 first = list_first(to->replyq->entries) == NULL;
979 if (!list_push(to->replyq->entries, rq)) {
980 pthread_mutex_unlock(&to->replyq->mutex);
982 debug(DBG_ERR, "sendreply: malloc failed");
987 debug(DBG_DBG, "signalling server writer");
988 pthread_cond_signal(&to->replyq->cond);
990 pthread_mutex_unlock(&to->replyq->mutex);
993 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
994 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
995 static unsigned char first = 1;
996 static EVP_MD_CTX mdctx;
997 unsigned char hash[EVP_MAX_MD_SIZE], *input;
999 uint8_t i, offset = 0, out[128];
1001 pthread_mutex_lock(&lock);
1003 EVP_MD_CTX_init(&mdctx);
1009 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1010 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1011 !EVP_DigestUpdate(&mdctx, input, 16) ||
1012 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1014 pthread_mutex_unlock(&lock);
1017 for (i = 0; i < 16; i++)
1018 out[offset + i] = hash[i] ^ in[offset + i];
1019 input = out + offset - 16;
1024 memcpy(in, out, len);
1025 pthread_mutex_unlock(&lock);
1029 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1030 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1031 static unsigned char first = 1;
1032 static EVP_MD_CTX mdctx;
1033 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1034 unsigned int md_len;
1035 uint8_t i, offset = 0, out[128];
1037 pthread_mutex_lock(&lock);
1039 EVP_MD_CTX_init(&mdctx);
1045 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1046 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1047 !EVP_DigestUpdate(&mdctx, input, 16) ||
1048 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1050 pthread_mutex_unlock(&lock);
1053 for (i = 0; i < 16; i++)
1054 out[offset + i] = hash[i] ^ in[offset + i];
1055 input = in + offset;
1060 memcpy(in, out, len);
1061 pthread_mutex_unlock(&lock);
1065 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1066 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1067 static unsigned char first = 1;
1068 static EVP_MD_CTX mdctx;
1069 unsigned char hash[EVP_MAX_MD_SIZE];
1070 unsigned int md_len;
1073 pthread_mutex_lock(&lock);
1075 EVP_MD_CTX_init(&mdctx);
1080 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1081 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1082 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1085 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1086 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1087 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1088 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1089 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1090 pthread_mutex_unlock(&lock);
1095 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1098 for (i = 0; i < 16; i++)
1101 for (offset = 16; offset < len; offset += 16) {
1103 printf("text + offset - 16 c(%d): ", offset / 16);
1104 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1106 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1107 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1108 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1109 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1111 pthread_mutex_unlock(&lock);
1115 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1118 for (i = 0; i < 16; i++)
1119 text[offset + i] ^= hash[i];
1123 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1126 pthread_mutex_unlock(&lock);
1130 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1131 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1132 static unsigned char first = 1;
1133 static EVP_MD_CTX mdctx;
1134 unsigned char hash[EVP_MAX_MD_SIZE];
1135 unsigned int md_len;
1139 pthread_mutex_lock(&lock);
1141 EVP_MD_CTX_init(&mdctx);
1146 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1147 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1148 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1151 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1152 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1153 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1154 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1155 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1156 pthread_mutex_unlock(&lock);
1161 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1164 for (i = 0; i < 16; i++)
1165 plain[i] = text[i] ^ hash[i];
1167 for (offset = 16; offset < len; offset += 16) {
1169 printf("text + offset - 16 c(%d): ", offset / 16);
1170 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1172 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1173 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1174 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1175 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1177 pthread_mutex_unlock(&lock);
1181 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1184 for (i = 0; i < 16; i++)
1185 plain[offset + i] = text[offset + i] ^ hash[i];
1188 memcpy(text, plain, len);
1190 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1193 pthread_mutex_unlock(&lock);
1197 struct realm *newrealmref(struct realm *r) {
1203 /* returns with lock on realm */
1204 struct realm *id2realm(struct list *realmlist, char *id) {
1205 struct list_node *entry;
1206 struct realm *realm, *subrealm;
1208 /* need to do locking for subrealms and check subrealm timers */
1209 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1210 realm = (struct realm *)entry->data;
1211 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1212 pthread_mutex_lock(&realm->mutex);
1213 if (realm->subrealms) {
1214 subrealm = id2realm(realm->subrealms, id);
1216 pthread_mutex_unlock(&realm->mutex);
1220 return newrealmref(realm);
1226 /* helper function, only used by removeserversubrealms() */
1227 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1228 struct list_node *entry, *entry2;
1229 struct realm *realm;
1231 for (entry = list_first(realmlist); entry;) {
1232 realm = newrealmref((struct realm *)entry->data);
1233 pthread_mutex_lock(&realm->mutex);
1234 entry = list_next(entry);
1236 if (realm->srvconfs) {
1237 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1238 if (entry2->data == srv)
1240 list_removedata(realm->srvconfs, srv);
1241 if (!list_first(realm->srvconfs)) {
1242 list_destroy(realm->srvconfs);
1243 realm->srvconfs = NULL;
1246 if (realm->accsrvconfs) {
1247 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1248 if (entry2->data == srv)
1250 list_removedata(realm->accsrvconfs, srv);
1251 if (!list_first(realm->accsrvconfs)) {
1252 list_destroy(realm->accsrvconfs);
1253 realm->accsrvconfs = NULL;
1257 /* remove subrealm if no servers */
1258 if (!realm->srvconfs && !realm->accsrvconfs)
1259 list_removedata(realmlist, realm);
1261 pthread_mutex_unlock(&realm->mutex);
1266 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1267 struct list_node *entry;
1268 struct realm *realm;
1270 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1271 realm = (struct realm *)entry->data;
1272 pthread_mutex_lock(&realm->mutex);
1273 if (realm->subrealms) {
1274 _internal_removeserversubrealms(realm->subrealms, srv);
1275 if (!list_first(realm->subrealms)) {
1276 list_destroy(realm->subrealms);
1277 realm->subrealms = NULL;
1280 pthread_mutex_unlock(&realm->mutex);
1284 int attrvalidate(unsigned char *attrs, int length) {
1285 while (length > 1) {
1286 if (ATTRLEN(attrs) < 2) {
1287 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1290 length -= ATTRLEN(attrs);
1292 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1295 attrs += ATTRLEN(attrs);
1298 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1302 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1303 if (len < 16 || len > 128 || len % 16) {
1304 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1308 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1309 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1313 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1315 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1316 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1322 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1325 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1326 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1329 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1330 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1336 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1337 char *oldsecret, char *newsecret) {
1338 unsigned char *attr;
1340 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1341 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1342 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1348 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1352 for (; attrs[0]; attrs += 2)
1353 if (attrs[0] == vendor && attrs[1] == subattr)
1358 /* returns 1 if entire element is to be removed, else 0 */
1359 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1360 uint8_t alen, sublen;
1364 if (!removevendorattrs)
1367 memcpy(&vendor, attr->v, 4);
1368 vendor = ntohl(vendor);
1369 while (*removevendorattrs && *removevendorattrs != vendor)
1370 removevendorattrs += 2;
1371 if (!*removevendorattrs)
1374 if (findvendorsubattr(removevendorattrs, vendor, -1))
1375 return 1; /* remove entire vendor attribute */
1377 sublen = attr->l - 4;
1378 subattrs = attr->v + 4;
1380 if (!attrvalidate(subattrs, sublen)) {
1381 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1385 while (sublen > 1) {
1386 alen = ATTRLEN(subattrs);
1388 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1389 memmove(subattrs, subattrs + alen, sublen);
1397 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1398 struct list_node *n, *p;
1402 n = list_first(msg->attrs);
1404 attr = (struct tlv *)n->data;
1405 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1406 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1407 list_removedata(msg->attrs, attr);
1409 n = p ? list_next(p) : list_first(msg->attrs);
1416 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1417 struct list_node *n;
1420 for (n = list_first(addattrs); n; n = list_next(n)) {
1421 a = copytlv((struct tlv *)n->data);
1424 if (!radmsg_add(msg, a)) {
1432 int resizeattr(struct tlv *attr, uint8_t newlen) {
1435 if (newlen != attr->l) {
1436 newv = realloc(attr->v, newlen);
1445 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1446 size_t nmatch = 10, reslen = 0, start = 0;
1447 regmatch_t pmatch[10], *pfield;
1451 in = stringcopy((char *)attr->v, attr->l);
1455 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1460 out = modattr->replacement;
1462 for (i = start; out[i]; i++) {
1463 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1464 pfield = &pmatch[out[i + 1] - '0'];
1465 if (pfield->rm_so >= 0) {
1466 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1472 reslen += i - start;
1474 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1479 if (!resizeattr(attr, reslen)) {
1486 for (i = start; out[i]; i++) {
1487 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1488 pfield = &pmatch[out[i + 1] - '0'];
1489 if (pfield->rm_so >= 0) {
1490 memcpy(attr->v + reslen, out + start, i - start);
1491 reslen += i - start;
1492 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1493 reslen += pfield->rm_eo - pfield->rm_so;
1500 memcpy(attr->v + reslen, out + start, i - start);
1504 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1505 struct list_node *n, *m;
1507 for (n = list_first(msg->attrs); n; n = list_next(n))
1508 for (m = list_first(modattrs); m; m = list_next(m))
1509 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1510 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1515 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1518 if (rewrite->removeattrs || rewrite->removevendorattrs)
1519 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1520 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1522 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1527 int rewriteusername(struct request *rq, struct tlv *attr) {
1528 char *orig = (char *)tlv2str(attr);
1529 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1533 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1534 rq->origusername = (char *)orig;
1540 int addvendorattr(struct radmsg *msg, uint32_t vendor, struct tlv *attr) {
1547 vendor = htonl(vendor);
1548 memcpy(v, &vendor, 4);
1549 tlv2buf(v + 4, attr);
1551 vattr = maketlv(RAD_Attr_Vendor_Specific, l, v);
1552 if (vattr && radmsg_add(msg, vattr))
1559 void addttlattr(struct radmsg *msg, uint32_t *attrtype, uint8_t addttl) {
1566 if (attrtype[1] == -1) { /* not vendor */
1567 attr = maketlv(attrtype[0], 4, ttl);
1568 if (attr && !radmsg_add(msg, attr))
1571 attr = maketlv(attrtype[1], 4, ttl);
1573 addvendorattr(msg, attrtype[0], attr);
1579 int decttl(uint8_t l, uint8_t *v) {
1586 while (i >= 0 && !v[i])
1590 for (i--; i >= 0 && !v[i]; i--);
1599 /* returns -1 if no ttl, 0 if exceeded, 1 if ok */
1600 int checkttl(struct radmsg *msg, uint32_t *attrtype) {
1601 uint8_t alen, *subattrs;
1603 struct list_node *node;
1607 if (attrtype[1] == -1) { /* not vendor */
1608 attr = radmsg_gettype(msg, attrtype[0]);
1610 return decttl(attr->l, attr->v);
1612 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1613 attr = (struct tlv *)node->data;
1614 if (attr->t != RAD_Attr_Vendor_Specific || attr->l <= 4)
1616 memcpy(&vendor, attr->v, 4);
1617 if (ntohl(vendor) != attrtype[0])
1619 sublen = attr->l - 4;
1620 subattrs = attr->v + 4;
1621 if (!attrvalidate(subattrs, sublen))
1623 while (sublen > 1) {
1624 if (ATTRTYPE(subattrs) == attrtype[1])
1625 return decttl(ATTRVALLEN(subattrs), ATTRVAL(subattrs));
1626 alen = ATTRLEN(subattrs);
1634 const char *radmsgtype2string(uint8_t code) {
1635 static const char *rad_msg_names[] = {
1636 "", "Access-Request", "Access-Accept", "Access-Reject",
1637 "Accounting-Request", "Accounting-Response", "", "",
1638 "", "", "", "Access-Challenge",
1639 "Status-Server", "Status-Client"
1641 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1644 void char2hex(char *h, unsigned char c) {
1645 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1646 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1647 h[0] = hexdigits[c / 16];
1648 h[1] = hexdigits[c % 16];
1652 uint8_t *radattr2ascii(struct tlv *attr) {
1660 for (i = 0; i < attr->l; i++)
1661 if (attr->v[i] < 32 || attr->v[i] > 126)
1664 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1671 for (i = 0; i < attr->l; i++)
1672 if (attr->v[i] < 32 || attr->v[i] > 126) {
1674 char2hex((char *)d, attr->v[i]);
1682 void acclog(struct radmsg *msg, char *host) {
1686 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1688 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1691 username = radattr2ascii(attr);
1693 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1698 void respond(struct request *rq, uint8_t code, char *message) {
1702 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1704 debug(DBG_ERR, "respond: malloc failed");
1707 if (message && *message) {
1708 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1709 if (!attr || !radmsg_add(msg, attr)) {
1712 debug(DBG_ERR, "respond: malloc failed");
1717 radmsg_free(rq->msg);
1719 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1720 sendreply(newrqref(rq));
1723 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1724 struct list_node *entry;
1725 struct clsrvconf *server, *best = NULL, *first = NULL;
1727 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1728 server = (struct clsrvconf *)entry->data;
1729 if (!server->servers)
1733 if (!server->servers->connectionok)
1735 if (!server->servers->lostrqs)
1741 if (server->servers->lostrqs < best->servers->lostrqs)
1744 return best ? best : first;
1747 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1748 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1749 struct clsrvconf *srvconf;
1750 struct realm *subrealm;
1751 struct server *server = NULL;
1752 char *id = (char *)tlv2str(username);
1756 /* returns with lock on realm */
1757 *realm = id2realm(realms, id);
1760 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1761 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1764 server = srvconf->servers;
1765 if (!acc && !(*realm)->parent && !srvconf->servers) {
1766 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1768 pthread_mutex_lock(&subrealm->mutex);
1769 pthread_mutex_unlock(&(*realm)->mutex);
1772 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1781 struct request *newrequest() {
1784 rq = malloc(sizeof(struct request));
1786 debug(DBG_ERR, "newrequest: malloc failed");
1789 memset(rq, 0, sizeof(struct request));
1791 gettimeofday(&rq->created, NULL);
1795 int addclientrq(struct request *rq) {
1799 r = rq->from->rqs[rq->rqid];
1801 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1802 gettimeofday(&now, NULL);
1803 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1805 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1806 sendreply(newrqref(r));
1808 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1814 rq->from->rqs[rq->rqid] = newrqref(rq);
1818 void rmclientrq(struct request *rq, uint8_t id) {
1821 r = rq->from->rqs[id];
1824 rq->from->rqs[id] = NULL;
1828 /* returns 0 if validation/authentication fails, else 1 */
1829 int radsrv(struct request *rq) {
1830 struct radmsg *msg = NULL;
1832 uint8_t *userascii = NULL;
1833 struct realm *realm = NULL;
1834 struct server *to = NULL;
1835 struct client *from = rq->from;
1838 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1843 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1850 memcpy(rq->rqauth, msg->auth, 16);
1852 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1853 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1854 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1858 if (!addclientrq(rq))
1861 if (msg->code == RAD_Status_Server) {
1862 respond(rq, RAD_Access_Accept, NULL);
1866 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1868 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1871 ttlres = checkttl(msg, options.ttlattrtype);
1873 debug(DBG_WARN, "radsrv: ignoring request from client %s (%s), ttl exceeded", from->conf->name, addr2string(from->addr));
1877 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1879 if (msg->code == RAD_Accounting_Request) {
1880 acclog(msg, from->conf->host);
1881 respond(rq, RAD_Accounting_Response, NULL);
1883 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1887 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1888 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1892 userascii = radattr2ascii(attr);
1895 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1897 /* will return with lock on the realm */
1898 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1900 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1905 if (realm->message && msg->code == RAD_Access_Request) {
1906 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1907 respond(rq, RAD_Access_Reject, realm->message);
1908 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1909 acclog(msg, from->conf->host);
1910 respond(rq, RAD_Accounting_Response, NULL);
1915 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1916 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s (%s) to server %s, discarding",
1917 from->conf->name, addr2string(from->addr), to->conf->name);
1921 if (msg->code == RAD_Accounting_Request)
1922 memset(msg->auth, 0, 16);
1923 else if (!RAND_bytes(msg->auth, 16)) {
1924 debug(DBG_WARN, "radsrv: failed to generate random auth");
1929 printfchars(NULL, "auth", "%02x ", auth, 16);
1932 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1934 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1935 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1939 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1941 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1942 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1946 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1949 if (ttlres == -1 && (options.addttl || to->conf->addttl))
1950 addttlattr(msg, options.ttlattrtype, to->conf->addttl ? to->conf->addttl : options.addttl);
1955 pthread_mutex_unlock(&realm->mutex);
1960 rmclientrq(rq, msg->id);
1965 pthread_mutex_unlock(&realm->mutex);
1971 void replyh(struct server *server, unsigned char *buf) {
1972 struct client *from;
1973 struct rqout *rqout;
1975 unsigned char *subattrs;
1976 uint8_t *username, *stationid, *replymsg;
1977 struct radmsg *msg = NULL;
1979 struct list_node *node;
1981 server->connectionok = 1;
1982 server->lostrqs = 0;
1984 rqout = server->requests + buf[1];
1985 pthread_mutex_lock(rqout->lock);
1986 if (!rqout->tries) {
1989 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1993 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1997 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
2000 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
2001 && msg->code != RAD_Accounting_Response) {
2002 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
2005 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
2007 gettimeofday(&server->lastrcv, NULL);
2009 if (rqout->rq->msg->code == RAD_Status_Server) {
2010 freerqoutdata(rqout);
2011 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2015 gettimeofday(&server->lastreply, NULL);
2016 from = rqout->rq->from;
2018 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
2019 debug(DBG_WARN, "replyh: rewritein failed");
2023 ttlres = checkttl(msg, options.ttlattrtype);
2025 debug(DBG_WARN, "replyh: ignoring reply from server %s, ttl exceeded", server->conf->host);
2030 for (node = list_first(msg->attrs); node; node = list_next(node)) {
2031 attr = (struct tlv *)node->data;
2032 if (attr->t != RAD_Attr_Vendor_Specific)
2036 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
2039 sublen = attr->l - 4;
2040 subattrs = attr->v + 4;
2041 if (!attrvalidate(subattrs, sublen) ||
2042 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2043 rqout->rq, server->conf->secret, from->conf->secret) ||
2044 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2045 rqout->rq, server->conf->secret, from->conf->secret))
2049 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2053 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2054 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2056 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2057 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2060 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2061 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2064 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2065 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2069 debug(DBG_INFO, "%s for user %s from %s (%s)",
2070 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2073 debug(DBG_INFO, "%s for user %s from %s",
2074 radmsgtype2string(msg->code), username, server->conf->host);
2080 msg->id = (char)rqout->rq->rqid;
2081 memcpy(msg->auth, rqout->rq->rqauth, 16);
2084 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2087 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2088 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2089 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2092 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2095 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2096 debug(DBG_WARN, "replyh: rewriteout failed");
2100 if (ttlres == -1 && (options.addttl || from->conf->addttl))
2101 addttlattr(msg, options.ttlattrtype, from->conf->addttl ? from->conf->addttl : options.addttl);
2103 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2104 radmsg_free(rqout->rq->msg);
2105 rqout->rq->msg = msg;
2106 sendreply(newrqref(rqout->rq));
2107 freerqoutdata(rqout);
2108 pthread_mutex_unlock(rqout->lock);
2113 pthread_mutex_unlock(rqout->lock);
2117 struct request *createstatsrvrq() {
2124 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2127 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2130 if (!radmsg_add(rq->msg, attr)) {
2141 /* code for removing state not finished */
2142 void *clientwr(void *arg) {
2143 struct server *server = (struct server *)arg;
2144 struct rqout *rqout = NULL;
2145 pthread_t clientrdth;
2146 int i, dynconffail = 0;
2149 struct timeval now, laststatsrv;
2150 struct timespec timeout;
2151 struct request *statsrvrq;
2152 struct clsrvconf *conf;
2154 conf = server->conf;
2156 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2161 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2162 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2166 memset(&timeout, 0, sizeof(struct timespec));
2168 if (conf->statusserver) {
2169 gettimeofday(&server->lastrcv, NULL);
2170 gettimeofday(&laststatsrv, NULL);
2173 if (conf->pdef->connecter) {
2174 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2176 server->connectionok = 1;
2177 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2178 debug(DBG_ERR, "clientwr: pthread_create failed");
2182 server->connectionok = 1;
2185 pthread_mutex_lock(&server->newrq_mutex);
2186 if (!server->newrq) {
2187 gettimeofday(&now, NULL);
2188 /* random 0-7 seconds */
2189 RAND_bytes(&rnd, 1);
2191 if (conf->statusserver) {
2192 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2193 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2195 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2196 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2198 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2199 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2202 if (timeout.tv_sec > now.tv_sec)
2203 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2205 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2208 if (server->newrq) {
2209 debug(DBG_DBG, "clientwr: got new request");
2214 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2216 pthread_mutex_unlock(&server->newrq_mutex);
2218 for (i = 0; i < MAX_REQUESTS; i++) {
2219 if (server->clientrdgone) {
2220 pthread_join(clientrdth, NULL);
2224 for (; i < MAX_REQUESTS; i++) {
2225 rqout = server->requests + i;
2227 pthread_mutex_lock(rqout->lock);
2230 pthread_mutex_unlock(rqout->lock);
2234 if (i == MAX_REQUESTS)
2237 gettimeofday(&now, NULL);
2238 if (now.tv_sec < rqout->expiry.tv_sec) {
2239 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2240 timeout.tv_sec = rqout->expiry.tv_sec;
2241 pthread_mutex_unlock(rqout->lock);
2245 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2246 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2247 if (conf->statusserver) {
2248 if (*rqout->rq->buf == RAD_Status_Server) {
2249 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2250 if (server->lostrqs < 255)
2254 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2255 if (server->lostrqs < 255)
2258 freerqoutdata(rqout);
2259 pthread_mutex_unlock(rqout->lock);
2263 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2264 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2265 timeout.tv_sec = rqout->expiry.tv_sec;
2267 conf->pdef->clientradput(server, rqout->rq->buf);
2268 pthread_mutex_unlock(rqout->lock);
2270 if (conf->statusserver && server->connectionok) {
2271 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2272 gettimeofday(&now, NULL);
2273 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2275 statsrvrq = createstatsrvrq();
2277 statsrvrq->to = server;
2278 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2285 conf->servers = NULL;
2286 if (server->dynamiclookuparg) {
2287 removeserversubrealms(realms, conf);
2291 freeclsrvconf(conf);
2293 freeserver(server, 1);
2294 ERR_remove_state(0);
2298 void createlistener(uint8_t type, char *arg) {
2300 struct clsrvconf *listenres;
2301 struct addrinfo *res;
2302 int s = -1, on = 1, *sp = NULL;
2304 listenres = resolve_hostport(type, arg, protodefs[type]->portdefault);
2306 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2308 for (res = listenres->addrinfo; res; res = res->ai_next) {
2309 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2311 debug(DBG_WARN, "createlistener: socket failed");
2314 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2316 if (res->ai_family == AF_INET6)
2317 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2319 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2320 debug(DBG_WARN, "createlistener: bind failed");
2326 sp = malloc(sizeof(int));
2328 debugx(1, DBG_ERR, "malloc failed");
2330 if (pthread_create(&th, NULL, protodefs[type]->listener, (void *)sp))
2331 debugx(1, DBG_ERR, "pthread_create failed");
2335 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2337 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type]->name,
2338 listenres->host ? listenres->host : "*", listenres->port);
2339 freeclsrvres(listenres);
2342 void createlisteners(uint8_t type) {
2346 args = protodefs[type]->getlistenerargs();
2348 for (i = 0; args[i]; i++)
2349 createlistener(type, args[i]);
2351 createlistener(type, NULL);
2355 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2359 w = where & ~SSL_ST_MASK;
2361 if (w & SSL_ST_CONNECT)
2363 else if (w & SSL_ST_ACCEPT)
2368 if (where & SSL_CB_LOOP)
2369 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2370 else if (where & SSL_CB_ALERT) {
2371 s = (where & SSL_CB_READ) ? "read" : "write";
2372 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2374 else if (where & SSL_CB_EXIT) {
2376 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2378 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2388 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2389 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2390 for (i = 0; i < CRYPTO_num_locks(); i++) {
2391 ssl_lock_count[i] = 0;
2392 pthread_mutex_init(&ssl_locks[i], NULL);
2394 CRYPTO_set_id_callback(ssl_thread_id);
2395 CRYPTO_set_locking_callback(ssl_locking_callback);
2397 SSL_load_error_strings();
2400 while (!RAND_status()) {
2403 RAND_seed((unsigned char *)&t, sizeof(time_t));
2404 RAND_seed((unsigned char *)&pid, sizeof(pid));
2408 X509_VERIFY_PARAM *createverifyparams(char **poids) {
2409 X509_VERIFY_PARAM *pm;
2410 ASN1_OBJECT *pobject;
2413 pm = X509_VERIFY_PARAM_new();
2417 for (i = 0; poids[i]; i++) {
2418 pobject = OBJ_txt2obj(poids[i], 0);
2420 X509_VERIFY_PARAM_free(pm);
2423 X509_VERIFY_PARAM_add0_policy(pm, pobject);
2426 X509_VERIFY_PARAM_set_flags(pm, X509_V_FLAG_POLICY_CHECK | X509_V_FLAG_EXPLICIT_POLICY);
2430 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2431 STACK_OF(X509_NAME) *calist;
2433 unsigned long error;
2435 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2436 while ((error = ERR_get_error()))
2437 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2438 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2442 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2443 if (!conf->cacertfile || calist) {
2444 if (conf->cacertpath) {
2446 calist = sk_X509_NAME_new_null();
2447 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2448 sk_X509_NAME_free(calist);
2454 while ((error = ERR_get_error()))
2455 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2456 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2459 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2460 SSL_CTX_set_client_CA_list(ctx, calist);
2462 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2463 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2465 if (conf->crlcheck || conf->vpm) {
2466 x509_s = SSL_CTX_get_cert_store(ctx);
2468 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2470 X509_STORE_set1_param(x509_s, conf->vpm);
2473 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2477 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2478 SSL_CTX *ctx = NULL;
2479 unsigned long error;
2486 ctx = SSL_CTX_new(TLSv1_method());
2488 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2492 ctx = SSL_CTX_new(DTLSv1_method());
2494 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2496 SSL_CTX_set_read_ahead(ctx, 1);
2500 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2504 if (conf->certkeypwd) {
2505 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2506 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2508 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2509 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2510 !SSL_CTX_check_private_key(ctx)) {
2511 while ((error = ERR_get_error()))
2512 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2513 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2518 if (conf->policyoids) {
2520 conf->vpm = createverifyparams(conf->policyoids);
2522 debug(DBG_ERR, "tlsaddcacrl: Failed to add policyOIDs in TLS context %s", conf->name);
2529 if (!tlsaddcacrl(ctx, conf)) {
2531 X509_VERIFY_PARAM_free(conf->vpm);
2538 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2542 struct tls *tlsgettls(char *alt1, char *alt2) {
2545 t = hash_read(tlsconfs, alt1, strlen(alt1));
2547 t = hash_read(tlsconfs, alt2, strlen(alt2));
2551 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2556 gettimeofday(&now, NULL);
2560 if (t->tlsexpiry && t->tlsctx) {
2561 if (t->tlsexpiry < now.tv_sec) {
2562 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2563 tlsaddcacrl(t->tlsctx, t);
2567 t->tlsctx = tlscreatectx(RAD_TLS, t);
2569 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2573 if (t->dtlsexpiry && t->dtlsctx) {
2574 if (t->dtlsexpiry < now.tv_sec) {
2575 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2576 tlsaddcacrl(t->dtlsctx, t);
2580 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2582 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2589 struct list *addsrvconfs(char *value, char **names) {
2590 struct list *conflist;
2592 struct list_node *entry;
2593 struct clsrvconf *conf = NULL;
2595 if (!names || !*names)
2598 conflist = list_create();
2600 debug(DBG_ERR, "malloc failed");
2604 for (n = 0; names[n]; n++) {
2605 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2606 conf = (struct clsrvconf *)entry->data;
2607 if (!strcasecmp(names[n], conf->name))
2611 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2612 list_destroy(conflist);
2615 if (!list_push(conflist, conf)) {
2616 debug(DBG_ERR, "malloc failed");
2617 list_destroy(conflist);
2620 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2625 void freerealm(struct realm *realm) {
2628 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2629 if (--realm->refcount)
2633 free(realm->message);
2634 regfree(&realm->regex);
2635 pthread_mutex_destroy(&realm->mutex);
2636 /* if refcount == 0, all subrealms gone */
2637 list_destroy(realm->subrealms);
2638 /* if refcount == 0, all srvconfs gone */
2639 list_destroy(realm->srvconfs);
2640 /* if refcount == 0, all accsrvconfs gone */
2641 list_destroy(realm->accsrvconfs);
2642 freerealm(realm->parent);
2646 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2648 struct realm *realm;
2649 char *s, *regex = NULL;
2651 if (*value == '/') {
2652 /* regexp, remove optional trailing / if present */
2653 if (value[strlen(value) - 1] == '/')
2654 value[strlen(value) - 1] = '\0';
2656 /* not a regexp, let us make it one */
2657 if (*value == '*' && !value[1])
2658 regex = stringcopy(".*", 0);
2660 for (n = 0, s = value; *s;)
2663 regex = malloc(strlen(value) + n + 3);
2666 for (n = 1, s = value; *s; s++) {
2676 debug(DBG_ERR, "malloc failed");
2680 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2683 realm = malloc(sizeof(struct realm));
2685 debug(DBG_ERR, "malloc failed");
2688 memset(realm, 0, sizeof(struct realm));
2690 if (pthread_mutex_init(&realm->mutex, NULL)) {
2691 debug(DBG_ERR, "mutex init failed");
2697 realm->name = stringcopy(value, 0);
2699 debug(DBG_ERR, "malloc failed");
2702 if (message && strlen(message) > 253) {
2703 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2706 realm->message = message;
2707 realm->accresp = accresp;
2709 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2710 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2714 if (servers && *servers) {
2715 realm->srvconfs = addsrvconfs(value, servers);
2716 if (!realm->srvconfs)
2720 if (accservers && *accservers) {
2721 realm->accsrvconfs = addsrvconfs(value, accservers);
2722 if (!realm->accsrvconfs)
2726 if (!list_push(realmlist, realm)) {
2727 debug(DBG_ERR, "malloc failed");
2728 pthread_mutex_destroy(&realm->mutex);
2732 debug(DBG_DBG, "addrealm: added realm %s", value);
2736 while (list_shift(realm->srvconfs));
2737 while (list_shift(realm->accsrvconfs));
2744 for (n = 0; servers[n]; n++)
2746 freegconfmstr(servers);
2750 for (n = 0; accservers[n]; n++)
2752 freegconfmstr(accservers);
2754 return newrealmref(realm);
2757 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2758 struct clsrvconf *srvconf;
2759 struct realm *newrealm = NULL;
2760 char *realmname, *s;
2763 if (!conf->dynamiclookupcommand)
2766 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2767 realmname = strrchr(id, '@');
2773 for (s = realmname; *s; s++)
2774 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2777 srvconf = malloc(sizeof(struct clsrvconf));
2779 debug(DBG_ERR, "malloc failed");
2783 if (!addserver(srvconf))
2786 if (!realm->subrealms)
2787 realm->subrealms = list_create();
2788 if (!realm->subrealms)
2790 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2793 newrealm->parent = newrealmref(realm);
2795 /* add server and accserver to newrealm */
2796 newrealm->srvconfs = list_create();
2797 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2798 debug(DBG_ERR, "malloc failed");
2801 newrealmref(newrealm);
2802 newrealm->accsrvconfs = list_create();
2803 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2804 debug(DBG_ERR, "malloc failed");
2805 list_shift(realm->srvconfs);
2806 freerealm(newrealm);
2809 newrealmref(newrealm);
2811 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2812 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2813 debug(DBG_ERR, "pthread_create failed");
2814 list_shift(realm->srvconfs);
2815 freerealm(newrealm);
2816 list_shift(realm->accsrvconfs);
2817 freerealm(newrealm);
2820 pthread_detach(clientth);
2825 list_removedata(realm->subrealms, newrealm);
2826 freerealm(newrealm);
2827 if (!list_first(realm->subrealms)) {
2828 list_destroy(realm->subrealms);
2829 realm->subrealms = NULL;
2832 freeserver(srvconf->servers, 1);
2834 debug(DBG_ERR, "failed to create dynamic server");
2838 int dynamicconfig(struct server *server) {
2839 int ok, fd[2], status;
2841 struct clsrvconf *conf = server->conf;
2842 struct gconffile *cf = NULL;
2844 /* for now we only learn hostname/address */
2845 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2848 debug(DBG_ERR, "dynamicconfig: pipe error");
2853 debug(DBG_ERR, "dynamicconfig: fork error");
2857 } else if (pid == 0) {
2860 if (fd[1] != STDOUT_FILENO) {
2861 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2862 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2865 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2866 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2870 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2871 ok = getgenericconfig(&cf, NULL,
2872 "Server", CONF_CBK, confserver_cb, (void *)conf,
2877 if (waitpid(pid, &status, 0) < 0) {
2878 debug(DBG_ERR, "dynamicconfig: wait error");
2883 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2891 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2895 int addmatchcertattr(struct clsrvconf *conf) {
2899 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2900 r = &conf->certcnregex;
2901 v = conf->matchcertattr + 4;
2902 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2903 r = &conf->certuriregex;
2904 v = conf->matchcertattr + 20;
2909 /* regexp, remove optional trailing / if present */
2910 if (v[strlen(v) - 1] == '/')
2911 v[strlen(v) - 1] = '\0';
2915 *r = malloc(sizeof(regex_t));
2917 debug(DBG_ERR, "malloc failed");
2920 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2923 debug(DBG_ERR, "failed to compile regular expression %s", v);
2929 /* should accept both names and numeric values, only numeric right now */
2930 uint8_t attrname2val(char *attrname) {
2933 val = atoi(attrname);
2934 return val > 0 && val < 256 ? val : 0;
2937 /* should accept both names and numeric values, only numeric right now */
2938 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2941 *vendor = atoi(attrname);
2942 s = strchr(attrname, ':');
2947 *type = atoi(s + 1);
2948 return *type >= 0 && *type < 256;
2951 /* should accept both names and numeric values, only numeric right now */
2952 struct tlv *extractattr(char *nameval) {
2957 s = strchr(nameval, ':');
2958 name = atoi(nameval);
2959 if (!s || name < 1 || name > 255)
2961 len = strlen(s + 1);
2964 a = malloc(sizeof(struct tlv));
2967 a->v = (uint8_t *)stringcopy(s + 1, 0);
2977 /* should accept both names and numeric values, only numeric right now */
2978 struct modattr *extractmodattr(char *nameval) {
2983 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2987 s = strchr(nameval, ':');
2988 name = atoi(nameval);
2989 if (!s || name < 1 || name > 255 || s[1] != '/')
2993 /* regexp, remove optional trailing / if present */
2994 if (s[strlen(s) - 1] == '/')
2995 s[strlen(s) - 1] = '\0';
3003 m = malloc(sizeof(struct modattr));
3005 debug(DBG_ERR, "malloc failed");
3010 m->replacement = stringcopy(t, 0);
3011 if (!m->replacement) {
3013 debug(DBG_ERR, "malloc failed");
3017 m->regex = malloc(sizeof(regex_t));
3019 free(m->replacement);
3021 debug(DBG_ERR, "malloc failed");
3025 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
3027 free(m->replacement);
3029 debug(DBG_ERR, "failed to compile regular expression %s", s);
3036 struct rewrite *getrewrite(char *alt1, char *alt2) {
3039 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
3041 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
3046 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
3047 struct rewrite *rewrite = NULL;
3049 uint8_t *rma = NULL;
3050 uint32_t *p, *rmva = NULL;
3051 struct list *adda = NULL, *moda = NULL;
3056 for (n = 0; rmattrs[n]; n++);
3057 rma = calloc(n + 1, sizeof(uint8_t));
3059 debugx(1, DBG_ERR, "malloc failed");
3061 for (i = 0; i < n; i++)
3062 if (!(rma[i] = attrname2val(rmattrs[i])))
3063 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
3064 freegconfmstr(rmattrs);
3069 for (n = 0; rmvattrs[n]; n++);
3070 rmva = calloc(2 * n + 1, sizeof(uint32_t));
3072 debugx(1, DBG_ERR, "malloc failed");
3074 for (p = rmva, i = 0; i < n; i++, p += 2)
3075 if (!vattrname2val(rmvattrs[i], p, p + 1))
3076 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
3077 freegconfmstr(rmvattrs);
3082 adda = list_create();
3084 debugx(1, DBG_ERR, "malloc failed");
3085 for (i = 0; addattrs[i]; i++) {
3086 a = extractattr(addattrs[i]);
3088 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3089 if (!list_push(adda, a))
3090 debugx(1, DBG_ERR, "malloc failed");
3092 freegconfmstr(addattrs);
3096 moda = list_create();
3098 debugx(1, DBG_ERR, "malloc failed");
3099 for (i = 0; modattrs[i]; i++) {
3100 m = extractmodattr(modattrs[i]);
3102 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3103 if (!list_push(moda, m))
3104 debugx(1, DBG_ERR, "malloc failed");
3106 freegconfmstr(modattrs);
3109 if (rma || rmva || adda || moda) {
3110 rewrite = malloc(sizeof(struct rewrite));
3112 debugx(1, DBG_ERR, "malloc failed");
3113 rewrite->removeattrs = rma;
3114 rewrite->removevendorattrs = rmva;
3115 rewrite->addattrs = adda;
3116 rewrite->modattrs = moda;
3119 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3120 debugx(1, DBG_ERR, "malloc failed");
3121 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3124 int setttlattr(struct options *opts, char *defaultattr) {
3125 char *ttlattr = opts->ttlattr ? opts->ttlattr : defaultattr;
3127 if (vattrname2val(ttlattr, opts->ttlattrtype, opts->ttlattrtype + 1) &&
3128 (opts->ttlattrtype[1] != -1 || opts->ttlattrtype[0] < 256))
3130 debug(DBG_ERR, "setttlattr: invalid TTLAttribute value %s", ttlattr);
3134 void freeclsrvconf(struct clsrvconf *conf) {
3140 free(conf->matchcertattr);
3141 if (conf->certcnregex)
3142 regfree(conf->certcnregex);
3143 if (conf->certuriregex)
3144 regfree(conf->certuriregex);
3145 free(conf->confrewritein);
3146 free(conf->confrewriteout);
3147 if (conf->rewriteusername) {
3148 if (conf->rewriteusername->regex)
3149 regfree(conf->rewriteusername->regex);
3150 free(conf->rewriteusername->replacement);
3151 free(conf->rewriteusername);
3153 free(conf->dynamiclookupcommand);
3154 free(conf->rewritein);
3155 free(conf->rewriteout);
3157 freeaddrinfo(conf->addrinfo);
3159 pthread_mutex_destroy(conf->lock);
3162 /* not touching ssl_ctx, clients and servers */
3166 int mergeconfstring(char **dst, char **src) {
3175 t = stringcopy(*dst, 0);
3177 debug(DBG_ERR, "malloc failed");
3185 /* assumes dst is a shallow copy */
3186 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3187 if (!mergeconfstring(&dst->name, &src->name) ||
3188 !mergeconfstring(&dst->host, &src->host) ||
3189 !mergeconfstring(&dst->port, &src->port) ||
3190 !mergeconfstring(&dst->secret, &src->secret) ||
3191 !mergeconfstring(&dst->tls, &src->tls) ||
3192 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3193 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3194 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3195 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3198 dst->pdef = src->pdef;
3199 dst->statusserver = src->statusserver;
3200 dst->certnamecheck = src->certnamecheck;
3201 if (src->retryinterval != 255)
3202 dst->retryinterval = src->retryinterval;
3203 if (src->retrycount != 255)
3204 dst->retrycount = src->retrycount;
3208 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3209 struct clsrvconf *conf;
3210 char *conftype = NULL, *rewriteinalias = NULL;
3211 long int dupinterval = LONG_MIN, addttl = LONG_MIN;
3213 debug(DBG_DBG, "confclient_cb called for %s", block);
3215 conf = malloc(sizeof(struct clsrvconf));
3217 debugx(1, DBG_ERR, "malloc failed");
3218 memset(conf, 0, sizeof(struct clsrvconf));
3219 conf->certnamecheck = 1;
3221 if (!getgenericconfig(cf, block,
3222 "type", CONF_STR, &conftype,
3223 "host", CONF_STR, &conf->host,
3224 "secret", CONF_STR, &conf->secret,
3225 "tls", CONF_STR, &conf->tls,
3226 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3227 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3228 "DuplicateInterval", CONF_LINT, &dupinterval,
3229 "addTTL", CONF_LINT, &addttl,
3230 "rewrite", CONF_STR, &rewriteinalias,
3231 "rewriteIn", CONF_STR, &conf->confrewritein,
3232 "rewriteOut", CONF_STR, &conf->confrewriteout,
3233 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3236 debugx(1, DBG_ERR, "configuration error");
3238 conf->name = stringcopy(val, 0);
3240 conf->host = stringcopy(val, 0);
3241 if (!conf->name || !conf->host)
3242 debugx(1, DBG_ERR, "malloc failed");
3245 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3246 conf->type = protoname2int(conftype);
3247 if (conf->type == 255)
3248 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3250 conf->pdef = protodefs[conf->type];
3252 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3253 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3255 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3256 if (conf->matchcertattr && !addmatchcertattr(conf))
3257 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3260 if (dupinterval != LONG_MIN) {
3261 if (dupinterval < 0 || dupinterval > 255)
3262 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3263 conf->dupinterval = (uint8_t)dupinterval;
3265 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3267 if (addttl != LONG_MIN) {
3268 if (addttl < 1 || addttl > 255)
3269 debugx(1, DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3270 conf->addttl = (uint8_t)addttl;
3273 if (!conf->confrewritein)
3274 conf->confrewritein = rewriteinalias;
3276 free(rewriteinalias);
3277 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3278 if (conf->confrewriteout)
3279 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3281 if (conf->confrewriteusername) {
3282 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3283 if (!conf->rewriteusername)
3284 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3287 if (!resolvepeer(conf, 0))
3288 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3290 if (!conf->secret) {
3291 if (!conf->pdef->secretdefault)
3292 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3293 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3295 debugx(1, DBG_ERR, "malloc failed");
3298 conf->lock = malloc(sizeof(pthread_mutex_t));
3300 debugx(1, DBG_ERR, "malloc failed");
3302 pthread_mutex_init(conf->lock, NULL);
3303 if (!list_push(clconfs, conf))
3304 debugx(1, DBG_ERR, "malloc failed");
3308 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3309 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3310 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3311 if (!conf->tlsconf) {
3312 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3315 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3316 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3322 conf->port = stringcopy(conf->pdef->portdefault, 0);
3324 debug(DBG_ERR, "malloc failed");
3329 if (conf->retryinterval == 255)
3330 conf->retryinterval = conf->pdef->retryintervaldefault;
3331 if (conf->retrycount == 255)
3332 conf->retrycount = conf->pdef->retrycountdefault;
3334 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3335 if (conf->confrewriteout)
3336 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3338 if (!conf->secret) {
3339 if (!conf->pdef->secretdefault) {
3340 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3343 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3344 if (!conf->secret) {
3345 debug(DBG_ERR, "malloc failed");
3350 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3351 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3357 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3358 struct clsrvconf *conf, *resconf;
3359 char *conftype = NULL, *rewriteinalias = NULL;
3360 long int retryinterval = LONG_MIN, retrycount = LONG_MIN, addttl = LONG_MIN;
3362 debug(DBG_DBG, "confserver_cb called for %s", block);
3364 conf = malloc(sizeof(struct clsrvconf));
3366 debug(DBG_ERR, "malloc failed");
3369 memset(conf, 0, sizeof(struct clsrvconf));
3370 resconf = (struct clsrvconf *)arg;
3372 conf->statusserver = resconf->statusserver;
3373 conf->certnamecheck = resconf->certnamecheck;
3375 conf->certnamecheck = 1;
3377 if (!getgenericconfig(cf, block,
3378 "type", CONF_STR, &conftype,
3379 "host", CONF_STR, &conf->host,
3380 "port", CONF_STR, &conf->port,
3381 "secret", CONF_STR, &conf->secret,
3382 "tls", CONF_STR, &conf->tls,
3383 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3384 "addTTL", CONF_LINT, &addttl,
3385 "rewrite", CONF_STR, &rewriteinalias,
3386 "rewriteIn", CONF_STR, &conf->confrewritein,
3387 "rewriteOut", CONF_STR, &conf->confrewriteout,
3388 "StatusServer", CONF_BLN, &conf->statusserver,
3389 "RetryInterval", CONF_LINT, &retryinterval,
3390 "RetryCount", CONF_LINT, &retrycount,
3391 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3392 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3395 debug(DBG_ERR, "configuration error");
3399 conf->name = stringcopy(val, 0);
3401 debug(DBG_ERR, "malloc failed");
3405 conf->host = stringcopy(val, 0);
3407 debug(DBG_ERR, "malloc failed");
3413 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3414 conf->type = protoname2int(conftype);
3415 if (conf->type == 255) {
3416 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3422 conf->pdef = protodefs[conf->type];
3424 if (!conf->confrewritein)
3425 conf->confrewritein = rewriteinalias;
3427 free(rewriteinalias);
3428 rewriteinalias = NULL;
3430 if (retryinterval != LONG_MIN) {
3431 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3432 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3435 conf->retryinterval = (uint8_t)retryinterval;
3437 conf->retryinterval = 255;
3439 if (retrycount != LONG_MIN) {
3440 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3441 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3444 conf->retrycount = (uint8_t)retrycount;
3446 conf->retrycount = 255;
3448 if (addttl != LONG_MIN) {
3449 if (addttl < 1 || addttl > 255) {
3450 debug(DBG_ERR, "error in block %s, value of option addTTL is %d, must be 1-255", block, addttl);
3453 conf->addttl = (uint8_t)addttl;
3457 if (!mergesrvconf(resconf, conf))
3461 if (conf->dynamiclookupcommand) {
3462 free(conf->dynamiclookupcommand);
3463 conf->dynamiclookupcommand = NULL;
3467 if (resconf || !conf->dynamiclookupcommand) {
3468 if (!compileserverconfig(conf, block))
3475 if (!list_push(srvconfs, conf)) {
3476 debug(DBG_ERR, "malloc failed");
3483 free(rewriteinalias);
3484 freeclsrvconf(conf);
3488 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3489 char **servers = NULL, **accservers = NULL, *msg = NULL;
3490 uint8_t accresp = 0;
3492 debug(DBG_DBG, "confrealm_cb called for %s", block);
3494 if (!getgenericconfig(cf, block,
3495 "server", CONF_MSTR, &servers,
3496 "accountingServer", CONF_MSTR, &accservers,
3497 "ReplyMessage", CONF_STR, &msg,
3498 "AccountingResponse", CONF_BLN, &accresp,
3501 debugx(1, DBG_ERR, "configuration error");
3503 addrealm(realms, val, servers, accservers, msg, accresp);
3507 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3509 long int expiry = LONG_MIN;
3511 debug(DBG_DBG, "conftls_cb called for %s", block);
3513 conf = malloc(sizeof(struct tls));
3515 debug(DBG_ERR, "conftls_cb: malloc failed");
3518 memset(conf, 0, sizeof(struct tls));
3520 if (!getgenericconfig(cf, block,
3521 "CACertificateFile", CONF_STR, &conf->cacertfile,
3522 "CACertificatePath", CONF_STR, &conf->cacertpath,
3523 "CertificateFile", CONF_STR, &conf->certfile,
3524 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3525 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3526 "CacheExpiry", CONF_LINT, &expiry,
3527 "CRLCheck", CONF_BLN, &conf->crlcheck,
3528 "PolicyOID", CONF_MSTR, &conf->policyoids,
3531 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3534 if (!conf->certfile || !conf->certkeyfile) {
3535 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3538 if (!conf->cacertfile && !conf->cacertpath) {
3539 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3542 if (expiry != LONG_MIN) {
3544 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3547 conf->cacheexpiry = expiry;
3550 conf->name = stringcopy(val, 0);
3552 debug(DBG_ERR, "conftls_cb: malloc failed");
3556 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3557 debug(DBG_ERR, "conftls_cb: malloc failed");
3560 if (!tlsgetctx(RAD_TLS, conf))
3561 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3562 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3566 free(conf->cacertfile);
3567 free(conf->cacertpath);
3568 free(conf->certfile);
3569 free(conf->certkeyfile);
3570 free(conf->certkeypwd);
3571 freegconfmstr(conf->policyoids);
3576 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3577 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3579 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3581 if (!getgenericconfig(cf, block,
3582 "removeAttribute", CONF_MSTR, &rmattrs,
3583 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3584 "addAttribute", CONF_MSTR, &addattrs,
3585 "modifyAttribute", CONF_MSTR, &modattrs,
3588 debugx(1, DBG_ERR, "configuration error");
3589 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3593 int setprotoopts(uint8_t type, char **listenargs, char *sourcearg) {
3594 struct commonprotoopts *protoopts;
3596 protoopts = malloc(sizeof(struct commonprotoopts));
3599 memset(protoopts, 0, sizeof(struct commonprotoopts));
3600 protoopts->listenargs = listenargs;
3601 protoopts->sourcearg = sourcearg;
3602 protodefs[type]->setprotoopts(protoopts);
3606 void getmainconfig(const char *configfile) {
3607 long int addttl = LONG_MIN, loglevel = LONG_MIN;
3608 struct gconffile *cfs;
3609 char **listenargs[RAD_PROTOCOUNT];
3610 char *sourcearg[RAD_PROTOCOUNT];
3613 cfs = openconfigfile(configfile);
3614 memset(&options, 0, sizeof(options));
3615 memset(&listenargs, 0, sizeof(listenargs));
3616 memset(&sourcearg, 0, sizeof(sourcearg));
3618 clconfs = list_create();
3620 debugx(1, DBG_ERR, "malloc failed");
3622 srvconfs = list_create();
3624 debugx(1, DBG_ERR, "malloc failed");
3626 realms = list_create();
3628 debugx(1, DBG_ERR, "malloc failed");
3630 tlsconfs = hash_create();
3632 debugx(1, DBG_ERR, "malloc failed");
3634 rewriteconfs = hash_create();
3636 debugx(1, DBG_ERR, "malloc failed");
3638 if (!getgenericconfig(&cfs, NULL,
3639 "ListenUDP", CONF_MSTR, &listenargs[RAD_UDP],
3640 "ListenTCP", CONF_MSTR, &listenargs[RAD_TCP],
3641 "ListenTLS", CONF_MSTR, &listenargs[RAD_TLS],
3642 "ListenDTLS", CONF_MSTR, &listenargs[RAD_DTLS],
3643 "SourceUDP", CONF_STR, &sourcearg[RAD_UDP],
3644 "SourceTCP", CONF_STR, &sourcearg[RAD_TCP],
3645 "SourceTLS", CONF_STR, &sourcearg[RAD_TLS],
3646 "SourceDTLS", CONF_STR, &sourcearg[RAD_DTLS],
3647 "TTLAttribute", CONF_STR, &options.ttlattr,
3648 "addTTL", CONF_LINT, &addttl,
3649 "LogLevel", CONF_LINT, &loglevel,
3650 "LogDestination", CONF_STR, &options.logdestination,
3651 "LoopPrevention", CONF_BLN, &options.loopprevention,
3652 "Client", CONF_CBK, confclient_cb, NULL,
3653 "Server", CONF_CBK, confserver_cb, NULL,
3654 "Realm", CONF_CBK, confrealm_cb, NULL,
3655 "TLS", CONF_CBK, conftls_cb, NULL,
3656 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3659 debugx(1, DBG_ERR, "configuration error");
3661 if (loglevel != LONG_MIN) {
3662 if (loglevel < 1 || loglevel > 4)
3663 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3664 options.loglevel = (uint8_t)loglevel;
3666 if (addttl != LONG_MIN) {
3667 if (addttl < 1 || addttl > 255)
3668 debugx(1, DBG_ERR, "error in %s, value of option addTTL is %d, must be 1-255", configfile, addttl);
3669 options.addttl = (uint8_t)addttl;
3671 if (!setttlattr(&options, DEFAULT_TTL_ATTR))
3672 debugx(1, DBG_ERR, "Failed to set TTLAttribute, exiting");
3674 for (i = 0; i < RAD_PROTOCOUNT; i++)
3675 if (listenargs[i] || sourcearg[i])
3676 setprotoopts(i, listenargs[i], sourcearg[i]);
3679 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3682 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3685 *configfile = optarg;
3688 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3689 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3690 *loglevel = *optarg - '0';
3699 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3704 if (!(argc - optind))
3708 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3712 int daemon(int a, int b) {
3720 for (i = 0; i < 3; i++) {
3722 open("/dev/null", O_RDWR);
3728 void *sighandler(void *arg) {
3733 sigemptyset(&sigset);
3734 sigaddset(&sigset, SIGPIPE);
3735 sigwait(&sigset, &sig);
3736 /* only get SIGPIPE right now, so could simplify below code */
3739 /* completely ignoring this */
3742 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3745 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3750 int main(int argc, char **argv) {
3753 struct list_node *entry;
3754 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3755 char *configfile = NULL;
3756 struct clsrvconf *srvconf;
3759 debug_init("radsecproxy");
3760 debug_set_level(DEBUG_LEVEL);
3762 for (i = 0; i < RAD_PROTOCOUNT; i++)
3763 protodefs[i] = protoinits[i](i);
3765 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3767 debug_set_level(loglevel);
3768 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3770 options.loglevel = loglevel;
3771 else if (options.loglevel)
3772 debug_set_level(options.loglevel);
3774 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3775 free(options.logdestination);
3777 if (!list_first(clconfs))
3778 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3779 if (!list_first(realms))
3780 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3783 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3785 if (!foreground && (daemon(0, 0) < 0))
3786 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3788 debug_timestamp_on();
3789 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3791 sigemptyset(&sigset);
3792 /* exit on all but SIGPIPE, ignore more? */
3793 sigaddset(&sigset, SIGPIPE);
3794 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3795 pthread_create(&sigth, NULL, sighandler, NULL);
3797 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3798 srvconf = (struct clsrvconf *)entry->data;
3799 if (srvconf->dynamiclookupcommand)
3801 if (!addserver(srvconf))
3802 debugx(1, DBG_ERR, "failed to add server");
3803 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3804 (void *)(srvconf->servers)))
3805 debugx(1, DBG_ERR, "pthread_create failed");
3808 for (i = 0; i < RAD_PROTOCOUNT; i++) {
3809 if (protodefs[i]->initextra)
3810 protodefs[i]->initextra();
3811 if (find_clconf_type(i, NULL))
3815 /* just hang around doing nothing, anything to do here? */