2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* Code contributions from:
11 * Arne Schwabe <schwabe at uni-paderborn.de>
14 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
15 * rd is responsible for init and launching wr
16 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
17 * each tlsserverrd launches tlsserverwr
18 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
19 * for init and launching rd
21 * serverrd will receive a request, processes it and puts it in the requestq of
22 * the appropriate clientwr
23 * clientwr monitors its requestq and sends requests
24 * clientrd looks for responses, processes them and puts them in the replyq of
25 * the peer the request came from
26 * serverwr monitors its reply and sends replies
28 * In addition to the main thread, we have:
29 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
30 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
31 * For each TLS peer connecting to us there will be 2 more TLS threads
32 * This is only for connected peers
33 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
34 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
38 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
39 * Also useful for TCP accounting which is not yet supported?
40 * We are not removing client requests from dynamic servers, see removeclientrqs()
41 * Reserve ID 0 for statusserver requests?
42 * Need to remove UDP clients when no activity for a while...
43 * Remove expired stuff from clients request list?
47 #include <sys/socket.h>
48 #include <netinet/in.h>
57 #include <sys/types.h>
58 #include <sys/select.h>
61 #include <arpa/inet.h>
65 #include <openssl/ssl.h>
66 #include <openssl/rand.h>
67 #include <openssl/err.h>
68 #include <openssl/md5.h>
69 #include <openssl/hmac.h>
70 #include <openssl/x509v3.h>
76 #include "radsecproxy.h"
82 static struct options options;
83 static struct list *clconfs, *srvconfs;
85 struct hash *tlsconfs, *rewriteconfs;
87 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
89 static pthread_mutex_t *ssl_locks = NULL;
90 static long *ssl_lock_count;
94 /* minimum required declarations to avoid reordering code */
95 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
96 int dynamicconfig(struct server *server);
97 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
98 void freerealm(struct realm *realm);
99 void freeclsrvconf(struct clsrvconf *conf);
100 void freerq(struct request *rq);
101 void freerqoutdata(struct rqout *rqout);
102 void rmclientrq(struct request *rq, uint8_t id);
104 static const struct protodefs protodefs[] = {
105 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
106 NULL, /* secretdefault */
107 SOCK_DGRAM, /* socktype */
108 "1812", /* portdefault */
109 REQUEST_RETRY_COUNT, /* retrycountdefault */
110 10, /* retrycountmax */
111 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
112 60, /* retryintervalmax */
113 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
114 udpserverrd, /* listener */
115 &options.sourceudp, /* srcaddrport */
116 NULL, /* connecter */
117 NULL, /* clientconnreader */
118 clientradputudp, /* clientradput */
119 addclientudp, /* addclient */
120 addserverextraudp, /* addserverextra */
121 initextraudp /* initextra */
123 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
124 "mysecret", /* secretdefault */
125 SOCK_STREAM, /* socktype */
126 "2083", /* portdefault */
127 0, /* retrycountdefault */
128 0, /* retrycountmax */
129 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
130 60, /* retryintervalmax */
131 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
132 tlslistener, /* listener */
133 &options.sourcetls, /* srcaddrport */
134 tlsconnect, /* connecter */
135 tlsclientrd, /* clientconnreader */
136 clientradputtls, /* clientradput */
137 NULL, /* addclient */
138 NULL, /* addserverextra */
141 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
142 NULL, /* secretdefault */
143 SOCK_STREAM, /* socktype */
144 "1812", /* portdefault */
145 0, /* retrycountdefault */
146 0, /* retrycountmax */
147 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
148 60, /* retryintervalmax */
149 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
150 tcplistener, /* listener */
151 &options.sourcetcp, /* srcaddrport */
152 tcpconnect, /* connecter */
153 tcpclientrd, /* clientconnreader */
154 clientradputtcp, /* clientradput */
155 NULL, /* addclient */
156 NULL, /* addserverextra */
159 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
160 "mysecret", /* secretdefault */
161 SOCK_DGRAM, /* socktype */
162 "2083", /* portdefault */
163 REQUEST_RETRY_COUNT, /* retrycountdefault */
164 10, /* retrycountmax */
165 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
166 60, /* retryintervalmax */
167 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
168 udpdtlsserverrd, /* listener */
169 &options.sourcedtls, /* srcaddrport */
170 dtlsconnect, /* connecter */
171 dtlsclientrd, /* clientconnreader */
172 clientradputdtls, /* clientradput */
173 NULL, /* addclient */
174 addserverextradtls, /* addserverextra */
175 initextradtls /* initextra */
181 uint8_t protoname2int(const char *name) {
184 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
188 /* callbacks for making OpenSSL thread safe */
189 unsigned long ssl_thread_id() {
190 return (unsigned long)pthread_self();
193 void ssl_locking_callback(int mode, int type, const char *file, int line) {
194 if (mode & CRYPTO_LOCK) {
195 pthread_mutex_lock(&ssl_locks[type]);
196 ssl_lock_count[type]++;
198 pthread_mutex_unlock(&ssl_locks[type]);
201 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
202 int pwdlen = strlen(userdata);
203 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
205 memcpy(buf, userdata, pwdlen);
209 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
214 err_cert = X509_STORE_CTX_get_current_cert(ctx);
215 err = X509_STORE_CTX_get_error(ctx);
216 depth = X509_STORE_CTX_get_error_depth(ctx);
218 if (depth > MAX_CERT_DEPTH) {
220 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
221 X509_STORE_CTX_set_error(ctx, err);
225 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
226 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
229 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
230 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
231 debug(DBG_WARN, "\tIssuer=%s", buf);
233 case X509_V_ERR_CERT_NOT_YET_VALID:
234 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
235 debug(DBG_WARN, "\tCertificate not yet valid");
237 case X509_V_ERR_CERT_HAS_EXPIRED:
238 debug(DBG_WARN, "Certificate has expired");
240 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
241 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
246 printf("certificate verify returns %d\n", ok);
251 struct addrinfo *getsrcprotores(uint8_t type) {
252 return srcprotores[type];
255 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
256 struct addrinfo hints, *addrinfo, *res;
260 slash = conf->host ? strchr(conf->host, '/') : NULL;
264 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
268 if (*s < '0' || *s > '9') {
269 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
272 plen = atoi(slash + 1);
273 if (plen < 0 || plen > 128) {
274 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
279 memset(&hints, 0, sizeof(hints));
280 hints.ai_socktype = conf->pdef->socktype;
281 hints.ai_family = AF_UNSPEC;
282 hints.ai_flags = ai_flags;
283 if (!conf->host && !conf->port) {
284 /* getaddrinfo() doesn't like host and port to be NULL */
285 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
286 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
289 for (res = addrinfo; res; res = res->ai_next)
290 port_set(res->ai_addr, 0);
293 hints.ai_flags |= AI_NUMERICHOST;
294 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
295 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
300 switch (addrinfo->ai_family) {
303 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
304 freeaddrinfo(addrinfo);
311 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
312 freeaddrinfo(addrinfo);
315 conf->prefixlen = plen;
317 conf->prefixlen = 255;
320 freeaddrinfo(conf->addrinfo);
321 conf->addrinfo = addrinfo;
325 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
330 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
334 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
336 debugx(1, DBG_ERR, "no ] matching initial [");
340 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
343 debugx(1, DBG_ERR, "missing host/address");
345 conf->host = stringcopy(field, p - field);
348 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
349 debugx(1, DBG_ERR, "unexpected character after ]");
352 /* port number or service name is specified */;
354 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
356 debugx(1, DBG_ERR, "syntax error, : but no following port");
357 conf->port = stringcopy(field, p - field);
359 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
363 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
364 struct clsrvconf *conf;
366 conf = malloc(sizeof(struct clsrvconf));
368 debugx(1, DBG_ERR, "malloc failed");
369 memset(conf, 0, sizeof(struct clsrvconf));
371 conf->pdef = &protodefs[conf->type];
373 parsehostport(lconf, conf, default_port);
374 if (!strcmp(conf->host, "*")) {
379 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
380 if (!resolvepeer(conf, AI_PASSIVE))
381 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
385 void freeclsrvres(struct clsrvconf *res) {
389 freeaddrinfo(res->addrinfo);
393 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
395 struct addrinfo *res;
397 for (res = addrinfo; res; res = res->ai_next) {
398 if (family != AF_UNSPEC && family != res->ai_family)
400 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
402 debug(DBG_WARN, "bindtoaddr: socket failed");
406 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
409 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
411 if (!bind(s, res->ai_addr, res->ai_addrlen))
413 debug(DBG_WARN, "bindtoaddr: bind failed");
419 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
421 struct addrinfo *res;
424 for (res = addrinfo; res; res = res->ai_next) {
425 s = bindtoaddr(src, res->ai_family, 1, 1);
427 debug(DBG_WARN, "connecttoserver: socket failed");
430 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
432 debug(DBG_WARN, "connecttoserver: connect failed");
439 /* returns 1 if the len first bits are equal, else 0 */
440 int prefixmatch(void *a1, void *a2, uint8_t len) {
441 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
443 if (l && memcmp(a1, a2, l))
448 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
451 /* returns next config with matching address, or NULL */
452 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
453 struct sockaddr_in6 *sa6 = NULL;
454 struct in_addr *a4 = NULL;
455 struct addrinfo *res;
456 struct list_node *entry;
457 struct clsrvconf *conf;
459 if (addr->sa_family == AF_INET6) {
460 sa6 = (struct sockaddr_in6 *)addr;
461 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
462 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
466 a4 = &((struct sockaddr_in *)addr)->sin_addr;
468 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
469 conf = (struct clsrvconf *)entry->data;
470 if (conf->type == type) {
471 if (conf->prefixlen == 255) {
472 for (res = conf->addrinfo; res; res = res->ai_next)
473 if ((a4 && res->ai_family == AF_INET &&
474 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
475 (sa6 && res->ai_family == AF_INET6 &&
476 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
482 res = conf->addrinfo;
484 ((a4 && res->ai_family == AF_INET &&
485 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
486 (sa6 && res->ai_family == AF_INET6 &&
487 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
498 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
499 return find_conf(type, addr, clconfs, cur);
502 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
503 return find_conf(type, addr, srvconfs, cur);
506 /* returns next config of given type, or NULL */
507 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
508 struct list_node *entry;
509 struct clsrvconf *conf;
511 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
512 conf = (struct clsrvconf *)entry->data;
513 if (conf->type == type) {
522 struct queue *newqueue() {
525 q = malloc(sizeof(struct queue));
527 debugx(1, DBG_ERR, "malloc failed");
528 q->entries = list_create();
530 debugx(1, DBG_ERR, "malloc failed");
531 pthread_mutex_init(&q->mutex, NULL);
532 pthread_cond_init(&q->cond, NULL);
536 void removequeue(struct queue *q) {
537 struct list_node *entry;
541 pthread_mutex_lock(&q->mutex);
542 for (entry = list_first(q->entries); entry; entry = list_next(entry))
543 freerq((struct request *)entry);
544 list_destroy(q->entries);
545 pthread_cond_destroy(&q->cond);
546 pthread_mutex_unlock(&q->mutex);
547 pthread_mutex_destroy(&q->mutex);
551 void freebios(struct queue *q) {
554 pthread_mutex_lock(&q->mutex);
555 while ((bio = (BIO *)list_shift(q->entries)))
557 pthread_mutex_unlock(&q->mutex);
561 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
562 struct client *new = malloc(sizeof(struct client));
565 debug(DBG_ERR, "malloc failed");
570 pthread_mutex_lock(conf->lock);
571 if (!conf->clients) {
572 conf->clients = list_create();
573 if (!conf->clients) {
575 pthread_mutex_unlock(conf->lock);
576 debug(DBG_ERR, "malloc failed");
581 memset(new, 0, sizeof(struct client));
583 if (conf->pdef->addclient)
584 conf->pdef->addclient(new);
586 new->replyq = newqueue();
587 list_push(conf->clients, new);
589 pthread_mutex_unlock(conf->lock);
593 void removeclient(struct client *client) {
594 struct clsrvconf *conf;
599 pthread_mutex_lock(conf->lock);
601 removequeue(client->replyq);
602 list_removedata(conf->clients, client);
606 pthread_mutex_unlock(conf->lock);
609 void removeclientrqs(struct client *client) {
610 struct list_node *entry;
611 struct server *server;
615 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
616 server = ((struct clsrvconf *)entry->data)->servers;
619 for (i = 0; i < MAX_REQUESTS; i++) {
620 rqout = server->requests + i;
621 pthread_mutex_lock(rqout->lock);
622 if (rqout->rq && rqout->rq->from == client)
623 freerqoutdata(rqout);
624 pthread_mutex_unlock(rqout->lock);
629 void freeserver(struct server *server, uint8_t destroymutex) {
630 struct rqout *rqout, *end;
635 if (server->requests) {
636 rqout = server->requests;
637 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
638 freerqoutdata(rqout);
639 pthread_mutex_destroy(rqout->lock);
642 free(server->requests);
645 freebios(server->rbios);
646 free(server->dynamiclookuparg);
648 SSL_free(server->ssl);
650 pthread_mutex_destroy(&server->lock);
651 pthread_cond_destroy(&server->newrq_cond);
652 pthread_mutex_destroy(&server->newrq_mutex);
657 int addserver(struct clsrvconf *conf) {
658 struct clsrvconf *res;
663 debug(DBG_ERR, "addserver: currently works with just one server per conf");
666 conf->servers = malloc(sizeof(struct server));
667 if (!conf->servers) {
668 debug(DBG_ERR, "malloc failed");
671 memset(conf->servers, 0, sizeof(struct server));
672 conf->servers->conf = conf;
675 if (type == RAD_DTLS)
676 conf->servers->rbios = newqueue();
678 if (!srcprotores[type]) {
679 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
680 srcprotores[type] = res->addrinfo;
681 res->addrinfo = NULL;
685 conf->servers->sock = -1;
686 if (conf->pdef->addserverextra)
687 conf->pdef->addserverextra(conf);
689 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
690 if (!conf->servers->requests) {
691 debug(DBG_ERR, "malloc failed");
694 for (i = 0; i < MAX_REQUESTS; i++) {
695 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
696 if (!conf->servers->requests[i].lock) {
697 debug(DBG_ERR, "malloc failed");
700 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
701 debug(DBG_ERR, "mutex init failed");
702 free(conf->servers->requests[i].lock);
703 conf->servers->requests[i].lock = NULL;
707 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
708 debug(DBG_ERR, "mutex init failed");
711 conf->servers->newrq = 0;
712 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
713 debug(DBG_ERR, "mutex init failed");
714 pthread_mutex_destroy(&conf->servers->lock);
717 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
718 debug(DBG_ERR, "mutex init failed");
719 pthread_mutex_destroy(&conf->servers->newrq_mutex);
720 pthread_mutex_destroy(&conf->servers->lock);
727 freeserver(conf->servers, 0);
728 conf->servers = NULL;
732 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
733 int loc, i, l, n, r = 0;
736 STACK_OF(GENERAL_NAME) *alt;
739 debug(DBG_DBG, "subjectaltnameaddr");
741 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
745 ex = X509_get_ext(cert, loc);
746 alt = X509V3_EXT_d2i(ex);
750 n = sk_GENERAL_NAME_num(alt);
751 for (i = 0; i < n; i++) {
752 gn = sk_GENERAL_NAME_value(alt, i);
753 if (gn->type != GEN_IPADD)
756 v = (char *)ASN1_STRING_data(gn->d.ia5);
757 l = ASN1_STRING_length(gn->d.ia5);
758 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
759 && !memcmp(v, &addr, l)) {
764 GENERAL_NAMES_free(alt);
768 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
775 nm = X509_get_subject_name(cert);
778 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
781 e = X509_NAME_get_entry(nm, loc);
782 t = X509_NAME_ENTRY_get_data(e);
783 v = (char *) ASN1_STRING_data(t);
784 l = ASN1_STRING_length(t);
788 if (l == strlen(exact) && !strncasecmp(exact, v, l))
791 s = stringcopy((char *)v, l);
793 debug(DBG_ERR, "malloc failed");
796 if (regexec(regex, s, 0, NULL, 0)) {
807 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
808 int loc, i, l, n, r = 0;
811 STACK_OF(GENERAL_NAME) *alt;
814 debug(DBG_DBG, "subjectaltnameregexp");
816 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
820 ex = X509_get_ext(cert, loc);
821 alt = X509V3_EXT_d2i(ex);
825 n = sk_GENERAL_NAME_num(alt);
826 for (i = 0; i < n; i++) {
827 gn = sk_GENERAL_NAME_value(alt, i);
828 if (gn->type != type)
831 v = (char *)ASN1_STRING_data(gn->d.ia5);
832 l = ASN1_STRING_length(gn->d.ia5);
836 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
839 if (memcmp(v, exact, l))
842 s = stringcopy((char *)v, l);
844 debug(DBG_ERR, "malloc failed");
847 if (regexec(regex, s, 0, NULL, 0)) {
856 GENERAL_NAMES_free(alt);
860 X509 *verifytlscert(SSL *ssl) {
864 if (SSL_get_verify_result(ssl) != X509_V_OK) {
865 debug(DBG_ERR, "verifytlscert: basic validation failed");
866 while ((error = ERR_get_error()))
867 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
871 cert = SSL_get_peer_certificate(ssl);
873 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
877 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
879 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
880 struct in6_addr addr;
882 if (conf->certnamecheck && conf->prefixlen == 255) {
883 if (inet_pton(AF_INET, conf->host, &addr))
885 else if (inet_pton(AF_INET6, conf->host, &addr))
888 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
891 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
894 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
896 if (!cnregexp(cert, conf->host, NULL)) {
897 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
900 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
903 if (conf->certcnregex) {
904 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
905 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
908 debug(DBG_DBG, "verifyconfcert: CN matching regex");
910 if (conf->certuriregex) {
911 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
912 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
915 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
920 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
922 if (ATTRTYPE(attrs) == type)
924 length -= ATTRLEN(attrs);
925 attrs += ATTRLEN(attrs);
930 void freerq(struct request *rq) {
933 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
936 if (rq->origusername)
937 free(rq->origusername);
943 radmsg_free(rq->msg);
947 void freerqoutdata(struct rqout *rqout) {
955 memset(&rqout->expiry, 0, sizeof(struct timeval));
958 void sendrq(struct server *to, struct request *rq) {
961 pthread_mutex_lock(&to->newrq_mutex);
962 /* might simplify if only try nextid, might be ok */
963 for (i = to->nextid; i < MAX_REQUESTS; i++) {
964 if (!to->requests[i].rq) {
965 pthread_mutex_lock(to->requests[i].lock);
966 if (!to->requests[i].rq)
968 pthread_mutex_unlock(to->requests[i].lock);
971 if (i == MAX_REQUESTS) {
972 for (i = 0; i < to->nextid; i++) {
973 if (!to->requests[i].rq) {
974 pthread_mutex_lock(to->requests[i].lock);
975 if (!to->requests[i].rq)
977 pthread_mutex_unlock(to->requests[i].lock);
980 if (i == to->nextid) {
981 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
982 rmclientrq(rq, rq->msg->id);
988 rq->msg->id = (uint8_t)i;
989 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
991 pthread_mutex_unlock(to->requests[i].lock);
992 debug(DBG_ERR, "sendrq: radmsg2buf failed");
993 rmclientrq(rq, rq->msg->id);
998 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
999 to->requests[i].rq = rq;
1000 pthread_mutex_unlock(to->requests[i].lock);
1005 debug(DBG_DBG, "sendrq: signalling client writer");
1006 pthread_cond_signal(&to->newrq_cond);
1010 pthread_mutex_unlock(&to->newrq_mutex);
1013 void sendreply(struct request *rq) {
1015 struct client *to = rq->from;
1018 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1019 radmsg_free(rq->msg);
1021 if (!rq->replybuf) {
1023 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1027 pthread_mutex_lock(&to->replyq->mutex);
1028 first = list_first(to->replyq->entries) == NULL;
1030 if (!list_push(to->replyq->entries, rq)) {
1031 pthread_mutex_unlock(&to->replyq->mutex);
1033 debug(DBG_ERR, "sendreply: malloc failed");
1038 debug(DBG_DBG, "signalling server writer");
1039 pthread_cond_signal(&to->replyq->cond);
1041 pthread_mutex_unlock(&to->replyq->mutex);
1044 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1045 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1046 static unsigned char first = 1;
1047 static EVP_MD_CTX mdctx;
1048 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1049 unsigned int md_len;
1050 uint8_t i, offset = 0, out[128];
1052 pthread_mutex_lock(&lock);
1054 EVP_MD_CTX_init(&mdctx);
1060 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1061 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1062 !EVP_DigestUpdate(&mdctx, input, 16) ||
1063 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1065 pthread_mutex_unlock(&lock);
1068 for (i = 0; i < 16; i++)
1069 out[offset + i] = hash[i] ^ in[offset + i];
1070 input = out + offset - 16;
1075 memcpy(in, out, len);
1076 pthread_mutex_unlock(&lock);
1080 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1081 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1082 static unsigned char first = 1;
1083 static EVP_MD_CTX mdctx;
1084 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1085 unsigned int md_len;
1086 uint8_t i, offset = 0, out[128];
1088 pthread_mutex_lock(&lock);
1090 EVP_MD_CTX_init(&mdctx);
1096 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1097 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1098 !EVP_DigestUpdate(&mdctx, input, 16) ||
1099 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1101 pthread_mutex_unlock(&lock);
1104 for (i = 0; i < 16; i++)
1105 out[offset + i] = hash[i] ^ in[offset + i];
1106 input = in + offset;
1111 memcpy(in, out, len);
1112 pthread_mutex_unlock(&lock);
1116 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1117 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1118 static unsigned char first = 1;
1119 static EVP_MD_CTX mdctx;
1120 unsigned char hash[EVP_MAX_MD_SIZE];
1121 unsigned int md_len;
1124 pthread_mutex_lock(&lock);
1126 EVP_MD_CTX_init(&mdctx);
1131 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1132 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1133 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1136 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1137 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1138 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1139 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1140 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1141 pthread_mutex_unlock(&lock);
1146 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1149 for (i = 0; i < 16; i++)
1152 for (offset = 16; offset < len; offset += 16) {
1154 printf("text + offset - 16 c(%d): ", offset / 16);
1155 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1157 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1158 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1159 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1160 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1162 pthread_mutex_unlock(&lock);
1166 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1169 for (i = 0; i < 16; i++)
1170 text[offset + i] ^= hash[i];
1174 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1177 pthread_mutex_unlock(&lock);
1181 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1182 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1183 static unsigned char first = 1;
1184 static EVP_MD_CTX mdctx;
1185 unsigned char hash[EVP_MAX_MD_SIZE];
1186 unsigned int md_len;
1190 pthread_mutex_lock(&lock);
1192 EVP_MD_CTX_init(&mdctx);
1197 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1198 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1199 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1202 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1203 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1204 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1205 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1206 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1207 pthread_mutex_unlock(&lock);
1212 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1215 for (i = 0; i < 16; i++)
1216 plain[i] = text[i] ^ hash[i];
1218 for (offset = 16; offset < len; offset += 16) {
1220 printf("text + offset - 16 c(%d): ", offset / 16);
1221 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1223 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1224 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1225 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1226 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1228 pthread_mutex_unlock(&lock);
1232 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1235 for (i = 0; i < 16; i++)
1236 plain[offset + i] = text[offset + i] ^ hash[i];
1239 memcpy(text, plain, len);
1241 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1244 pthread_mutex_unlock(&lock);
1248 struct realm *id2realm(struct list *realmlist, char *id) {
1249 struct list_node *entry;
1250 struct realm *realm, *subrealm = NULL;
1252 /* need to do locking for subrealms and check subrealm timers */
1253 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1254 realm = (struct realm *)entry->data;
1255 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1256 pthread_mutex_lock(&realm->subrealms_mutex);
1257 if (realm->subrealms)
1258 subrealm = id2realm(realm->subrealms, id);
1259 pthread_mutex_unlock(&realm->subrealms_mutex);
1260 return subrealm ? subrealm : realm;
1266 /* helper function, only used by removeserversubrealms() */
1267 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1268 struct list_node *entry;
1269 struct realm *realm;
1271 for (entry = list_first(realmlist); entry;) {
1272 realm = (struct realm *)entry->data;
1273 entry = list_next(entry);
1274 if (realm->srvconfs) {
1275 list_removedata(realm->srvconfs, srv);
1276 if (!list_first(realm->srvconfs)) {
1277 list_destroy(realm->srvconfs);
1278 realm->srvconfs = NULL;
1281 if (realm->accsrvconfs) {
1282 list_removedata(realm->accsrvconfs, srv);
1283 if (!list_first(realm->accsrvconfs)) {
1284 list_destroy(realm->accsrvconfs);
1285 realm->accsrvconfs = NULL;
1289 /* remove subrealm if no servers */
1290 if (!realm->srvconfs && !realm->accsrvconfs) {
1291 list_removedata(realmlist, realm);
1297 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1298 struct list_node *entry;
1299 struct realm *realm;
1301 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1302 realm = (struct realm *)entry->data;
1303 pthread_mutex_lock(&realm->subrealms_mutex);
1304 if (realm->subrealms) {
1305 _internal_removeserversubrealms(realm->subrealms, srv);
1306 if (!list_first(realm->subrealms)) {
1307 list_destroy(realm->subrealms);
1308 realm->subrealms = NULL;
1311 pthread_mutex_unlock(&realm->subrealms_mutex);
1315 int attrvalidate(unsigned char *attrs, int length) {
1316 while (length > 1) {
1317 if (ATTRLEN(attrs) < 2) {
1318 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1321 length -= ATTRLEN(attrs);
1323 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1326 attrs += ATTRLEN(attrs);
1329 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1333 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1334 if (len < 16 || len > 128 || len % 16) {
1335 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1339 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1340 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1344 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1346 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1347 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1353 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1356 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1357 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1360 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1361 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1367 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1368 char *oldsecret, char *newsecret) {
1369 unsigned char *attr;
1371 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1372 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1373 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1379 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1383 for (; attrs[0]; attrs += 2)
1384 if (attrs[0] == vendor && attrs[1] == subattr)
1389 /* returns 1 if entire element is to be removed, else 0 */
1390 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1391 uint8_t alen, sublen;
1395 if (!removevendorattrs)
1398 memcpy(&vendor, attr->v, 4);
1399 vendor = ntohl(vendor);
1400 while (*removevendorattrs && *removevendorattrs != vendor)
1401 removevendorattrs += 2;
1402 if (!*removevendorattrs)
1405 if (findvendorsubattr(removevendorattrs, vendor, -1))
1406 return 1; /* remove entire vendor attribute */
1408 sublen = attr->l - 4;
1409 subattrs = attr->v + 4;
1411 if (!attrvalidate(subattrs, sublen)) {
1412 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1416 while (sublen > 1) {
1417 alen = ATTRLEN(subattrs);
1419 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1420 memmove(subattrs, subattrs + alen, sublen);
1428 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1429 struct list_node *n, *p;
1433 n = list_first(msg->attrs);
1435 attr = (struct tlv *)n->data;
1436 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1437 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1438 list_removedata(msg->attrs, attr);
1440 n = p ? list_next(p) : list_first(msg->attrs);
1447 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1448 struct list_node *n;
1451 for (n = list_first(addattrs); n; n = list_next(n)) {
1452 a = copytlv((struct tlv *)n->data);
1455 if (!radmsg_add(msg, a)) {
1463 int resizeattr(struct tlv *attr, uint8_t newlen) {
1466 if (newlen != attr->l) {
1467 newv = realloc(attr->v, newlen);
1476 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1477 size_t nmatch = 10, reslen = 0, start = 0;
1478 regmatch_t pmatch[10], *pfield;
1482 in = stringcopy((char *)attr->v, attr->l);
1486 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1491 out = modattr->replacement;
1493 for (i = start; out[i]; i++) {
1494 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1495 pfield = &pmatch[out[i + 1] - '0'];
1496 if (pfield->rm_so >= 0) {
1497 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1503 reslen += i - start;
1505 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1510 if (!resizeattr(attr, reslen)) {
1517 for (i = start; out[i]; i++) {
1518 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1519 pfield = &pmatch[out[i + 1] - '0'];
1520 if (pfield->rm_so >= 0) {
1521 memcpy(attr->v + reslen, out + start, i - start);
1522 reslen += i - start;
1523 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1524 reslen += pfield->rm_eo - pfield->rm_so;
1531 memcpy(attr->v + reslen, out + start, i - start);
1535 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1536 struct list_node *n, *m;
1538 for (n = list_first(msg->attrs); n; n = list_next(n))
1539 for (m = list_first(modattrs); m; m = list_next(m))
1540 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1541 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1546 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1549 if (rewrite->removeattrs || rewrite->removevendorattrs)
1550 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1551 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1553 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1558 int rewriteusername(struct request *rq, struct tlv *attr) {
1559 char *orig = (char *)tlv2str(attr);
1560 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1564 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1565 rq->origusername = (char *)orig;
1571 const char *radmsgtype2string(uint8_t code) {
1572 static const char *rad_msg_names[] = {
1573 "", "Access-Request", "Access-Accept", "Access-Reject",
1574 "Accounting-Request", "Accounting-Response", "", "",
1575 "", "", "", "Access-Challenge",
1576 "Status-Server", "Status-Client"
1578 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1581 void char2hex(char *h, unsigned char c) {
1582 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1583 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1584 h[0] = hexdigits[c / 16];
1585 h[1] = hexdigits[c % 16];
1589 uint8_t *radattr2ascii(struct tlv *attr) {
1597 for (i = 0; i < attr->l; i++)
1598 if (attr->v[i] < 32 || attr->v[i] > 126)
1601 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1608 for (i = 0; i < attr->l; i++)
1609 if (attr->v[i] < 32 || attr->v[i] > 126) {
1611 char2hex((char *)d, attr->v[i]);
1619 void acclog(struct radmsg *msg, char *host) {
1623 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1625 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1628 username = radattr2ascii(attr);
1630 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1635 void respond(struct request *rq, uint8_t code, char *message) {
1639 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1641 debug(DBG_ERR, "respond: malloc failed");
1644 if (message && *message) {
1645 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1646 if (!attr || !radmsg_add(msg, attr)) {
1649 debug(DBG_ERR, "respond: malloc failed");
1654 radmsg_free(rq->msg);
1656 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1661 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1662 struct list_node *entry;
1663 struct clsrvconf *server, *best = NULL, *first = NULL;
1665 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1666 server = (struct clsrvconf *)entry->data;
1667 if (!server->servers)
1671 if (!server->servers->connectionok)
1673 if (!server->servers->lostrqs)
1679 if (server->servers->lostrqs < best->servers->lostrqs)
1682 return best ? best : first;
1685 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1686 struct clsrvconf *srvconf;
1687 char *id = (char *)tlv2str(username);
1691 *realm = id2realm(realms, id);
1696 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1697 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1702 if (!acc && !srvconf->servers)
1703 adddynamicrealmserver(*realm, srvconf, id);
1705 return srvconf->servers;
1709 struct request *newrequest() {
1712 rq = malloc(sizeof(struct request));
1714 debug(DBG_ERR, "newrequest: malloc failed");
1717 memset(rq, 0, sizeof(struct request));
1719 gettimeofday(&rq->created, NULL);
1723 int addclientrq(struct request *rq) {
1727 r = rq->from->rqs[rq->rqid];
1729 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1730 gettimeofday(&now, NULL);
1731 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1733 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1737 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1744 rq->from->rqs[rq->rqid] = rq;
1748 void rmclientrq(struct request *rq, uint8_t id) {
1751 r = rq->from->rqs[id];
1754 rq->from->rqs[id] = NULL;
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 struct realm *realm = NULL;
1764 struct server *to = NULL;
1765 struct client *from = rq->from;
1767 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1772 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1779 memcpy(rq->rqauth, msg->auth, 16);
1781 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1782 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1783 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1787 if (!addclientrq(rq))
1790 if (msg->code == RAD_Status_Server) {
1791 respond(rq, RAD_Access_Accept, NULL);
1795 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1797 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1800 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1802 if (msg->code == RAD_Accounting_Request) {
1803 acclog(msg, from->conf->host);
1804 respond(rq, RAD_Accounting_Response, NULL);
1806 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1810 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1811 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1815 userascii = radattr2ascii(attr);
1818 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1820 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1822 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1827 if (realm->message && msg->code == RAD_Access_Request) {
1828 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1829 respond(rq, RAD_Access_Reject, realm->message);
1830 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1831 acclog(msg, from->conf->host);
1832 respond(rq, RAD_Accounting_Response, NULL);
1837 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1838 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1839 from->conf->name, to->conf->name);
1843 if (msg->code == RAD_Accounting_Request)
1844 memset(msg->auth, 0, 16);
1845 else if (!RAND_bytes(msg->auth, 16)) {
1846 debug(DBG_WARN, "radsrv: failed to generate random auth");
1851 printfchars(NULL, "auth", "%02x ", auth, 16);
1854 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1856 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1857 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1861 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1863 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1864 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1868 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1876 rmclientrq(rq, msg->id);
1883 void replyh(struct server *server, unsigned char *buf) {
1884 struct client *from;
1885 struct rqout *rqout;
1887 unsigned char *subattrs;
1888 uint8_t *username, *stationid, *replymsg;
1889 struct radmsg *msg = NULL;
1891 struct list_node *node;
1893 server->connectionok = 1;
1894 server->lostrqs = 0;
1896 rqout = server->requests + buf[1];
1897 pthread_mutex_lock(rqout->lock);
1898 if (!rqout->tries) {
1901 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1905 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1909 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1912 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1913 && msg->code != RAD_Accounting_Response) {
1914 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1917 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1919 gettimeofday(&server->lastrcv, NULL);
1921 if (rqout->rq->msg->code == RAD_Status_Server) {
1922 freerqoutdata(rqout);
1923 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1927 gettimeofday(&server->lastreply, NULL);
1928 from = rqout->rq->from;
1930 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1931 debug(DBG_WARN, "replyh: rewritein failed");
1936 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1937 attr = (struct tlv *)node->data;
1938 if (attr->t != RAD_Attr_Vendor_Specific)
1942 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1945 sublen = attr->l - 4;
1946 subattrs = attr->v + 4;
1947 if (!attrvalidate(subattrs, sublen) ||
1948 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1949 rqout->rq, server->conf->secret, from->conf->secret) ||
1950 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1951 rqout->rq, server->conf->secret, from->conf->secret))
1955 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1959 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1960 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1962 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1963 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1966 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1967 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1970 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1971 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1975 debug(DBG_INFO, "%s for user %s from %s (%s)",
1976 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1979 debug(DBG_INFO, "%s for user %s from %s",
1980 radmsgtype2string(msg->code), username, server->conf->host);
1986 msg->id = (char)rqout->rq->rqid;
1987 memcpy(msg->auth, rqout->rq->rqauth, 16);
1990 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1993 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1994 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1995 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1998 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2001 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2002 debug(DBG_WARN, "replyh: rewriteout failed");
2006 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2007 radmsg_free(rqout->rq->msg);
2008 rqout->rq->msg = msg;
2009 rqout->rq->refcount++;
2010 sendreply(rqout->rq);
2011 freerqoutdata(rqout);
2012 pthread_mutex_unlock(rqout->lock);
2017 pthread_mutex_unlock(rqout->lock);
2021 struct request *createstatsrvrq() {
2028 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2031 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2034 if (!radmsg_add(rq->msg, attr)) {
2045 /* code for removing state not finished */
2046 void *clientwr(void *arg) {
2047 struct server *server = (struct server *)arg;
2048 struct rqout *rqout = NULL;
2049 pthread_t clientrdth;
2050 int i, secs, dynconffail = 0;
2052 struct timeval now, laststatsrv;
2053 struct timespec timeout;
2054 struct request *statsrvrq;
2055 struct clsrvconf *conf;
2057 conf = server->conf;
2059 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2064 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2065 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2069 memset(&timeout, 0, sizeof(struct timespec));
2071 if (conf->statusserver) {
2072 gettimeofday(&server->lastrcv, NULL);
2073 gettimeofday(&laststatsrv, NULL);
2076 if (conf->pdef->connecter) {
2077 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2079 server->connectionok = 1;
2080 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2081 debug(DBG_ERR, "clientwr: pthread_create failed");
2085 server->connectionok = 1;
2088 pthread_mutex_lock(&server->newrq_mutex);
2089 if (!server->newrq) {
2090 gettimeofday(&now, NULL);
2091 /* random 0-7 seconds */
2092 RAND_bytes(&rnd, 1);
2094 if (conf->statusserver) {
2095 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2096 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2097 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2099 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2100 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2103 if (timeout.tv_sec > now.tv_sec)
2104 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2106 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2109 if (server->newrq) {
2110 debug(DBG_DBG, "clientwr: got new request");
2115 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2117 pthread_mutex_unlock(&server->newrq_mutex);
2119 for (i = 0; i < MAX_REQUESTS; i++) {
2120 if (server->clientrdgone) {
2121 pthread_join(clientrdth, NULL);
2125 for (; i < MAX_REQUESTS; i++) {
2126 rqout = server->requests + i;
2128 pthread_mutex_lock(rqout->lock);
2131 pthread_mutex_unlock(rqout->lock);
2135 if (i == MAX_REQUESTS)
2138 gettimeofday(&now, NULL);
2139 if (now.tv_sec < rqout->expiry.tv_sec) {
2140 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2141 timeout.tv_sec = rqout->expiry.tv_sec;
2142 pthread_mutex_unlock(rqout->lock);
2146 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2147 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2148 if (conf->statusserver) {
2149 if (*rqout->rq->buf == RAD_Status_Server) {
2150 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2151 if (server->lostrqs < 255)
2155 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2156 if (server->lostrqs < 255)
2159 freerqoutdata(rqout);
2160 pthread_mutex_unlock(rqout->lock);
2164 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2165 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2166 timeout.tv_sec = rqout->expiry.tv_sec;
2168 conf->pdef->clientradput(server, rqout->rq->buf);
2169 pthread_mutex_unlock(rqout->lock);
2171 if (conf->statusserver) {
2172 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2173 gettimeofday(&now, NULL);
2174 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2176 statsrvrq = createstatsrvrq();
2178 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2179 sendrq(server, statsrvrq);
2185 conf->servers = NULL;
2186 if (server->dynamiclookuparg) {
2187 removeserversubrealms(realms, conf);
2191 freeclsrvconf(conf);
2193 freeserver(server, 1);
2194 ERR_remove_state(0);
2198 void createlistener(uint8_t type, char *arg) {
2200 struct clsrvconf *listenres;
2201 struct addrinfo *res;
2202 int s = -1, on = 1, *sp = NULL;
2204 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2206 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2208 for (res = listenres->addrinfo; res; res = res->ai_next) {
2209 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2211 debug(DBG_WARN, "createlistener: socket failed");
2214 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2216 if (res->ai_family == AF_INET6)
2217 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2219 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2220 debug(DBG_WARN, "createlistener: bind failed");
2226 sp = malloc(sizeof(int));
2228 debugx(1, DBG_ERR, "malloc failed");
2230 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2231 debugx(1, DBG_ERR, "pthread_create failed");
2235 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2237 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2238 listenres->host ? listenres->host : "*", listenres->port);
2239 freeclsrvres(listenres);
2242 void createlisteners(uint8_t type, char **args) {
2246 for (i = 0; args[i]; i++)
2247 createlistener(type, args[i]);
2249 createlistener(type, NULL);
2253 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2257 w = where & ~SSL_ST_MASK;
2259 if (w & SSL_ST_CONNECT)
2261 else if (w & SSL_ST_ACCEPT)
2266 if (where & SSL_CB_LOOP)
2267 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2268 else if (where & SSL_CB_ALERT) {
2269 s = (where & SSL_CB_READ) ? "read" : "write";
2270 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2272 else if (where & SSL_CB_EXIT) {
2274 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2276 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2281 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2282 SSL_CTX *ctx = NULL;
2283 STACK_OF(X509_NAME) *calist;
2286 unsigned long error;
2289 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2290 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2291 for (i = 0; i < CRYPTO_num_locks(); i++) {
2292 ssl_lock_count[i] = 0;
2293 pthread_mutex_init(&ssl_locks[i], NULL);
2295 CRYPTO_set_id_callback(ssl_thread_id);
2296 CRYPTO_set_locking_callback(ssl_locking_callback);
2298 SSL_load_error_strings();
2301 while (!RAND_status()) {
2302 time_t t = time(NULL);
2303 pid_t pid = getpid();
2304 RAND_seed((unsigned char *)&t, sizeof(time_t));
2305 RAND_seed((unsigned char *)&pid, sizeof(pid));
2311 ctx = SSL_CTX_new(TLSv1_method());
2313 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2317 ctx = SSL_CTX_new(DTLSv1_method());
2319 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2321 SSL_CTX_set_read_ahead(ctx, 1);
2325 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2329 if (conf->certkeypwd) {
2330 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2331 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2333 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2334 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2335 !SSL_CTX_check_private_key(ctx) ||
2336 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2337 while ((error = ERR_get_error()))
2338 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2339 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2344 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2345 if (!conf->cacertfile || calist) {
2346 if (conf->cacertpath) {
2348 calist = sk_X509_NAME_new_null();
2349 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2350 sk_X509_NAME_free(calist);
2356 while ((error = ERR_get_error()))
2357 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2358 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2362 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2363 SSL_CTX_set_client_CA_list(ctx, calist);
2365 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2366 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2368 if (conf->crlcheck) {
2369 x509_s = SSL_CTX_get_cert_store(ctx);
2370 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2373 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2377 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2380 t = hash_read(tlsconfs, alt1, strlen(alt1));
2382 t = hash_read(tlsconfs, alt2, strlen(alt2));
2390 t->tlsctx = tlscreatectx(RAD_TLS, t);
2394 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2400 struct list *addsrvconfs(char *value, char **names) {
2401 struct list *conflist;
2403 struct list_node *entry;
2404 struct clsrvconf *conf = NULL;
2406 if (!names || !*names)
2409 conflist = list_create();
2411 debug(DBG_ERR, "malloc failed");
2415 for (n = 0; names[n]; n++) {
2416 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2417 conf = (struct clsrvconf *)entry->data;
2418 if (!strcasecmp(names[n], conf->name))
2422 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2423 list_destroy(conflist);
2426 if (!list_push(conflist, conf)) {
2427 debug(DBG_ERR, "malloc failed");
2428 list_destroy(conflist);
2431 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2436 void freerealm(struct realm *realm) {
2440 free(realm->message);
2441 regfree(&realm->regex);
2442 pthread_mutex_destroy(&realm->subrealms_mutex);
2443 if (realm->subrealms)
2444 list_destroy(realm->subrealms);
2445 if (realm->srvconfs) {
2446 /* emptying list without freeing data */
2447 while (list_shift(realm->srvconfs));
2448 list_destroy(realm->srvconfs);
2450 if (realm->accsrvconfs) {
2451 /* emptying list without freeing data */
2452 while (list_shift(realm->accsrvconfs));
2453 list_destroy(realm->accsrvconfs);
2458 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2460 struct realm *realm;
2461 char *s, *regex = NULL;
2463 if (*value == '/') {
2464 /* regexp, remove optional trailing / if present */
2465 if (value[strlen(value) - 1] == '/')
2466 value[strlen(value) - 1] = '\0';
2468 /* not a regexp, let us make it one */
2469 if (*value == '*' && !value[1])
2470 regex = stringcopy(".*", 0);
2472 for (n = 0, s = value; *s;)
2475 regex = malloc(strlen(value) + n + 3);
2478 for (n = 1, s = value; *s; s++) {
2488 debug(DBG_ERR, "malloc failed");
2492 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2495 realm = malloc(sizeof(struct realm));
2497 debug(DBG_ERR, "malloc failed");
2500 memset(realm, 0, sizeof(struct realm));
2502 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2503 debug(DBG_ERR, "mutex init failed");
2509 realm->name = stringcopy(value, 0);
2511 debug(DBG_ERR, "malloc failed");
2514 if (message && strlen(message) > 253) {
2515 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2518 realm->message = message;
2519 realm->accresp = accresp;
2521 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2522 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2526 if (servers && *servers) {
2527 realm->srvconfs = addsrvconfs(value, servers);
2528 if (!realm->srvconfs)
2532 if (accservers && *accservers) {
2533 realm->accsrvconfs = addsrvconfs(value, accservers);
2534 if (!realm->accsrvconfs)
2538 if (!list_push(realmlist, realm)) {
2539 debug(DBG_ERR, "malloc failed");
2540 pthread_mutex_destroy(&realm->subrealms_mutex);
2544 debug(DBG_DBG, "addrealm: added realm %s", value);
2554 for (n = 0; servers[n]; n++)
2559 for (n = 0; accservers[n]; n++)
2560 free(accservers[n]);
2566 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2567 struct clsrvconf *srvconf;
2568 struct realm *newrealm = NULL;
2569 char *realmname, *s;
2572 if (!conf->dynamiclookupcommand)
2575 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2576 realmname = strrchr(id, '@');
2582 for (s = realmname; *s; s++)
2583 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2586 pthread_mutex_lock(&realm->subrealms_mutex);
2587 /* exit if we now already got a matching subrealm */
2588 if (id2realm(realm->subrealms, id))
2590 srvconf = malloc(sizeof(struct clsrvconf));
2592 debug(DBG_ERR, "malloc failed");
2596 if (!addserver(srvconf))
2599 if (!realm->subrealms)
2600 realm->subrealms = list_create();
2601 if (!realm->subrealms)
2603 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2607 /* add server and accserver to newrealm */
2608 newrealm->srvconfs = list_create();
2609 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2610 debug(DBG_ERR, "malloc failed");
2613 newrealm->accsrvconfs = list_create();
2614 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2615 debug(DBG_ERR, "malloc failed");
2619 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2621 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2622 debug(DBG_ERR, "pthread_create failed");
2625 pthread_detach(clientth);
2630 list_removedata(realm->subrealms, newrealm);
2631 freerealm(newrealm);
2632 if (!list_first(realm->subrealms)) {
2633 list_destroy(realm->subrealms);
2634 realm->subrealms = NULL;
2637 freeserver(srvconf->servers, 1);
2639 debug(DBG_ERR, "failed to create dynamic server");
2642 pthread_mutex_unlock(&realm->subrealms_mutex);
2645 int dynamicconfig(struct server *server) {
2646 int ok, fd[2], status;
2648 struct clsrvconf *conf = server->conf;
2649 struct gconffile *cf = NULL;
2651 /* for now we only learn hostname/address */
2652 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2655 debug(DBG_ERR, "dynamicconfig: pipe error");
2660 debug(DBG_ERR, "dynamicconfig: fork error");
2664 } else if (pid == 0) {
2667 if (fd[1] != STDOUT_FILENO) {
2668 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2669 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2672 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2673 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2677 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2678 ok = getgenericconfig(&cf, NULL,
2679 "Server", CONF_CBK, confserver_cb, (void *)conf,
2684 if (waitpid(pid, &status, 0) < 0) {
2685 debug(DBG_ERR, "dynamicconfig: wait error");
2690 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2698 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2702 int addmatchcertattr(struct clsrvconf *conf) {
2706 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2707 r = &conf->certcnregex;
2708 v = conf->matchcertattr + 4;
2709 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2710 r = &conf->certuriregex;
2711 v = conf->matchcertattr + 20;
2716 /* regexp, remove optional trailing / if present */
2717 if (v[strlen(v) - 1] == '/')
2718 v[strlen(v) - 1] = '\0';
2722 *r = malloc(sizeof(regex_t));
2724 debug(DBG_ERR, "malloc failed");
2727 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2730 debug(DBG_ERR, "failed to compile regular expression %s", v);
2736 /* should accept both names and numeric values, only numeric right now */
2737 uint8_t attrname2val(char *attrname) {
2740 val = atoi(attrname);
2741 return val > 0 && val < 256 ? val : 0;
2744 /* should accept both names and numeric values, only numeric right now */
2745 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2748 *vendor = atoi(attrname);
2749 s = strchr(attrname, ':');
2754 *type = atoi(s + 1);
2755 return *type >= 0 && *type < 256;
2758 /* should accept both names and numeric values, only numeric right now */
2759 struct tlv *extractattr(char *nameval) {
2764 s = strchr(nameval, ':');
2765 name = atoi(nameval);
2766 if (!s || name < 1 || name > 255)
2768 len = strlen(s + 1);
2771 a = malloc(sizeof(struct tlv));
2774 a->v = (uint8_t *)stringcopy(s + 1, 0);
2784 /* should accept both names and numeric values, only numeric right now */
2785 struct modattr *extractmodattr(char *nameval) {
2790 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2794 s = strchr(nameval, ':');
2795 name = atoi(nameval);
2796 if (!s || name < 1 || name > 255 || s[1] != '/')
2800 /* regexp, remove optional trailing / if present */
2801 if (s[strlen(s) - 1] == '/')
2802 s[strlen(s) - 1] = '\0';
2810 m = malloc(sizeof(struct modattr));
2812 debug(DBG_ERR, "malloc failed");
2817 m->replacement = stringcopy(t, 0);
2818 if (!m->replacement) {
2820 debug(DBG_ERR, "malloc failed");
2824 m->regex = malloc(sizeof(regex_t));
2826 free(m->replacement);
2828 debug(DBG_ERR, "malloc failed");
2832 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2834 free(m->replacement);
2836 debug(DBG_ERR, "failed to compile regular expression %s", s);
2843 struct rewrite *getrewrite(char *alt1, char *alt2) {
2846 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2848 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2853 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2854 struct rewrite *rewrite = NULL;
2856 uint8_t *rma = NULL;
2857 uint32_t *p, *rmva = NULL;
2858 struct list *adda = NULL, *moda = NULL;
2863 for (n = 0; rmattrs[n]; n++);
2864 rma = calloc(n + 1, sizeof(uint8_t));
2866 debugx(1, DBG_ERR, "malloc failed");
2868 for (i = 0; i < n; i++) {
2869 if (!(rma[i] = attrname2val(rmattrs[i])))
2870 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2878 for (n = 0; rmvattrs[n]; n++);
2879 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2881 debugx(1, DBG_ERR, "malloc failed");
2883 for (p = rmva, i = 0; i < n; i++, p += 2) {
2884 if (!vattrname2val(rmvattrs[i], p, p + 1))
2885 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2893 adda = list_create();
2895 debugx(1, DBG_ERR, "malloc failed");
2896 for (i = 0; addattrs[i]; i++) {
2897 a = extractattr(addattrs[i]);
2899 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2901 if (!list_push(adda, a))
2902 debugx(1, DBG_ERR, "malloc failed");
2908 moda = list_create();
2910 debugx(1, DBG_ERR, "malloc failed");
2911 for (i = 0; modattrs[i]; i++) {
2912 m = extractmodattr(modattrs[i]);
2914 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2916 if (!list_push(moda, m))
2917 debugx(1, DBG_ERR, "malloc failed");
2922 if (rma || rmva || adda || moda) {
2923 rewrite = malloc(sizeof(struct rewrite));
2925 debugx(1, DBG_ERR, "malloc failed");
2926 rewrite->removeattrs = rma;
2927 rewrite->removevendorattrs = rmva;
2928 rewrite->addattrs = adda;
2929 rewrite->modattrs = moda;
2932 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2933 debugx(1, DBG_ERR, "malloc failed");
2934 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2937 void freeclsrvconf(struct clsrvconf *conf) {
2943 free(conf->matchcertattr);
2944 if (conf->certcnregex)
2945 regfree(conf->certcnregex);
2946 if (conf->certuriregex)
2947 regfree(conf->certuriregex);
2948 free(conf->confrewritein);
2949 free(conf->confrewriteout);
2950 if (conf->rewriteusername) {
2951 if (conf->rewriteusername->regex)
2952 regfree(conf->rewriteusername->regex);
2953 free(conf->rewriteusername->replacement);
2954 free(conf->rewriteusername);
2956 free(conf->dynamiclookupcommand);
2957 free(conf->rewritein);
2958 free(conf->rewriteout);
2960 freeaddrinfo(conf->addrinfo);
2962 pthread_mutex_destroy(conf->lock);
2965 /* not touching ssl_ctx, clients and servers */
2969 int mergeconfstring(char **dst, char **src) {
2978 t = stringcopy(*dst, 0);
2980 debug(DBG_ERR, "malloc failed");
2988 /* assumes dst is a shallow copy */
2989 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
2990 if (!mergeconfstring(&dst->name, &src->name) ||
2991 !mergeconfstring(&dst->host, &src->host) ||
2992 !mergeconfstring(&dst->port, &src->port) ||
2993 !mergeconfstring(&dst->secret, &src->secret) ||
2994 !mergeconfstring(&dst->tls, &src->tls) ||
2995 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
2996 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
2997 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
2998 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3001 dst->pdef = src->pdef;
3002 dst->statusserver = src->statusserver;
3003 dst->certnamecheck = src->certnamecheck;
3004 if (src->retryinterval != 255)
3005 dst->retryinterval = src->retryinterval;
3006 if (src->retrycount != 255)
3007 dst->retrycount = src->retrycount;
3011 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3012 struct clsrvconf *conf;
3013 char *conftype = NULL, *rewriteinalias = NULL;
3014 long int dupinterval = LONG_MIN;
3016 debug(DBG_DBG, "confclient_cb called for %s", block);
3018 conf = malloc(sizeof(struct clsrvconf));
3020 debugx(1, DBG_ERR, "malloc failed");
3021 memset(conf, 0, sizeof(struct clsrvconf));
3022 conf->certnamecheck = 1;
3024 if (!getgenericconfig(cf, block,
3025 "type", CONF_STR, &conftype,
3026 "host", CONF_STR, &conf->host,
3027 "secret", CONF_STR, &conf->secret,
3028 "tls", CONF_STR, &conf->tls,
3029 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3030 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3031 "DuplicateInterval", CONF_LINT, &dupinterval,
3032 "rewrite", CONF_STR, &rewriteinalias,
3033 "rewriteIn", CONF_STR, &conf->confrewritein,
3034 "rewriteOut", CONF_STR, &conf->confrewriteout,
3035 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3038 debugx(1, DBG_ERR, "configuration error");
3040 conf->name = stringcopy(val, 0);
3042 conf->host = stringcopy(val, 0);
3043 if (!conf->name || !conf->host)
3044 debugx(1, DBG_ERR, "malloc failed");
3047 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3048 conf->type = protoname2int(conftype);
3049 conf->pdef = &protodefs[conf->type];
3050 if (!conf->pdef->name)
3051 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3054 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3055 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3057 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3058 if (conf->matchcertattr && !addmatchcertattr(conf))
3059 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3062 if (dupinterval != LONG_MIN) {
3063 if (dupinterval < 0 || dupinterval > 255)
3064 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3065 conf->dupinterval = (uint8_t)dupinterval;
3067 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3069 if (!conf->confrewritein)
3070 conf->confrewritein = rewriteinalias;
3072 free(rewriteinalias);
3073 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3074 if (conf->confrewriteout)
3075 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3077 if (conf->confrewriteusername) {
3078 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3079 if (!conf->rewriteusername)
3080 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3083 if (!resolvepeer(conf, 0))
3084 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3086 if (!conf->secret) {
3087 if (!conf->pdef->secretdefault)
3088 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3089 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3091 debugx(1, DBG_ERR, "malloc failed");
3094 conf->lock = malloc(sizeof(pthread_mutex_t));
3096 debugx(1, DBG_ERR, "malloc failed");
3098 pthread_mutex_init(conf->lock, NULL);
3099 if (!list_push(clconfs, conf))
3100 debugx(1, DBG_ERR, "malloc failed");
3104 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3105 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3106 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3107 if (!conf->ssl_ctx) {
3108 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3111 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3112 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3118 conf->port = stringcopy(conf->pdef->portdefault, 0);
3120 debug(DBG_ERR, "malloc failed");
3125 if (conf->retryinterval == 255)
3126 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3127 if (conf->retrycount == 255)
3128 conf->retrycount = protodefs[conf->type].retrycountdefault;
3130 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3131 if (conf->confrewriteout)
3132 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3134 if (!conf->secret) {
3135 if (!conf->pdef->secretdefault) {
3136 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3139 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3140 if (!conf->secret) {
3141 debug(DBG_ERR, "malloc failed");
3146 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3147 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3153 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3154 struct clsrvconf *conf, *resconf;
3155 char *conftype = NULL, *rewriteinalias = NULL;
3156 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3158 debug(DBG_DBG, "confserver_cb called for %s", block);
3160 conf = malloc(sizeof(struct clsrvconf));
3162 debug(DBG_ERR, "malloc failed");
3165 memset(conf, 0, sizeof(struct clsrvconf));
3166 resconf = (struct clsrvconf *)arg;
3168 conf->statusserver = resconf->statusserver;
3169 conf->certnamecheck = resconf->certnamecheck;
3171 conf->certnamecheck = 1;
3173 if (!getgenericconfig(cf, block,
3174 "type", CONF_STR, &conftype,
3175 "host", CONF_STR, &conf->host,
3176 "port", CONF_STR, &conf->port,
3177 "secret", CONF_STR, &conf->secret,
3178 "tls", CONF_STR, &conf->tls,
3179 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3180 "rewrite", CONF_STR, &rewriteinalias,
3181 "rewriteIn", CONF_STR, &conf->confrewritein,
3182 "rewriteOut", CONF_STR, &conf->confrewriteout,
3183 "StatusServer", CONF_BLN, &conf->statusserver,
3184 "RetryInterval", CONF_LINT, &retryinterval,
3185 "RetryCount", CONF_LINT, &retrycount,
3186 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3187 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3190 debug(DBG_ERR, "configuration error");
3194 conf->name = stringcopy(val, 0);
3196 debug(DBG_ERR, "malloc failed");
3200 conf->host = stringcopy(val, 0);
3202 debug(DBG_ERR, "malloc failed");
3208 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3209 conf->type = protoname2int(conftype);
3210 conf->pdef = &protodefs[conf->type];
3211 if (!conf->pdef->name) {
3212 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3218 if (!conf->confrewritein)
3219 conf->confrewritein = rewriteinalias;
3221 free(rewriteinalias);
3222 rewriteinalias = NULL;
3224 if (retryinterval != LONG_MIN) {
3225 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3226 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3229 conf->retryinterval = (uint8_t)retryinterval;
3231 conf->retryinterval = 255;
3233 if (retrycount != LONG_MIN) {
3234 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3235 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3238 conf->retrycount = (uint8_t)retrycount;
3240 conf->retrycount = 255;
3243 if (!mergesrvconf(resconf, conf))
3247 if (conf->dynamiclookupcommand) {
3248 free(conf->dynamiclookupcommand);
3249 conf->dynamiclookupcommand = NULL;
3253 if (resconf || !conf->dynamiclookupcommand) {
3254 if (!compileserverconfig(conf, block))
3261 if (!list_push(srvconfs, conf)) {
3262 debug(DBG_ERR, "malloc failed");
3269 free(rewriteinalias);
3270 freeclsrvconf(conf);
3274 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3275 char **servers = NULL, **accservers = NULL, *msg = NULL;
3276 uint8_t accresp = 0;
3278 debug(DBG_DBG, "confrealm_cb called for %s", block);
3280 if (!getgenericconfig(cf, block,
3281 "server", CONF_MSTR, &servers,
3282 "accountingServer", CONF_MSTR, &accservers,
3283 "ReplyMessage", CONF_STR, &msg,
3284 "AccountingResponse", CONF_BLN, &accresp,
3287 debugx(1, DBG_ERR, "configuration error");
3289 addrealm(realms, val, servers, accservers, msg, accresp);
3293 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3296 debug(DBG_DBG, "conftls_cb called for %s", block);
3298 conf = malloc(sizeof(struct tls));
3300 debug(DBG_ERR, "conftls_cb: malloc failed");
3303 memset(conf, 0, sizeof(struct tls));
3305 if (!getgenericconfig(cf, block,
3306 "CACertificateFile", CONF_STR, &conf->cacertfile,
3307 "CACertificatePath", CONF_STR, &conf->cacertpath,
3308 "CertificateFile", CONF_STR, &conf->certfile,
3309 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3310 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3311 "CRLCheck", CONF_BLN, &conf->crlcheck,
3314 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3317 if (!conf->certfile || !conf->certkeyfile) {
3318 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3321 if (!conf->cacertfile && !conf->cacertpath) {
3322 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3326 conf->name = stringcopy(val, 0);
3328 debug(DBG_ERR, "conftls_cb: malloc failed");
3332 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3333 debug(DBG_ERR, "conftls_cb: malloc failed");
3337 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3341 free(conf->cacertfile);
3342 free(conf->cacertpath);
3343 free(conf->certfile);
3344 free(conf->certkeyfile);
3345 free(conf->certkeypwd);
3350 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3351 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3353 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3355 if (!getgenericconfig(cf, block,
3356 "removeAttribute", CONF_MSTR, &rmattrs,
3357 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3358 "addAttribute", CONF_MSTR, &addattrs,
3359 "modifyAttribute", CONF_MSTR, &modattrs,
3362 debugx(1, DBG_ERR, "configuration error");
3363 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3367 void getmainconfig(const char *configfile) {
3368 long int loglevel = LONG_MIN;
3369 struct gconffile *cfs;
3371 cfs = openconfigfile(configfile);
3372 memset(&options, 0, sizeof(options));
3374 clconfs = list_create();
3376 debugx(1, DBG_ERR, "malloc failed");
3378 srvconfs = list_create();
3380 debugx(1, DBG_ERR, "malloc failed");
3382 realms = list_create();
3384 debugx(1, DBG_ERR, "malloc failed");
3386 tlsconfs = hash_create();
3388 debugx(1, DBG_ERR, "malloc failed");
3390 rewriteconfs = hash_create();
3392 debugx(1, DBG_ERR, "malloc failed");
3394 if (!getgenericconfig(&cfs, NULL,
3395 "ListenUDP", CONF_MSTR, &options.listenudp,
3396 "ListenTCP", CONF_MSTR, &options.listentcp,
3397 "ListenTLS", CONF_MSTR, &options.listentls,
3398 "ListenDTLS", CONF_MSTR, &options.listendtls,
3399 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3400 "SourceUDP", CONF_STR, &options.sourceudp,
3401 "SourceTCP", CONF_STR, &options.sourcetcp,
3402 "SourceTLS", CONF_STR, &options.sourcetls,
3403 "SourceDTLS", CONF_STR, &options.sourcedtls,
3404 "LogLevel", CONF_LINT, &loglevel,
3405 "LogDestination", CONF_STR, &options.logdestination,
3406 "LoopPrevention", CONF_BLN, &options.loopprevention,
3407 "Client", CONF_CBK, confclient_cb, NULL,
3408 "Server", CONF_CBK, confserver_cb, NULL,
3409 "Realm", CONF_CBK, confrealm_cb, NULL,
3410 "TLS", CONF_CBK, conftls_cb, NULL,
3411 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3414 debugx(1, DBG_ERR, "configuration error");
3416 if (loglevel != LONG_MIN) {
3417 if (loglevel < 1 || loglevel > 4)
3418 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3419 options.loglevel = (uint8_t)loglevel;
3423 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3426 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3429 *configfile = optarg;
3432 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3433 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3434 *loglevel = *optarg - '0';
3443 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3448 if (!(argc - optind))
3452 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3456 int daemon(int a, int b) {
3464 for (i = 0; i < 3; i++) {
3466 open("/dev/null", O_RDWR);
3472 void *sighandler(void *arg) {
3477 sigemptyset(&sigset);
3478 sigaddset(&sigset, SIGPIPE);
3479 sigwait(&sigset, &sig);
3480 /* only get SIGPIPE right now, so could simplify below code */
3483 /* completely ignoring this */
3486 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3489 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3494 int main(int argc, char **argv) {
3497 struct list_node *entry;
3498 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3499 char *configfile = NULL;
3500 struct clsrvconf *srvconf;
3503 debug_init("radsecproxy");
3504 debug_set_level(DEBUG_LEVEL);
3506 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3508 debug_set_level(loglevel);
3509 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3511 options.loglevel = loglevel;
3512 else if (options.loglevel)
3513 debug_set_level(options.loglevel);
3515 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3516 free(options.logdestination);
3518 if (!list_first(clconfs))
3519 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3520 if (!list_first(realms))
3521 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3524 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3526 if (!foreground && (daemon(0, 0) < 0))
3527 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3529 debug_timestamp_on();
3530 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3532 sigemptyset(&sigset);
3533 /* exit on all but SIGPIPE, ignore more? */
3534 sigaddset(&sigset, SIGPIPE);
3535 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3536 pthread_create(&sigth, NULL, sighandler, NULL);
3538 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3539 srvconf = (struct clsrvconf *)entry->data;
3540 if (srvconf->dynamiclookupcommand)
3542 if (!addserver(srvconf))
3543 debugx(1, DBG_ERR, "failed to add server");
3544 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3545 (void *)(srvconf->servers)))
3546 debugx(1, DBG_ERR, "pthread_create failed");
3548 /* srcprotores for UDP no longer needed */
3549 if (srcprotores[RAD_UDP]) {
3550 freeaddrinfo(srcprotores[RAD_UDP]);
3551 srcprotores[RAD_UDP] = NULL;
3554 for (i = 0; protodefs[i].name; i++)
3555 if (protodefs[i].initextra)
3556 protodefs[i].initextra();
3558 if (find_clconf_type(RAD_TCP, NULL))
3559 createlisteners(RAD_TCP, options.listentcp);
3561 if (find_clconf_type(RAD_TLS, NULL))
3562 createlisteners(RAD_TLS, options.listentls);
3564 if (find_clconf_type(RAD_DTLS, NULL))
3565 createlisteners(RAD_DTLS, options.listendtls);
3567 if (find_clconf_type(RAD_UDP, NULL)) {
3568 createlisteners(RAD_UDP, options.listenudp);
3569 if (options.listenaccudp)
3570 createlisteners(RAD_UDP, options.listenaccudp);
3573 /* just hang around doing nothing, anything to do here? */