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 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
69 #include "radsecproxy.h"
75 static struct options options;
76 static struct list *clconfs, *srvconfs;
78 struct hash *tlsconfs, *rewriteconfs;
80 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
82 static pthread_mutex_t *ssl_locks = NULL;
83 static long *ssl_lock_count;
87 /* minimum required declarations to avoid reordering code */
88 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
89 int dynamicconfig(struct server *server);
90 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
91 void freerealm(struct realm *realm);
92 void freeclsrvconf(struct clsrvconf *conf);
93 void freerqdata(struct request *rq);
95 static const struct protodefs protodefs[] = {
96 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
97 NULL, /* secretdefault */
98 SOCK_DGRAM, /* socktype */
99 "1812", /* portdefault */
100 REQUEST_RETRY_COUNT, /* retrycountdefault */
101 10, /* retrycountmax */
102 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
103 60, /* retryintervalmax */
104 udpserverrd, /* listener */
105 &options.sourceudp, /* srcaddrport */
106 NULL, /* connecter */
107 NULL, /* clientconnreader */
108 clientradputudp, /* clientradput */
109 addclientudp, /* addclient */
110 addserverextraudp, /* addserverextra */
111 initextraudp /* initextra */
113 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
114 "mysecret", /* secretdefault */
115 SOCK_STREAM, /* socktype */
116 "2083", /* portdefault */
117 0, /* retrycountdefault */
118 0, /* retrycountmax */
119 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
120 60, /* retryintervalmax */
121 tlslistener, /* listener */
122 &options.sourcetls, /* srcaddrport */
123 tlsconnect, /* connecter */
124 tlsclientrd, /* clientconnreader */
125 clientradputtls, /* clientradput */
126 NULL, /* addclient */
127 NULL, /* addserverextra */
130 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
131 NULL, /* secretdefault */
132 SOCK_STREAM, /* socktype */
133 "1812", /* portdefault */
134 0, /* retrycountdefault */
135 0, /* retrycountmax */
136 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
137 60, /* retryintervalmax */
138 tcplistener, /* listener */
139 &options.sourcetcp, /* srcaddrport */
140 tcpconnect, /* connecter */
141 tcpclientrd, /* clientconnreader */
142 clientradputtcp, /* clientradput */
143 NULL, /* addclient */
144 NULL, /* addserverextra */
147 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
148 "mysecret", /* secretdefault */
149 SOCK_DGRAM, /* socktype */
150 "2083", /* portdefault */
151 REQUEST_RETRY_COUNT, /* retrycountdefault */
152 10, /* retrycountmax */
153 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
154 60, /* retryintervalmax */
155 udpdtlsserverrd, /* listener */
156 &options.sourcedtls, /* srcaddrport */
157 dtlsconnect, /* connecter */
158 dtlsclientrd, /* clientconnreader */
159 clientradputdtls, /* clientradput */
160 NULL, /* addclient */
161 addserverextradtls, /* addserverextra */
162 initextradtls /* initextra */
168 uint8_t protoname2int(const char *name) {
171 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
175 /* callbacks for making OpenSSL thread safe */
176 unsigned long ssl_thread_id() {
177 return (unsigned long)pthread_self();
180 void ssl_locking_callback(int mode, int type, const char *file, int line) {
181 if (mode & CRYPTO_LOCK) {
182 pthread_mutex_lock(&ssl_locks[type]);
183 ssl_lock_count[type]++;
185 pthread_mutex_unlock(&ssl_locks[type]);
188 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
189 int pwdlen = strlen(userdata);
190 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
192 memcpy(buf, userdata, pwdlen);
196 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
201 err_cert = X509_STORE_CTX_get_current_cert(ctx);
202 err = X509_STORE_CTX_get_error(ctx);
203 depth = X509_STORE_CTX_get_error_depth(ctx);
205 if (depth > MAX_CERT_DEPTH) {
207 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
208 X509_STORE_CTX_set_error(ctx, err);
212 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
213 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
216 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
217 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
218 debug(DBG_WARN, "\tIssuer=%s", buf);
220 case X509_V_ERR_CERT_NOT_YET_VALID:
221 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
222 debug(DBG_WARN, "\tCertificate not yet valid");
224 case X509_V_ERR_CERT_HAS_EXPIRED:
225 debug(DBG_WARN, "Certificate has expired");
227 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
228 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
233 printf("certificate verify returns %d\n", ok);
238 struct addrinfo *getsrcprotores(uint8_t type) {
239 return srcprotores[type];
242 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
243 struct addrinfo hints, *addrinfo, *res;
247 slash = conf->host ? strchr(conf->host, '/') : NULL;
251 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
255 if (*s < '0' || *s > '9') {
256 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
259 plen = atoi(slash + 1);
260 if (plen < 0 || plen > 128) {
261 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
266 memset(&hints, 0, sizeof(hints));
267 hints.ai_socktype = conf->pdef->socktype;
268 hints.ai_family = AF_UNSPEC;
269 hints.ai_flags = ai_flags;
270 if (!conf->host && !conf->port) {
271 /* getaddrinfo() doesn't like host and port to be NULL */
272 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
273 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
276 for (res = addrinfo; res; res = res->ai_next) {
277 switch (res->ai_family) {
279 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
282 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
288 hints.ai_flags |= AI_NUMERICHOST;
289 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
290 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
295 switch (addrinfo->ai_family) {
298 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
299 freeaddrinfo(addrinfo);
306 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
307 freeaddrinfo(addrinfo);
310 conf->prefixlen = plen;
312 conf->prefixlen = 255;
315 freeaddrinfo(conf->addrinfo);
316 conf->addrinfo = addrinfo;
320 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
325 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
329 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
331 debugx(1, DBG_ERR, "no ] matching initial [");
335 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
338 debugx(1, DBG_ERR, "missing host/address");
340 conf->host = stringcopy(field, p - field);
343 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
344 debugx(1, DBG_ERR, "unexpected character after ]");
347 /* port number or service name is specified */;
349 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
351 debugx(1, DBG_ERR, "syntax error, : but no following port");
352 conf->port = stringcopy(field, p - field);
354 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
358 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
359 struct clsrvconf *conf;
361 conf = malloc(sizeof(struct clsrvconf));
363 debugx(1, DBG_ERR, "malloc failed");
364 memset(conf, 0, sizeof(struct clsrvconf));
366 conf->pdef = &protodefs[conf->type];
368 parsehostport(lconf, conf, default_port);
369 if (!strcmp(conf->host, "*")) {
374 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
375 if (!resolvepeer(conf, AI_PASSIVE))
376 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
380 void freeclsrvres(struct clsrvconf *res) {
384 freeaddrinfo(res->addrinfo);
388 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
390 struct addrinfo *res;
392 for (res = addrinfo; res; res = res->ai_next) {
393 if (family != AF_UNSPEC && family != res->ai_family)
395 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
397 debug(DBG_WARN, "bindtoaddr: socket failed");
401 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
404 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
406 if (!bind(s, res->ai_addr, res->ai_addrlen))
408 debug(DBG_WARN, "bindtoaddr: bind failed");
414 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
416 struct addrinfo *res;
419 for (res = addrinfo; res; res = res->ai_next) {
420 s = bindtoaddr(src, res->ai_family, 1, 1);
422 debug(DBG_WARN, "connecttoserver: socket failed");
425 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
427 debug(DBG_WARN, "connecttoserver: connect failed");
434 /* returns 1 if the len first bits are equal, else 0 */
435 int prefixmatch(void *a1, void *a2, uint8_t len) {
436 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
438 if (l && memcmp(a1, a2, l))
443 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
446 /* returns next config with matching address, or NULL */
447 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
448 struct sockaddr_in6 *sa6 = NULL;
449 struct in_addr *a4 = NULL;
450 struct addrinfo *res;
451 struct list_node *entry;
452 struct clsrvconf *conf;
454 if (addr->sa_family == AF_INET6) {
455 sa6 = (struct sockaddr_in6 *)addr;
456 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
457 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
461 a4 = &((struct sockaddr_in *)addr)->sin_addr;
463 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
464 conf = (struct clsrvconf *)entry->data;
465 if (conf->type == type) {
466 if (conf->prefixlen == 255) {
467 for (res = conf->addrinfo; res; res = res->ai_next)
468 if ((a4 && res->ai_family == AF_INET &&
469 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
470 (sa6 && res->ai_family == AF_INET6 &&
471 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
477 res = conf->addrinfo;
479 ((a4 && res->ai_family == AF_INET &&
480 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
481 (sa6 && res->ai_family == AF_INET6 &&
482 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
493 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
494 return find_conf(type, addr, clconfs, cur);
497 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
498 return find_conf(type, addr, srvconfs, cur);
501 /* returns next config of given type, or NULL */
502 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
503 struct list_node *entry;
504 struct clsrvconf *conf;
506 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
507 conf = (struct clsrvconf *)entry->data;
508 if (conf->type == type) {
517 struct queue *newqueue() {
520 q = malloc(sizeof(struct queue));
522 debugx(1, DBG_ERR, "malloc failed");
523 q->entries = list_create();
525 debugx(1, DBG_ERR, "malloc failed");
526 pthread_mutex_init(&q->mutex, NULL);
527 pthread_cond_init(&q->cond, NULL);
531 void removequeue(struct queue *q) {
532 struct list_node *entry;
536 pthread_mutex_lock(&q->mutex);
537 for (entry = list_first(q->entries); entry; entry = list_next(entry))
538 free(((struct reply *)entry)->buf);
539 list_destroy(q->entries);
540 pthread_cond_destroy(&q->cond);
541 pthread_mutex_unlock(&q->mutex);
542 pthread_mutex_destroy(&q->mutex);
546 void freebios(struct queue *q) {
549 pthread_mutex_lock(&q->mutex);
550 while ((bio = (BIO *)list_shift(q->entries)))
552 pthread_mutex_unlock(&q->mutex);
556 struct client *addclient(struct clsrvconf *conf) {
557 struct client *new = malloc(sizeof(struct client));
560 debug(DBG_ERR, "malloc failed");
563 if (!conf->clients) {
564 conf->clients = list_create();
565 if (!conf->clients) {
566 debug(DBG_ERR, "malloc failed");
571 memset(new, 0, sizeof(struct client));
573 if (conf->pdef->addclient)
574 conf->pdef->addclient(new);
576 new->replyq = newqueue();
577 list_push(conf->clients, new);
581 void removeclient(struct client *client) {
582 if (!client || !client->conf->clients)
584 removequeue(client->replyq);
585 list_removedata(client->conf->clients, client);
589 void removeclientrqs(struct client *client) {
590 struct list_node *entry;
591 struct server *server;
595 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
596 server = ((struct clsrvconf *)entry->data)->servers;
599 pthread_mutex_lock(&server->newrq_mutex);
600 for (i = 0; i < MAX_REQUESTS; i++) {
601 rq = server->requests + i;
602 if (rq->from == client)
605 pthread_mutex_unlock(&server->newrq_mutex);
609 void freeserver(struct server *server, uint8_t destroymutex) {
610 struct request *rq, *end;
615 if (server->requests) {
616 rq = server->requests;
617 for (end = rq + MAX_REQUESTS; rq < end; rq++)
619 free(server->requests);
622 freebios(server->rbios);
623 free(server->dynamiclookuparg);
625 SSL_free(server->ssl);
627 pthread_mutex_destroy(&server->lock);
628 pthread_cond_destroy(&server->newrq_cond);
629 pthread_mutex_destroy(&server->newrq_mutex);
634 int addserver(struct clsrvconf *conf) {
635 struct clsrvconf *res;
639 debug(DBG_ERR, "addserver: currently works with just one server per conf");
642 conf->servers = malloc(sizeof(struct server));
643 if (!conf->servers) {
644 debug(DBG_ERR, "malloc failed");
647 memset(conf->servers, 0, sizeof(struct server));
648 conf->servers->conf = conf;
651 if (type == RAD_DTLS)
652 conf->servers->rbios = newqueue();
654 if (!srcprotores[type]) {
655 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
656 srcprotores[type] = res->addrinfo;
657 res->addrinfo = NULL;
661 conf->servers->sock = -1;
662 if (conf->pdef->addserverextra)
663 conf->pdef->addserverextra(conf);
665 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
666 if (!conf->servers->requests) {
667 debug(DBG_ERR, "malloc failed");
670 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
671 debug(DBG_ERR, "mutex init failed");
674 conf->servers->newrq = 0;
675 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
676 debug(DBG_ERR, "mutex init failed");
677 pthread_mutex_destroy(&conf->servers->lock);
680 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
681 debug(DBG_ERR, "mutex init failed");
682 pthread_mutex_destroy(&conf->servers->newrq_mutex);
683 pthread_mutex_destroy(&conf->servers->lock);
690 freeserver(conf->servers, 0);
691 conf->servers = NULL;
695 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
696 int loc, i, l, n, r = 0;
699 STACK_OF(GENERAL_NAME) *alt;
702 debug(DBG_DBG, "subjectaltnameaddr");
704 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
708 ex = X509_get_ext(cert, loc);
709 alt = X509V3_EXT_d2i(ex);
713 n = sk_GENERAL_NAME_num(alt);
714 for (i = 0; i < n; i++) {
715 gn = sk_GENERAL_NAME_value(alt, i);
716 if (gn->type != GEN_IPADD)
719 v = (char *)ASN1_STRING_data(gn->d.ia5);
720 l = ASN1_STRING_length(gn->d.ia5);
721 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
722 && !memcmp(v, &addr, l)) {
727 GENERAL_NAMES_free(alt);
731 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
738 nm = X509_get_subject_name(cert);
741 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
744 e = X509_NAME_get_entry(nm, loc);
745 t = X509_NAME_ENTRY_get_data(e);
746 v = (char *) ASN1_STRING_data(t);
747 l = ASN1_STRING_length(t);
751 if (l == strlen(exact) && !strncasecmp(exact, v, l))
754 s = stringcopy((char *)v, l);
756 debug(DBG_ERR, "malloc failed");
759 if (regexec(regex, s, 0, NULL, 0)) {
770 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
771 int loc, i, l, n, r = 0;
774 STACK_OF(GENERAL_NAME) *alt;
777 debug(DBG_DBG, "subjectaltnameregexp");
779 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
783 ex = X509_get_ext(cert, loc);
784 alt = X509V3_EXT_d2i(ex);
788 n = sk_GENERAL_NAME_num(alt);
789 for (i = 0; i < n; i++) {
790 gn = sk_GENERAL_NAME_value(alt, i);
791 if (gn->type != type)
794 v = (char *)ASN1_STRING_data(gn->d.ia5);
795 l = ASN1_STRING_length(gn->d.ia5);
799 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
802 if (memcmp(v, exact, l))
805 s = stringcopy((char *)v, l);
807 debug(DBG_ERR, "malloc failed");
810 if (regexec(regex, s, 0, NULL, 0)) {
819 GENERAL_NAMES_free(alt);
823 X509 *verifytlscert(SSL *ssl) {
827 if (SSL_get_verify_result(ssl) != X509_V_OK) {
828 debug(DBG_ERR, "verifytlscert: basic validation failed");
829 while ((error = ERR_get_error()))
830 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
834 cert = SSL_get_peer_certificate(ssl);
836 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
840 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
842 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
843 struct in6_addr addr;
845 if (conf->certnamecheck && conf->prefixlen == 255) {
846 if (inet_pton(AF_INET, conf->host, &addr))
848 else if (inet_pton(AF_INET6, conf->host, &addr))
851 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
854 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
857 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
859 if (!cnregexp(cert, conf->host, NULL)) {
860 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
863 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
866 if (conf->certcnregex) {
867 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
868 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
871 debug(DBG_DBG, "verifyconfcert: CN matching regex");
873 if (conf->certuriregex) {
874 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
875 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
878 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
883 int radsign(unsigned char *rad, unsigned char *sec) {
884 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
885 static unsigned char first = 1;
886 static EVP_MD_CTX mdctx;
890 pthread_mutex_lock(&lock);
892 EVP_MD_CTX_init(&mdctx);
896 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
897 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
898 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
899 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
901 pthread_mutex_unlock(&lock);
905 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
906 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
907 static unsigned char first = 1;
908 static HMAC_CTX hmacctx;
914 pthread_mutex_lock(&lock);
916 HMAC_CTX_init(&hmacctx);
920 memset(authattrval, 0, 16);
922 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
923 HMAC_Update(&hmacctx, rad, RADLEN(rad));
924 HMAC_Final(&hmacctx, authattrval, &md_len);
926 debug(DBG_WARN, "message auth computation failed");
927 pthread_mutex_unlock(&lock);
931 pthread_mutex_unlock(&lock);
935 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
937 if (ATTRTYPE(attrs) == type)
939 length -= ATTRLEN(attrs);
940 attrs += ATTRLEN(attrs);
945 void freerqdata(struct request *rq) {
946 if (rq->origusername)
947 free(rq->origusername);
952 void sendrq(struct server *to, struct request *rq) {
956 pthread_mutex_lock(&to->newrq_mutex);
957 /* might simplify if only try nextid, might be ok */
958 for (i = to->nextid; i < MAX_REQUESTS; i++)
959 if (!to->requests[i].buf)
961 if (i == MAX_REQUESTS) {
962 for (i = 0; i < to->nextid; i++)
963 if (!to->requests[i].buf)
965 if (i == to->nextid) {
966 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
972 rq->buf[1] = (char)i;
974 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
975 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
980 if (*rq->buf == RAD_Accounting_Request) {
981 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
982 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
988 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
989 to->requests[i] = *rq;
994 debug(DBG_DBG, "sendrq: signalling client writer");
995 pthread_cond_signal(&to->newrq_cond);
998 pthread_mutex_unlock(&to->newrq_mutex);
1001 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1002 struct reply *reply;
1005 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1007 debug(DBG_WARN, "sendreply: failed to sign message");
1011 reply = malloc(sizeof(struct reply));
1014 debug(DBG_ERR, "sendreply: malloc failed");
1017 memset(reply, 0, sizeof(struct reply));
1020 reply->tosa = *tosa;
1021 reply->toudpsock = toudpsock;
1023 pthread_mutex_lock(&to->replyq->mutex);
1025 first = list_first(to->replyq->entries) == NULL;
1027 if (!list_push(to->replyq->entries, reply)) {
1028 pthread_mutex_unlock(&to->replyq->mutex);
1031 debug(DBG_ERR, "sendreply: malloc failed");
1036 debug(DBG_DBG, "signalling server writer");
1037 pthread_cond_signal(&to->replyq->cond);
1039 pthread_mutex_unlock(&to->replyq->mutex);
1042 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1043 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1044 static unsigned char first = 1;
1045 static EVP_MD_CTX mdctx;
1046 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1047 unsigned int md_len;
1048 uint8_t i, offset = 0, out[128];
1050 pthread_mutex_lock(&lock);
1052 EVP_MD_CTX_init(&mdctx);
1058 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1059 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1060 !EVP_DigestUpdate(&mdctx, input, 16) ||
1061 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1063 pthread_mutex_unlock(&lock);
1066 for (i = 0; i < 16; i++)
1067 out[offset + i] = hash[i] ^ in[offset + i];
1068 input = out + offset - 16;
1073 memcpy(in, out, len);
1074 pthread_mutex_unlock(&lock);
1078 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1079 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1080 static unsigned char first = 1;
1081 static EVP_MD_CTX mdctx;
1082 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1083 unsigned int md_len;
1084 uint8_t i, offset = 0, out[128];
1086 pthread_mutex_lock(&lock);
1088 EVP_MD_CTX_init(&mdctx);
1094 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1095 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1096 !EVP_DigestUpdate(&mdctx, input, 16) ||
1097 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1099 pthread_mutex_unlock(&lock);
1102 for (i = 0; i < 16; i++)
1103 out[offset + i] = hash[i] ^ in[offset + i];
1104 input = in + offset;
1109 memcpy(in, out, len);
1110 pthread_mutex_unlock(&lock);
1114 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1115 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1116 static unsigned char first = 1;
1117 static EVP_MD_CTX mdctx;
1118 unsigned char hash[EVP_MAX_MD_SIZE];
1119 unsigned int md_len;
1122 pthread_mutex_lock(&lock);
1124 EVP_MD_CTX_init(&mdctx);
1129 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1130 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1131 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1134 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1135 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1136 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1137 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1138 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1139 pthread_mutex_unlock(&lock);
1144 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1147 for (i = 0; i < 16; i++)
1150 for (offset = 16; offset < len; offset += 16) {
1152 printf("text + offset - 16 c(%d): ", offset / 16);
1153 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1155 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1156 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1157 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1158 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1160 pthread_mutex_unlock(&lock);
1164 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1167 for (i = 0; i < 16; i++)
1168 text[offset + i] ^= hash[i];
1172 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1175 pthread_mutex_unlock(&lock);
1179 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1180 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1181 static unsigned char first = 1;
1182 static EVP_MD_CTX mdctx;
1183 unsigned char hash[EVP_MAX_MD_SIZE];
1184 unsigned int md_len;
1188 pthread_mutex_lock(&lock);
1190 EVP_MD_CTX_init(&mdctx);
1195 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1196 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1197 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1200 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1201 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1202 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1203 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1204 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1205 pthread_mutex_unlock(&lock);
1210 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1213 for (i = 0; i < 16; i++)
1214 plain[i] = text[i] ^ hash[i];
1216 for (offset = 16; offset < len; offset += 16) {
1218 printf("text + offset - 16 c(%d): ", offset / 16);
1219 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1221 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1222 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1223 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1224 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1226 pthread_mutex_unlock(&lock);
1230 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1233 for (i = 0; i < 16; i++)
1234 plain[offset + i] = text[offset + i] ^ hash[i];
1237 memcpy(text, plain, len);
1239 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1242 pthread_mutex_unlock(&lock);
1246 struct realm *id2realm(struct list *realmlist, char *id) {
1247 struct list_node *entry;
1248 struct realm *realm, *subrealm = NULL;
1250 /* need to do locking for subrealms and check subrealm timers */
1251 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1252 realm = (struct realm *)entry->data;
1253 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1254 pthread_mutex_lock(&realm->subrealms_mutex);
1255 if (realm->subrealms)
1256 subrealm = id2realm(realm->subrealms, id);
1257 pthread_mutex_unlock(&realm->subrealms_mutex);
1258 return subrealm ? subrealm : realm;
1264 /* helper function, only used by removeserversubrealms() */
1265 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1266 struct list_node *entry;
1267 struct realm *realm;
1269 for (entry = list_first(realmlist); entry;) {
1270 realm = (struct realm *)entry->data;
1271 entry = list_next(entry);
1272 if (realm->srvconfs) {
1273 list_removedata(realm->srvconfs, srv);
1274 if (!list_first(realm->srvconfs)) {
1275 list_destroy(realm->srvconfs);
1276 realm->srvconfs = NULL;
1279 if (realm->accsrvconfs) {
1280 list_removedata(realm->accsrvconfs, srv);
1281 if (!list_first(realm->accsrvconfs)) {
1282 list_destroy(realm->accsrvconfs);
1283 realm->accsrvconfs = NULL;
1287 /* remove subrealm if no servers */
1288 if (!realm->srvconfs && !realm->accsrvconfs) {
1289 list_removedata(realmlist, realm);
1295 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1296 struct list_node *entry;
1297 struct realm *realm;
1299 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1300 realm = (struct realm *)entry->data;
1301 pthread_mutex_lock(&realm->subrealms_mutex);
1302 if (realm->subrealms) {
1303 _internal_removeserversubrealms(realm->subrealms, srv);
1304 if (!list_first(realm->subrealms)) {
1305 list_destroy(realm->subrealms);
1306 realm->subrealms = NULL;
1309 pthread_mutex_unlock(&realm->subrealms_mutex);
1313 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1314 struct request *rq = to->requests, *end;
1316 pthread_mutex_lock(&to->newrq_mutex);
1317 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1318 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1320 pthread_mutex_unlock(&to->newrq_mutex);
1325 int attrvalidate(unsigned char *attrs, int length) {
1326 while (length > 1) {
1327 if (ATTRLEN(attrs) < 2) {
1328 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1331 length -= ATTRLEN(attrs);
1333 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1336 attrs += ATTRLEN(attrs);
1339 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1343 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1344 if (len < 16 || len > 128 || len % 16) {
1345 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1349 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1350 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1354 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1356 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1357 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1363 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1366 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1367 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1370 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1371 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1377 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1378 char *oldsecret, char *newsecret) {
1379 unsigned char *attr;
1381 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1382 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1383 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1389 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1393 for (; attrs[0]; attrs += 2)
1394 if (attrs[0] == vendor && attrs[1] == subattr)
1399 /* returns 1 if entire element is to be removed, else 0 */
1400 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1401 uint8_t alen, sublen;
1405 if (!removevendorattrs)
1408 memcpy(&vendor, attr->v, 4);
1409 vendor = ntohl(vendor);
1410 while (*removevendorattrs && *removevendorattrs != vendor)
1411 removevendorattrs += 2;
1412 if (!*removevendorattrs)
1415 if (findvendorsubattr(removevendorattrs, vendor, -1))
1416 return 1; /* remove entire vendor attribute */
1418 sublen = attr->l - 4;
1419 subattrs = attr->v + 4;
1421 if (!attrvalidate(subattrs, sublen)) {
1422 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1426 while (sublen > 1) {
1427 alen = ATTRLEN(subattrs);
1429 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1430 memmove(subattrs, subattrs + alen, sublen);
1438 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1439 struct list_node *n, *p;
1443 n = list_first(msg->attrs);
1445 attr = (struct tlv *)n->data;
1446 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1447 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1448 list_removedata(msg->attrs, attr);
1450 n = p ? list_next(p) : list_first(msg->attrs);
1457 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1458 struct list_node *n;
1461 for (n = list_first(addattrs); n; n = list_next(n)) {
1462 a = copytlv((struct tlv *)n->data);
1465 if (!radmsg_add(msg, a)) {
1473 int resizeattr2(struct tlv *attr, uint8_t newlen) {
1476 if (newlen != attr->l) {
1477 newv = realloc(attr->v, newlen);
1486 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1487 size_t nmatch = 10, reslen = 0, start = 0;
1488 regmatch_t pmatch[10], *pfield;
1492 in = stringcopy((char *)attr->v, attr->l);
1496 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1501 out = modattr->replacement;
1503 for (i = start; out[i]; i++) {
1504 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1505 pfield = &pmatch[out[i + 1] - '0'];
1506 if (pfield->rm_so >= 0) {
1507 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1513 reslen += i - start;
1515 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1520 if (!resizeattr2(attr, reslen)) {
1527 for (i = start; out[i]; i++) {
1528 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1529 pfield = &pmatch[out[i + 1] - '0'];
1530 if (pfield->rm_so >= 0) {
1531 memcpy(attr->v + reslen, out + start, i - start);
1532 reslen += i - start;
1533 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1534 reslen += pfield->rm_eo - pfield->rm_so;
1541 memcpy(attr->v + reslen, out + start, i - start);
1545 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1546 struct list_node *n, *m;
1548 for (n = list_first(msg->attrs); n; n = list_next(n))
1549 for (m = list_first(modattrs); m; m = list_next(m))
1550 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1551 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1556 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1559 if (rewrite->removeattrs || rewrite->removevendorattrs)
1560 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1561 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1563 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1568 int rewriteusername(struct request *rq, struct tlv *attr) {
1569 char *orig = (char *)tlv2str(attr);
1570 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1574 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1575 rq->origusername = (char *)orig;
1581 const char *radmsgtype2string(uint8_t code) {
1582 static const char *rad_msg_names[] = {
1583 "", "Access-Request", "Access-Accept", "Access-Reject",
1584 "Accounting-Request", "Accounting-Response", "", "",
1585 "", "", "", "Access-Challenge",
1586 "Status-Server", "Status-Client"
1588 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1591 void char2hex(char *h, unsigned char c) {
1592 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1593 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1594 h[0] = hexdigits[c / 16];
1595 h[1] = hexdigits[c % 16];
1599 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1603 if (!attr || len == 1) {
1608 l = ATTRVALLEN(attr);
1609 s = (char *)ATTRVAL(attr);
1612 for (i = 0; i < l; i++) {
1613 if (s[i] > 31 && s[i] < 127) {
1615 if (d - ascii == len - 1)
1618 if (d - ascii > len - 4)
1623 if (d - ascii == len - 1)
1631 uint8_t *radattr2ascii2(struct tlv *attr) {
1639 for (i = 0; i < attr->l; i++)
1640 if (attr->v[i] < 32 || attr->v[i] > 126)
1643 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1650 for (i = 0; i < attr->l; i++)
1651 if (attr->v[i] < 32 || attr->v[i] > 126) {
1653 char2hex((char *)d, attr->v[i]);
1661 void acclog(struct radmsg *msg, char *host) {
1665 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1667 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1670 username = radattr2ascii2(attr);
1672 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1677 void respondaccounting(struct request *rq) {
1678 unsigned char *resp;
1682 debug(DBG_ERR, "respondaccounting: malloc failed");
1685 memcpy(resp, rq->buf, 20);
1686 resp[0] = RAD_Accounting_Response;
1689 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1690 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1693 void respondstatusserver(struct request *rq) {
1694 unsigned char *resp;
1698 debug(DBG_ERR, "respondstatusserver: malloc failed");
1701 memcpy(resp, rq->buf, 20);
1702 resp[0] = RAD_Access_Accept;
1705 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1706 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1709 void respondreject(struct request *rq, char *message) {
1710 unsigned char *resp;
1713 if (message && *message)
1714 len += 2 + strlen(message);
1718 debug(DBG_ERR, "respondreject: malloc failed");
1721 memcpy(resp, rq->buf, 20);
1722 resp[0] = RAD_Access_Reject;
1723 *(uint16_t *)(resp + 2) = htons(len);
1724 if (message && *message) {
1725 resp[20] = RAD_Attr_Reply_Message;
1726 resp[21] = len - 20;
1727 memcpy(resp + 22, message, len - 22);
1729 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1732 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1733 struct list_node *entry;
1734 struct clsrvconf *server, *best = NULL, *first = NULL;
1736 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1737 server = (struct clsrvconf *)entry->data;
1738 if (!server->servers)
1742 if (!server->servers->connectionok)
1744 if (!server->servers->lostrqs)
1750 if (server->servers->lostrqs < best->servers->lostrqs)
1753 return best ? best : first;
1756 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1757 struct clsrvconf *srvconf;
1758 char *id = (char *)tlv2str(username);
1762 *realm = id2realm(realms, id);
1767 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1768 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1773 if (!acc && !srvconf->servers)
1774 adddynamicrealmserver(*realm, srvconf, id);
1776 return srvconf->servers;
1779 /* returns 0 if validation/authentication fails, else 1 */
1780 int radsrv(struct request *rq) {
1781 struct radmsg *msg = NULL;
1783 uint8_t *userascii = NULL;
1784 unsigned char newauth[16];
1785 struct realm *realm = NULL;
1786 struct server *to = NULL;
1788 msg = buf2radmsg(rq->buf, (uint8_t *)rq->from->conf->secret, NULL);
1790 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1794 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1796 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1797 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1801 if (msg->code == RAD_Status_Server) {
1802 respondstatusserver(rq);
1806 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1808 if (rq->from->conf->rewritein && !dorewrite(msg, rq->from->conf->rewritein))
1811 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1813 if (msg->code == RAD_Accounting_Request) {
1814 acclog(msg, rq->from->conf->host);
1815 respondaccounting(rq);
1817 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1821 if (rq->from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1822 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1826 userascii = radattr2ascii2(attr);
1829 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1831 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1833 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1837 if (realm->message && msg->code == RAD_Access_Request) {
1838 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1839 respondreject(rq, realm->message);
1840 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1841 acclog(msg, rq->from->conf->host);
1842 respondaccounting(rq);
1847 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1848 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1849 rq->from->conf->name, to->conf->name);
1853 if (rqinqueue(to, rq->from, msg->id, msg->code)) {
1854 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1855 radmsgtype2string(msg->code), rq->from->conf->host, msg->id);
1859 if (msg->code != RAD_Accounting_Request) {
1860 if (!RAND_bytes(newauth, 16)) {
1861 debug(DBG_WARN, "radsrv: failed to generate random auth");
1867 printfchars(NULL, "auth", "%02x ", auth, 16);
1870 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1872 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1873 if (!pwdrecrypt(attr->v, attr->l, rq->from->conf->secret, to->conf->secret, msg->auth, newauth))
1877 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1879 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1880 if (!pwdrecrypt(attr->v, attr->l, rq->from->conf->secret, to->conf->secret, msg->auth, newauth))
1884 rq->origid = msg->id;
1885 memcpy(rq->origauth, msg->auth, 16);
1886 memcpy(msg->auth, newauth, 16);
1888 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1892 rq->buf = radmsg2buf(msg);
1908 int replyh(struct server *server, unsigned char *buf) {
1909 struct client *from;
1912 unsigned char *subattrs, *rqattr;
1913 struct sockaddr_storage fromsa;
1914 char tmp[760], stationid[760];
1915 struct radmsg *msg = NULL;
1916 struct tlv *attr, *messageauth;
1917 struct list_node *node;
1919 server->connectionok = 1;
1920 server->lostrqs = 0;
1922 rq = server->requests + buf[1];
1923 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rq->buf + 4);
1925 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1928 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1929 && msg->code != RAD_Accounting_Response) {
1930 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1934 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1936 pthread_mutex_lock(&server->newrq_mutex);
1937 if (!rq->buf || !rq->tries) {
1938 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1943 debug(DBG_INFO, "replyh: already received, ignoring reply");
1947 gettimeofday(&server->lastrcv, NULL);
1949 if (*rq->buf == RAD_Status_Server) {
1951 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1955 gettimeofday(&server->lastreply, NULL);
1959 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1963 if (server->conf->rewritein && !dorewrite(msg, rq->from->conf->rewritein)) {
1964 debug(DBG_WARN, "replyh: rewritein failed");
1969 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1970 attr = (struct tlv *)node->data;
1971 if (attr->t != RAD_Attr_Vendor_Specific)
1975 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1978 sublen = attr->l - 4;
1979 subattrs = attr->v + 4;
1980 if (!attrvalidate(subattrs, sublen) ||
1981 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1982 rq, server->conf->secret, from->conf->secret) ||
1983 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1984 rq, server->conf->secret, from->conf->secret))
1988 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1992 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1993 rqattr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1995 radattr2ascii(tmp, sizeof(tmp), rqattr);
1996 rqattr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
1998 radattr2ascii(stationid, sizeof(stationid), rqattr);
1999 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2000 radmsgtype2string(msg->code), tmp, stationid, server->conf->host);
2002 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(msg->code), tmp, server->conf->host);
2006 msg->id = (char)rq->origid;
2007 memcpy(msg->auth, rq->origauth, 16);
2010 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2013 if (rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2014 if (!resizeattr2(attr, strlen(rq->origusername))) {
2015 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2018 memcpy(attr->v, rq->origusername, strlen(rq->origusername));
2021 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2022 debug(DBG_WARN, "replyh: rewriteout failed");
2027 buf = radmsg2buf(msg);
2031 debug(DBG_ERR, "replyh: malloc failed");
2036 rqattr = attrget(buf + 20, RADLEN(buf) - 20, RAD_Attr_Message_Authenticator);
2038 if (!createmessageauth(buf, ATTRVAL(rqattr), from->conf->secret)) {
2039 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2042 debug(DBG_DBG, "replyh: computed messageauthattr");
2046 fromsa = rq->fromsa; /* only needed for UDP */
2047 /* once we set received = 1, rq may be reused */
2050 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2051 sendreply(from, buf, &fromsa, rq->fromudpsock);
2052 pthread_mutex_unlock(&server->newrq_mutex);
2057 pthread_mutex_unlock(&server->newrq_mutex);
2061 /* code for removing state not finished */
2062 void *clientwr(void *arg) {
2063 struct server *server = (struct server *)arg;
2065 pthread_t clientrdth;
2066 int i, secs, dynconffail = 0;
2068 struct timeval now, laststatsrv;
2069 struct timespec timeout;
2070 struct request statsrvrq;
2071 unsigned char statsrvbuf[38];
2072 struct clsrvconf *conf;
2074 conf = server->conf;
2076 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2081 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2082 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2086 memset(&timeout, 0, sizeof(struct timespec));
2088 if (conf->statusserver) {
2089 memset(&statsrvrq, 0, sizeof(struct request));
2090 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2091 statsrvbuf[0] = RAD_Status_Server;
2093 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2094 statsrvbuf[21] = 18;
2095 gettimeofday(&server->lastrcv, NULL);
2096 gettimeofday(&laststatsrv, NULL);
2099 if (conf->pdef->connecter) {
2100 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2102 server->connectionok = 1;
2103 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2104 debug(DBG_ERR, "clientwr: pthread_create failed");
2108 server->connectionok = 1;
2111 pthread_mutex_lock(&server->newrq_mutex);
2112 if (!server->newrq) {
2113 gettimeofday(&now, NULL);
2114 /* random 0-7 seconds */
2115 RAND_bytes(&rnd, 1);
2117 if (conf->statusserver) {
2118 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2119 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2120 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2122 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2123 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2126 if (timeout.tv_sec > now.tv_sec)
2127 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2129 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2132 if (server->newrq) {
2133 debug(DBG_DBG, "clientwr: got new request");
2138 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2140 pthread_mutex_unlock(&server->newrq_mutex);
2142 for (i = 0; i < MAX_REQUESTS; i++) {
2143 if (server->clientrdgone) {
2144 pthread_join(clientrdth, NULL);
2147 pthread_mutex_lock(&server->newrq_mutex);
2148 while (i < MAX_REQUESTS && !server->requests[i].buf)
2150 if (i == MAX_REQUESTS) {
2151 pthread_mutex_unlock(&server->newrq_mutex);
2154 rq = server->requests + i;
2157 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2159 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2161 /* setting this to NULL means that it can be reused */
2164 pthread_mutex_unlock(&server->newrq_mutex);
2168 gettimeofday(&now, NULL);
2169 if (now.tv_sec < rq->expiry.tv_sec) {
2170 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2171 timeout.tv_sec = rq->expiry.tv_sec;
2172 pthread_mutex_unlock(&server->newrq_mutex);
2176 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2177 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2178 if (conf->statusserver) {
2179 if (*rq->buf == RAD_Status_Server) {
2180 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2181 if (server->lostrqs < 255)
2185 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2186 if (server->lostrqs < 255)
2190 /* setting this to NULL means that it can be reused */
2192 pthread_mutex_unlock(&server->newrq_mutex);
2195 pthread_mutex_unlock(&server->newrq_mutex);
2197 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2198 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2199 timeout.tv_sec = rq->expiry.tv_sec;
2201 conf->pdef->clientradput(server, server->requests[i].buf);
2203 if (conf->statusserver) {
2204 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2205 gettimeofday(&now, NULL);
2206 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2208 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2209 debug(DBG_WARN, "clientwr: failed to generate random auth");
2212 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2213 if (!statsrvrq.buf) {
2214 debug(DBG_ERR, "clientwr: malloc failed");
2217 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2218 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2219 sendrq(server, &statsrvrq);
2224 conf->servers = NULL;
2225 if (server->dynamiclookuparg) {
2226 removeserversubrealms(realms, conf);
2230 freeclsrvconf(conf);
2232 freeserver(server, 1);
2233 ERR_remove_state(0);
2237 void createlistener(uint8_t type, char *arg) {
2239 struct clsrvconf *listenres;
2240 struct addrinfo *res;
2241 int s = -1, on = 1, *sp = NULL;
2243 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2245 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2247 for (res = listenres->addrinfo; res; res = res->ai_next) {
2248 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2250 debug(DBG_WARN, "createlistener: socket failed");
2253 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2255 if (res->ai_family == AF_INET6)
2256 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2258 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2259 debug(DBG_WARN, "createlistener: bind failed");
2265 sp = malloc(sizeof(int));
2267 debugx(1, DBG_ERR, "malloc failed");
2269 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2270 debugx(1, DBG_ERR, "pthread_create failed");
2274 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2276 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2277 listenres->host ? listenres->host : "*", listenres->port);
2278 freeclsrvres(listenres);
2281 void createlisteners(uint8_t type, char **args) {
2285 for (i = 0; args[i]; i++)
2286 createlistener(type, args[i]);
2288 createlistener(type, NULL);
2292 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2296 w = where & ~SSL_ST_MASK;
2298 if (w & SSL_ST_CONNECT)
2300 else if (w & SSL_ST_ACCEPT)
2305 if (where & SSL_CB_LOOP)
2306 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2307 else if (where & SSL_CB_ALERT) {
2308 s = (where & SSL_CB_READ) ? "read" : "write";
2309 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2311 else if (where & SSL_CB_EXIT) {
2313 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2315 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2320 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2321 SSL_CTX *ctx = NULL;
2322 STACK_OF(X509_NAME) *calist;
2325 unsigned long error;
2328 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2329 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2330 for (i = 0; i < CRYPTO_num_locks(); i++) {
2331 ssl_lock_count[i] = 0;
2332 pthread_mutex_init(&ssl_locks[i], NULL);
2334 CRYPTO_set_id_callback(ssl_thread_id);
2335 CRYPTO_set_locking_callback(ssl_locking_callback);
2337 SSL_load_error_strings();
2340 while (!RAND_status()) {
2341 time_t t = time(NULL);
2342 pid_t pid = getpid();
2343 RAND_seed((unsigned char *)&t, sizeof(time_t));
2344 RAND_seed((unsigned char *)&pid, sizeof(pid));
2350 ctx = SSL_CTX_new(TLSv1_method());
2352 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2356 ctx = SSL_CTX_new(DTLSv1_method());
2358 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2360 SSL_CTX_set_read_ahead(ctx, 1);
2364 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2368 if (conf->certkeypwd) {
2369 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2370 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2372 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2373 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2374 !SSL_CTX_check_private_key(ctx) ||
2375 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2376 while ((error = ERR_get_error()))
2377 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2378 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2383 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2384 if (!conf->cacertfile || calist) {
2385 if (conf->cacertpath) {
2387 calist = sk_X509_NAME_new_null();
2388 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2389 sk_X509_NAME_free(calist);
2395 while ((error = ERR_get_error()))
2396 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2397 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2401 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2402 SSL_CTX_set_client_CA_list(ctx, calist);
2404 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2405 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2407 if (conf->crlcheck) {
2408 x509_s = SSL_CTX_get_cert_store(ctx);
2409 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2412 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2416 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2419 t = hash_read(tlsconfs, alt1, strlen(alt1));
2421 t = hash_read(tlsconfs, alt2, strlen(alt2));
2429 t->tlsctx = tlscreatectx(RAD_TLS, t);
2433 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2439 struct list *addsrvconfs(char *value, char **names) {
2440 struct list *conflist;
2442 struct list_node *entry;
2443 struct clsrvconf *conf = NULL;
2445 if (!names || !*names)
2448 conflist = list_create();
2450 debug(DBG_ERR, "malloc failed");
2454 for (n = 0; names[n]; n++) {
2455 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2456 conf = (struct clsrvconf *)entry->data;
2457 if (!strcasecmp(names[n], conf->name))
2461 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2462 list_destroy(conflist);
2465 if (!list_push(conflist, conf)) {
2466 debug(DBG_ERR, "malloc failed");
2467 list_destroy(conflist);
2470 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2475 void freerealm(struct realm *realm) {
2479 free(realm->message);
2480 regfree(&realm->regex);
2481 pthread_mutex_destroy(&realm->subrealms_mutex);
2482 if (realm->subrealms)
2483 list_destroy(realm->subrealms);
2484 if (realm->srvconfs) {
2485 /* emptying list without freeing data */
2486 while (list_shift(realm->srvconfs));
2487 list_destroy(realm->srvconfs);
2489 if (realm->accsrvconfs) {
2490 /* emptying list without freeing data */
2491 while (list_shift(realm->accsrvconfs));
2492 list_destroy(realm->accsrvconfs);
2497 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2499 struct realm *realm;
2500 char *s, *regex = NULL;
2502 if (*value == '/') {
2503 /* regexp, remove optional trailing / if present */
2504 if (value[strlen(value) - 1] == '/')
2505 value[strlen(value) - 1] = '\0';
2507 /* not a regexp, let us make it one */
2508 if (*value == '*' && !value[1])
2509 regex = stringcopy(".*", 0);
2511 for (n = 0, s = value; *s;)
2514 regex = malloc(strlen(value) + n + 3);
2517 for (n = 1, s = value; *s; s++) {
2527 debug(DBG_ERR, "malloc failed");
2531 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2534 realm = malloc(sizeof(struct realm));
2536 debug(DBG_ERR, "malloc failed");
2539 memset(realm, 0, sizeof(struct realm));
2541 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2542 debug(DBG_ERR, "mutex init failed");
2548 realm->name = stringcopy(value, 0);
2550 debug(DBG_ERR, "malloc failed");
2553 if (message && strlen(message) > 253) {
2554 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2557 realm->message = message;
2558 realm->accresp = accresp;
2560 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2561 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2565 if (servers && *servers) {
2566 realm->srvconfs = addsrvconfs(value, servers);
2567 if (!realm->srvconfs)
2571 if (accservers && *accservers) {
2572 realm->accsrvconfs = addsrvconfs(value, accservers);
2573 if (!realm->accsrvconfs)
2577 if (!list_push(realmlist, realm)) {
2578 debug(DBG_ERR, "malloc failed");
2579 pthread_mutex_destroy(&realm->subrealms_mutex);
2583 debug(DBG_DBG, "addrealm: added realm %s", value);
2593 for (n = 0; servers[n]; n++)
2598 for (n = 0; accservers[n]; n++)
2599 free(accservers[n]);
2605 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2606 struct clsrvconf *srvconf;
2607 struct realm *newrealm = NULL;
2608 char *realmname, *s;
2611 if (!conf->dynamiclookupcommand)
2614 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2615 realmname = strrchr(id, '@');
2621 for (s = realmname; *s; s++)
2622 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2625 pthread_mutex_lock(&realm->subrealms_mutex);
2626 /* exit if we now already got a matching subrealm */
2627 if (id2realm(realm->subrealms, id))
2629 srvconf = malloc(sizeof(struct clsrvconf));
2631 debug(DBG_ERR, "malloc failed");
2635 if (!addserver(srvconf))
2638 if (!realm->subrealms)
2639 realm->subrealms = list_create();
2640 if (!realm->subrealms)
2642 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2646 /* add server and accserver to newrealm */
2647 newrealm->srvconfs = list_create();
2648 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2649 debug(DBG_ERR, "malloc failed");
2652 newrealm->accsrvconfs = list_create();
2653 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2654 debug(DBG_ERR, "malloc failed");
2658 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2660 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2661 debug(DBG_ERR, "pthread_create failed");
2664 pthread_detach(clientth);
2669 list_removedata(realm->subrealms, newrealm);
2670 freerealm(newrealm);
2671 if (!list_first(realm->subrealms)) {
2672 list_destroy(realm->subrealms);
2673 realm->subrealms = NULL;
2676 freeserver(srvconf->servers, 1);
2678 debug(DBG_ERR, "failed to create dynamic server");
2681 pthread_mutex_unlock(&realm->subrealms_mutex);
2684 int dynamicconfig(struct server *server) {
2685 int ok, fd[2], status;
2687 struct clsrvconf *conf = server->conf;
2688 struct gconffile *cf = NULL;
2690 /* for now we only learn hostname/address */
2691 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2694 debug(DBG_ERR, "dynamicconfig: pipe error");
2699 debug(DBG_ERR, "dynamicconfig: fork error");
2703 } else if (pid == 0) {
2706 if (fd[1] != STDOUT_FILENO) {
2707 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2708 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2711 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2712 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2716 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2717 ok = getgenericconfig(&cf, NULL,
2718 "Server", CONF_CBK, confserver_cb, (void *)conf,
2723 if (waitpid(pid, &status, 0) < 0) {
2724 debug(DBG_ERR, "dynamicconfig: wait error");
2729 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2737 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2741 int addmatchcertattr(struct clsrvconf *conf) {
2745 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2746 r = &conf->certcnregex;
2747 v = conf->matchcertattr + 4;
2748 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2749 r = &conf->certuriregex;
2750 v = conf->matchcertattr + 20;
2755 /* regexp, remove optional trailing / if present */
2756 if (v[strlen(v) - 1] == '/')
2757 v[strlen(v) - 1] = '\0';
2761 *r = malloc(sizeof(regex_t));
2763 debug(DBG_ERR, "malloc failed");
2766 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2769 debug(DBG_ERR, "failed to compile regular expression %s", v);
2775 /* should accept both names and numeric values, only numeric right now */
2776 uint8_t attrname2val(char *attrname) {
2779 val = atoi(attrname);
2780 return val > 0 && val < 256 ? val : 0;
2783 /* should accept both names and numeric values, only numeric right now */
2784 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2787 *vendor = atoi(attrname);
2788 s = strchr(attrname, ':');
2793 *type = atoi(s + 1);
2794 return *type >= 0 && *type < 256;
2797 /* should accept both names and numeric values, only numeric right now */
2798 struct tlv *extractattr(char *nameval) {
2803 s = strchr(nameval, ':');
2804 name = atoi(nameval);
2805 if (!s || name < 1 || name > 255)
2807 len = strlen(s + 1);
2810 a = malloc(sizeof(struct tlv));
2813 a->v = (uint8_t *)stringcopy(s + 1, 0);
2823 /* should accept both names and numeric values, only numeric right now */
2824 struct modattr *extractmodattr(char *nameval) {
2829 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2833 s = strchr(nameval, ':');
2834 name = atoi(nameval);
2835 if (!s || name < 1 || name > 255 || s[1] != '/')
2839 /* regexp, remove optional trailing / if present */
2840 if (s[strlen(s) - 1] == '/')
2841 s[strlen(s) - 1] = '\0';
2849 m = malloc(sizeof(struct modattr));
2851 debug(DBG_ERR, "malloc failed");
2856 m->replacement = stringcopy(t, 0);
2857 if (!m->replacement) {
2859 debug(DBG_ERR, "malloc failed");
2863 m->regex = malloc(sizeof(regex_t));
2865 free(m->replacement);
2867 debug(DBG_ERR, "malloc failed");
2871 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2873 free(m->replacement);
2875 debug(DBG_ERR, "failed to compile regular expression %s", s);
2882 struct rewrite *getrewrite(char *alt1, char *alt2) {
2885 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2887 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2892 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2893 struct rewrite *rewrite = NULL;
2895 uint8_t *rma = NULL;
2896 uint32_t *p, *rmva = NULL;
2897 struct list *adda = NULL, *moda = NULL;
2902 for (n = 0; rmattrs[n]; n++);
2903 rma = calloc(n + 1, sizeof(uint8_t));
2905 debugx(1, DBG_ERR, "malloc failed");
2907 for (i = 0; i < n; i++) {
2908 if (!(rma[i] = attrname2val(rmattrs[i])))
2909 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2917 for (n = 0; rmvattrs[n]; n++);
2918 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2920 debugx(1, DBG_ERR, "malloc failed");
2922 for (p = rmva, i = 0; i < n; i++, p += 2) {
2923 if (!vattrname2val(rmvattrs[i], p, p + 1))
2924 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2932 adda = list_create();
2934 debugx(1, DBG_ERR, "malloc failed");
2935 for (i = 0; addattrs[i]; i++) {
2936 a = extractattr(addattrs[i]);
2938 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2940 if (!list_push(adda, a))
2941 debugx(1, DBG_ERR, "malloc failed");
2947 moda = list_create();
2949 debugx(1, DBG_ERR, "malloc failed");
2950 for (i = 0; modattrs[i]; i++) {
2951 m = extractmodattr(modattrs[i]);
2953 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2955 if (!list_push(moda, m))
2956 debugx(1, DBG_ERR, "malloc failed");
2961 if (rma || rmva || adda || moda) {
2962 rewrite = malloc(sizeof(struct rewrite));
2964 debugx(1, DBG_ERR, "malloc failed");
2965 rewrite->removeattrs = rma;
2966 rewrite->removevendorattrs = rmva;
2967 rewrite->addattrs = adda;
2968 rewrite->modattrs = moda;
2971 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2972 debugx(1, DBG_ERR, "malloc failed");
2973 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2976 void freeclsrvconf(struct clsrvconf *conf) {
2982 free(conf->matchcertattr);
2983 if (conf->certcnregex)
2984 regfree(conf->certcnregex);
2985 if (conf->certuriregex)
2986 regfree(conf->certuriregex);
2987 free(conf->confrewritein);
2988 free(conf->confrewriteout);
2989 if (conf->rewriteusername) {
2990 if (conf->rewriteusername->regex)
2991 regfree(conf->rewriteusername->regex);
2992 free(conf->rewriteusername->replacement);
2993 free(conf->rewriteusername);
2995 free(conf->dynamiclookupcommand);
2996 free(conf->rewritein);
2997 free(conf->rewriteout);
2999 freeaddrinfo(conf->addrinfo);
3000 /* not touching ssl_ctx, clients and servers */
3004 int mergeconfstring(char **dst, char **src) {
3013 t = stringcopy(*dst, 0);
3015 debug(DBG_ERR, "malloc failed");
3023 /* assumes dst is a shallow copy */
3024 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3025 if (!mergeconfstring(&dst->name, &src->name) ||
3026 !mergeconfstring(&dst->host, &src->host) ||
3027 !mergeconfstring(&dst->port, &src->port) ||
3028 !mergeconfstring(&dst->secret, &src->secret) ||
3029 !mergeconfstring(&dst->tls, &src->tls) ||
3030 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3031 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3032 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3033 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3036 dst->pdef = src->pdef;
3037 dst->statusserver = src->statusserver;
3038 dst->certnamecheck = src->certnamecheck;
3039 if (src->retryinterval != 255)
3040 dst->retryinterval = src->retryinterval;
3041 if (src->retrycount != 255)
3042 dst->retrycount = src->retrycount;
3046 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3047 struct clsrvconf *conf;
3048 char *conftype = NULL, *rewriteinalias = NULL;
3050 debug(DBG_DBG, "confclient_cb called for %s", block);
3052 conf = malloc(sizeof(struct clsrvconf));
3053 if (!conf || !list_push(clconfs, conf))
3054 debugx(1, DBG_ERR, "malloc failed");
3055 memset(conf, 0, sizeof(struct clsrvconf));
3056 conf->certnamecheck = 1;
3058 if (!getgenericconfig(cf, block,
3059 "type", CONF_STR, &conftype,
3060 "host", CONF_STR, &conf->host,
3061 "secret", CONF_STR, &conf->secret,
3062 "tls", CONF_STR, &conf->tls,
3063 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3064 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3065 "rewrite", CONF_STR, &rewriteinalias,
3066 "rewriteIn", CONF_STR, &conf->confrewritein,
3067 "rewriteOut", CONF_STR, &conf->confrewriteout,
3068 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3071 debugx(1, DBG_ERR, "configuration error");
3073 conf->name = stringcopy(val, 0);
3075 conf->host = stringcopy(val, 0);
3076 if (!conf->name || !conf->host)
3077 debugx(1, DBG_ERR, "malloc failed");
3080 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3081 conf->type = protoname2int(conftype);
3082 conf->pdef = &protodefs[conf->type];
3083 if (!conf->pdef->name)
3084 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3087 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3088 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3090 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3091 if (conf->matchcertattr && !addmatchcertattr(conf))
3092 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3095 if (!conf->confrewritein)
3096 conf->confrewritein = rewriteinalias;
3098 free(rewriteinalias);
3099 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3100 if (conf->confrewriteout)
3101 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3103 if (conf->confrewriteusername) {
3104 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3105 if (!conf->rewriteusername)
3106 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3109 if (!resolvepeer(conf, 0))
3110 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3112 if (!conf->secret) {
3113 if (!conf->pdef->secretdefault)
3114 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3115 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3117 debugx(1, DBG_ERR, "malloc failed");
3122 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3123 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3124 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3125 if (!conf->ssl_ctx) {
3126 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3129 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3130 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3136 conf->port = stringcopy(conf->pdef->portdefault, 0);
3138 debug(DBG_ERR, "malloc failed");
3143 if (conf->retryinterval == 255)
3144 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3145 if (conf->retrycount == 255)
3146 conf->retrycount = protodefs[conf->type].retrycountdefault;
3148 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3149 if (conf->confrewriteout)
3150 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3152 if (!conf->secret) {
3153 if (!conf->pdef->secretdefault) {
3154 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3157 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3158 if (!conf->secret) {
3159 debug(DBG_ERR, "malloc failed");
3164 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3165 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3171 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3172 struct clsrvconf *conf, *resconf;
3173 char *conftype = NULL, *rewriteinalias = NULL;
3174 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3176 debug(DBG_DBG, "confserver_cb called for %s", block);
3178 conf = malloc(sizeof(struct clsrvconf));
3180 debug(DBG_ERR, "malloc failed");
3183 memset(conf, 0, sizeof(struct clsrvconf));
3184 resconf = (struct clsrvconf *)arg;
3186 conf->statusserver = resconf->statusserver;
3187 conf->certnamecheck = resconf->certnamecheck;
3189 conf->certnamecheck = 1;
3191 if (!getgenericconfig(cf, block,
3192 "type", CONF_STR, &conftype,
3193 "host", CONF_STR, &conf->host,
3194 "port", CONF_STR, &conf->port,
3195 "secret", CONF_STR, &conf->secret,
3196 "tls", CONF_STR, &conf->tls,
3197 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3198 "rewrite", CONF_STR, &rewriteinalias,
3199 "rewriteIn", CONF_STR, &conf->confrewritein,
3200 "rewriteOut", CONF_STR, &conf->confrewriteout,
3201 "StatusServer", CONF_BLN, &conf->statusserver,
3202 "RetryInterval", CONF_LINT, &retryinterval,
3203 "RetryCount", CONF_LINT, &retrycount,
3204 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3205 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3208 debug(DBG_ERR, "configuration error");
3212 conf->name = stringcopy(val, 0);
3214 debug(DBG_ERR, "malloc failed");
3218 conf->host = stringcopy(val, 0);
3220 debug(DBG_ERR, "malloc failed");
3226 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3227 conf->type = protoname2int(conftype);
3228 conf->pdef = &protodefs[conf->type];
3229 if (!conf->pdef->name) {
3230 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3236 if (!conf->confrewritein)
3237 conf->confrewritein = rewriteinalias;
3239 free(rewriteinalias);
3240 rewriteinalias = NULL;
3242 if (retryinterval != LONG_MIN) {
3243 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3244 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3247 conf->retryinterval = (uint8_t)retryinterval;
3249 conf->retryinterval = 255;
3251 if (retrycount != LONG_MIN) {
3252 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3253 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3256 conf->retrycount = (uint8_t)retrycount;
3258 conf->retrycount = 255;
3261 if (!mergesrvconf(resconf, conf))
3265 if (conf->dynamiclookupcommand) {
3266 free(conf->dynamiclookupcommand);
3267 conf->dynamiclookupcommand = NULL;
3271 if (resconf || !conf->dynamiclookupcommand) {
3272 if (!compileserverconfig(conf, block))
3279 if (!list_push(srvconfs, conf)) {
3280 debug(DBG_ERR, "malloc failed");
3287 free(rewriteinalias);
3288 freeclsrvconf(conf);
3292 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3293 char **servers = NULL, **accservers = NULL, *msg = NULL;
3294 uint8_t accresp = 0;
3296 debug(DBG_DBG, "confrealm_cb called for %s", block);
3298 if (!getgenericconfig(cf, block,
3299 "server", CONF_MSTR, &servers,
3300 "accountingServer", CONF_MSTR, &accservers,
3301 "ReplyMessage", CONF_STR, &msg,
3302 "AccountingResponse", CONF_BLN, &accresp,
3305 debugx(1, DBG_ERR, "configuration error");
3307 addrealm(realms, val, servers, accservers, msg, accresp);
3311 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3314 debug(DBG_DBG, "conftls_cb called for %s", block);
3316 conf = malloc(sizeof(struct tls));
3318 debug(DBG_ERR, "conftls_cb: malloc failed");
3321 memset(conf, 0, sizeof(struct tls));
3323 if (!getgenericconfig(cf, block,
3324 "CACertificateFile", CONF_STR, &conf->cacertfile,
3325 "CACertificatePath", CONF_STR, &conf->cacertpath,
3326 "CertificateFile", CONF_STR, &conf->certfile,
3327 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3328 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3329 "CRLCheck", CONF_BLN, &conf->crlcheck,
3332 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3335 if (!conf->certfile || !conf->certkeyfile) {
3336 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3339 if (!conf->cacertfile && !conf->cacertpath) {
3340 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3344 conf->name = stringcopy(val, 0);
3346 debug(DBG_ERR, "conftls_cb: malloc failed");
3350 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3351 debug(DBG_ERR, "conftls_cb: malloc failed");
3355 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3359 free(conf->cacertfile);
3360 free(conf->cacertpath);
3361 free(conf->certfile);
3362 free(conf->certkeyfile);
3363 free(conf->certkeypwd);
3368 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3369 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3371 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3373 if (!getgenericconfig(cf, block,
3374 "removeAttribute", CONF_MSTR, &rmattrs,
3375 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3376 "addAttribute", CONF_MSTR, &addattrs,
3377 "modifyAttribute", CONF_MSTR, &modattrs,
3380 debugx(1, DBG_ERR, "configuration error");
3381 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3385 void getmainconfig(const char *configfile) {
3386 long int loglevel = LONG_MIN;
3387 struct gconffile *cfs;
3389 cfs = openconfigfile(configfile);
3390 memset(&options, 0, sizeof(options));
3392 clconfs = list_create();
3394 debugx(1, DBG_ERR, "malloc failed");
3396 srvconfs = list_create();
3398 debugx(1, DBG_ERR, "malloc failed");
3400 realms = list_create();
3402 debugx(1, DBG_ERR, "malloc failed");
3404 tlsconfs = hash_create();
3406 debugx(1, DBG_ERR, "malloc failed");
3408 rewriteconfs = hash_create();
3410 debugx(1, DBG_ERR, "malloc failed");
3412 if (!getgenericconfig(&cfs, NULL,
3413 "ListenUDP", CONF_MSTR, &options.listenudp,
3414 "ListenTCP", CONF_MSTR, &options.listentcp,
3415 "ListenTLS", CONF_MSTR, &options.listentls,
3416 "ListenDTLS", CONF_MSTR, &options.listendtls,
3417 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3418 "SourceUDP", CONF_STR, &options.sourceudp,
3419 "SourceTCP", CONF_STR, &options.sourcetcp,
3420 "SourceTLS", CONF_STR, &options.sourcetls,
3421 "SourceDTLS", CONF_STR, &options.sourcedtls,
3422 "LogLevel", CONF_LINT, &loglevel,
3423 "LogDestination", CONF_STR, &options.logdestination,
3424 "LoopPrevention", CONF_BLN, &options.loopprevention,
3425 "Client", CONF_CBK, confclient_cb, NULL,
3426 "Server", CONF_CBK, confserver_cb, NULL,
3427 "Realm", CONF_CBK, confrealm_cb, NULL,
3428 "TLS", CONF_CBK, conftls_cb, NULL,
3429 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3432 debugx(1, DBG_ERR, "configuration error");
3434 if (loglevel != LONG_MIN) {
3435 if (loglevel < 1 || loglevel > 4)
3436 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3437 options.loglevel = (uint8_t)loglevel;
3441 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3444 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3447 *configfile = optarg;
3450 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3451 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3452 *loglevel = *optarg - '0';
3461 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3466 if (!(argc - optind))
3470 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3474 int daemon(int a, int b) {
3482 for (i = 0; i < 3; i++) {
3484 open("/dev/null", O_RDWR);
3490 void *sighandler(void *arg) {
3495 sigemptyset(&sigset);
3496 sigaddset(&sigset, SIGPIPE);
3497 sigwait(&sigset, &sig);
3498 /* only get SIGPIPE right now, so could simplify below code */
3501 /* completely ignoring this */
3504 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3507 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3512 int main(int argc, char **argv) {
3515 struct list_node *entry;
3516 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3517 char *configfile = NULL;
3518 struct clsrvconf *srvconf;
3521 debug_init("radsecproxy");
3522 debug_set_level(DEBUG_LEVEL);
3524 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3526 debug_set_level(loglevel);
3527 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3529 options.loglevel = loglevel;
3530 else if (options.loglevel)
3531 debug_set_level(options.loglevel);
3533 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3534 free(options.logdestination);
3536 if (!list_first(clconfs))
3537 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3538 if (!list_first(realms))
3539 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3542 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3544 if (!foreground && (daemon(0, 0) < 0))
3545 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3547 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3549 sigemptyset(&sigset);
3550 /* exit on all but SIGPIPE, ignore more? */
3551 sigaddset(&sigset, SIGPIPE);
3552 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3553 pthread_create(&sigth, NULL, sighandler, NULL);
3555 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3556 srvconf = (struct clsrvconf *)entry->data;
3557 if (srvconf->dynamiclookupcommand)
3559 if (!addserver(srvconf))
3560 debugx(1, DBG_ERR, "failed to add server");
3561 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3562 (void *)(srvconf->servers)))
3563 debugx(1, DBG_ERR, "pthread_create failed");
3565 /* srcprotores for UDP no longer needed */
3566 if (srcprotores[RAD_UDP]) {
3567 freeaddrinfo(srcprotores[RAD_UDP]);
3568 srcprotores[RAD_UDP] = NULL;
3571 for (i = 0; protodefs[i].name; i++)
3572 if (protodefs[i].initextra)
3573 protodefs[i].initextra();
3575 if (find_clconf_type(RAD_TCP, NULL))
3576 createlisteners(RAD_TCP, options.listentcp);
3578 if (find_clconf_type(RAD_TLS, NULL))
3579 createlisteners(RAD_TLS, options.listentls);
3581 if (find_clconf_type(RAD_DTLS, NULL))
3582 createlisteners(RAD_DTLS, options.listendtls);
3584 if (find_clconf_type(RAD_UDP, NULL)) {
3585 createlisteners(RAD_UDP, options.listenudp);
3586 if (options.listenaccudp)
3587 createlisteners(RAD_UDP, options.listenaccudp);
3590 /* just hang around doing nothing, anything to do here? */