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()
35 * Need to remove UDP clients when no activity for a while...
36 * Remove expired stuff from clients request list?
40 #include <sys/socket.h>
41 #include <netinet/in.h>
50 #include <sys/types.h>
51 #include <sys/select.h>
54 #include <arpa/inet.h>
58 #include <openssl/ssl.h>
59 #include <openssl/rand.h>
60 #include <openssl/err.h>
61 #include <openssl/md5.h>
62 #include <openssl/hmac.h>
63 #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 freerq(struct request *rq);
94 void freerqoutdata(struct rqout *rqout);
95 void rmclientrq(struct request *rq, uint8_t id);
97 static const struct protodefs protodefs[] = {
98 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
99 NULL, /* secretdefault */
100 SOCK_DGRAM, /* socktype */
101 "1812", /* portdefault */
102 REQUEST_RETRY_COUNT, /* retrycountdefault */
103 10, /* retrycountmax */
104 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
105 60, /* retryintervalmax */
106 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
107 udpserverrd, /* listener */
108 &options.sourceudp, /* srcaddrport */
109 NULL, /* connecter */
110 NULL, /* clientconnreader */
111 clientradputudp, /* clientradput */
112 addclientudp, /* addclient */
113 addserverextraudp, /* addserverextra */
114 initextraudp /* initextra */
116 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
117 "mysecret", /* secretdefault */
118 SOCK_STREAM, /* socktype */
119 "2083", /* portdefault */
120 0, /* retrycountdefault */
121 0, /* retrycountmax */
122 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
123 60, /* retryintervalmax */
124 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
125 tlslistener, /* listener */
126 &options.sourcetls, /* srcaddrport */
127 tlsconnect, /* connecter */
128 tlsclientrd, /* clientconnreader */
129 clientradputtls, /* clientradput */
130 NULL, /* addclient */
131 NULL, /* addserverextra */
134 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
135 NULL, /* secretdefault */
136 SOCK_STREAM, /* socktype */
137 "1812", /* portdefault */
138 0, /* retrycountdefault */
139 0, /* retrycountmax */
140 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
141 60, /* retryintervalmax */
142 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
143 tcplistener, /* listener */
144 &options.sourcetcp, /* srcaddrport */
145 tcpconnect, /* connecter */
146 tcpclientrd, /* clientconnreader */
147 clientradputtcp, /* clientradput */
148 NULL, /* addclient */
149 NULL, /* addserverextra */
152 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
153 "mysecret", /* secretdefault */
154 SOCK_DGRAM, /* socktype */
155 "2083", /* portdefault */
156 REQUEST_RETRY_COUNT, /* retrycountdefault */
157 10, /* retrycountmax */
158 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
159 60, /* retryintervalmax */
160 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
161 udpdtlsserverrd, /* listener */
162 &options.sourcedtls, /* srcaddrport */
163 dtlsconnect, /* connecter */
164 dtlsclientrd, /* clientconnreader */
165 clientradputdtls, /* clientradput */
166 NULL, /* addclient */
167 addserverextradtls, /* addserverextra */
168 initextradtls /* initextra */
174 uint8_t protoname2int(const char *name) {
177 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
181 /* callbacks for making OpenSSL thread safe */
182 unsigned long ssl_thread_id() {
183 return (unsigned long)pthread_self();
186 void ssl_locking_callback(int mode, int type, const char *file, int line) {
187 if (mode & CRYPTO_LOCK) {
188 pthread_mutex_lock(&ssl_locks[type]);
189 ssl_lock_count[type]++;
191 pthread_mutex_unlock(&ssl_locks[type]);
194 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
195 int pwdlen = strlen(userdata);
196 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
198 memcpy(buf, userdata, pwdlen);
202 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
207 err_cert = X509_STORE_CTX_get_current_cert(ctx);
208 err = X509_STORE_CTX_get_error(ctx);
209 depth = X509_STORE_CTX_get_error_depth(ctx);
211 if (depth > MAX_CERT_DEPTH) {
213 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
214 X509_STORE_CTX_set_error(ctx, err);
218 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
219 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
222 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
223 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
224 debug(DBG_WARN, "\tIssuer=%s", buf);
226 case X509_V_ERR_CERT_NOT_YET_VALID:
227 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
228 debug(DBG_WARN, "\tCertificate not yet valid");
230 case X509_V_ERR_CERT_HAS_EXPIRED:
231 debug(DBG_WARN, "Certificate has expired");
233 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
234 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
239 printf("certificate verify returns %d\n", ok);
244 struct addrinfo *getsrcprotores(uint8_t type) {
245 return srcprotores[type];
248 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
249 struct addrinfo hints, *addrinfo, *res;
253 slash = conf->host ? strchr(conf->host, '/') : NULL;
257 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
261 if (*s < '0' || *s > '9') {
262 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
265 plen = atoi(slash + 1);
266 if (plen < 0 || plen > 128) {
267 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
272 memset(&hints, 0, sizeof(hints));
273 hints.ai_socktype = conf->pdef->socktype;
274 hints.ai_family = AF_UNSPEC;
275 hints.ai_flags = ai_flags;
276 if (!conf->host && !conf->port) {
277 /* getaddrinfo() doesn't like host and port to be NULL */
278 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
279 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
282 for (res = addrinfo; res; res = res->ai_next)
283 port_set(res->ai_addr, 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 freerq((struct request *)entry);
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, uint8_t lock) {
555 struct client *new = malloc(sizeof(struct client));
558 debug(DBG_ERR, "malloc failed");
563 pthread_mutex_lock(conf->lock);
564 if (!conf->clients) {
565 conf->clients = list_create();
566 if (!conf->clients) {
568 pthread_mutex_unlock(conf->lock);
569 debug(DBG_ERR, "malloc failed");
574 memset(new, 0, sizeof(struct client));
575 pthread_mutex_init(&new->lock, NULL);
577 if (conf->pdef->addclient)
578 conf->pdef->addclient(new);
580 new->replyq = newqueue();
581 list_push(conf->clients, new);
583 pthread_mutex_unlock(conf->lock);
587 void removeclient(struct client *client) {
591 pthread_mutex_lock(client->conf->lock);
592 if (client->conf->clients) {
593 pthread_mutex_lock(&client->lock);
594 removequeue(client->replyq);
595 list_removedata(client->conf->clients, client);
596 pthread_mutex_unlock(&client->lock);
597 pthread_mutex_destroy(&client->lock);
601 pthread_mutex_unlock(client->conf->lock);
604 void removeclientrqs(struct client *client) {
605 struct list_node *entry;
606 struct server *server;
610 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
611 server = ((struct clsrvconf *)entry->data)->servers;
614 for (i = 0; i < MAX_REQUESTS; i++) {
615 rqout = server->requests + i;
616 pthread_mutex_lock(rqout->lock);
617 if (rqout->rq && rqout->rq->from == client)
618 freerqoutdata(rqout);
619 pthread_mutex_unlock(rqout->lock);
624 void freeserver(struct server *server, uint8_t destroymutex) {
625 struct rqout *rqout, *end;
630 if (server->requests) {
631 rqout = server->requests;
632 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
633 freerqoutdata(rqout);
634 pthread_mutex_destroy(rqout->lock);
637 free(server->requests);
640 freebios(server->rbios);
641 free(server->dynamiclookuparg);
643 SSL_free(server->ssl);
645 pthread_mutex_destroy(&server->lock);
646 pthread_cond_destroy(&server->newrq_cond);
647 pthread_mutex_destroy(&server->newrq_mutex);
652 int addserver(struct clsrvconf *conf) {
653 struct clsrvconf *res;
658 debug(DBG_ERR, "addserver: currently works with just one server per conf");
661 conf->servers = malloc(sizeof(struct server));
662 if (!conf->servers) {
663 debug(DBG_ERR, "malloc failed");
666 memset(conf->servers, 0, sizeof(struct server));
667 conf->servers->conf = conf;
670 if (type == RAD_DTLS)
671 conf->servers->rbios = newqueue();
673 if (!srcprotores[type]) {
674 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
675 srcprotores[type] = res->addrinfo;
676 res->addrinfo = NULL;
680 conf->servers->sock = -1;
681 if (conf->pdef->addserverextra)
682 conf->pdef->addserverextra(conf);
684 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
685 if (!conf->servers->requests) {
686 debug(DBG_ERR, "malloc failed");
689 for (i = 0; i < MAX_REQUESTS; i++) {
690 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
691 if (!conf->servers->requests[i].lock) {
692 debug(DBG_ERR, "malloc failed");
695 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
696 debug(DBG_ERR, "mutex init failed");
697 free(conf->servers->requests[i].lock);
698 conf->servers->requests[i].lock = NULL;
702 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
703 debug(DBG_ERR, "mutex init failed");
706 conf->servers->newrq = 0;
707 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
708 debug(DBG_ERR, "mutex init failed");
709 pthread_mutex_destroy(&conf->servers->lock);
712 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
713 debug(DBG_ERR, "mutex init failed");
714 pthread_mutex_destroy(&conf->servers->newrq_mutex);
715 pthread_mutex_destroy(&conf->servers->lock);
722 freeserver(conf->servers, 0);
723 conf->servers = NULL;
727 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
728 int loc, i, l, n, r = 0;
731 STACK_OF(GENERAL_NAME) *alt;
734 debug(DBG_DBG, "subjectaltnameaddr");
736 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
740 ex = X509_get_ext(cert, loc);
741 alt = X509V3_EXT_d2i(ex);
745 n = sk_GENERAL_NAME_num(alt);
746 for (i = 0; i < n; i++) {
747 gn = sk_GENERAL_NAME_value(alt, i);
748 if (gn->type != GEN_IPADD)
751 v = (char *)ASN1_STRING_data(gn->d.ia5);
752 l = ASN1_STRING_length(gn->d.ia5);
753 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
754 && !memcmp(v, &addr, l)) {
759 GENERAL_NAMES_free(alt);
763 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
770 nm = X509_get_subject_name(cert);
773 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
776 e = X509_NAME_get_entry(nm, loc);
777 t = X509_NAME_ENTRY_get_data(e);
778 v = (char *) ASN1_STRING_data(t);
779 l = ASN1_STRING_length(t);
783 if (l == strlen(exact) && !strncasecmp(exact, v, l))
786 s = stringcopy((char *)v, l);
788 debug(DBG_ERR, "malloc failed");
791 if (regexec(regex, s, 0, NULL, 0)) {
802 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
803 int loc, i, l, n, r = 0;
806 STACK_OF(GENERAL_NAME) *alt;
809 debug(DBG_DBG, "subjectaltnameregexp");
811 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
815 ex = X509_get_ext(cert, loc);
816 alt = X509V3_EXT_d2i(ex);
820 n = sk_GENERAL_NAME_num(alt);
821 for (i = 0; i < n; i++) {
822 gn = sk_GENERAL_NAME_value(alt, i);
823 if (gn->type != type)
826 v = (char *)ASN1_STRING_data(gn->d.ia5);
827 l = ASN1_STRING_length(gn->d.ia5);
831 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
834 if (memcmp(v, exact, l))
837 s = stringcopy((char *)v, l);
839 debug(DBG_ERR, "malloc failed");
842 if (regexec(regex, s, 0, NULL, 0)) {
851 GENERAL_NAMES_free(alt);
855 X509 *verifytlscert(SSL *ssl) {
859 if (SSL_get_verify_result(ssl) != X509_V_OK) {
860 debug(DBG_ERR, "verifytlscert: basic validation failed");
861 while ((error = ERR_get_error()))
862 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
866 cert = SSL_get_peer_certificate(ssl);
868 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
872 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
874 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
875 struct in6_addr addr;
877 if (conf->certnamecheck && conf->prefixlen == 255) {
878 if (inet_pton(AF_INET, conf->host, &addr))
880 else if (inet_pton(AF_INET6, conf->host, &addr))
883 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
886 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
889 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
891 if (!cnregexp(cert, conf->host, NULL)) {
892 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
895 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
898 if (conf->certcnregex) {
899 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
900 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
903 debug(DBG_DBG, "verifyconfcert: CN matching regex");
905 if (conf->certuriregex) {
906 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
907 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
910 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
915 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
917 if (ATTRTYPE(attrs) == type)
919 length -= ATTRLEN(attrs);
920 attrs += ATTRLEN(attrs);
925 void freerq(struct request *rq) {
928 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
931 if (rq->origusername)
932 free(rq->origusername);
938 radmsg_free(rq->msg);
942 void freerqoutdata(struct rqout *rqout) {
950 memset(&rqout->expiry, 0, sizeof(struct timeval));
953 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].rq) {
960 pthread_mutex_lock(to->requests[i].lock);
961 if (!to->requests[i].rq)
963 pthread_mutex_unlock(to->requests[i].lock);
966 if (i == MAX_REQUESTS) {
967 for (i = 0; i < to->nextid; i++) {
968 if (!to->requests[i].rq) {
969 pthread_mutex_lock(to->requests[i].lock);
970 if (!to->requests[i].rq)
972 pthread_mutex_unlock(to->requests[i].lock);
975 if (i == to->nextid) {
976 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
977 rmclientrq(rq, rq->msg->id);
983 rq->msg->id = (uint8_t)i;
984 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
986 pthread_mutex_unlock(to->requests[i].lock);
987 debug(DBG_ERR, "sendrq: radmsg2buf failed");
988 rmclientrq(rq, rq->msg->id);
993 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
994 to->requests[i].rq = rq;
995 pthread_mutex_unlock(to->requests[i].lock);
1000 debug(DBG_DBG, "sendrq: signalling client writer");
1001 pthread_cond_signal(&to->newrq_cond);
1005 pthread_mutex_unlock(&to->newrq_mutex);
1008 void sendreply(struct request *rq) {
1010 struct client *to = rq->from;
1013 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1014 radmsg_free(rq->msg);
1016 if (!rq->replybuf) {
1018 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1022 pthread_mutex_lock(&to->replyq->mutex);
1023 first = list_first(to->replyq->entries) == NULL;
1025 if (!list_push(to->replyq->entries, rq)) {
1026 pthread_mutex_unlock(&to->replyq->mutex);
1028 debug(DBG_ERR, "sendreply: malloc failed");
1033 debug(DBG_DBG, "signalling server writer");
1034 pthread_cond_signal(&to->replyq->cond);
1036 pthread_mutex_unlock(&to->replyq->mutex);
1039 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1040 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1041 static unsigned char first = 1;
1042 static EVP_MD_CTX mdctx;
1043 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1044 unsigned int md_len;
1045 uint8_t i, offset = 0, out[128];
1047 pthread_mutex_lock(&lock);
1049 EVP_MD_CTX_init(&mdctx);
1055 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1056 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1057 !EVP_DigestUpdate(&mdctx, input, 16) ||
1058 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1060 pthread_mutex_unlock(&lock);
1063 for (i = 0; i < 16; i++)
1064 out[offset + i] = hash[i] ^ in[offset + i];
1065 input = out + offset - 16;
1070 memcpy(in, out, len);
1071 pthread_mutex_unlock(&lock);
1075 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1076 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1077 static unsigned char first = 1;
1078 static EVP_MD_CTX mdctx;
1079 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1080 unsigned int md_len;
1081 uint8_t i, offset = 0, out[128];
1083 pthread_mutex_lock(&lock);
1085 EVP_MD_CTX_init(&mdctx);
1091 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1092 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1093 !EVP_DigestUpdate(&mdctx, input, 16) ||
1094 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1096 pthread_mutex_unlock(&lock);
1099 for (i = 0; i < 16; i++)
1100 out[offset + i] = hash[i] ^ in[offset + i];
1101 input = in + offset;
1106 memcpy(in, out, len);
1107 pthread_mutex_unlock(&lock);
1111 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1112 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1113 static unsigned char first = 1;
1114 static EVP_MD_CTX mdctx;
1115 unsigned char hash[EVP_MAX_MD_SIZE];
1116 unsigned int md_len;
1119 pthread_mutex_lock(&lock);
1121 EVP_MD_CTX_init(&mdctx);
1126 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1127 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1128 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1131 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1132 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1133 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1134 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1135 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1136 pthread_mutex_unlock(&lock);
1141 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1144 for (i = 0; i < 16; i++)
1147 for (offset = 16; offset < len; offset += 16) {
1149 printf("text + offset - 16 c(%d): ", offset / 16);
1150 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1152 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1153 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1154 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1155 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1157 pthread_mutex_unlock(&lock);
1161 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1164 for (i = 0; i < 16; i++)
1165 text[offset + i] ^= hash[i];
1169 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1172 pthread_mutex_unlock(&lock);
1176 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1177 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1178 static unsigned char first = 1;
1179 static EVP_MD_CTX mdctx;
1180 unsigned char hash[EVP_MAX_MD_SIZE];
1181 unsigned int md_len;
1185 pthread_mutex_lock(&lock);
1187 EVP_MD_CTX_init(&mdctx);
1192 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1193 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1194 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1197 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1198 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1199 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1200 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1201 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1202 pthread_mutex_unlock(&lock);
1207 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1210 for (i = 0; i < 16; i++)
1211 plain[i] = text[i] ^ hash[i];
1213 for (offset = 16; offset < len; offset += 16) {
1215 printf("text + offset - 16 c(%d): ", offset / 16);
1216 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1218 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1219 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1220 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1221 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1223 pthread_mutex_unlock(&lock);
1227 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1230 for (i = 0; i < 16; i++)
1231 plain[offset + i] = text[offset + i] ^ hash[i];
1234 memcpy(text, plain, len);
1236 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1239 pthread_mutex_unlock(&lock);
1243 struct realm *id2realm(struct list *realmlist, char *id) {
1244 struct list_node *entry;
1245 struct realm *realm, *subrealm = NULL;
1247 /* need to do locking for subrealms and check subrealm timers */
1248 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1249 realm = (struct realm *)entry->data;
1250 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1251 pthread_mutex_lock(&realm->subrealms_mutex);
1252 if (realm->subrealms)
1253 subrealm = id2realm(realm->subrealms, id);
1254 pthread_mutex_unlock(&realm->subrealms_mutex);
1255 return subrealm ? subrealm : realm;
1261 /* helper function, only used by removeserversubrealms() */
1262 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1263 struct list_node *entry;
1264 struct realm *realm;
1266 for (entry = list_first(realmlist); entry;) {
1267 realm = (struct realm *)entry->data;
1268 entry = list_next(entry);
1269 if (realm->srvconfs) {
1270 list_removedata(realm->srvconfs, srv);
1271 if (!list_first(realm->srvconfs)) {
1272 list_destroy(realm->srvconfs);
1273 realm->srvconfs = NULL;
1276 if (realm->accsrvconfs) {
1277 list_removedata(realm->accsrvconfs, srv);
1278 if (!list_first(realm->accsrvconfs)) {
1279 list_destroy(realm->accsrvconfs);
1280 realm->accsrvconfs = NULL;
1284 /* remove subrealm if no servers */
1285 if (!realm->srvconfs && !realm->accsrvconfs) {
1286 list_removedata(realmlist, realm);
1292 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1293 struct list_node *entry;
1294 struct realm *realm;
1296 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1297 realm = (struct realm *)entry->data;
1298 pthread_mutex_lock(&realm->subrealms_mutex);
1299 if (realm->subrealms) {
1300 _internal_removeserversubrealms(realm->subrealms, srv);
1301 if (!list_first(realm->subrealms)) {
1302 list_destroy(realm->subrealms);
1303 realm->subrealms = NULL;
1306 pthread_mutex_unlock(&realm->subrealms_mutex);
1310 int attrvalidate(unsigned char *attrs, int length) {
1311 while (length > 1) {
1312 if (ATTRLEN(attrs) < 2) {
1313 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1316 length -= ATTRLEN(attrs);
1318 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1321 attrs += ATTRLEN(attrs);
1324 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1328 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1329 if (len < 16 || len > 128 || len % 16) {
1330 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1334 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1335 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1339 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1341 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1342 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1348 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1351 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1352 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1355 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1356 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1362 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1363 char *oldsecret, char *newsecret) {
1364 unsigned char *attr;
1366 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1367 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1368 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1374 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1378 for (; attrs[0]; attrs += 2)
1379 if (attrs[0] == vendor && attrs[1] == subattr)
1384 /* returns 1 if entire element is to be removed, else 0 */
1385 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1386 uint8_t alen, sublen;
1390 if (!removevendorattrs)
1393 memcpy(&vendor, attr->v, 4);
1394 vendor = ntohl(vendor);
1395 while (*removevendorattrs && *removevendorattrs != vendor)
1396 removevendorattrs += 2;
1397 if (!*removevendorattrs)
1400 if (findvendorsubattr(removevendorattrs, vendor, -1))
1401 return 1; /* remove entire vendor attribute */
1403 sublen = attr->l - 4;
1404 subattrs = attr->v + 4;
1406 if (!attrvalidate(subattrs, sublen)) {
1407 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1411 while (sublen > 1) {
1412 alen = ATTRLEN(subattrs);
1414 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1415 memmove(subattrs, subattrs + alen, sublen);
1423 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1424 struct list_node *n, *p;
1428 n = list_first(msg->attrs);
1430 attr = (struct tlv *)n->data;
1431 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1432 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1433 list_removedata(msg->attrs, attr);
1435 n = p ? list_next(p) : list_first(msg->attrs);
1442 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1443 struct list_node *n;
1446 for (n = list_first(addattrs); n; n = list_next(n)) {
1447 a = copytlv((struct tlv *)n->data);
1450 if (!radmsg_add(msg, a)) {
1458 int resizeattr(struct tlv *attr, uint8_t newlen) {
1461 if (newlen != attr->l) {
1462 newv = realloc(attr->v, newlen);
1471 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1472 size_t nmatch = 10, reslen = 0, start = 0;
1473 regmatch_t pmatch[10], *pfield;
1477 in = stringcopy((char *)attr->v, attr->l);
1481 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1486 out = modattr->replacement;
1488 for (i = start; out[i]; i++) {
1489 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1490 pfield = &pmatch[out[i + 1] - '0'];
1491 if (pfield->rm_so >= 0) {
1492 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1498 reslen += i - start;
1500 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1505 if (!resizeattr(attr, reslen)) {
1512 for (i = start; out[i]; i++) {
1513 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1514 pfield = &pmatch[out[i + 1] - '0'];
1515 if (pfield->rm_so >= 0) {
1516 memcpy(attr->v + reslen, out + start, i - start);
1517 reslen += i - start;
1518 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1519 reslen += pfield->rm_eo - pfield->rm_so;
1526 memcpy(attr->v + reslen, out + start, i - start);
1530 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1531 struct list_node *n, *m;
1533 for (n = list_first(msg->attrs); n; n = list_next(n))
1534 for (m = list_first(modattrs); m; m = list_next(m))
1535 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1536 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1541 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1544 if (rewrite->removeattrs || rewrite->removevendorattrs)
1545 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1546 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1548 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1553 int rewriteusername(struct request *rq, struct tlv *attr) {
1554 char *orig = (char *)tlv2str(attr);
1555 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1559 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1560 rq->origusername = (char *)orig;
1566 const char *radmsgtype2string(uint8_t code) {
1567 static const char *rad_msg_names[] = {
1568 "", "Access-Request", "Access-Accept", "Access-Reject",
1569 "Accounting-Request", "Accounting-Response", "", "",
1570 "", "", "", "Access-Challenge",
1571 "Status-Server", "Status-Client"
1573 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1576 void char2hex(char *h, unsigned char c) {
1577 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1578 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1579 h[0] = hexdigits[c / 16];
1580 h[1] = hexdigits[c % 16];
1584 uint8_t *radattr2ascii(struct tlv *attr) {
1592 for (i = 0; i < attr->l; i++)
1593 if (attr->v[i] < 32 || attr->v[i] > 126)
1596 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1603 for (i = 0; i < attr->l; i++)
1604 if (attr->v[i] < 32 || attr->v[i] > 126) {
1606 char2hex((char *)d, attr->v[i]);
1614 void acclog(struct radmsg *msg, char *host) {
1618 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1620 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1623 username = radattr2ascii(attr);
1625 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1630 void respond(struct request *rq, uint8_t code, char *message) {
1634 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1636 debug(DBG_ERR, "respond: malloc failed");
1639 if (message && *message) {
1640 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1641 if (!attr || !radmsg_add(msg, attr)) {
1644 debug(DBG_ERR, "respond: malloc failed");
1649 radmsg_free(rq->msg);
1651 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1655 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1656 struct list_node *entry;
1657 struct clsrvconf *server, *best = NULL, *first = NULL;
1659 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1660 server = (struct clsrvconf *)entry->data;
1661 if (!server->servers)
1665 if (!server->servers->connectionok)
1667 if (!server->servers->lostrqs)
1673 if (server->servers->lostrqs < best->servers->lostrqs)
1676 return best ? best : first;
1679 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1680 struct clsrvconf *srvconf;
1681 char *id = (char *)tlv2str(username);
1685 *realm = id2realm(realms, id);
1690 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1691 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1696 if (!acc && !srvconf->servers)
1697 adddynamicrealmserver(*realm, srvconf, id);
1699 return srvconf->servers;
1703 struct request *newrequest() {
1706 rq = malloc(sizeof(struct request));
1708 debug(DBG_ERR, "newrequest: malloc failed");
1711 memset(rq, 0, sizeof(struct request));
1713 gettimeofday(&rq->created, NULL);
1717 int addclientrq(struct request *rq, uint8_t id) {
1721 pthread_mutex_lock(&rq->from->lock);
1722 gettimeofday(&now, NULL);
1723 r = rq->from->rqs[id];
1725 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1729 debug(DBG_INFO, "radsrv: already sent reply to request with id %d from %s, resending", id, r->from->conf->host);
1734 debug(DBG_INFO, "radsrv: already got request with id %d from %s, ignoring", id, r->from->conf->host);
1735 pthread_mutex_unlock(&rq->from->lock);
1741 rq->from->rqs[id] = rq;
1742 pthread_mutex_unlock(&rq->from->lock);
1746 void rmclientrq(struct request *rq, uint8_t id) {
1749 pthread_mutex_lock(&rq->from->lock);
1750 r = rq->from->rqs[id];
1753 rq->from->rqs[id] = NULL;
1755 pthread_mutex_unlock(&rq->from->lock);
1758 /* returns 0 if validation/authentication fails, else 1 */
1759 int radsrv(struct request *rq) {
1760 struct radmsg *msg = NULL;
1762 uint8_t *userascii = NULL;
1763 unsigned char newauth[16];
1764 struct realm *realm = NULL;
1765 struct server *to = NULL;
1766 struct client *from = rq->from;
1768 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1773 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1779 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1780 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1781 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1785 if (!addclientrq(rq, msg->id))
1788 if (msg->code == RAD_Status_Server) {
1789 respond(rq, RAD_Access_Accept, NULL);
1793 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1795 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1798 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1800 if (msg->code == RAD_Accounting_Request) {
1801 acclog(msg, from->conf->host);
1802 respond(rq, RAD_Accounting_Response, NULL);
1804 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1808 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1809 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1813 userascii = radattr2ascii(attr);
1816 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1818 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1820 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1825 if (realm->message && msg->code == RAD_Access_Request) {
1826 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1827 respond(rq, RAD_Access_Reject, realm->message);
1828 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1829 acclog(msg, from->conf->host);
1830 respond(rq, RAD_Accounting_Response, NULL);
1835 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1836 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1837 from->conf->name, to->conf->name);
1841 if (msg->code != RAD_Accounting_Request) {
1842 if (!RAND_bytes(newauth, 16)) {
1843 debug(DBG_WARN, "radsrv: failed to generate random auth");
1849 printfchars(NULL, "auth", "%02x ", auth, 16);
1852 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1854 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1855 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1859 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1861 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1862 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1866 rq->origid = msg->id;
1867 memcpy(rq->origauth, msg->auth, 16);
1868 memcpy(msg->auth, newauth, 16);
1870 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1878 rmclientrq(rq, msg->id);
1885 void replyh(struct server *server, unsigned char *buf) {
1886 struct client *from;
1887 struct rqout *rqout;
1889 unsigned char *subattrs;
1890 uint8_t *username, *stationid;
1891 struct radmsg *msg = NULL;
1893 struct list_node *node;
1895 server->connectionok = 1;
1896 server->lostrqs = 0;
1898 rqout = server->requests + buf[1];
1899 pthread_mutex_lock(rqout->lock);
1900 if (!rqout->tries) {
1903 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1907 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1911 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1914 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1915 && msg->code != RAD_Accounting_Response) {
1916 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1919 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1921 gettimeofday(&server->lastrcv, NULL);
1923 if (rqout->rq->msg->code == RAD_Status_Server) {
1924 freerqoutdata(rqout);
1925 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1929 gettimeofday(&server->lastreply, NULL);
1930 from = rqout->rq->from;
1932 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1933 debug(DBG_WARN, "replyh: rewritein failed");
1938 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1939 attr = (struct tlv *)node->data;
1940 if (attr->t != RAD_Attr_Vendor_Specific)
1944 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1947 sublen = attr->l - 4;
1948 subattrs = attr->v + 4;
1949 if (!attrvalidate(subattrs, sublen) ||
1950 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1951 rqout->rq, server->conf->secret, from->conf->secret) ||
1952 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1953 rqout->rq, server->conf->secret, from->conf->secret))
1957 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1961 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1962 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1964 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1966 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1967 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1970 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(msg->code), username, server->conf->host);
1975 msg->id = (char)rqout->rq->origid;
1976 memcpy(msg->auth, rqout->rq->origauth, 16);
1979 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1982 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1983 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1984 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1987 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1990 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1991 debug(DBG_WARN, "replyh: rewriteout failed");
1995 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
1996 radmsg_free(rqout->rq->msg);
1997 rqout->rq->msg = msg;
1998 rqout->rq->refcount++;
1999 sendreply(rqout->rq);
2000 freerqoutdata(rqout);
2001 pthread_mutex_unlock(rqout->lock);
2006 pthread_mutex_unlock(rqout->lock);
2010 struct request *createstatsrvrq() {
2017 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2020 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2023 if (!radmsg_add(rq->msg, attr)) {
2034 /* code for removing state not finished */
2035 void *clientwr(void *arg) {
2036 struct server *server = (struct server *)arg;
2037 struct rqout *rqout;
2038 pthread_t clientrdth;
2039 int i, secs, dynconffail = 0;
2041 struct timeval now, laststatsrv;
2042 struct timespec timeout;
2043 struct request *statsrvrq;
2044 struct clsrvconf *conf;
2046 conf = server->conf;
2048 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2053 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2054 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2058 memset(&timeout, 0, sizeof(struct timespec));
2060 if (conf->statusserver) {
2061 gettimeofday(&server->lastrcv, NULL);
2062 gettimeofday(&laststatsrv, NULL);
2065 if (conf->pdef->connecter) {
2066 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2068 server->connectionok = 1;
2069 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2070 debug(DBG_ERR, "clientwr: pthread_create failed");
2074 server->connectionok = 1;
2077 pthread_mutex_lock(&server->newrq_mutex);
2078 if (!server->newrq) {
2079 gettimeofday(&now, NULL);
2080 /* random 0-7 seconds */
2081 RAND_bytes(&rnd, 1);
2083 if (conf->statusserver) {
2084 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2085 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2086 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2088 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2089 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2092 if (timeout.tv_sec > now.tv_sec)
2093 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2095 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2098 if (server->newrq) {
2099 debug(DBG_DBG, "clientwr: got new request");
2104 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2106 pthread_mutex_unlock(&server->newrq_mutex);
2108 for (i = 0; i < MAX_REQUESTS; i++) {
2109 if (server->clientrdgone) {
2110 pthread_join(clientrdth, NULL);
2114 for (; i < MAX_REQUESTS; i++) {
2115 rqout = server->requests + i;
2117 pthread_mutex_lock(rqout->lock);
2120 pthread_mutex_unlock(rqout->lock);
2124 if (i == MAX_REQUESTS)
2127 gettimeofday(&now, NULL);
2128 if (now.tv_sec < rqout->expiry.tv_sec) {
2129 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2130 timeout.tv_sec = rqout->expiry.tv_sec;
2131 pthread_mutex_unlock(rqout->lock);
2135 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2136 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2137 if (conf->statusserver) {
2138 if (*rqout->rq->buf == RAD_Status_Server) {
2139 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2140 if (server->lostrqs < 255)
2144 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2145 if (server->lostrqs < 255)
2148 freerqoutdata(rqout);
2149 pthread_mutex_unlock(rqout->lock);
2153 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2154 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2155 timeout.tv_sec = rqout->expiry.tv_sec;
2157 conf->pdef->clientradput(server, rqout->rq->buf);
2158 pthread_mutex_unlock(rqout->lock);
2160 if (conf->statusserver) {
2161 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2162 gettimeofday(&now, NULL);
2163 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2165 statsrvrq = createstatsrvrq();
2167 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2168 sendrq(server, statsrvrq);
2174 conf->servers = NULL;
2175 if (server->dynamiclookuparg) {
2176 removeserversubrealms(realms, conf);
2180 freeclsrvconf(conf);
2182 freeserver(server, 1);
2183 ERR_remove_state(0);
2187 void createlistener(uint8_t type, char *arg) {
2189 struct clsrvconf *listenres;
2190 struct addrinfo *res;
2191 int s = -1, on = 1, *sp = NULL;
2193 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2195 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2197 for (res = listenres->addrinfo; res; res = res->ai_next) {
2198 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2200 debug(DBG_WARN, "createlistener: socket failed");
2203 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2205 if (res->ai_family == AF_INET6)
2206 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2208 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2209 debug(DBG_WARN, "createlistener: bind failed");
2215 sp = malloc(sizeof(int));
2217 debugx(1, DBG_ERR, "malloc failed");
2219 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2220 debugx(1, DBG_ERR, "pthread_create failed");
2224 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2226 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2227 listenres->host ? listenres->host : "*", listenres->port);
2228 freeclsrvres(listenres);
2231 void createlisteners(uint8_t type, char **args) {
2235 for (i = 0; args[i]; i++)
2236 createlistener(type, args[i]);
2238 createlistener(type, NULL);
2242 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2246 w = where & ~SSL_ST_MASK;
2248 if (w & SSL_ST_CONNECT)
2250 else if (w & SSL_ST_ACCEPT)
2255 if (where & SSL_CB_LOOP)
2256 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2257 else if (where & SSL_CB_ALERT) {
2258 s = (where & SSL_CB_READ) ? "read" : "write";
2259 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2261 else if (where & SSL_CB_EXIT) {
2263 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2265 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2270 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2271 SSL_CTX *ctx = NULL;
2272 STACK_OF(X509_NAME) *calist;
2275 unsigned long error;
2278 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2279 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2280 for (i = 0; i < CRYPTO_num_locks(); i++) {
2281 ssl_lock_count[i] = 0;
2282 pthread_mutex_init(&ssl_locks[i], NULL);
2284 CRYPTO_set_id_callback(ssl_thread_id);
2285 CRYPTO_set_locking_callback(ssl_locking_callback);
2287 SSL_load_error_strings();
2290 while (!RAND_status()) {
2291 time_t t = time(NULL);
2292 pid_t pid = getpid();
2293 RAND_seed((unsigned char *)&t, sizeof(time_t));
2294 RAND_seed((unsigned char *)&pid, sizeof(pid));
2300 ctx = SSL_CTX_new(TLSv1_method());
2302 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2306 ctx = SSL_CTX_new(DTLSv1_method());
2308 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2310 SSL_CTX_set_read_ahead(ctx, 1);
2314 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2318 if (conf->certkeypwd) {
2319 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2320 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2322 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2323 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2324 !SSL_CTX_check_private_key(ctx) ||
2325 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2326 while ((error = ERR_get_error()))
2327 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2328 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2333 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2334 if (!conf->cacertfile || calist) {
2335 if (conf->cacertpath) {
2337 calist = sk_X509_NAME_new_null();
2338 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2339 sk_X509_NAME_free(calist);
2345 while ((error = ERR_get_error()))
2346 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2347 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2351 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2352 SSL_CTX_set_client_CA_list(ctx, calist);
2354 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2355 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2357 if (conf->crlcheck) {
2358 x509_s = SSL_CTX_get_cert_store(ctx);
2359 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2362 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2366 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2369 t = hash_read(tlsconfs, alt1, strlen(alt1));
2371 t = hash_read(tlsconfs, alt2, strlen(alt2));
2379 t->tlsctx = tlscreatectx(RAD_TLS, t);
2383 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2389 struct list *addsrvconfs(char *value, char **names) {
2390 struct list *conflist;
2392 struct list_node *entry;
2393 struct clsrvconf *conf = NULL;
2395 if (!names || !*names)
2398 conflist = list_create();
2400 debug(DBG_ERR, "malloc failed");
2404 for (n = 0; names[n]; n++) {
2405 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2406 conf = (struct clsrvconf *)entry->data;
2407 if (!strcasecmp(names[n], conf->name))
2411 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2412 list_destroy(conflist);
2415 if (!list_push(conflist, conf)) {
2416 debug(DBG_ERR, "malloc failed");
2417 list_destroy(conflist);
2420 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2425 void freerealm(struct realm *realm) {
2429 free(realm->message);
2430 regfree(&realm->regex);
2431 pthread_mutex_destroy(&realm->subrealms_mutex);
2432 if (realm->subrealms)
2433 list_destroy(realm->subrealms);
2434 if (realm->srvconfs) {
2435 /* emptying list without freeing data */
2436 while (list_shift(realm->srvconfs));
2437 list_destroy(realm->srvconfs);
2439 if (realm->accsrvconfs) {
2440 /* emptying list without freeing data */
2441 while (list_shift(realm->accsrvconfs));
2442 list_destroy(realm->accsrvconfs);
2447 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2449 struct realm *realm;
2450 char *s, *regex = NULL;
2452 if (*value == '/') {
2453 /* regexp, remove optional trailing / if present */
2454 if (value[strlen(value) - 1] == '/')
2455 value[strlen(value) - 1] = '\0';
2457 /* not a regexp, let us make it one */
2458 if (*value == '*' && !value[1])
2459 regex = stringcopy(".*", 0);
2461 for (n = 0, s = value; *s;)
2464 regex = malloc(strlen(value) + n + 3);
2467 for (n = 1, s = value; *s; s++) {
2477 debug(DBG_ERR, "malloc failed");
2481 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2484 realm = malloc(sizeof(struct realm));
2486 debug(DBG_ERR, "malloc failed");
2489 memset(realm, 0, sizeof(struct realm));
2491 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2492 debug(DBG_ERR, "mutex init failed");
2498 realm->name = stringcopy(value, 0);
2500 debug(DBG_ERR, "malloc failed");
2503 if (message && strlen(message) > 253) {
2504 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2507 realm->message = message;
2508 realm->accresp = accresp;
2510 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2511 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2515 if (servers && *servers) {
2516 realm->srvconfs = addsrvconfs(value, servers);
2517 if (!realm->srvconfs)
2521 if (accservers && *accservers) {
2522 realm->accsrvconfs = addsrvconfs(value, accservers);
2523 if (!realm->accsrvconfs)
2527 if (!list_push(realmlist, realm)) {
2528 debug(DBG_ERR, "malloc failed");
2529 pthread_mutex_destroy(&realm->subrealms_mutex);
2533 debug(DBG_DBG, "addrealm: added realm %s", value);
2543 for (n = 0; servers[n]; n++)
2548 for (n = 0; accservers[n]; n++)
2549 free(accservers[n]);
2555 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2556 struct clsrvconf *srvconf;
2557 struct realm *newrealm = NULL;
2558 char *realmname, *s;
2561 if (!conf->dynamiclookupcommand)
2564 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2565 realmname = strrchr(id, '@');
2571 for (s = realmname; *s; s++)
2572 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2575 pthread_mutex_lock(&realm->subrealms_mutex);
2576 /* exit if we now already got a matching subrealm */
2577 if (id2realm(realm->subrealms, id))
2579 srvconf = malloc(sizeof(struct clsrvconf));
2581 debug(DBG_ERR, "malloc failed");
2585 if (!addserver(srvconf))
2588 if (!realm->subrealms)
2589 realm->subrealms = list_create();
2590 if (!realm->subrealms)
2592 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2596 /* add server and accserver to newrealm */
2597 newrealm->srvconfs = list_create();
2598 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2599 debug(DBG_ERR, "malloc failed");
2602 newrealm->accsrvconfs = list_create();
2603 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2604 debug(DBG_ERR, "malloc failed");
2608 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2610 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2611 debug(DBG_ERR, "pthread_create failed");
2614 pthread_detach(clientth);
2619 list_removedata(realm->subrealms, newrealm);
2620 freerealm(newrealm);
2621 if (!list_first(realm->subrealms)) {
2622 list_destroy(realm->subrealms);
2623 realm->subrealms = NULL;
2626 freeserver(srvconf->servers, 1);
2628 debug(DBG_ERR, "failed to create dynamic server");
2631 pthread_mutex_unlock(&realm->subrealms_mutex);
2634 int dynamicconfig(struct server *server) {
2635 int ok, fd[2], status;
2637 struct clsrvconf *conf = server->conf;
2638 struct gconffile *cf = NULL;
2640 /* for now we only learn hostname/address */
2641 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2644 debug(DBG_ERR, "dynamicconfig: pipe error");
2649 debug(DBG_ERR, "dynamicconfig: fork error");
2653 } else if (pid == 0) {
2656 if (fd[1] != STDOUT_FILENO) {
2657 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2658 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2661 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2662 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2666 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2667 ok = getgenericconfig(&cf, NULL,
2668 "Server", CONF_CBK, confserver_cb, (void *)conf,
2673 if (waitpid(pid, &status, 0) < 0) {
2674 debug(DBG_ERR, "dynamicconfig: wait error");
2679 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2687 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2691 int addmatchcertattr(struct clsrvconf *conf) {
2695 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2696 r = &conf->certcnregex;
2697 v = conf->matchcertattr + 4;
2698 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2699 r = &conf->certuriregex;
2700 v = conf->matchcertattr + 20;
2705 /* regexp, remove optional trailing / if present */
2706 if (v[strlen(v) - 1] == '/')
2707 v[strlen(v) - 1] = '\0';
2711 *r = malloc(sizeof(regex_t));
2713 debug(DBG_ERR, "malloc failed");
2716 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2719 debug(DBG_ERR, "failed to compile regular expression %s", v);
2725 /* should accept both names and numeric values, only numeric right now */
2726 uint8_t attrname2val(char *attrname) {
2729 val = atoi(attrname);
2730 return val > 0 && val < 256 ? val : 0;
2733 /* should accept both names and numeric values, only numeric right now */
2734 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2737 *vendor = atoi(attrname);
2738 s = strchr(attrname, ':');
2743 *type = atoi(s + 1);
2744 return *type >= 0 && *type < 256;
2747 /* should accept both names and numeric values, only numeric right now */
2748 struct tlv *extractattr(char *nameval) {
2753 s = strchr(nameval, ':');
2754 name = atoi(nameval);
2755 if (!s || name < 1 || name > 255)
2757 len = strlen(s + 1);
2760 a = malloc(sizeof(struct tlv));
2763 a->v = (uint8_t *)stringcopy(s + 1, 0);
2773 /* should accept both names and numeric values, only numeric right now */
2774 struct modattr *extractmodattr(char *nameval) {
2779 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2783 s = strchr(nameval, ':');
2784 name = atoi(nameval);
2785 if (!s || name < 1 || name > 255 || s[1] != '/')
2789 /* regexp, remove optional trailing / if present */
2790 if (s[strlen(s) - 1] == '/')
2791 s[strlen(s) - 1] = '\0';
2799 m = malloc(sizeof(struct modattr));
2801 debug(DBG_ERR, "malloc failed");
2806 m->replacement = stringcopy(t, 0);
2807 if (!m->replacement) {
2809 debug(DBG_ERR, "malloc failed");
2813 m->regex = malloc(sizeof(regex_t));
2815 free(m->replacement);
2817 debug(DBG_ERR, "malloc failed");
2821 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2823 free(m->replacement);
2825 debug(DBG_ERR, "failed to compile regular expression %s", s);
2832 struct rewrite *getrewrite(char *alt1, char *alt2) {
2835 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2837 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2842 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2843 struct rewrite *rewrite = NULL;
2845 uint8_t *rma = NULL;
2846 uint32_t *p, *rmva = NULL;
2847 struct list *adda = NULL, *moda = NULL;
2852 for (n = 0; rmattrs[n]; n++);
2853 rma = calloc(n + 1, sizeof(uint8_t));
2855 debugx(1, DBG_ERR, "malloc failed");
2857 for (i = 0; i < n; i++) {
2858 if (!(rma[i] = attrname2val(rmattrs[i])))
2859 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2867 for (n = 0; rmvattrs[n]; n++);
2868 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2870 debugx(1, DBG_ERR, "malloc failed");
2872 for (p = rmva, i = 0; i < n; i++, p += 2) {
2873 if (!vattrname2val(rmvattrs[i], p, p + 1))
2874 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2882 adda = list_create();
2884 debugx(1, DBG_ERR, "malloc failed");
2885 for (i = 0; addattrs[i]; i++) {
2886 a = extractattr(addattrs[i]);
2888 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2890 if (!list_push(adda, a))
2891 debugx(1, DBG_ERR, "malloc failed");
2897 moda = list_create();
2899 debugx(1, DBG_ERR, "malloc failed");
2900 for (i = 0; modattrs[i]; i++) {
2901 m = extractmodattr(modattrs[i]);
2903 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2905 if (!list_push(moda, m))
2906 debugx(1, DBG_ERR, "malloc failed");
2911 if (rma || rmva || adda || moda) {
2912 rewrite = malloc(sizeof(struct rewrite));
2914 debugx(1, DBG_ERR, "malloc failed");
2915 rewrite->removeattrs = rma;
2916 rewrite->removevendorattrs = rmva;
2917 rewrite->addattrs = adda;
2918 rewrite->modattrs = moda;
2921 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2922 debugx(1, DBG_ERR, "malloc failed");
2923 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2926 void freeclsrvconf(struct clsrvconf *conf) {
2932 free(conf->matchcertattr);
2933 if (conf->certcnregex)
2934 regfree(conf->certcnregex);
2935 if (conf->certuriregex)
2936 regfree(conf->certuriregex);
2937 free(conf->confrewritein);
2938 free(conf->confrewriteout);
2939 if (conf->rewriteusername) {
2940 if (conf->rewriteusername->regex)
2941 regfree(conf->rewriteusername->regex);
2942 free(conf->rewriteusername->replacement);
2943 free(conf->rewriteusername);
2945 free(conf->dynamiclookupcommand);
2946 free(conf->rewritein);
2947 free(conf->rewriteout);
2949 freeaddrinfo(conf->addrinfo);
2951 pthread_mutex_destroy(conf->lock);
2954 /* not touching ssl_ctx, clients and servers */
2958 int mergeconfstring(char **dst, char **src) {
2967 t = stringcopy(*dst, 0);
2969 debug(DBG_ERR, "malloc failed");
2977 /* assumes dst is a shallow copy */
2978 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2979 if (!mergeconfstring(&dst->name, &src->name) ||
2980 !mergeconfstring(&dst->host, &src->host) ||
2981 !mergeconfstring(&dst->port, &src->port) ||
2982 !mergeconfstring(&dst->secret, &src->secret) ||
2983 !mergeconfstring(&dst->tls, &src->tls) ||
2984 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2985 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2986 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2987 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
2990 dst->pdef = src->pdef;
2991 dst->statusserver = src->statusserver;
2992 dst->certnamecheck = src->certnamecheck;
2993 if (src->retryinterval != 255)
2994 dst->retryinterval = src->retryinterval;
2995 if (src->retrycount != 255)
2996 dst->retrycount = src->retrycount;
3000 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3001 struct clsrvconf *conf;
3002 char *conftype = NULL, *rewriteinalias = NULL;
3003 long int dupinterval = LONG_MIN;
3005 debug(DBG_DBG, "confclient_cb called for %s", block);
3007 conf = malloc(sizeof(struct clsrvconf));
3009 debugx(1, DBG_ERR, "malloc failed");
3010 memset(conf, 0, sizeof(struct clsrvconf));
3011 conf->certnamecheck = 1;
3013 if (!getgenericconfig(cf, block,
3014 "type", CONF_STR, &conftype,
3015 "host", CONF_STR, &conf->host,
3016 "secret", CONF_STR, &conf->secret,
3017 "tls", CONF_STR, &conf->tls,
3018 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3019 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3020 "DuplicateInterval", CONF_LINT, &dupinterval,
3021 "rewrite", CONF_STR, &rewriteinalias,
3022 "rewriteIn", CONF_STR, &conf->confrewritein,
3023 "rewriteOut", CONF_STR, &conf->confrewriteout,
3024 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3027 debugx(1, DBG_ERR, "configuration error");
3029 conf->name = stringcopy(val, 0);
3031 conf->host = stringcopy(val, 0);
3032 if (!conf->name || !conf->host)
3033 debugx(1, DBG_ERR, "malloc failed");
3036 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3037 conf->type = protoname2int(conftype);
3038 conf->pdef = &protodefs[conf->type];
3039 if (!conf->pdef->name)
3040 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3043 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3044 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3046 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3047 if (conf->matchcertattr && !addmatchcertattr(conf))
3048 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3051 if (dupinterval != LONG_MIN) {
3052 if (dupinterval < 0 || dupinterval > 255)
3053 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3054 conf->dupinterval = (uint8_t)dupinterval;
3056 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3058 if (!conf->confrewritein)
3059 conf->confrewritein = rewriteinalias;
3061 free(rewriteinalias);
3062 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3063 if (conf->confrewriteout)
3064 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3066 if (conf->confrewriteusername) {
3067 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3068 if (!conf->rewriteusername)
3069 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3072 if (!resolvepeer(conf, 0))
3073 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3075 if (!conf->secret) {
3076 if (!conf->pdef->secretdefault)
3077 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3078 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3080 debugx(1, DBG_ERR, "malloc failed");
3083 conf->lock = malloc(sizeof(pthread_mutex_t));
3085 debugx(1, DBG_ERR, "malloc failed");
3087 pthread_mutex_init(conf->lock, NULL);
3088 if (!list_push(clconfs, conf))
3089 debugx(1, DBG_ERR, "malloc failed");
3093 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3094 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3095 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3096 if (!conf->ssl_ctx) {
3097 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3100 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3101 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3107 conf->port = stringcopy(conf->pdef->portdefault, 0);
3109 debug(DBG_ERR, "malloc failed");
3114 if (conf->retryinterval == 255)
3115 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3116 if (conf->retrycount == 255)
3117 conf->retrycount = protodefs[conf->type].retrycountdefault;
3119 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3120 if (conf->confrewriteout)
3121 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3123 if (!conf->secret) {
3124 if (!conf->pdef->secretdefault) {
3125 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3128 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3129 if (!conf->secret) {
3130 debug(DBG_ERR, "malloc failed");
3135 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3136 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3142 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3143 struct clsrvconf *conf, *resconf;
3144 char *conftype = NULL, *rewriteinalias = NULL;
3145 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3147 debug(DBG_DBG, "confserver_cb called for %s", block);
3149 conf = malloc(sizeof(struct clsrvconf));
3151 debug(DBG_ERR, "malloc failed");
3154 memset(conf, 0, sizeof(struct clsrvconf));
3155 resconf = (struct clsrvconf *)arg;
3157 conf->statusserver = resconf->statusserver;
3158 conf->certnamecheck = resconf->certnamecheck;
3160 conf->certnamecheck = 1;
3162 if (!getgenericconfig(cf, block,
3163 "type", CONF_STR, &conftype,
3164 "host", CONF_STR, &conf->host,
3165 "port", CONF_STR, &conf->port,
3166 "secret", CONF_STR, &conf->secret,
3167 "tls", CONF_STR, &conf->tls,
3168 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3169 "rewrite", CONF_STR, &rewriteinalias,
3170 "rewriteIn", CONF_STR, &conf->confrewritein,
3171 "rewriteOut", CONF_STR, &conf->confrewriteout,
3172 "StatusServer", CONF_BLN, &conf->statusserver,
3173 "RetryInterval", CONF_LINT, &retryinterval,
3174 "RetryCount", CONF_LINT, &retrycount,
3175 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3176 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3179 debug(DBG_ERR, "configuration error");
3183 conf->name = stringcopy(val, 0);
3185 debug(DBG_ERR, "malloc failed");
3189 conf->host = stringcopy(val, 0);
3191 debug(DBG_ERR, "malloc failed");
3197 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3198 conf->type = protoname2int(conftype);
3199 conf->pdef = &protodefs[conf->type];
3200 if (!conf->pdef->name) {
3201 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3207 if (!conf->confrewritein)
3208 conf->confrewritein = rewriteinalias;
3210 free(rewriteinalias);
3211 rewriteinalias = NULL;
3213 if (retryinterval != LONG_MIN) {
3214 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3215 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3218 conf->retryinterval = (uint8_t)retryinterval;
3220 conf->retryinterval = 255;
3222 if (retrycount != LONG_MIN) {
3223 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3224 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3227 conf->retrycount = (uint8_t)retrycount;
3229 conf->retrycount = 255;
3232 if (!mergesrvconf(resconf, conf))
3236 if (conf->dynamiclookupcommand) {
3237 free(conf->dynamiclookupcommand);
3238 conf->dynamiclookupcommand = NULL;
3242 if (resconf || !conf->dynamiclookupcommand) {
3243 if (!compileserverconfig(conf, block))
3250 if (!list_push(srvconfs, conf)) {
3251 debug(DBG_ERR, "malloc failed");
3258 free(rewriteinalias);
3259 freeclsrvconf(conf);
3263 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3264 char **servers = NULL, **accservers = NULL, *msg = NULL;
3265 uint8_t accresp = 0;
3267 debug(DBG_DBG, "confrealm_cb called for %s", block);
3269 if (!getgenericconfig(cf, block,
3270 "server", CONF_MSTR, &servers,
3271 "accountingServer", CONF_MSTR, &accservers,
3272 "ReplyMessage", CONF_STR, &msg,
3273 "AccountingResponse", CONF_BLN, &accresp,
3276 debugx(1, DBG_ERR, "configuration error");
3278 addrealm(realms, val, servers, accservers, msg, accresp);
3282 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3285 debug(DBG_DBG, "conftls_cb called for %s", block);
3287 conf = malloc(sizeof(struct tls));
3289 debug(DBG_ERR, "conftls_cb: malloc failed");
3292 memset(conf, 0, sizeof(struct tls));
3294 if (!getgenericconfig(cf, block,
3295 "CACertificateFile", CONF_STR, &conf->cacertfile,
3296 "CACertificatePath", CONF_STR, &conf->cacertpath,
3297 "CertificateFile", CONF_STR, &conf->certfile,
3298 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3299 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3300 "CRLCheck", CONF_BLN, &conf->crlcheck,
3303 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3306 if (!conf->certfile || !conf->certkeyfile) {
3307 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3310 if (!conf->cacertfile && !conf->cacertpath) {
3311 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3315 conf->name = stringcopy(val, 0);
3317 debug(DBG_ERR, "conftls_cb: malloc failed");
3321 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3322 debug(DBG_ERR, "conftls_cb: malloc failed");
3326 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3330 free(conf->cacertfile);
3331 free(conf->cacertpath);
3332 free(conf->certfile);
3333 free(conf->certkeyfile);
3334 free(conf->certkeypwd);
3339 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3340 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3342 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3344 if (!getgenericconfig(cf, block,
3345 "removeAttribute", CONF_MSTR, &rmattrs,
3346 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3347 "addAttribute", CONF_MSTR, &addattrs,
3348 "modifyAttribute", CONF_MSTR, &modattrs,
3351 debugx(1, DBG_ERR, "configuration error");
3352 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3356 void getmainconfig(const char *configfile) {
3357 long int loglevel = LONG_MIN;
3358 struct gconffile *cfs;
3360 cfs = openconfigfile(configfile);
3361 memset(&options, 0, sizeof(options));
3363 clconfs = list_create();
3365 debugx(1, DBG_ERR, "malloc failed");
3367 srvconfs = list_create();
3369 debugx(1, DBG_ERR, "malloc failed");
3371 realms = list_create();
3373 debugx(1, DBG_ERR, "malloc failed");
3375 tlsconfs = hash_create();
3377 debugx(1, DBG_ERR, "malloc failed");
3379 rewriteconfs = hash_create();
3381 debugx(1, DBG_ERR, "malloc failed");
3383 if (!getgenericconfig(&cfs, NULL,
3384 "ListenUDP", CONF_MSTR, &options.listenudp,
3385 "ListenTCP", CONF_MSTR, &options.listentcp,
3386 "ListenTLS", CONF_MSTR, &options.listentls,
3387 "ListenDTLS", CONF_MSTR, &options.listendtls,
3388 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3389 "SourceUDP", CONF_STR, &options.sourceudp,
3390 "SourceTCP", CONF_STR, &options.sourcetcp,
3391 "SourceTLS", CONF_STR, &options.sourcetls,
3392 "SourceDTLS", CONF_STR, &options.sourcedtls,
3393 "LogLevel", CONF_LINT, &loglevel,
3394 "LogDestination", CONF_STR, &options.logdestination,
3395 "LoopPrevention", CONF_BLN, &options.loopprevention,
3396 "Client", CONF_CBK, confclient_cb, NULL,
3397 "Server", CONF_CBK, confserver_cb, NULL,
3398 "Realm", CONF_CBK, confrealm_cb, NULL,
3399 "TLS", CONF_CBK, conftls_cb, NULL,
3400 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3403 debugx(1, DBG_ERR, "configuration error");
3405 if (loglevel != LONG_MIN) {
3406 if (loglevel < 1 || loglevel > 4)
3407 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3408 options.loglevel = (uint8_t)loglevel;
3412 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3415 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3418 *configfile = optarg;
3421 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3422 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3423 *loglevel = *optarg - '0';
3432 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3437 if (!(argc - optind))
3441 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3445 int daemon(int a, int b) {
3453 for (i = 0; i < 3; i++) {
3455 open("/dev/null", O_RDWR);
3461 void *sighandler(void *arg) {
3466 sigemptyset(&sigset);
3467 sigaddset(&sigset, SIGPIPE);
3468 sigwait(&sigset, &sig);
3469 /* only get SIGPIPE right now, so could simplify below code */
3472 /* completely ignoring this */
3475 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3478 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3483 int main(int argc, char **argv) {
3486 struct list_node *entry;
3487 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3488 char *configfile = NULL;
3489 struct clsrvconf *srvconf;
3492 debug_init("radsecproxy");
3493 debug_set_level(DEBUG_LEVEL);
3495 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3497 debug_set_level(loglevel);
3498 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3500 options.loglevel = loglevel;
3501 else if (options.loglevel)
3502 debug_set_level(options.loglevel);
3504 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3505 free(options.logdestination);
3507 if (!list_first(clconfs))
3508 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3509 if (!list_first(realms))
3510 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3513 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3515 if (!foreground && (daemon(0, 0) < 0))
3516 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3518 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3520 sigemptyset(&sigset);
3521 /* exit on all but SIGPIPE, ignore more? */
3522 sigaddset(&sigset, SIGPIPE);
3523 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3524 pthread_create(&sigth, NULL, sighandler, NULL);
3526 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3527 srvconf = (struct clsrvconf *)entry->data;
3528 if (srvconf->dynamiclookupcommand)
3530 if (!addserver(srvconf))
3531 debugx(1, DBG_ERR, "failed to add server");
3532 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3533 (void *)(srvconf->servers)))
3534 debugx(1, DBG_ERR, "pthread_create failed");
3536 /* srcprotores for UDP no longer needed */
3537 if (srcprotores[RAD_UDP]) {
3538 freeaddrinfo(srcprotores[RAD_UDP]);
3539 srcprotores[RAD_UDP] = NULL;
3542 for (i = 0; protodefs[i].name; i++)
3543 if (protodefs[i].initextra)
3544 protodefs[i].initextra();
3546 if (find_clconf_type(RAD_TCP, NULL))
3547 createlisteners(RAD_TCP, options.listentcp);
3549 if (find_clconf_type(RAD_TLS, NULL))
3550 createlisteners(RAD_TLS, options.listentls);
3552 if (find_clconf_type(RAD_DTLS, NULL))
3553 createlisteners(RAD_DTLS, options.listendtls);
3555 if (find_clconf_type(RAD_UDP, NULL)) {
3556 createlisteners(RAD_UDP, options.listenudp);
3557 if (options.listenaccudp)
3558 createlisteners(RAD_UDP, options.listenaccudp);
3561 /* just hang around doing nothing, anything to do here? */