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>
67 #include "radsecproxy.h"
73 static struct options options;
74 static struct list *clconfs, *srvconfs;
76 struct hash *tlsconfs, *rewriteconfs;
78 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
80 static pthread_mutex_t *ssl_locks = NULL;
81 static long *ssl_lock_count;
85 /* minimum required declarations to avoid reordering code */
86 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
87 int dynamicconfig(struct server *server);
88 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
89 void freerealm(struct realm *realm);
90 void freeclsrvconf(struct clsrvconf *conf);
91 void freerqdata(struct request *rq);
93 static const struct protodefs protodefs[] = {
94 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
95 NULL, /* secretdefault */
96 SOCK_DGRAM, /* socktype */
97 "1812", /* portdefault */
98 REQUEST_RETRY_COUNT, /* retrycountdefault */
99 10, /* retrycountmax */
100 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
101 60, /* retryintervalmax */
102 udpserverrd, /* listener */
103 &options.sourceudp, /* srcaddrport */
104 NULL, /* connecter */
105 NULL, /* clientconnreader */
106 clientradputudp, /* clientradput */
107 addclientudp, /* addclient */
108 addserverextraudp, /* addserverextra */
109 initextraudp /* initextra */
111 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
112 "mysecret", /* secretdefault */
113 SOCK_STREAM, /* socktype */
114 "2083", /* portdefault */
115 0, /* retrycountdefault */
116 0, /* retrycountmax */
117 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
118 60, /* retryintervalmax */
119 tlslistener, /* listener */
120 &options.sourcetls, /* srcaddrport */
121 tlsconnect, /* connecter */
122 tlsclientrd, /* clientconnreader */
123 clientradputtls, /* clientradput */
124 NULL, /* addclient */
125 NULL, /* addserverextra */
128 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
129 NULL, /* secretdefault */
130 SOCK_STREAM, /* socktype */
131 "1812", /* portdefault */
132 0, /* retrycountdefault */
133 0, /* retrycountmax */
134 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
135 60, /* retryintervalmax */
136 tcplistener, /* listener */
137 &options.sourcetcp, /* srcaddrport */
138 tcpconnect, /* connecter */
139 tcpclientrd, /* clientconnreader */
140 clientradputtcp, /* clientradput */
141 NULL, /* addclient */
142 NULL, /* addserverextra */
145 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
146 "mysecret", /* secretdefault */
147 SOCK_DGRAM, /* socktype */
148 "2083", /* portdefault */
149 REQUEST_RETRY_COUNT, /* retrycountdefault */
150 10, /* retrycountmax */
151 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
152 60, /* retryintervalmax */
153 udpdtlsserverrd, /* listener */
154 &options.sourcedtls, /* srcaddrport */
155 dtlsconnect, /* connecter */
156 dtlsclientrd, /* clientconnreader */
157 clientradputdtls, /* clientradput */
158 NULL, /* addclient */
159 addserverextradtls, /* addserverextra */
160 initextradtls /* initextra */
166 uint8_t protoname2int(const char *name) {
169 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
173 /* callbacks for making OpenSSL thread safe */
174 unsigned long ssl_thread_id() {
175 return (unsigned long)pthread_self();
178 void ssl_locking_callback(int mode, int type, const char *file, int line) {
179 if (mode & CRYPTO_LOCK) {
180 pthread_mutex_lock(&ssl_locks[type]);
181 ssl_lock_count[type]++;
183 pthread_mutex_unlock(&ssl_locks[type]);
186 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
187 int pwdlen = strlen(userdata);
188 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
190 memcpy(buf, userdata, pwdlen);
194 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
199 err_cert = X509_STORE_CTX_get_current_cert(ctx);
200 err = X509_STORE_CTX_get_error(ctx);
201 depth = X509_STORE_CTX_get_error_depth(ctx);
203 if (depth > MAX_CERT_DEPTH) {
205 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
206 X509_STORE_CTX_set_error(ctx, err);
210 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
211 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
214 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
215 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
216 debug(DBG_WARN, "\tIssuer=%s", buf);
218 case X509_V_ERR_CERT_NOT_YET_VALID:
219 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
220 debug(DBG_WARN, "\tCertificate not yet valid");
222 case X509_V_ERR_CERT_HAS_EXPIRED:
223 debug(DBG_WARN, "Certificate has expired");
225 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
226 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
231 printf("certificate verify returns %d\n", ok);
236 struct addrinfo *getsrcprotores(uint8_t type) {
237 return srcprotores[type];
240 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
241 struct addrinfo hints, *addrinfo, *res;
245 slash = conf->host ? strchr(conf->host, '/') : NULL;
249 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
253 if (*s < '0' || *s > '9') {
254 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
257 plen = atoi(slash + 1);
258 if (plen < 0 || plen > 128) {
259 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
264 memset(&hints, 0, sizeof(hints));
265 hints.ai_socktype = conf->pdef->socktype;
266 hints.ai_family = AF_UNSPEC;
267 hints.ai_flags = ai_flags;
268 if (!conf->host && !conf->port) {
269 /* getaddrinfo() doesn't like host and port to be NULL */
270 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
271 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
274 for (res = addrinfo; res; res = res->ai_next) {
275 switch (res->ai_family) {
277 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
280 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
286 hints.ai_flags |= AI_NUMERICHOST;
287 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
288 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
293 switch (addrinfo->ai_family) {
296 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
297 freeaddrinfo(addrinfo);
304 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
305 freeaddrinfo(addrinfo);
308 conf->prefixlen = plen;
310 conf->prefixlen = 255;
313 freeaddrinfo(conf->addrinfo);
314 conf->addrinfo = addrinfo;
318 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
323 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
327 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
329 debugx(1, DBG_ERR, "no ] matching initial [");
333 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "missing host/address");
338 conf->host = stringcopy(field, p - field);
341 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
342 debugx(1, DBG_ERR, "unexpected character after ]");
345 /* port number or service name is specified */;
347 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
349 debugx(1, DBG_ERR, "syntax error, : but no following port");
350 conf->port = stringcopy(field, p - field);
352 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
356 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
357 struct clsrvconf *conf;
359 conf = malloc(sizeof(struct clsrvconf));
361 debugx(1, DBG_ERR, "malloc failed");
362 memset(conf, 0, sizeof(struct clsrvconf));
364 conf->pdef = &protodefs[conf->type];
366 parsehostport(lconf, conf, default_port);
367 if (!strcmp(conf->host, "*")) {
372 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
373 if (!resolvepeer(conf, AI_PASSIVE))
374 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
378 void freeclsrvres(struct clsrvconf *res) {
382 freeaddrinfo(res->addrinfo);
386 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
388 struct addrinfo *res;
390 for (res = addrinfo; res; res = res->ai_next) {
391 if (family != AF_UNSPEC && family != res->ai_family)
393 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
395 debug(DBG_WARN, "bindtoaddr: socket failed");
399 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
402 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
404 if (!bind(s, res->ai_addr, res->ai_addrlen))
406 debug(DBG_WARN, "bindtoaddr: bind failed");
412 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
414 struct addrinfo *res;
417 for (res = addrinfo; res; res = res->ai_next) {
418 s = bindtoaddr(src, res->ai_family, 1, 1);
420 debug(DBG_WARN, "connecttoserver: socket failed");
423 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
425 debug(DBG_WARN, "connecttoserver: connect failed");
432 /* returns 1 if the len first bits are equal, else 0 */
433 int prefixmatch(void *a1, void *a2, uint8_t len) {
434 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
436 if (l && memcmp(a1, a2, l))
441 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
444 /* returns next config with matching address, or NULL */
445 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
446 struct sockaddr_in6 *sa6 = NULL;
447 struct in_addr *a4 = NULL;
448 struct addrinfo *res;
449 struct list_node *entry;
450 struct clsrvconf *conf;
452 if (addr->sa_family == AF_INET6) {
453 sa6 = (struct sockaddr_in6 *)addr;
454 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
455 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
459 a4 = &((struct sockaddr_in *)addr)->sin_addr;
461 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
462 conf = (struct clsrvconf *)entry->data;
463 if (conf->type == type) {
464 if (conf->prefixlen == 255) {
465 for (res = conf->addrinfo; res; res = res->ai_next)
466 if ((a4 && res->ai_family == AF_INET &&
467 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
468 (sa6 && res->ai_family == AF_INET6 &&
469 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
475 res = conf->addrinfo;
477 ((a4 && res->ai_family == AF_INET &&
478 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
479 (sa6 && res->ai_family == AF_INET6 &&
480 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
491 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
492 return find_conf(type, addr, clconfs, cur);
495 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
496 return find_conf(type, addr, srvconfs, cur);
499 /* returns next config of given type, or NULL */
500 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
501 struct list_node *entry;
502 struct clsrvconf *conf;
504 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
505 conf = (struct clsrvconf *)entry->data;
506 if (conf->type == type) {
515 struct queue *newqueue() {
518 q = malloc(sizeof(struct queue));
520 debugx(1, DBG_ERR, "malloc failed");
521 q->entries = list_create();
523 debugx(1, DBG_ERR, "malloc failed");
524 pthread_mutex_init(&q->mutex, NULL);
525 pthread_cond_init(&q->cond, NULL);
529 void removequeue(struct queue *q) {
530 struct list_node *entry;
534 pthread_mutex_lock(&q->mutex);
535 for (entry = list_first(q->entries); entry; entry = list_next(entry))
536 free(((struct reply *)entry)->buf);
537 list_destroy(q->entries);
538 pthread_cond_destroy(&q->cond);
539 pthread_mutex_unlock(&q->mutex);
540 pthread_mutex_destroy(&q->mutex);
544 void freebios(struct queue *q) {
547 pthread_mutex_lock(&q->mutex);
548 while ((bio = (BIO *)list_shift(q->entries)))
550 pthread_mutex_unlock(&q->mutex);
554 struct client *addclient(struct clsrvconf *conf) {
555 struct client *new = malloc(sizeof(struct client));
558 debug(DBG_ERR, "malloc failed");
561 if (!conf->clients) {
562 conf->clients = list_create();
563 if (!conf->clients) {
564 debug(DBG_ERR, "malloc failed");
569 memset(new, 0, sizeof(struct client));
571 if (conf->pdef->addclient)
572 conf->pdef->addclient(new);
574 new->replyq = newqueue();
575 list_push(conf->clients, new);
579 void removeclient(struct client *client) {
580 if (!client || !client->conf->clients)
582 removequeue(client->replyq);
583 list_removedata(client->conf->clients, client);
587 void removeclientrqs(struct client *client) {
588 struct list_node *entry;
589 struct server *server;
593 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
594 server = ((struct clsrvconf *)entry->data)->servers;
597 pthread_mutex_lock(&server->newrq_mutex);
598 for (i = 0; i < MAX_REQUESTS; i++) {
599 rq = server->requests + i;
600 if (rq->from == client)
603 pthread_mutex_unlock(&server->newrq_mutex);
607 void freeserver(struct server *server, uint8_t destroymutex) {
608 struct request *rq, *end;
613 if (server->requests) {
614 rq = server->requests;
615 for (end = rq + MAX_REQUESTS; rq < end; rq++)
617 free(server->requests);
620 freebios(server->rbios);
621 free(server->dynamiclookuparg);
623 SSL_free(server->ssl);
625 pthread_mutex_destroy(&server->lock);
626 pthread_cond_destroy(&server->newrq_cond);
627 pthread_mutex_destroy(&server->newrq_mutex);
632 int addserver(struct clsrvconf *conf) {
633 struct clsrvconf *res;
637 debug(DBG_ERR, "addserver: currently works with just one server per conf");
640 conf->servers = malloc(sizeof(struct server));
641 if (!conf->servers) {
642 debug(DBG_ERR, "malloc failed");
645 memset(conf->servers, 0, sizeof(struct server));
646 conf->servers->conf = conf;
649 if (type == RAD_DTLS)
650 conf->servers->rbios = newqueue();
652 if (!srcprotores[type]) {
653 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
654 srcprotores[type] = res->addrinfo;
655 res->addrinfo = NULL;
659 conf->servers->sock = -1;
660 if (conf->pdef->addserverextra)
661 conf->pdef->addserverextra(conf);
663 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
664 if (!conf->servers->requests) {
665 debug(DBG_ERR, "malloc failed");
668 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
669 debug(DBG_ERR, "mutex init failed");
672 conf->servers->newrq = 0;
673 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
674 debug(DBG_ERR, "mutex init failed");
675 pthread_mutex_destroy(&conf->servers->lock);
678 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
679 debug(DBG_ERR, "mutex init failed");
680 pthread_mutex_destroy(&conf->servers->newrq_mutex);
681 pthread_mutex_destroy(&conf->servers->lock);
688 freeserver(conf->servers, 0);
689 conf->servers = NULL;
693 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
694 int loc, i, l, n, r = 0;
697 STACK_OF(GENERAL_NAME) *alt;
700 debug(DBG_DBG, "subjectaltnameaddr");
702 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
706 ex = X509_get_ext(cert, loc);
707 alt = X509V3_EXT_d2i(ex);
711 n = sk_GENERAL_NAME_num(alt);
712 for (i = 0; i < n; i++) {
713 gn = sk_GENERAL_NAME_value(alt, i);
714 if (gn->type != GEN_IPADD)
717 v = (char *)ASN1_STRING_data(gn->d.ia5);
718 l = ASN1_STRING_length(gn->d.ia5);
719 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
720 && !memcmp(v, &addr, l)) {
725 GENERAL_NAMES_free(alt);
729 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
736 nm = X509_get_subject_name(cert);
739 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
742 e = X509_NAME_get_entry(nm, loc);
743 t = X509_NAME_ENTRY_get_data(e);
744 v = (char *) ASN1_STRING_data(t);
745 l = ASN1_STRING_length(t);
749 if (l == strlen(exact) && !strncasecmp(exact, v, l))
752 s = stringcopy((char *)v, l);
754 debug(DBG_ERR, "malloc failed");
757 if (regexec(regex, s, 0, NULL, 0)) {
768 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
769 int loc, i, l, n, r = 0;
772 STACK_OF(GENERAL_NAME) *alt;
775 debug(DBG_DBG, "subjectaltnameregexp");
777 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
781 ex = X509_get_ext(cert, loc);
782 alt = X509V3_EXT_d2i(ex);
786 n = sk_GENERAL_NAME_num(alt);
787 for (i = 0; i < n; i++) {
788 gn = sk_GENERAL_NAME_value(alt, i);
789 if (gn->type != type)
792 v = (char *)ASN1_STRING_data(gn->d.ia5);
793 l = ASN1_STRING_length(gn->d.ia5);
797 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
800 if (memcmp(v, exact, l))
803 s = stringcopy((char *)v, l);
805 debug(DBG_ERR, "malloc failed");
808 if (regexec(regex, s, 0, NULL, 0)) {
817 GENERAL_NAMES_free(alt);
821 X509 *verifytlscert(SSL *ssl) {
825 if (SSL_get_verify_result(ssl) != X509_V_OK) {
826 debug(DBG_ERR, "verifytlscert: basic validation failed");
827 while ((error = ERR_get_error()))
828 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
832 cert = SSL_get_peer_certificate(ssl);
834 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
838 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
840 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
841 struct in6_addr addr;
843 if (conf->certnamecheck && conf->prefixlen == 255) {
844 if (inet_pton(AF_INET, conf->host, &addr))
846 else if (inet_pton(AF_INET6, conf->host, &addr))
849 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
852 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
855 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
857 if (!cnregexp(cert, conf->host, NULL)) {
858 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
861 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
864 if (conf->certcnregex) {
865 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
866 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
869 debug(DBG_DBG, "verifyconfcert: CN matching regex");
871 if (conf->certuriregex) {
872 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
873 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
876 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
881 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
883 if (ATTRTYPE(attrs) == type)
885 length -= ATTRLEN(attrs);
886 attrs += ATTRLEN(attrs);
891 void freerqdata(struct request *rq) {
892 if (rq->origusername)
893 free(rq->origusername);
895 radmsg_free(rq->msg);
900 void sendrq(struct server *to, struct request *rq) {
903 pthread_mutex_lock(&to->newrq_mutex);
904 /* might simplify if only try nextid, might be ok */
905 for (i = to->nextid; i < MAX_REQUESTS; i++)
906 if (!to->requests[i].buf)
908 if (i == MAX_REQUESTS) {
909 for (i = 0; i < to->nextid; i++)
910 if (!to->requests[i].buf)
912 if (i == to->nextid) {
913 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
919 rq->msg->id = (uint8_t)i;
920 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
922 debug(DBG_ERR, "sendrq: radmsg2buf failed");
927 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
928 to->requests[i] = *rq;
933 debug(DBG_DBG, "sendrq: signalling client writer");
934 pthread_cond_signal(&to->newrq_cond);
938 pthread_mutex_unlock(&to->newrq_mutex);
941 void sendreply(struct client *to, struct radmsg *msg, struct sockaddr_storage *tosa, int toudpsock) {
946 buf = radmsg2buf(msg, (uint8_t *)to->conf->secret);
949 debug(DBG_ERR, "sendreply: radmsg2buf failed");
953 reply = malloc(sizeof(struct reply));
956 debug(DBG_ERR, "sendreply: malloc failed");
959 memset(reply, 0, sizeof(struct reply));
963 reply->toudpsock = toudpsock;
965 pthread_mutex_lock(&to->replyq->mutex);
967 first = list_first(to->replyq->entries) == NULL;
969 if (!list_push(to->replyq->entries, reply)) {
970 pthread_mutex_unlock(&to->replyq->mutex);
973 debug(DBG_ERR, "sendreply: malloc failed");
978 debug(DBG_DBG, "signalling server writer");
979 pthread_cond_signal(&to->replyq->cond);
981 pthread_mutex_unlock(&to->replyq->mutex);
984 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
985 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
986 static unsigned char first = 1;
987 static EVP_MD_CTX mdctx;
988 unsigned char hash[EVP_MAX_MD_SIZE], *input;
990 uint8_t i, offset = 0, out[128];
992 pthread_mutex_lock(&lock);
994 EVP_MD_CTX_init(&mdctx);
1000 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1001 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1002 !EVP_DigestUpdate(&mdctx, input, 16) ||
1003 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1005 pthread_mutex_unlock(&lock);
1008 for (i = 0; i < 16; i++)
1009 out[offset + i] = hash[i] ^ in[offset + i];
1010 input = out + offset - 16;
1015 memcpy(in, out, len);
1016 pthread_mutex_unlock(&lock);
1020 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1021 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1022 static unsigned char first = 1;
1023 static EVP_MD_CTX mdctx;
1024 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1025 unsigned int md_len;
1026 uint8_t i, offset = 0, out[128];
1028 pthread_mutex_lock(&lock);
1030 EVP_MD_CTX_init(&mdctx);
1036 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1037 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1038 !EVP_DigestUpdate(&mdctx, input, 16) ||
1039 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1041 pthread_mutex_unlock(&lock);
1044 for (i = 0; i < 16; i++)
1045 out[offset + i] = hash[i] ^ in[offset + i];
1046 input = in + offset;
1051 memcpy(in, out, len);
1052 pthread_mutex_unlock(&lock);
1056 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1057 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1058 static unsigned char first = 1;
1059 static EVP_MD_CTX mdctx;
1060 unsigned char hash[EVP_MAX_MD_SIZE];
1061 unsigned int md_len;
1064 pthread_mutex_lock(&lock);
1066 EVP_MD_CTX_init(&mdctx);
1071 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1072 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1073 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1076 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1077 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1078 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1079 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1080 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1081 pthread_mutex_unlock(&lock);
1086 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1089 for (i = 0; i < 16; i++)
1092 for (offset = 16; offset < len; offset += 16) {
1094 printf("text + offset - 16 c(%d): ", offset / 16);
1095 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1097 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1098 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1099 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1100 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1102 pthread_mutex_unlock(&lock);
1106 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1109 for (i = 0; i < 16; i++)
1110 text[offset + i] ^= hash[i];
1114 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1117 pthread_mutex_unlock(&lock);
1121 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1122 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1123 static unsigned char first = 1;
1124 static EVP_MD_CTX mdctx;
1125 unsigned char hash[EVP_MAX_MD_SIZE];
1126 unsigned int md_len;
1130 pthread_mutex_lock(&lock);
1132 EVP_MD_CTX_init(&mdctx);
1137 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1138 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1139 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1142 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1143 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1144 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1145 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1146 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1147 pthread_mutex_unlock(&lock);
1152 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1155 for (i = 0; i < 16; i++)
1156 plain[i] = text[i] ^ hash[i];
1158 for (offset = 16; offset < len; offset += 16) {
1160 printf("text + offset - 16 c(%d): ", offset / 16);
1161 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1163 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1164 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1165 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1166 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1168 pthread_mutex_unlock(&lock);
1172 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1175 for (i = 0; i < 16; i++)
1176 plain[offset + i] = text[offset + i] ^ hash[i];
1179 memcpy(text, plain, len);
1181 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1184 pthread_mutex_unlock(&lock);
1188 struct realm *id2realm(struct list *realmlist, char *id) {
1189 struct list_node *entry;
1190 struct realm *realm, *subrealm = NULL;
1192 /* need to do locking for subrealms and check subrealm timers */
1193 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1194 realm = (struct realm *)entry->data;
1195 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1196 pthread_mutex_lock(&realm->subrealms_mutex);
1197 if (realm->subrealms)
1198 subrealm = id2realm(realm->subrealms, id);
1199 pthread_mutex_unlock(&realm->subrealms_mutex);
1200 return subrealm ? subrealm : realm;
1206 /* helper function, only used by removeserversubrealms() */
1207 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1208 struct list_node *entry;
1209 struct realm *realm;
1211 for (entry = list_first(realmlist); entry;) {
1212 realm = (struct realm *)entry->data;
1213 entry = list_next(entry);
1214 if (realm->srvconfs) {
1215 list_removedata(realm->srvconfs, srv);
1216 if (!list_first(realm->srvconfs)) {
1217 list_destroy(realm->srvconfs);
1218 realm->srvconfs = NULL;
1221 if (realm->accsrvconfs) {
1222 list_removedata(realm->accsrvconfs, srv);
1223 if (!list_first(realm->accsrvconfs)) {
1224 list_destroy(realm->accsrvconfs);
1225 realm->accsrvconfs = NULL;
1229 /* remove subrealm if no servers */
1230 if (!realm->srvconfs && !realm->accsrvconfs) {
1231 list_removedata(realmlist, realm);
1237 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1238 struct list_node *entry;
1239 struct realm *realm;
1241 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1242 realm = (struct realm *)entry->data;
1243 pthread_mutex_lock(&realm->subrealms_mutex);
1244 if (realm->subrealms) {
1245 _internal_removeserversubrealms(realm->subrealms, srv);
1246 if (!list_first(realm->subrealms)) {
1247 list_destroy(realm->subrealms);
1248 realm->subrealms = NULL;
1251 pthread_mutex_unlock(&realm->subrealms_mutex);
1255 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1256 struct request *rq = to->requests, *end;
1258 pthread_mutex_lock(&to->newrq_mutex);
1259 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1260 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1262 pthread_mutex_unlock(&to->newrq_mutex);
1267 int attrvalidate(unsigned char *attrs, int length) {
1268 while (length > 1) {
1269 if (ATTRLEN(attrs) < 2) {
1270 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1273 length -= ATTRLEN(attrs);
1275 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1278 attrs += ATTRLEN(attrs);
1281 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1285 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1286 if (len < 16 || len > 128 || len % 16) {
1287 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1291 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1292 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1296 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1298 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1299 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1305 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1308 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1309 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1312 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1313 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1319 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1320 char *oldsecret, char *newsecret) {
1321 unsigned char *attr;
1323 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1324 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1325 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1331 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1335 for (; attrs[0]; attrs += 2)
1336 if (attrs[0] == vendor && attrs[1] == subattr)
1341 /* returns 1 if entire element is to be removed, else 0 */
1342 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1343 uint8_t alen, sublen;
1347 if (!removevendorattrs)
1350 memcpy(&vendor, attr->v, 4);
1351 vendor = ntohl(vendor);
1352 while (*removevendorattrs && *removevendorattrs != vendor)
1353 removevendorattrs += 2;
1354 if (!*removevendorattrs)
1357 if (findvendorsubattr(removevendorattrs, vendor, -1))
1358 return 1; /* remove entire vendor attribute */
1360 sublen = attr->l - 4;
1361 subattrs = attr->v + 4;
1363 if (!attrvalidate(subattrs, sublen)) {
1364 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1368 while (sublen > 1) {
1369 alen = ATTRLEN(subattrs);
1371 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1372 memmove(subattrs, subattrs + alen, sublen);
1380 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1381 struct list_node *n, *p;
1385 n = list_first(msg->attrs);
1387 attr = (struct tlv *)n->data;
1388 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1389 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1390 list_removedata(msg->attrs, attr);
1392 n = p ? list_next(p) : list_first(msg->attrs);
1399 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1400 struct list_node *n;
1403 for (n = list_first(addattrs); n; n = list_next(n)) {
1404 a = copytlv((struct tlv *)n->data);
1407 if (!radmsg_add(msg, a)) {
1415 int resizeattr(struct tlv *attr, uint8_t newlen) {
1418 if (newlen != attr->l) {
1419 newv = realloc(attr->v, newlen);
1428 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1429 size_t nmatch = 10, reslen = 0, start = 0;
1430 regmatch_t pmatch[10], *pfield;
1434 in = stringcopy((char *)attr->v, attr->l);
1438 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1443 out = modattr->replacement;
1445 for (i = start; out[i]; i++) {
1446 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1447 pfield = &pmatch[out[i + 1] - '0'];
1448 if (pfield->rm_so >= 0) {
1449 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1455 reslen += i - start;
1457 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1462 if (!resizeattr(attr, reslen)) {
1469 for (i = start; out[i]; i++) {
1470 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1471 pfield = &pmatch[out[i + 1] - '0'];
1472 if (pfield->rm_so >= 0) {
1473 memcpy(attr->v + reslen, out + start, i - start);
1474 reslen += i - start;
1475 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1476 reslen += pfield->rm_eo - pfield->rm_so;
1483 memcpy(attr->v + reslen, out + start, i - start);
1487 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1488 struct list_node *n, *m;
1490 for (n = list_first(msg->attrs); n; n = list_next(n))
1491 for (m = list_first(modattrs); m; m = list_next(m))
1492 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1493 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1498 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1501 if (rewrite->removeattrs || rewrite->removevendorattrs)
1502 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1503 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1505 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1510 int rewriteusername(struct request *rq, struct tlv *attr) {
1511 char *orig = (char *)tlv2str(attr);
1512 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1516 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1517 rq->origusername = (char *)orig;
1523 const char *radmsgtype2string(uint8_t code) {
1524 static const char *rad_msg_names[] = {
1525 "", "Access-Request", "Access-Accept", "Access-Reject",
1526 "Accounting-Request", "Accounting-Response", "", "",
1527 "", "", "", "Access-Challenge",
1528 "Status-Server", "Status-Client"
1530 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1533 void char2hex(char *h, unsigned char c) {
1534 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1535 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1536 h[0] = hexdigits[c / 16];
1537 h[1] = hexdigits[c % 16];
1541 uint8_t *radattr2ascii(struct tlv *attr) {
1549 for (i = 0; i < attr->l; i++)
1550 if (attr->v[i] < 32 || attr->v[i] > 126)
1553 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1560 for (i = 0; i < attr->l; i++)
1561 if (attr->v[i] < 32 || attr->v[i] > 126) {
1563 char2hex((char *)d, attr->v[i]);
1571 void acclog(struct radmsg *msg, char *host) {
1575 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1577 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1580 username = radattr2ascii(attr);
1582 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1587 void respondaccounting(struct request *rq) {
1590 msg = radmsg_init(RAD_Accounting_Response, rq->msg->id, rq->msg->auth);
1592 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1593 sendreply(rq->from, msg, &rq->fromsa, rq->fromudpsock);
1595 debug(DBG_ERR, "respondaccounting: malloc failed");
1598 void respondstatusserver(struct request *rq) {
1601 msg = radmsg_init(RAD_Access_Accept, rq->msg->id, rq->msg->auth);
1603 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1604 sendreply(rq->from, msg, &rq->fromsa, rq->fromudpsock);
1606 debug(DBG_ERR, "respondstatusserver: malloc failed");
1609 void respondreject(struct request *rq, char *message) {
1613 msg = radmsg_init(RAD_Access_Reject, rq->msg->id, rq->msg->auth);
1615 debug(DBG_ERR, "respondreject: malloc failed");
1618 if (message && *message) {
1619 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1620 if (!attr || !radmsg_add(msg, attr)) {
1623 debug(DBG_ERR, "respondreject: malloc failed");
1628 debug(DBG_DBG, "respondreject: responding to %s", rq->from->conf->host);
1629 sendreply(rq->from, msg, &rq->fromsa, rq->fromudpsock);
1632 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1633 struct list_node *entry;
1634 struct clsrvconf *server, *best = NULL, *first = NULL;
1636 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1637 server = (struct clsrvconf *)entry->data;
1638 if (!server->servers)
1642 if (!server->servers->connectionok)
1644 if (!server->servers->lostrqs)
1650 if (server->servers->lostrqs < best->servers->lostrqs)
1653 return best ? best : first;
1656 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1657 struct clsrvconf *srvconf;
1658 char *id = (char *)tlv2str(username);
1662 *realm = id2realm(realms, id);
1667 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1668 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1673 if (!acc && !srvconf->servers)
1674 adddynamicrealmserver(*realm, srvconf, id);
1676 return srvconf->servers;
1679 /* returns 0 if validation/authentication fails, else 1 */
1680 int radsrv(struct request *rq) {
1681 struct radmsg *msg = NULL;
1683 uint8_t *userascii = NULL;
1684 unsigned char newauth[16];
1685 struct realm *realm = NULL;
1686 struct server *to = NULL;
1688 msg = buf2radmsg(rq->buf, (uint8_t *)rq->from->conf->secret, NULL);
1690 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1695 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1697 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1698 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1702 if (msg->code == RAD_Status_Server) {
1703 respondstatusserver(rq);
1707 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1709 if (rq->from->conf->rewritein && !dorewrite(msg, rq->from->conf->rewritein))
1712 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1714 if (msg->code == RAD_Accounting_Request) {
1715 acclog(msg, rq->from->conf->host);
1716 respondaccounting(rq);
1718 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1722 if (rq->from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1723 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1727 userascii = radattr2ascii(attr);
1730 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1732 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1734 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1738 if (realm->message && msg->code == RAD_Access_Request) {
1739 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
1740 respondreject(rq, realm->message);
1741 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1742 acclog(msg, rq->from->conf->host);
1743 respondaccounting(rq);
1751 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
1752 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1753 rq->from->conf->name, to->conf->name);
1757 if (rqinqueue(to, rq->from, msg->id, msg->code)) {
1758 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1759 radmsgtype2string(msg->code), rq->from->conf->host, msg->id);
1763 if (msg->code != RAD_Accounting_Request) {
1764 if (!RAND_bytes(newauth, 16)) {
1765 debug(DBG_WARN, "radsrv: failed to generate random auth");
1771 printfchars(NULL, "auth", "%02x ", auth, 16);
1774 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1776 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1777 if (!pwdrecrypt(attr->v, attr->l, rq->from->conf->secret, to->conf->secret, msg->auth, newauth))
1781 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1783 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1784 if (!pwdrecrypt(attr->v, attr->l, rq->from->conf->secret, to->conf->secret, msg->auth, newauth))
1788 rq->origid = msg->id;
1789 memcpy(rq->origauth, msg->auth, 16);
1790 memcpy(msg->auth, newauth, 16);
1792 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1805 void replyh(struct server *server, unsigned char *buf) {
1806 struct client *from;
1809 unsigned char *subattrs;
1810 struct sockaddr_storage fromsa;
1811 uint8_t *username, *stationid;
1812 struct radmsg *msg = NULL;
1814 struct list_node *node;
1816 server->connectionok = 1;
1817 server->lostrqs = 0;
1819 rq = server->requests + buf[1];
1820 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rq->msg->auth);
1824 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1827 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1828 && msg->code != RAD_Accounting_Response) {
1829 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1833 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1835 pthread_mutex_lock(&server->newrq_mutex);
1836 if (!rq->buf || !rq->tries) {
1837 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1842 debug(DBG_INFO, "replyh: already received, ignoring reply");
1846 gettimeofday(&server->lastrcv, NULL);
1848 if (rq->msg->code == RAD_Status_Server) {
1850 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1854 gettimeofday(&server->lastreply, NULL);
1858 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1862 if (server->conf->rewritein && !dorewrite(msg, rq->from->conf->rewritein)) {
1863 debug(DBG_WARN, "replyh: rewritein failed");
1868 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1869 attr = (struct tlv *)node->data;
1870 if (attr->t != RAD_Attr_Vendor_Specific)
1874 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1877 sublen = attr->l - 4;
1878 subattrs = attr->v + 4;
1879 if (!attrvalidate(subattrs, sublen) ||
1880 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1881 rq, server->conf->secret, from->conf->secret) ||
1882 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1883 rq, server->conf->secret, from->conf->secret))
1887 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1891 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1892 username = radattr2ascii(radmsg_gettype(rq->msg, RAD_Attr_User_Name));
1894 stationid = radattr2ascii(radmsg_gettype(rq->msg, RAD_Attr_Calling_Station_Id));
1896 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1897 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1900 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(msg->code), username, server->conf->host);
1905 msg->id = (char)rq->origid;
1906 memcpy(msg->auth, rq->origauth, 16);
1909 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1912 if (rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1913 if (!resizeattr(attr, strlen(rq->origusername))) {
1914 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1917 memcpy(attr->v, rq->origusername, strlen(rq->origusername));
1920 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1921 debug(DBG_WARN, "replyh: rewriteout failed");
1925 fromsa = rq->fromsa; /* only needed for UDP */
1926 /* once we set received = 1, rq may be reused */
1929 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
1930 sendreply(from, msg, &fromsa, rq->fromudpsock);
1931 pthread_mutex_unlock(&server->newrq_mutex);
1936 pthread_mutex_unlock(&server->newrq_mutex);
1940 struct radmsg *createstatsrvmsg() {
1944 msg = radmsg_init(RAD_Status_Server, 0, NULL);
1948 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
1953 if (!radmsg_add(msg, attr)) {
1961 /* code for removing state not finished */
1962 void *clientwr(void *arg) {
1963 struct server *server = (struct server *)arg;
1965 pthread_t clientrdth;
1966 int i, secs, dynconffail = 0;
1968 struct timeval now, laststatsrv;
1969 struct timespec timeout;
1970 struct request statsrvrq;
1971 struct clsrvconf *conf;
1973 conf = server->conf;
1975 if (server->dynamiclookuparg && !dynamicconfig(server)) {
1980 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
1981 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
1985 memset(&timeout, 0, sizeof(struct timespec));
1987 if (conf->statusserver) {
1988 gettimeofday(&server->lastrcv, NULL);
1989 gettimeofday(&laststatsrv, NULL);
1992 if (conf->pdef->connecter) {
1993 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
1995 server->connectionok = 1;
1996 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
1997 debug(DBG_ERR, "clientwr: pthread_create failed");
2001 server->connectionok = 1;
2004 pthread_mutex_lock(&server->newrq_mutex);
2005 if (!server->newrq) {
2006 gettimeofday(&now, NULL);
2007 /* random 0-7 seconds */
2008 RAND_bytes(&rnd, 1);
2010 if (conf->statusserver) {
2011 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2012 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2013 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2015 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2016 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2019 if (timeout.tv_sec > now.tv_sec)
2020 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2022 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2025 if (server->newrq) {
2026 debug(DBG_DBG, "clientwr: got new request");
2031 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2033 pthread_mutex_unlock(&server->newrq_mutex);
2035 for (i = 0; i < MAX_REQUESTS; i++) {
2036 if (server->clientrdgone) {
2037 pthread_join(clientrdth, NULL);
2040 pthread_mutex_lock(&server->newrq_mutex);
2041 while (i < MAX_REQUESTS && !server->requests[i].buf)
2043 if (i == MAX_REQUESTS) {
2044 pthread_mutex_unlock(&server->newrq_mutex);
2047 rq = server->requests + i;
2050 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2052 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2054 /* setting this to NULL means that it can be reused */
2057 pthread_mutex_unlock(&server->newrq_mutex);
2061 gettimeofday(&now, NULL);
2062 if (now.tv_sec < rq->expiry.tv_sec) {
2063 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2064 timeout.tv_sec = rq->expiry.tv_sec;
2065 pthread_mutex_unlock(&server->newrq_mutex);
2069 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2070 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2071 if (conf->statusserver) {
2072 if (*rq->buf == RAD_Status_Server) {
2073 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2074 if (server->lostrqs < 255)
2078 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2079 if (server->lostrqs < 255)
2083 /* setting this to NULL means that it can be reused */
2085 pthread_mutex_unlock(&server->newrq_mutex);
2088 pthread_mutex_unlock(&server->newrq_mutex);
2090 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2091 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2092 timeout.tv_sec = rq->expiry.tv_sec;
2094 conf->pdef->clientradput(server, server->requests[i].buf);
2096 if (conf->statusserver) {
2097 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2098 gettimeofday(&now, NULL);
2099 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2101 memset(&statsrvrq, 0, sizeof(struct request));
2102 statsrvrq.msg = createstatsrvmsg();
2103 if (statsrvrq.msg) {
2104 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2105 sendrq(server, &statsrvrq);
2111 conf->servers = NULL;
2112 if (server->dynamiclookuparg) {
2113 removeserversubrealms(realms, conf);
2117 freeclsrvconf(conf);
2119 freeserver(server, 1);
2120 ERR_remove_state(0);
2124 void createlistener(uint8_t type, char *arg) {
2126 struct clsrvconf *listenres;
2127 struct addrinfo *res;
2128 int s = -1, on = 1, *sp = NULL;
2130 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2132 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2134 for (res = listenres->addrinfo; res; res = res->ai_next) {
2135 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2137 debug(DBG_WARN, "createlistener: socket failed");
2140 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2142 if (res->ai_family == AF_INET6)
2143 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2145 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2146 debug(DBG_WARN, "createlistener: bind failed");
2152 sp = malloc(sizeof(int));
2154 debugx(1, DBG_ERR, "malloc failed");
2156 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2157 debugx(1, DBG_ERR, "pthread_create failed");
2161 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2163 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2164 listenres->host ? listenres->host : "*", listenres->port);
2165 freeclsrvres(listenres);
2168 void createlisteners(uint8_t type, char **args) {
2172 for (i = 0; args[i]; i++)
2173 createlistener(type, args[i]);
2175 createlistener(type, NULL);
2179 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2183 w = where & ~SSL_ST_MASK;
2185 if (w & SSL_ST_CONNECT)
2187 else if (w & SSL_ST_ACCEPT)
2192 if (where & SSL_CB_LOOP)
2193 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2194 else if (where & SSL_CB_ALERT) {
2195 s = (where & SSL_CB_READ) ? "read" : "write";
2196 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2198 else if (where & SSL_CB_EXIT) {
2200 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2202 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2207 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2208 SSL_CTX *ctx = NULL;
2209 STACK_OF(X509_NAME) *calist;
2212 unsigned long error;
2215 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2216 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2217 for (i = 0; i < CRYPTO_num_locks(); i++) {
2218 ssl_lock_count[i] = 0;
2219 pthread_mutex_init(&ssl_locks[i], NULL);
2221 CRYPTO_set_id_callback(ssl_thread_id);
2222 CRYPTO_set_locking_callback(ssl_locking_callback);
2224 SSL_load_error_strings();
2227 while (!RAND_status()) {
2228 time_t t = time(NULL);
2229 pid_t pid = getpid();
2230 RAND_seed((unsigned char *)&t, sizeof(time_t));
2231 RAND_seed((unsigned char *)&pid, sizeof(pid));
2237 ctx = SSL_CTX_new(TLSv1_method());
2239 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2243 ctx = SSL_CTX_new(DTLSv1_method());
2245 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2247 SSL_CTX_set_read_ahead(ctx, 1);
2251 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2255 if (conf->certkeypwd) {
2256 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2257 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2259 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2260 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2261 !SSL_CTX_check_private_key(ctx) ||
2262 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2263 while ((error = ERR_get_error()))
2264 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2265 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2270 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2271 if (!conf->cacertfile || calist) {
2272 if (conf->cacertpath) {
2274 calist = sk_X509_NAME_new_null();
2275 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2276 sk_X509_NAME_free(calist);
2282 while ((error = ERR_get_error()))
2283 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2284 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2288 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2289 SSL_CTX_set_client_CA_list(ctx, calist);
2291 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2292 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2294 if (conf->crlcheck) {
2295 x509_s = SSL_CTX_get_cert_store(ctx);
2296 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2299 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2303 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2306 t = hash_read(tlsconfs, alt1, strlen(alt1));
2308 t = hash_read(tlsconfs, alt2, strlen(alt2));
2316 t->tlsctx = tlscreatectx(RAD_TLS, t);
2320 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2326 struct list *addsrvconfs(char *value, char **names) {
2327 struct list *conflist;
2329 struct list_node *entry;
2330 struct clsrvconf *conf = NULL;
2332 if (!names || !*names)
2335 conflist = list_create();
2337 debug(DBG_ERR, "malloc failed");
2341 for (n = 0; names[n]; n++) {
2342 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2343 conf = (struct clsrvconf *)entry->data;
2344 if (!strcasecmp(names[n], conf->name))
2348 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2349 list_destroy(conflist);
2352 if (!list_push(conflist, conf)) {
2353 debug(DBG_ERR, "malloc failed");
2354 list_destroy(conflist);
2357 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2362 void freerealm(struct realm *realm) {
2366 free(realm->message);
2367 regfree(&realm->regex);
2368 pthread_mutex_destroy(&realm->subrealms_mutex);
2369 if (realm->subrealms)
2370 list_destroy(realm->subrealms);
2371 if (realm->srvconfs) {
2372 /* emptying list without freeing data */
2373 while (list_shift(realm->srvconfs));
2374 list_destroy(realm->srvconfs);
2376 if (realm->accsrvconfs) {
2377 /* emptying list without freeing data */
2378 while (list_shift(realm->accsrvconfs));
2379 list_destroy(realm->accsrvconfs);
2384 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2386 struct realm *realm;
2387 char *s, *regex = NULL;
2389 if (*value == '/') {
2390 /* regexp, remove optional trailing / if present */
2391 if (value[strlen(value) - 1] == '/')
2392 value[strlen(value) - 1] = '\0';
2394 /* not a regexp, let us make it one */
2395 if (*value == '*' && !value[1])
2396 regex = stringcopy(".*", 0);
2398 for (n = 0, s = value; *s;)
2401 regex = malloc(strlen(value) + n + 3);
2404 for (n = 1, s = value; *s; s++) {
2414 debug(DBG_ERR, "malloc failed");
2418 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2421 realm = malloc(sizeof(struct realm));
2423 debug(DBG_ERR, "malloc failed");
2426 memset(realm, 0, sizeof(struct realm));
2428 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2429 debug(DBG_ERR, "mutex init failed");
2435 realm->name = stringcopy(value, 0);
2437 debug(DBG_ERR, "malloc failed");
2440 if (message && strlen(message) > 253) {
2441 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2444 realm->message = message;
2445 realm->accresp = accresp;
2447 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2448 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2452 if (servers && *servers) {
2453 realm->srvconfs = addsrvconfs(value, servers);
2454 if (!realm->srvconfs)
2458 if (accservers && *accservers) {
2459 realm->accsrvconfs = addsrvconfs(value, accservers);
2460 if (!realm->accsrvconfs)
2464 if (!list_push(realmlist, realm)) {
2465 debug(DBG_ERR, "malloc failed");
2466 pthread_mutex_destroy(&realm->subrealms_mutex);
2470 debug(DBG_DBG, "addrealm: added realm %s", value);
2480 for (n = 0; servers[n]; n++)
2485 for (n = 0; accservers[n]; n++)
2486 free(accservers[n]);
2492 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2493 struct clsrvconf *srvconf;
2494 struct realm *newrealm = NULL;
2495 char *realmname, *s;
2498 if (!conf->dynamiclookupcommand)
2501 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2502 realmname = strrchr(id, '@');
2508 for (s = realmname; *s; s++)
2509 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2512 pthread_mutex_lock(&realm->subrealms_mutex);
2513 /* exit if we now already got a matching subrealm */
2514 if (id2realm(realm->subrealms, id))
2516 srvconf = malloc(sizeof(struct clsrvconf));
2518 debug(DBG_ERR, "malloc failed");
2522 if (!addserver(srvconf))
2525 if (!realm->subrealms)
2526 realm->subrealms = list_create();
2527 if (!realm->subrealms)
2529 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2533 /* add server and accserver to newrealm */
2534 newrealm->srvconfs = list_create();
2535 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2536 debug(DBG_ERR, "malloc failed");
2539 newrealm->accsrvconfs = list_create();
2540 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2541 debug(DBG_ERR, "malloc failed");
2545 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2547 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2548 debug(DBG_ERR, "pthread_create failed");
2551 pthread_detach(clientth);
2556 list_removedata(realm->subrealms, newrealm);
2557 freerealm(newrealm);
2558 if (!list_first(realm->subrealms)) {
2559 list_destroy(realm->subrealms);
2560 realm->subrealms = NULL;
2563 freeserver(srvconf->servers, 1);
2565 debug(DBG_ERR, "failed to create dynamic server");
2568 pthread_mutex_unlock(&realm->subrealms_mutex);
2571 int dynamicconfig(struct server *server) {
2572 int ok, fd[2], status;
2574 struct clsrvconf *conf = server->conf;
2575 struct gconffile *cf = NULL;
2577 /* for now we only learn hostname/address */
2578 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2581 debug(DBG_ERR, "dynamicconfig: pipe error");
2586 debug(DBG_ERR, "dynamicconfig: fork error");
2590 } else if (pid == 0) {
2593 if (fd[1] != STDOUT_FILENO) {
2594 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2595 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2598 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2599 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2603 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2604 ok = getgenericconfig(&cf, NULL,
2605 "Server", CONF_CBK, confserver_cb, (void *)conf,
2610 if (waitpid(pid, &status, 0) < 0) {
2611 debug(DBG_ERR, "dynamicconfig: wait error");
2616 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2624 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2628 int addmatchcertattr(struct clsrvconf *conf) {
2632 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2633 r = &conf->certcnregex;
2634 v = conf->matchcertattr + 4;
2635 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2636 r = &conf->certuriregex;
2637 v = conf->matchcertattr + 20;
2642 /* regexp, remove optional trailing / if present */
2643 if (v[strlen(v) - 1] == '/')
2644 v[strlen(v) - 1] = '\0';
2648 *r = malloc(sizeof(regex_t));
2650 debug(DBG_ERR, "malloc failed");
2653 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2656 debug(DBG_ERR, "failed to compile regular expression %s", v);
2662 /* should accept both names and numeric values, only numeric right now */
2663 uint8_t attrname2val(char *attrname) {
2666 val = atoi(attrname);
2667 return val > 0 && val < 256 ? val : 0;
2670 /* should accept both names and numeric values, only numeric right now */
2671 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2674 *vendor = atoi(attrname);
2675 s = strchr(attrname, ':');
2680 *type = atoi(s + 1);
2681 return *type >= 0 && *type < 256;
2684 /* should accept both names and numeric values, only numeric right now */
2685 struct tlv *extractattr(char *nameval) {
2690 s = strchr(nameval, ':');
2691 name = atoi(nameval);
2692 if (!s || name < 1 || name > 255)
2694 len = strlen(s + 1);
2697 a = malloc(sizeof(struct tlv));
2700 a->v = (uint8_t *)stringcopy(s + 1, 0);
2710 /* should accept both names and numeric values, only numeric right now */
2711 struct modattr *extractmodattr(char *nameval) {
2716 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2720 s = strchr(nameval, ':');
2721 name = atoi(nameval);
2722 if (!s || name < 1 || name > 255 || s[1] != '/')
2726 /* regexp, remove optional trailing / if present */
2727 if (s[strlen(s) - 1] == '/')
2728 s[strlen(s) - 1] = '\0';
2736 m = malloc(sizeof(struct modattr));
2738 debug(DBG_ERR, "malloc failed");
2743 m->replacement = stringcopy(t, 0);
2744 if (!m->replacement) {
2746 debug(DBG_ERR, "malloc failed");
2750 m->regex = malloc(sizeof(regex_t));
2752 free(m->replacement);
2754 debug(DBG_ERR, "malloc failed");
2758 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2760 free(m->replacement);
2762 debug(DBG_ERR, "failed to compile regular expression %s", s);
2769 struct rewrite *getrewrite(char *alt1, char *alt2) {
2772 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2774 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2779 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2780 struct rewrite *rewrite = NULL;
2782 uint8_t *rma = NULL;
2783 uint32_t *p, *rmva = NULL;
2784 struct list *adda = NULL, *moda = NULL;
2789 for (n = 0; rmattrs[n]; n++);
2790 rma = calloc(n + 1, sizeof(uint8_t));
2792 debugx(1, DBG_ERR, "malloc failed");
2794 for (i = 0; i < n; i++) {
2795 if (!(rma[i] = attrname2val(rmattrs[i])))
2796 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2804 for (n = 0; rmvattrs[n]; n++);
2805 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2807 debugx(1, DBG_ERR, "malloc failed");
2809 for (p = rmva, i = 0; i < n; i++, p += 2) {
2810 if (!vattrname2val(rmvattrs[i], p, p + 1))
2811 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2819 adda = list_create();
2821 debugx(1, DBG_ERR, "malloc failed");
2822 for (i = 0; addattrs[i]; i++) {
2823 a = extractattr(addattrs[i]);
2825 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2827 if (!list_push(adda, a))
2828 debugx(1, DBG_ERR, "malloc failed");
2834 moda = list_create();
2836 debugx(1, DBG_ERR, "malloc failed");
2837 for (i = 0; modattrs[i]; i++) {
2838 m = extractmodattr(modattrs[i]);
2840 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2842 if (!list_push(moda, m))
2843 debugx(1, DBG_ERR, "malloc failed");
2848 if (rma || rmva || adda || moda) {
2849 rewrite = malloc(sizeof(struct rewrite));
2851 debugx(1, DBG_ERR, "malloc failed");
2852 rewrite->removeattrs = rma;
2853 rewrite->removevendorattrs = rmva;
2854 rewrite->addattrs = adda;
2855 rewrite->modattrs = moda;
2858 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2859 debugx(1, DBG_ERR, "malloc failed");
2860 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2863 void freeclsrvconf(struct clsrvconf *conf) {
2869 free(conf->matchcertattr);
2870 if (conf->certcnregex)
2871 regfree(conf->certcnregex);
2872 if (conf->certuriregex)
2873 regfree(conf->certuriregex);
2874 free(conf->confrewritein);
2875 free(conf->confrewriteout);
2876 if (conf->rewriteusername) {
2877 if (conf->rewriteusername->regex)
2878 regfree(conf->rewriteusername->regex);
2879 free(conf->rewriteusername->replacement);
2880 free(conf->rewriteusername);
2882 free(conf->dynamiclookupcommand);
2883 free(conf->rewritein);
2884 free(conf->rewriteout);
2886 freeaddrinfo(conf->addrinfo);
2887 /* not touching ssl_ctx, clients and servers */
2891 int mergeconfstring(char **dst, char **src) {
2900 t = stringcopy(*dst, 0);
2902 debug(DBG_ERR, "malloc failed");
2910 /* assumes dst is a shallow copy */
2911 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2912 if (!mergeconfstring(&dst->name, &src->name) ||
2913 !mergeconfstring(&dst->host, &src->host) ||
2914 !mergeconfstring(&dst->port, &src->port) ||
2915 !mergeconfstring(&dst->secret, &src->secret) ||
2916 !mergeconfstring(&dst->tls, &src->tls) ||
2917 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2918 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2919 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2920 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2923 dst->pdef = src->pdef;
2924 dst->statusserver = src->statusserver;
2925 dst->certnamecheck = src->certnamecheck;
2926 if (src->retryinterval != 255)
2927 dst->retryinterval = src->retryinterval;
2928 if (src->retrycount != 255)
2929 dst->retrycount = src->retrycount;
2933 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
2934 struct clsrvconf *conf;
2935 char *conftype = NULL, *rewriteinalias = NULL;
2937 debug(DBG_DBG, "confclient_cb called for %s", block);
2939 conf = malloc(sizeof(struct clsrvconf));
2940 if (!conf || !list_push(clconfs, conf))
2941 debugx(1, DBG_ERR, "malloc failed");
2942 memset(conf, 0, sizeof(struct clsrvconf));
2943 conf->certnamecheck = 1;
2945 if (!getgenericconfig(cf, block,
2946 "type", CONF_STR, &conftype,
2947 "host", CONF_STR, &conf->host,
2948 "secret", CONF_STR, &conf->secret,
2949 "tls", CONF_STR, &conf->tls,
2950 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
2951 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
2952 "rewrite", CONF_STR, &rewriteinalias,
2953 "rewriteIn", CONF_STR, &conf->confrewritein,
2954 "rewriteOut", CONF_STR, &conf->confrewriteout,
2955 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
2958 debugx(1, DBG_ERR, "configuration error");
2960 conf->name = stringcopy(val, 0);
2962 conf->host = stringcopy(val, 0);
2963 if (!conf->name || !conf->host)
2964 debugx(1, DBG_ERR, "malloc failed");
2967 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
2968 conf->type = protoname2int(conftype);
2969 conf->pdef = &protodefs[conf->type];
2970 if (!conf->pdef->name)
2971 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
2974 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
2975 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
2977 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2978 if (conf->matchcertattr && !addmatchcertattr(conf))
2979 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2982 if (!conf->confrewritein)
2983 conf->confrewritein = rewriteinalias;
2985 free(rewriteinalias);
2986 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
2987 if (conf->confrewriteout)
2988 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
2990 if (conf->confrewriteusername) {
2991 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
2992 if (!conf->rewriteusername)
2993 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2996 if (!resolvepeer(conf, 0))
2997 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2999 if (!conf->secret) {
3000 if (!conf->pdef->secretdefault)
3001 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3002 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3004 debugx(1, DBG_ERR, "malloc failed");
3009 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3010 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3011 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3012 if (!conf->ssl_ctx) {
3013 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3016 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3017 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3023 conf->port = stringcopy(conf->pdef->portdefault, 0);
3025 debug(DBG_ERR, "malloc failed");
3030 if (conf->retryinterval == 255)
3031 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3032 if (conf->retrycount == 255)
3033 conf->retrycount = protodefs[conf->type].retrycountdefault;
3035 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3036 if (conf->confrewriteout)
3037 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3039 if (!conf->secret) {
3040 if (!conf->pdef->secretdefault) {
3041 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3044 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3045 if (!conf->secret) {
3046 debug(DBG_ERR, "malloc failed");
3051 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3052 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3058 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3059 struct clsrvconf *conf, *resconf;
3060 char *conftype = NULL, *rewriteinalias = NULL;
3061 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3063 debug(DBG_DBG, "confserver_cb called for %s", block);
3065 conf = malloc(sizeof(struct clsrvconf));
3067 debug(DBG_ERR, "malloc failed");
3070 memset(conf, 0, sizeof(struct clsrvconf));
3071 resconf = (struct clsrvconf *)arg;
3073 conf->statusserver = resconf->statusserver;
3074 conf->certnamecheck = resconf->certnamecheck;
3076 conf->certnamecheck = 1;
3078 if (!getgenericconfig(cf, block,
3079 "type", CONF_STR, &conftype,
3080 "host", CONF_STR, &conf->host,
3081 "port", CONF_STR, &conf->port,
3082 "secret", CONF_STR, &conf->secret,
3083 "tls", CONF_STR, &conf->tls,
3084 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3085 "rewrite", CONF_STR, &rewriteinalias,
3086 "rewriteIn", CONF_STR, &conf->confrewritein,
3087 "rewriteOut", CONF_STR, &conf->confrewriteout,
3088 "StatusServer", CONF_BLN, &conf->statusserver,
3089 "RetryInterval", CONF_LINT, &retryinterval,
3090 "RetryCount", CONF_LINT, &retrycount,
3091 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3092 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3095 debug(DBG_ERR, "configuration error");
3099 conf->name = stringcopy(val, 0);
3101 debug(DBG_ERR, "malloc failed");
3105 conf->host = stringcopy(val, 0);
3107 debug(DBG_ERR, "malloc failed");
3113 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3114 conf->type = protoname2int(conftype);
3115 conf->pdef = &protodefs[conf->type];
3116 if (!conf->pdef->name) {
3117 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3123 if (!conf->confrewritein)
3124 conf->confrewritein = rewriteinalias;
3126 free(rewriteinalias);
3127 rewriteinalias = NULL;
3129 if (retryinterval != LONG_MIN) {
3130 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3131 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3134 conf->retryinterval = (uint8_t)retryinterval;
3136 conf->retryinterval = 255;
3138 if (retrycount != LONG_MIN) {
3139 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3140 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3143 conf->retrycount = (uint8_t)retrycount;
3145 conf->retrycount = 255;
3148 if (!mergesrvconf(resconf, conf))
3152 if (conf->dynamiclookupcommand) {
3153 free(conf->dynamiclookupcommand);
3154 conf->dynamiclookupcommand = NULL;
3158 if (resconf || !conf->dynamiclookupcommand) {
3159 if (!compileserverconfig(conf, block))
3166 if (!list_push(srvconfs, conf)) {
3167 debug(DBG_ERR, "malloc failed");
3174 free(rewriteinalias);
3175 freeclsrvconf(conf);
3179 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3180 char **servers = NULL, **accservers = NULL, *msg = NULL;
3181 uint8_t accresp = 0;
3183 debug(DBG_DBG, "confrealm_cb called for %s", block);
3185 if (!getgenericconfig(cf, block,
3186 "server", CONF_MSTR, &servers,
3187 "accountingServer", CONF_MSTR, &accservers,
3188 "ReplyMessage", CONF_STR, &msg,
3189 "AccountingResponse", CONF_BLN, &accresp,
3192 debugx(1, DBG_ERR, "configuration error");
3194 addrealm(realms, val, servers, accservers, msg, accresp);
3198 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3201 debug(DBG_DBG, "conftls_cb called for %s", block);
3203 conf = malloc(sizeof(struct tls));
3205 debug(DBG_ERR, "conftls_cb: malloc failed");
3208 memset(conf, 0, sizeof(struct tls));
3210 if (!getgenericconfig(cf, block,
3211 "CACertificateFile", CONF_STR, &conf->cacertfile,
3212 "CACertificatePath", CONF_STR, &conf->cacertpath,
3213 "CertificateFile", CONF_STR, &conf->certfile,
3214 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3215 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3216 "CRLCheck", CONF_BLN, &conf->crlcheck,
3219 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3222 if (!conf->certfile || !conf->certkeyfile) {
3223 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3226 if (!conf->cacertfile && !conf->cacertpath) {
3227 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3231 conf->name = stringcopy(val, 0);
3233 debug(DBG_ERR, "conftls_cb: malloc failed");
3237 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3238 debug(DBG_ERR, "conftls_cb: malloc failed");
3242 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3246 free(conf->cacertfile);
3247 free(conf->cacertpath);
3248 free(conf->certfile);
3249 free(conf->certkeyfile);
3250 free(conf->certkeypwd);
3255 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3256 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3258 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3260 if (!getgenericconfig(cf, block,
3261 "removeAttribute", CONF_MSTR, &rmattrs,
3262 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3263 "addAttribute", CONF_MSTR, &addattrs,
3264 "modifyAttribute", CONF_MSTR, &modattrs,
3267 debugx(1, DBG_ERR, "configuration error");
3268 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3272 void getmainconfig(const char *configfile) {
3273 long int loglevel = LONG_MIN;
3274 struct gconffile *cfs;
3276 cfs = openconfigfile(configfile);
3277 memset(&options, 0, sizeof(options));
3279 clconfs = list_create();
3281 debugx(1, DBG_ERR, "malloc failed");
3283 srvconfs = list_create();
3285 debugx(1, DBG_ERR, "malloc failed");
3287 realms = list_create();
3289 debugx(1, DBG_ERR, "malloc failed");
3291 tlsconfs = hash_create();
3293 debugx(1, DBG_ERR, "malloc failed");
3295 rewriteconfs = hash_create();
3297 debugx(1, DBG_ERR, "malloc failed");
3299 if (!getgenericconfig(&cfs, NULL,
3300 "ListenUDP", CONF_MSTR, &options.listenudp,
3301 "ListenTCP", CONF_MSTR, &options.listentcp,
3302 "ListenTLS", CONF_MSTR, &options.listentls,
3303 "ListenDTLS", CONF_MSTR, &options.listendtls,
3304 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3305 "SourceUDP", CONF_STR, &options.sourceudp,
3306 "SourceTCP", CONF_STR, &options.sourcetcp,
3307 "SourceTLS", CONF_STR, &options.sourcetls,
3308 "SourceDTLS", CONF_STR, &options.sourcedtls,
3309 "LogLevel", CONF_LINT, &loglevel,
3310 "LogDestination", CONF_STR, &options.logdestination,
3311 "LoopPrevention", CONF_BLN, &options.loopprevention,
3312 "Client", CONF_CBK, confclient_cb, NULL,
3313 "Server", CONF_CBK, confserver_cb, NULL,
3314 "Realm", CONF_CBK, confrealm_cb, NULL,
3315 "TLS", CONF_CBK, conftls_cb, NULL,
3316 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3319 debugx(1, DBG_ERR, "configuration error");
3321 if (loglevel != LONG_MIN) {
3322 if (loglevel < 1 || loglevel > 4)
3323 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3324 options.loglevel = (uint8_t)loglevel;
3328 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3331 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3334 *configfile = optarg;
3337 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3338 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3339 *loglevel = *optarg - '0';
3348 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3353 if (!(argc - optind))
3357 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3361 int daemon(int a, int b) {
3369 for (i = 0; i < 3; i++) {
3371 open("/dev/null", O_RDWR);
3377 void *sighandler(void *arg) {
3382 sigemptyset(&sigset);
3383 sigaddset(&sigset, SIGPIPE);
3384 sigwait(&sigset, &sig);
3385 /* only get SIGPIPE right now, so could simplify below code */
3388 /* completely ignoring this */
3391 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3394 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3399 int main(int argc, char **argv) {
3402 struct list_node *entry;
3403 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3404 char *configfile = NULL;
3405 struct clsrvconf *srvconf;
3408 debug_init("radsecproxy");
3409 debug_set_level(DEBUG_LEVEL);
3411 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3413 debug_set_level(loglevel);
3414 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3416 options.loglevel = loglevel;
3417 else if (options.loglevel)
3418 debug_set_level(options.loglevel);
3420 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3421 free(options.logdestination);
3423 if (!list_first(clconfs))
3424 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3425 if (!list_first(realms))
3426 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3429 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3431 if (!foreground && (daemon(0, 0) < 0))
3432 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3434 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3436 sigemptyset(&sigset);
3437 /* exit on all but SIGPIPE, ignore more? */
3438 sigaddset(&sigset, SIGPIPE);
3439 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3440 pthread_create(&sigth, NULL, sighandler, NULL);
3442 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3443 srvconf = (struct clsrvconf *)entry->data;
3444 if (srvconf->dynamiclookupcommand)
3446 if (!addserver(srvconf))
3447 debugx(1, DBG_ERR, "failed to add server");
3448 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3449 (void *)(srvconf->servers)))
3450 debugx(1, DBG_ERR, "pthread_create failed");
3452 /* srcprotores for UDP no longer needed */
3453 if (srcprotores[RAD_UDP]) {
3454 freeaddrinfo(srcprotores[RAD_UDP]);
3455 srcprotores[RAD_UDP] = NULL;
3458 for (i = 0; protodefs[i].name; i++)
3459 if (protodefs[i].initextra)
3460 protodefs[i].initextra();
3462 if (find_clconf_type(RAD_TCP, NULL))
3463 createlisteners(RAD_TCP, options.listentcp);
3465 if (find_clconf_type(RAD_TLS, NULL))
3466 createlisteners(RAD_TLS, options.listentls);
3468 if (find_clconf_type(RAD_DTLS, NULL))
3469 createlisteners(RAD_DTLS, options.listendtls);
3471 if (find_clconf_type(RAD_UDP, NULL)) {
3472 createlisteners(RAD_UDP, options.listenudp);
3473 if (options.listenaccudp)
3474 createlisteners(RAD_UDP, options.listenaccudp);
3477 /* just hang around doing nothing, anything to do here? */