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);
96 static const struct protodefs protodefs[] = {
97 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
98 NULL, /* secretdefault */
99 SOCK_DGRAM, /* socktype */
100 "1812", /* portdefault */
101 REQUEST_RETRY_COUNT, /* retrycountdefault */
102 10, /* retrycountmax */
103 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
104 60, /* retryintervalmax */
105 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
106 udpserverrd, /* listener */
107 &options.sourceudp, /* srcaddrport */
108 NULL, /* connecter */
109 NULL, /* clientconnreader */
110 clientradputudp, /* clientradput */
111 addclientudp, /* addclient */
112 addserverextraudp, /* addserverextra */
113 initextraudp /* initextra */
115 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
116 "mysecret", /* secretdefault */
117 SOCK_STREAM, /* socktype */
118 "2083", /* portdefault */
119 0, /* retrycountdefault */
120 0, /* retrycountmax */
121 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
122 60, /* retryintervalmax */
123 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
124 tlslistener, /* listener */
125 &options.sourcetls, /* srcaddrport */
126 tlsconnect, /* connecter */
127 tlsclientrd, /* clientconnreader */
128 clientradputtls, /* clientradput */
129 NULL, /* addclient */
130 NULL, /* addserverextra */
133 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
134 NULL, /* secretdefault */
135 SOCK_STREAM, /* socktype */
136 "1812", /* portdefault */
137 0, /* retrycountdefault */
138 0, /* retrycountmax */
139 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
140 60, /* retryintervalmax */
141 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
142 tcplistener, /* listener */
143 &options.sourcetcp, /* srcaddrport */
144 tcpconnect, /* connecter */
145 tcpclientrd, /* clientconnreader */
146 clientradputtcp, /* clientradput */
147 NULL, /* addclient */
148 NULL, /* addserverextra */
151 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
152 "mysecret", /* secretdefault */
153 SOCK_DGRAM, /* socktype */
154 "2083", /* portdefault */
155 REQUEST_RETRY_COUNT, /* retrycountdefault */
156 10, /* retrycountmax */
157 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
158 60, /* retryintervalmax */
159 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
160 udpdtlsserverrd, /* listener */
161 &options.sourcedtls, /* srcaddrport */
162 dtlsconnect, /* connecter */
163 dtlsclientrd, /* clientconnreader */
164 clientradputdtls, /* clientradput */
165 NULL, /* addclient */
166 addserverextradtls, /* addserverextra */
167 initextradtls /* initextra */
173 uint8_t protoname2int(const char *name) {
176 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
180 /* callbacks for making OpenSSL thread safe */
181 unsigned long ssl_thread_id() {
182 return (unsigned long)pthread_self();
185 void ssl_locking_callback(int mode, int type, const char *file, int line) {
186 if (mode & CRYPTO_LOCK) {
187 pthread_mutex_lock(&ssl_locks[type]);
188 ssl_lock_count[type]++;
190 pthread_mutex_unlock(&ssl_locks[type]);
193 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
194 int pwdlen = strlen(userdata);
195 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
197 memcpy(buf, userdata, pwdlen);
201 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
206 err_cert = X509_STORE_CTX_get_current_cert(ctx);
207 err = X509_STORE_CTX_get_error(ctx);
208 depth = X509_STORE_CTX_get_error_depth(ctx);
210 if (depth > MAX_CERT_DEPTH) {
212 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
213 X509_STORE_CTX_set_error(ctx, err);
217 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
218 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
221 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
222 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
223 debug(DBG_WARN, "\tIssuer=%s", buf);
225 case X509_V_ERR_CERT_NOT_YET_VALID:
226 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
227 debug(DBG_WARN, "\tCertificate not yet valid");
229 case X509_V_ERR_CERT_HAS_EXPIRED:
230 debug(DBG_WARN, "Certificate has expired");
232 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
233 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
238 printf("certificate verify returns %d\n", ok);
243 struct addrinfo *getsrcprotores(uint8_t type) {
244 return srcprotores[type];
247 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
248 struct addrinfo hints, *addrinfo, *res;
252 slash = conf->host ? strchr(conf->host, '/') : NULL;
256 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
260 if (*s < '0' || *s > '9') {
261 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
264 plen = atoi(slash + 1);
265 if (plen < 0 || plen > 128) {
266 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
271 memset(&hints, 0, sizeof(hints));
272 hints.ai_socktype = conf->pdef->socktype;
273 hints.ai_family = AF_UNSPEC;
274 hints.ai_flags = ai_flags;
275 if (!conf->host && !conf->port) {
276 /* getaddrinfo() doesn't like host and port to be NULL */
277 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
278 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
281 for (res = addrinfo; res; res = res->ai_next) {
282 switch (res->ai_family) {
284 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
287 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 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 free(((struct reply *)entry)->buf);
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));
582 pthread_mutex_init(&new->lock, NULL);
584 if (conf->pdef->addclient)
585 conf->pdef->addclient(new);
587 new->replyq = newqueue();
588 list_push(conf->clients, new);
590 pthread_mutex_unlock(conf->lock);
594 void removeclient(struct client *client) {
598 pthread_mutex_lock(client->conf->lock);
599 if (client->conf->clients) {
600 pthread_mutex_lock(&client->lock);
601 removequeue(client->replyq);
602 list_removedata(client->conf->clients, client);
603 pthread_mutex_unlock(&client->lock);
604 pthread_mutex_destroy(&client->lock);
608 pthread_mutex_unlock(client->conf->lock);
611 void removeclientrqs(struct client *client) {
612 struct list_node *entry;
613 struct server *server;
617 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
618 server = ((struct clsrvconf *)entry->data)->servers;
621 pthread_mutex_lock(&server->newrq_mutex);
622 for (i = 0; i < MAX_REQUESTS; i++) {
623 rqout = server->requests + i;
624 if (rqout->rq && rqout->rq->from == client) {
629 pthread_mutex_unlock(&server->newrq_mutex);
633 void freeserver(struct server *server, uint8_t destroymutex) {
634 struct rqout *rqout, *end;
639 if (server->requests) {
640 rqout = server->requests;
641 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++)
642 freerqoutdata(rqout);
643 free(server->requests);
646 freebios(server->rbios);
647 free(server->dynamiclookuparg);
649 SSL_free(server->ssl);
651 pthread_mutex_destroy(&server->lock);
652 pthread_cond_destroy(&server->newrq_cond);
653 pthread_mutex_destroy(&server->newrq_mutex);
658 int addserver(struct clsrvconf *conf) {
659 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 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
695 debug(DBG_ERR, "mutex init failed");
698 conf->servers->newrq = 0;
699 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
700 debug(DBG_ERR, "mutex init failed");
701 pthread_mutex_destroy(&conf->servers->lock);
704 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
705 debug(DBG_ERR, "mutex init failed");
706 pthread_mutex_destroy(&conf->servers->newrq_mutex);
707 pthread_mutex_destroy(&conf->servers->lock);
714 freeserver(conf->servers, 0);
715 conf->servers = NULL;
719 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
720 int loc, i, l, n, r = 0;
723 STACK_OF(GENERAL_NAME) *alt;
726 debug(DBG_DBG, "subjectaltnameaddr");
728 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
732 ex = X509_get_ext(cert, loc);
733 alt = X509V3_EXT_d2i(ex);
737 n = sk_GENERAL_NAME_num(alt);
738 for (i = 0; i < n; i++) {
739 gn = sk_GENERAL_NAME_value(alt, i);
740 if (gn->type != GEN_IPADD)
743 v = (char *)ASN1_STRING_data(gn->d.ia5);
744 l = ASN1_STRING_length(gn->d.ia5);
745 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
746 && !memcmp(v, &addr, l)) {
751 GENERAL_NAMES_free(alt);
755 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
762 nm = X509_get_subject_name(cert);
765 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
768 e = X509_NAME_get_entry(nm, loc);
769 t = X509_NAME_ENTRY_get_data(e);
770 v = (char *) ASN1_STRING_data(t);
771 l = ASN1_STRING_length(t);
775 if (l == strlen(exact) && !strncasecmp(exact, v, l))
778 s = stringcopy((char *)v, l);
780 debug(DBG_ERR, "malloc failed");
783 if (regexec(regex, s, 0, NULL, 0)) {
794 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
795 int loc, i, l, n, r = 0;
798 STACK_OF(GENERAL_NAME) *alt;
801 debug(DBG_DBG, "subjectaltnameregexp");
803 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
807 ex = X509_get_ext(cert, loc);
808 alt = X509V3_EXT_d2i(ex);
812 n = sk_GENERAL_NAME_num(alt);
813 for (i = 0; i < n; i++) {
814 gn = sk_GENERAL_NAME_value(alt, i);
815 if (gn->type != type)
818 v = (char *)ASN1_STRING_data(gn->d.ia5);
819 l = ASN1_STRING_length(gn->d.ia5);
823 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
826 if (memcmp(v, exact, l))
829 s = stringcopy((char *)v, l);
831 debug(DBG_ERR, "malloc failed");
834 if (regexec(regex, s, 0, NULL, 0)) {
843 GENERAL_NAMES_free(alt);
847 X509 *verifytlscert(SSL *ssl) {
851 if (SSL_get_verify_result(ssl) != X509_V_OK) {
852 debug(DBG_ERR, "verifytlscert: basic validation failed");
853 while ((error = ERR_get_error()))
854 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
858 cert = SSL_get_peer_certificate(ssl);
860 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
864 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
866 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
867 struct in6_addr addr;
869 if (conf->certnamecheck && conf->prefixlen == 255) {
870 if (inet_pton(AF_INET, conf->host, &addr))
872 else if (inet_pton(AF_INET6, conf->host, &addr))
875 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
878 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
881 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
883 if (!cnregexp(cert, conf->host, NULL)) {
884 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
887 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
890 if (conf->certcnregex) {
891 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
892 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
895 debug(DBG_DBG, "verifyconfcert: CN matching regex");
897 if (conf->certuriregex) {
898 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
899 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
902 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
907 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
909 if (ATTRTYPE(attrs) == type)
911 length -= ATTRLEN(attrs);
912 attrs += ATTRLEN(attrs);
917 void freerqdata(struct request *rq) {
920 if (rq->origusername)
921 free(rq->origusername);
926 void freerq(struct request *rq) {
929 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
936 void freerqoutdata(struct rqout *rqout) {
940 radmsg_free(rqout->msg);
947 void sendrq(struct server *to, struct rqout *rqout) {
950 pthread_mutex_lock(&to->newrq_mutex);
951 /* might simplify if only try nextid, might be ok */
952 for (i = to->nextid; i < MAX_REQUESTS; i++)
953 if (!to->requests[i].buf)
955 if (i == MAX_REQUESTS) {
956 for (i = 0; i < to->nextid; i++)
957 if (!to->requests[i].buf)
959 if (i == to->nextid) {
960 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
961 freerqoutdata(rqout);
966 rqout->msg->id = (uint8_t)i;
967 rqout->buf = radmsg2buf(rqout->msg, (uint8_t *)to->conf->secret);
969 debug(DBG_ERR, "sendrq: radmsg2buf failed");
970 freerqoutdata(rqout);
974 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
975 to->requests[i] = *rqout;
980 debug(DBG_DBG, "sendrq: signalling client writer");
981 pthread_cond_signal(&to->newrq_cond);
985 pthread_mutex_unlock(&to->newrq_mutex);
988 void sendreply(struct client *to, struct radmsg *msg, struct sockaddr_storage *tosa, int toudpsock) {
993 buf = radmsg2buf(msg, (uint8_t *)to->conf->secret);
996 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1000 reply = malloc(sizeof(struct reply));
1003 debug(DBG_ERR, "sendreply: malloc failed");
1006 memset(reply, 0, sizeof(struct reply));
1009 reply->tosa = *tosa;
1010 reply->toudpsock = toudpsock;
1012 pthread_mutex_lock(&to->replyq->mutex);
1014 first = list_first(to->replyq->entries) == NULL;
1016 if (!list_push(to->replyq->entries, reply)) {
1017 pthread_mutex_unlock(&to->replyq->mutex);
1020 debug(DBG_ERR, "sendreply: malloc failed");
1025 debug(DBG_DBG, "signalling server writer");
1026 pthread_cond_signal(&to->replyq->cond);
1028 pthread_mutex_unlock(&to->replyq->mutex);
1031 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1032 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1033 static unsigned char first = 1;
1034 static EVP_MD_CTX mdctx;
1035 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1036 unsigned int md_len;
1037 uint8_t i, offset = 0, out[128];
1039 pthread_mutex_lock(&lock);
1041 EVP_MD_CTX_init(&mdctx);
1047 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1048 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1049 !EVP_DigestUpdate(&mdctx, input, 16) ||
1050 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1052 pthread_mutex_unlock(&lock);
1055 for (i = 0; i < 16; i++)
1056 out[offset + i] = hash[i] ^ in[offset + i];
1057 input = out + offset - 16;
1062 memcpy(in, out, len);
1063 pthread_mutex_unlock(&lock);
1067 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1068 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1069 static unsigned char first = 1;
1070 static EVP_MD_CTX mdctx;
1071 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1072 unsigned int md_len;
1073 uint8_t i, offset = 0, out[128];
1075 pthread_mutex_lock(&lock);
1077 EVP_MD_CTX_init(&mdctx);
1083 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1084 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1085 !EVP_DigestUpdate(&mdctx, input, 16) ||
1086 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1088 pthread_mutex_unlock(&lock);
1091 for (i = 0; i < 16; i++)
1092 out[offset + i] = hash[i] ^ in[offset + i];
1093 input = in + offset;
1098 memcpy(in, out, len);
1099 pthread_mutex_unlock(&lock);
1103 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1104 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1105 static unsigned char first = 1;
1106 static EVP_MD_CTX mdctx;
1107 unsigned char hash[EVP_MAX_MD_SIZE];
1108 unsigned int md_len;
1111 pthread_mutex_lock(&lock);
1113 EVP_MD_CTX_init(&mdctx);
1118 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1119 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1120 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1123 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1124 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1125 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1126 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1127 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1128 pthread_mutex_unlock(&lock);
1133 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1136 for (i = 0; i < 16; i++)
1139 for (offset = 16; offset < len; offset += 16) {
1141 printf("text + offset - 16 c(%d): ", offset / 16);
1142 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1144 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1145 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1146 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1147 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1149 pthread_mutex_unlock(&lock);
1153 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1156 for (i = 0; i < 16; i++)
1157 text[offset + i] ^= hash[i];
1161 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1164 pthread_mutex_unlock(&lock);
1168 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1169 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1170 static unsigned char first = 1;
1171 static EVP_MD_CTX mdctx;
1172 unsigned char hash[EVP_MAX_MD_SIZE];
1173 unsigned int md_len;
1177 pthread_mutex_lock(&lock);
1179 EVP_MD_CTX_init(&mdctx);
1184 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1185 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1186 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1189 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1190 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1191 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1192 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1193 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1194 pthread_mutex_unlock(&lock);
1199 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1202 for (i = 0; i < 16; i++)
1203 plain[i] = text[i] ^ hash[i];
1205 for (offset = 16; offset < len; offset += 16) {
1207 printf("text + offset - 16 c(%d): ", offset / 16);
1208 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1210 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1211 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1212 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1213 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1215 pthread_mutex_unlock(&lock);
1219 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1222 for (i = 0; i < 16; i++)
1223 plain[offset + i] = text[offset + i] ^ hash[i];
1226 memcpy(text, plain, len);
1228 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1231 pthread_mutex_unlock(&lock);
1235 struct realm *id2realm(struct list *realmlist, char *id) {
1236 struct list_node *entry;
1237 struct realm *realm, *subrealm = NULL;
1239 /* need to do locking for subrealms and check subrealm timers */
1240 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1241 realm = (struct realm *)entry->data;
1242 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1243 pthread_mutex_lock(&realm->subrealms_mutex);
1244 if (realm->subrealms)
1245 subrealm = id2realm(realm->subrealms, id);
1246 pthread_mutex_unlock(&realm->subrealms_mutex);
1247 return subrealm ? subrealm : realm;
1253 /* helper function, only used by removeserversubrealms() */
1254 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1255 struct list_node *entry;
1256 struct realm *realm;
1258 for (entry = list_first(realmlist); entry;) {
1259 realm = (struct realm *)entry->data;
1260 entry = list_next(entry);
1261 if (realm->srvconfs) {
1262 list_removedata(realm->srvconfs, srv);
1263 if (!list_first(realm->srvconfs)) {
1264 list_destroy(realm->srvconfs);
1265 realm->srvconfs = NULL;
1268 if (realm->accsrvconfs) {
1269 list_removedata(realm->accsrvconfs, srv);
1270 if (!list_first(realm->accsrvconfs)) {
1271 list_destroy(realm->accsrvconfs);
1272 realm->accsrvconfs = NULL;
1276 /* remove subrealm if no servers */
1277 if (!realm->srvconfs && !realm->accsrvconfs) {
1278 list_removedata(realmlist, realm);
1284 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1285 struct list_node *entry;
1286 struct realm *realm;
1288 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1289 realm = (struct realm *)entry->data;
1290 pthread_mutex_lock(&realm->subrealms_mutex);
1291 if (realm->subrealms) {
1292 _internal_removeserversubrealms(realm->subrealms, srv);
1293 if (!list_first(realm->subrealms)) {
1294 list_destroy(realm->subrealms);
1295 realm->subrealms = NULL;
1298 pthread_mutex_unlock(&realm->subrealms_mutex);
1302 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1303 struct rqout *rqout = to->requests, *end;
1305 pthread_mutex_lock(&to->newrq_mutex);
1306 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++)
1307 if (rqout->buf && !rqout->received && rqout->rq && rqout->rq->origid == id && rqout->rq->from == from && *rqout->buf == code)
1309 pthread_mutex_unlock(&to->newrq_mutex);
1314 int attrvalidate(unsigned char *attrs, int length) {
1315 while (length > 1) {
1316 if (ATTRLEN(attrs) < 2) {
1317 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1320 length -= ATTRLEN(attrs);
1322 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1325 attrs += ATTRLEN(attrs);
1328 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1332 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1333 if (len < 16 || len > 128 || len % 16) {
1334 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1338 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1339 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1343 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1345 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1346 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1352 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1355 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1356 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1359 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1360 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1366 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct rqout *rqout,
1367 char *oldsecret, char *newsecret) {
1368 unsigned char *attr;
1370 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1371 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1372 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rqout->buf + 4, rqout->rq->origauth))
1378 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1382 for (; attrs[0]; attrs += 2)
1383 if (attrs[0] == vendor && attrs[1] == subattr)
1388 /* returns 1 if entire element is to be removed, else 0 */
1389 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1390 uint8_t alen, sublen;
1394 if (!removevendorattrs)
1397 memcpy(&vendor, attr->v, 4);
1398 vendor = ntohl(vendor);
1399 while (*removevendorattrs && *removevendorattrs != vendor)
1400 removevendorattrs += 2;
1401 if (!*removevendorattrs)
1404 if (findvendorsubattr(removevendorattrs, vendor, -1))
1405 return 1; /* remove entire vendor attribute */
1407 sublen = attr->l - 4;
1408 subattrs = attr->v + 4;
1410 if (!attrvalidate(subattrs, sublen)) {
1411 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1415 while (sublen > 1) {
1416 alen = ATTRLEN(subattrs);
1418 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1419 memmove(subattrs, subattrs + alen, sublen);
1427 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1428 struct list_node *n, *p;
1432 n = list_first(msg->attrs);
1434 attr = (struct tlv *)n->data;
1435 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1436 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1437 list_removedata(msg->attrs, attr);
1439 n = p ? list_next(p) : list_first(msg->attrs);
1446 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1447 struct list_node *n;
1450 for (n = list_first(addattrs); n; n = list_next(n)) {
1451 a = copytlv((struct tlv *)n->data);
1454 if (!radmsg_add(msg, a)) {
1462 int resizeattr(struct tlv *attr, uint8_t newlen) {
1465 if (newlen != attr->l) {
1466 newv = realloc(attr->v, newlen);
1475 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1476 size_t nmatch = 10, reslen = 0, start = 0;
1477 regmatch_t pmatch[10], *pfield;
1481 in = stringcopy((char *)attr->v, attr->l);
1485 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1490 out = modattr->replacement;
1492 for (i = start; out[i]; i++) {
1493 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1494 pfield = &pmatch[out[i + 1] - '0'];
1495 if (pfield->rm_so >= 0) {
1496 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1502 reslen += i - start;
1504 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1509 if (!resizeattr(attr, reslen)) {
1516 for (i = start; out[i]; i++) {
1517 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1518 pfield = &pmatch[out[i + 1] - '0'];
1519 if (pfield->rm_so >= 0) {
1520 memcpy(attr->v + reslen, out + start, i - start);
1521 reslen += i - start;
1522 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1523 reslen += pfield->rm_eo - pfield->rm_so;
1530 memcpy(attr->v + reslen, out + start, i - start);
1534 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1535 struct list_node *n, *m;
1537 for (n = list_first(msg->attrs); n; n = list_next(n))
1538 for (m = list_first(modattrs); m; m = list_next(m))
1539 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1540 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1545 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1548 if (rewrite->removeattrs || rewrite->removevendorattrs)
1549 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1550 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1552 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1557 int rewriteusername(struct rqout *rqout, struct tlv *attr) {
1558 char *orig = (char *)tlv2str(attr);
1559 if (!dorewritemodattr(attr, rqout->rq->from->conf->rewriteusername)) {
1563 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1564 rqout->rq->origusername = (char *)orig;
1570 const char *radmsgtype2string(uint8_t code) {
1571 static const char *rad_msg_names[] = {
1572 "", "Access-Request", "Access-Accept", "Access-Reject",
1573 "Accounting-Request", "Accounting-Response", "", "",
1574 "", "", "", "Access-Challenge",
1575 "Status-Server", "Status-Client"
1577 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1580 void char2hex(char *h, unsigned char c) {
1581 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1582 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1583 h[0] = hexdigits[c / 16];
1584 h[1] = hexdigits[c % 16];
1588 uint8_t *radattr2ascii(struct tlv *attr) {
1596 for (i = 0; i < attr->l; i++)
1597 if (attr->v[i] < 32 || attr->v[i] > 126)
1600 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1607 for (i = 0; i < attr->l; i++)
1608 if (attr->v[i] < 32 || attr->v[i] > 126) {
1610 char2hex((char *)d, attr->v[i]);
1618 void acclog(struct radmsg *msg, char *host) {
1622 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1624 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1627 username = radattr2ascii(attr);
1629 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1634 void respondaccounting(struct rqout *rqout) {
1637 msg = radmsg_init(RAD_Accounting_Response, rqout->msg->id, rqout->msg->auth);
1639 debug(DBG_DBG, "respondaccounting: responding to %s", rqout->rq->from->conf->host);
1640 sendreply(rqout->rq->from, msg, &rqout->rq->fromsa, rqout->rq->fromudpsock);
1642 debug(DBG_ERR, "respondaccounting: malloc failed");
1645 void respondstatusserver(struct rqout *rqout) {
1648 msg = radmsg_init(RAD_Access_Accept, rqout->msg->id, rqout->msg->auth);
1650 debug(DBG_DBG, "respondstatusserver: responding to %s", rqout->rq->from->conf->host);
1651 sendreply(rqout->rq->from, msg, &rqout->rq->fromsa, rqout->rq->fromudpsock);
1653 debug(DBG_ERR, "respondstatusserver: malloc failed");
1656 void respondreject(struct rqout *rqout, char *message) {
1660 msg = radmsg_init(RAD_Access_Reject, rqout->msg->id, rqout->msg->auth);
1662 debug(DBG_ERR, "respondreject: malloc failed");
1665 if (message && *message) {
1666 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1667 if (!attr || !radmsg_add(msg, attr)) {
1670 debug(DBG_ERR, "respondreject: malloc failed");
1675 debug(DBG_DBG, "respondreject: responding to %s", rqout->rq->from->conf->host);
1676 sendreply(rqout->rq->from, msg, &rqout->rq->fromsa, rqout->rq->fromudpsock);
1679 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1680 struct list_node *entry;
1681 struct clsrvconf *server, *best = NULL, *first = NULL;
1683 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1684 server = (struct clsrvconf *)entry->data;
1685 if (!server->servers)
1689 if (!server->servers->connectionok)
1691 if (!server->servers->lostrqs)
1697 if (server->servers->lostrqs < best->servers->lostrqs)
1700 return best ? best : first;
1703 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1704 struct clsrvconf *srvconf;
1705 char *id = (char *)tlv2str(username);
1709 *realm = id2realm(realms, id);
1714 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1715 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1720 if (!acc && !srvconf->servers)
1721 adddynamicrealmserver(*realm, srvconf, id);
1723 return srvconf->servers;
1727 struct request *newrequest() {
1730 rq = malloc(sizeof(struct request));
1732 debug(DBG_ERR, "newrequest: malloc failed");
1735 memset(rq, 0, sizeof(struct request));
1737 gettimeofday(&rq->created, NULL);
1741 int addclientrq(struct request *rq, uint8_t id) {
1745 pthread_mutex_lock(&rq->from->lock);
1746 gettimeofday(&now, NULL);
1747 r = rq->from->rqs[id];
1749 if (r->refcount > 1 && now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1750 pthread_mutex_unlock(&rq->from->lock);
1756 rq->from->rqs[id] = rq;
1757 pthread_mutex_unlock(&rq->from->lock);
1761 void rmclientrq(struct request *rq, uint8_t id) {
1764 pthread_mutex_lock(&rq->from->lock);
1765 r = rq->from->rqs[id];
1768 rq->from->rqs[id] = NULL;
1770 pthread_mutex_unlock(&rq->from->lock);
1773 /* returns 0 if validation/authentication fails, else 1 */
1774 int radsrv(struct request *rq) {
1775 struct radmsg *msg = NULL;
1776 struct rqout *rqout, rqdata;
1778 uint8_t *userascii = NULL;
1779 unsigned char newauth[16];
1780 struct realm *realm = NULL;
1781 struct server *to = NULL;
1782 struct client *from = rq->from;
1784 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1789 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1794 memset(rqout, 0, sizeof(struct rqout));
1796 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1798 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1799 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1800 freerqoutdata(rqout);
1804 if (!addclientrq(rq, msg->id)) {
1805 debug(DBG_INFO, "radsrv: already got request with id %d from %s, ignoring", msg->id, from->conf->host);
1806 freerqoutdata(rqout);
1812 if (msg->code == RAD_Status_Server) {
1813 respondstatusserver(rqout);
1817 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1819 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1822 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1824 if (msg->code == RAD_Accounting_Request) {
1825 acclog(msg, from->conf->host);
1826 respondaccounting(rqout);
1829 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1833 if (from->conf->rewriteusername && !rewriteusername(rqout, attr)) {
1834 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1838 userascii = radattr2ascii(attr);
1841 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1843 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1845 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1850 if (realm->message && msg->code == RAD_Access_Request) {
1851 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1852 respondreject(rqout, realm->message);
1853 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1854 acclog(msg, from->conf->host);
1855 respondaccounting(rqout);
1860 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1861 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1862 from->conf->name, to->conf->name);
1867 skip this now that we have rqrcv... per client?
1868 if (rqinqueue(to, from, msg->id, msg->code)) {
1869 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
1870 radmsgtype2string(msg->code), from->conf->host, msg->id);
1875 if (msg->code != RAD_Accounting_Request) {
1876 if (!RAND_bytes(newauth, 16)) {
1877 debug(DBG_WARN, "radsrv: failed to generate random auth");
1883 printfchars(NULL, "auth", "%02x ", auth, 16);
1886 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1888 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1889 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1893 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1895 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1896 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, msg->auth, newauth))
1900 rqout->rq->origid = msg->id;
1901 memcpy(rqout->rq->origauth, msg->auth, 16);
1902 memcpy(msg->auth, newauth, 16);
1904 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1912 rmclientrq(rq, msg->id);
1914 freerqoutdata(rqout);
1919 freerqoutdata(rqout);
1924 void replyh(struct server *server, unsigned char *buf) {
1925 struct client *from;
1926 struct rqout *rqout;
1928 unsigned char *subattrs;
1929 struct sockaddr_storage fromsa;
1930 uint8_t *username, *stationid;
1931 struct radmsg *msg = NULL;
1933 struct list_node *node;
1935 server->connectionok = 1;
1936 server->lostrqs = 0;
1938 rqout = server->requests + buf[1];
1939 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->msg->auth);
1943 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1946 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1947 && msg->code != RAD_Accounting_Response) {
1948 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1952 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1954 pthread_mutex_lock(&server->newrq_mutex);
1955 if (!rqout->buf || !rqout->tries) {
1956 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1960 if (rqout->received) {
1961 debug(DBG_INFO, "replyh: already received, ignoring reply");
1965 gettimeofday(&server->lastrcv, NULL);
1967 if (rqout->msg->code == RAD_Status_Server) {
1968 rqout->received = 1;
1969 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1973 gettimeofday(&server->lastreply, NULL);
1976 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1979 from = rqout->rq->from;
1981 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1982 debug(DBG_WARN, "replyh: rewritein failed");
1987 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1988 attr = (struct tlv *)node->data;
1989 if (attr->t != RAD_Attr_Vendor_Specific)
1993 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1996 sublen = attr->l - 4;
1997 subattrs = attr->v + 4;
1998 if (!attrvalidate(subattrs, sublen) ||
1999 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2000 rqout, server->conf->secret, from->conf->secret) ||
2001 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2002 rqout, server->conf->secret, from->conf->secret))
2006 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2010 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2011 username = radattr2ascii(radmsg_gettype(rqout->msg, RAD_Attr_User_Name));
2013 stationid = radattr2ascii(radmsg_gettype(rqout->msg, RAD_Attr_Calling_Station_Id));
2015 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2016 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2019 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(msg->code), username, server->conf->host);
2024 msg->id = (char)rqout->rq->origid;
2025 memcpy(msg->auth, rqout->rq->origauth, 16);
2028 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2031 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2032 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2033 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2036 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2039 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2040 debug(DBG_WARN, "replyh: rewriteout failed");
2044 fromsa = rqout->rq->fromsa; /* only needed for UDP */
2045 /* once we set received = 1, rq may be reused */
2046 rqout->received = 1;
2048 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2049 sendreply(from, msg, &fromsa, rqout->rq->fromudpsock);
2050 pthread_mutex_unlock(&server->newrq_mutex);
2055 pthread_mutex_unlock(&server->newrq_mutex);
2059 struct radmsg *createstatsrvmsg() {
2063 msg = radmsg_init(RAD_Status_Server, 0, NULL);
2067 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2072 if (!radmsg_add(msg, attr)) {
2080 /* code for removing state not finished */
2081 void *clientwr(void *arg) {
2082 struct server *server = (struct server *)arg;
2083 struct rqout *rqout;
2084 pthread_t clientrdth;
2085 int i, secs, dynconffail = 0;
2087 struct timeval now, laststatsrv;
2088 struct timespec timeout;
2089 struct rqout statsrvrq;
2090 struct clsrvconf *conf;
2092 conf = server->conf;
2094 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2099 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2100 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2104 memset(&timeout, 0, sizeof(struct timespec));
2106 if (conf->statusserver) {
2107 gettimeofday(&server->lastrcv, NULL);
2108 gettimeofday(&laststatsrv, NULL);
2111 if (conf->pdef->connecter) {
2112 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2114 server->connectionok = 1;
2115 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2116 debug(DBG_ERR, "clientwr: pthread_create failed");
2120 server->connectionok = 1;
2123 pthread_mutex_lock(&server->newrq_mutex);
2124 if (!server->newrq) {
2125 gettimeofday(&now, NULL);
2126 /* random 0-7 seconds */
2127 RAND_bytes(&rnd, 1);
2129 if (conf->statusserver) {
2130 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2131 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2132 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2134 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2135 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2138 if (timeout.tv_sec > now.tv_sec)
2139 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2141 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2144 if (server->newrq) {
2145 debug(DBG_DBG, "clientwr: got new request");
2150 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2152 pthread_mutex_unlock(&server->newrq_mutex);
2154 for (i = 0; i < MAX_REQUESTS; i++) {
2155 if (server->clientrdgone) {
2156 pthread_join(clientrdth, NULL);
2159 pthread_mutex_lock(&server->newrq_mutex);
2160 while (i < MAX_REQUESTS && !server->requests[i].buf)
2162 if (i == MAX_REQUESTS) {
2163 pthread_mutex_unlock(&server->newrq_mutex);
2166 rqout = server->requests + i;
2168 if (rqout->received) {
2169 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2171 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2172 freerqoutdata(rqout);
2173 /* setting this to NULL means that it can be reused */
2176 pthread_mutex_unlock(&server->newrq_mutex);
2180 gettimeofday(&now, NULL);
2181 if (now.tv_sec < rqout->expiry.tv_sec) {
2182 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2183 timeout.tv_sec = rqout->expiry.tv_sec;
2184 pthread_mutex_unlock(&server->newrq_mutex);
2188 if (rqout->tries == (*rqout->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2189 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2190 if (conf->statusserver) {
2191 if (*rqout->buf == RAD_Status_Server) {
2192 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2193 if (server->lostrqs < 255)
2197 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2198 if (server->lostrqs < 255)
2201 freerqoutdata(rqout);
2202 /* setting this to NULL means that it can be reused */
2204 pthread_mutex_unlock(&server->newrq_mutex);
2207 pthread_mutex_unlock(&server->newrq_mutex);
2209 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2210 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2211 timeout.tv_sec = rqout->expiry.tv_sec;
2213 conf->pdef->clientradput(server, server->requests[i].buf);
2215 if (conf->statusserver) {
2216 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2217 gettimeofday(&now, NULL);
2218 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2220 memset(&statsrvrq, 0, sizeof(struct rqout));
2221 statsrvrq.msg = createstatsrvmsg();
2222 if (statsrvrq.msg) {
2223 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2224 sendrq(server, &statsrvrq);
2230 conf->servers = NULL;
2231 if (server->dynamiclookuparg) {
2232 removeserversubrealms(realms, conf);
2236 freeclsrvconf(conf);
2238 freeserver(server, 1);
2239 ERR_remove_state(0);
2243 void createlistener(uint8_t type, char *arg) {
2245 struct clsrvconf *listenres;
2246 struct addrinfo *res;
2247 int s = -1, on = 1, *sp = NULL;
2249 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2251 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2253 for (res = listenres->addrinfo; res; res = res->ai_next) {
2254 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2256 debug(DBG_WARN, "createlistener: socket failed");
2259 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2261 if (res->ai_family == AF_INET6)
2262 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2264 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2265 debug(DBG_WARN, "createlistener: bind failed");
2271 sp = malloc(sizeof(int));
2273 debugx(1, DBG_ERR, "malloc failed");
2275 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2276 debugx(1, DBG_ERR, "pthread_create failed");
2280 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2282 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2283 listenres->host ? listenres->host : "*", listenres->port);
2284 freeclsrvres(listenres);
2287 void createlisteners(uint8_t type, char **args) {
2291 for (i = 0; args[i]; i++)
2292 createlistener(type, args[i]);
2294 createlistener(type, NULL);
2298 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2302 w = where & ~SSL_ST_MASK;
2304 if (w & SSL_ST_CONNECT)
2306 else if (w & SSL_ST_ACCEPT)
2311 if (where & SSL_CB_LOOP)
2312 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2313 else if (where & SSL_CB_ALERT) {
2314 s = (where & SSL_CB_READ) ? "read" : "write";
2315 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2317 else if (where & SSL_CB_EXIT) {
2319 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2321 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2326 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2327 SSL_CTX *ctx = NULL;
2328 STACK_OF(X509_NAME) *calist;
2331 unsigned long error;
2334 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2335 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2336 for (i = 0; i < CRYPTO_num_locks(); i++) {
2337 ssl_lock_count[i] = 0;
2338 pthread_mutex_init(&ssl_locks[i], NULL);
2340 CRYPTO_set_id_callback(ssl_thread_id);
2341 CRYPTO_set_locking_callback(ssl_locking_callback);
2343 SSL_load_error_strings();
2346 while (!RAND_status()) {
2347 time_t t = time(NULL);
2348 pid_t pid = getpid();
2349 RAND_seed((unsigned char *)&t, sizeof(time_t));
2350 RAND_seed((unsigned char *)&pid, sizeof(pid));
2356 ctx = SSL_CTX_new(TLSv1_method());
2358 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2362 ctx = SSL_CTX_new(DTLSv1_method());
2364 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2366 SSL_CTX_set_read_ahead(ctx, 1);
2370 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2374 if (conf->certkeypwd) {
2375 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2376 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2378 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2379 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2380 !SSL_CTX_check_private_key(ctx) ||
2381 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2382 while ((error = ERR_get_error()))
2383 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2384 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2389 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2390 if (!conf->cacertfile || calist) {
2391 if (conf->cacertpath) {
2393 calist = sk_X509_NAME_new_null();
2394 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2395 sk_X509_NAME_free(calist);
2401 while ((error = ERR_get_error()))
2402 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2403 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
2407 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2408 SSL_CTX_set_client_CA_list(ctx, calist);
2410 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2411 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2413 if (conf->crlcheck) {
2414 x509_s = SSL_CTX_get_cert_store(ctx);
2415 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2418 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2422 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
2425 t = hash_read(tlsconfs, alt1, strlen(alt1));
2427 t = hash_read(tlsconfs, alt2, strlen(alt2));
2435 t->tlsctx = tlscreatectx(RAD_TLS, t);
2439 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2445 struct list *addsrvconfs(char *value, char **names) {
2446 struct list *conflist;
2448 struct list_node *entry;
2449 struct clsrvconf *conf = NULL;
2451 if (!names || !*names)
2454 conflist = list_create();
2456 debug(DBG_ERR, "malloc failed");
2460 for (n = 0; names[n]; n++) {
2461 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2462 conf = (struct clsrvconf *)entry->data;
2463 if (!strcasecmp(names[n], conf->name))
2467 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2468 list_destroy(conflist);
2471 if (!list_push(conflist, conf)) {
2472 debug(DBG_ERR, "malloc failed");
2473 list_destroy(conflist);
2476 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2481 void freerealm(struct realm *realm) {
2485 free(realm->message);
2486 regfree(&realm->regex);
2487 pthread_mutex_destroy(&realm->subrealms_mutex);
2488 if (realm->subrealms)
2489 list_destroy(realm->subrealms);
2490 if (realm->srvconfs) {
2491 /* emptying list without freeing data */
2492 while (list_shift(realm->srvconfs));
2493 list_destroy(realm->srvconfs);
2495 if (realm->accsrvconfs) {
2496 /* emptying list without freeing data */
2497 while (list_shift(realm->accsrvconfs));
2498 list_destroy(realm->accsrvconfs);
2503 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2505 struct realm *realm;
2506 char *s, *regex = NULL;
2508 if (*value == '/') {
2509 /* regexp, remove optional trailing / if present */
2510 if (value[strlen(value) - 1] == '/')
2511 value[strlen(value) - 1] = '\0';
2513 /* not a regexp, let us make it one */
2514 if (*value == '*' && !value[1])
2515 regex = stringcopy(".*", 0);
2517 for (n = 0, s = value; *s;)
2520 regex = malloc(strlen(value) + n + 3);
2523 for (n = 1, s = value; *s; s++) {
2533 debug(DBG_ERR, "malloc failed");
2537 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2540 realm = malloc(sizeof(struct realm));
2542 debug(DBG_ERR, "malloc failed");
2545 memset(realm, 0, sizeof(struct realm));
2547 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2548 debug(DBG_ERR, "mutex init failed");
2554 realm->name = stringcopy(value, 0);
2556 debug(DBG_ERR, "malloc failed");
2559 if (message && strlen(message) > 253) {
2560 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2563 realm->message = message;
2564 realm->accresp = accresp;
2566 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2567 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2571 if (servers && *servers) {
2572 realm->srvconfs = addsrvconfs(value, servers);
2573 if (!realm->srvconfs)
2577 if (accservers && *accservers) {
2578 realm->accsrvconfs = addsrvconfs(value, accservers);
2579 if (!realm->accsrvconfs)
2583 if (!list_push(realmlist, realm)) {
2584 debug(DBG_ERR, "malloc failed");
2585 pthread_mutex_destroy(&realm->subrealms_mutex);
2589 debug(DBG_DBG, "addrealm: added realm %s", value);
2599 for (n = 0; servers[n]; n++)
2604 for (n = 0; accservers[n]; n++)
2605 free(accservers[n]);
2611 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2612 struct clsrvconf *srvconf;
2613 struct realm *newrealm = NULL;
2614 char *realmname, *s;
2617 if (!conf->dynamiclookupcommand)
2620 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2621 realmname = strrchr(id, '@');
2627 for (s = realmname; *s; s++)
2628 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2631 pthread_mutex_lock(&realm->subrealms_mutex);
2632 /* exit if we now already got a matching subrealm */
2633 if (id2realm(realm->subrealms, id))
2635 srvconf = malloc(sizeof(struct clsrvconf));
2637 debug(DBG_ERR, "malloc failed");
2641 if (!addserver(srvconf))
2644 if (!realm->subrealms)
2645 realm->subrealms = list_create();
2646 if (!realm->subrealms)
2648 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2652 /* add server and accserver to newrealm */
2653 newrealm->srvconfs = list_create();
2654 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2655 debug(DBG_ERR, "malloc failed");
2658 newrealm->accsrvconfs = list_create();
2659 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2660 debug(DBG_ERR, "malloc failed");
2664 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2666 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2667 debug(DBG_ERR, "pthread_create failed");
2670 pthread_detach(clientth);
2675 list_removedata(realm->subrealms, newrealm);
2676 freerealm(newrealm);
2677 if (!list_first(realm->subrealms)) {
2678 list_destroy(realm->subrealms);
2679 realm->subrealms = NULL;
2682 freeserver(srvconf->servers, 1);
2684 debug(DBG_ERR, "failed to create dynamic server");
2687 pthread_mutex_unlock(&realm->subrealms_mutex);
2690 int dynamicconfig(struct server *server) {
2691 int ok, fd[2], status;
2693 struct clsrvconf *conf = server->conf;
2694 struct gconffile *cf = NULL;
2696 /* for now we only learn hostname/address */
2697 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2700 debug(DBG_ERR, "dynamicconfig: pipe error");
2705 debug(DBG_ERR, "dynamicconfig: fork error");
2709 } else if (pid == 0) {
2712 if (fd[1] != STDOUT_FILENO) {
2713 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2714 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2717 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2718 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2722 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2723 ok = getgenericconfig(&cf, NULL,
2724 "Server", CONF_CBK, confserver_cb, (void *)conf,
2729 if (waitpid(pid, &status, 0) < 0) {
2730 debug(DBG_ERR, "dynamicconfig: wait error");
2735 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2743 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2747 int addmatchcertattr(struct clsrvconf *conf) {
2751 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2752 r = &conf->certcnregex;
2753 v = conf->matchcertattr + 4;
2754 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2755 r = &conf->certuriregex;
2756 v = conf->matchcertattr + 20;
2761 /* regexp, remove optional trailing / if present */
2762 if (v[strlen(v) - 1] == '/')
2763 v[strlen(v) - 1] = '\0';
2767 *r = malloc(sizeof(regex_t));
2769 debug(DBG_ERR, "malloc failed");
2772 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2775 debug(DBG_ERR, "failed to compile regular expression %s", v);
2781 /* should accept both names and numeric values, only numeric right now */
2782 uint8_t attrname2val(char *attrname) {
2785 val = atoi(attrname);
2786 return val > 0 && val < 256 ? val : 0;
2789 /* should accept both names and numeric values, only numeric right now */
2790 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2793 *vendor = atoi(attrname);
2794 s = strchr(attrname, ':');
2799 *type = atoi(s + 1);
2800 return *type >= 0 && *type < 256;
2803 /* should accept both names and numeric values, only numeric right now */
2804 struct tlv *extractattr(char *nameval) {
2809 s = strchr(nameval, ':');
2810 name = atoi(nameval);
2811 if (!s || name < 1 || name > 255)
2813 len = strlen(s + 1);
2816 a = malloc(sizeof(struct tlv));
2819 a->v = (uint8_t *)stringcopy(s + 1, 0);
2829 /* should accept both names and numeric values, only numeric right now */
2830 struct modattr *extractmodattr(char *nameval) {
2835 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2839 s = strchr(nameval, ':');
2840 name = atoi(nameval);
2841 if (!s || name < 1 || name > 255 || s[1] != '/')
2845 /* regexp, remove optional trailing / if present */
2846 if (s[strlen(s) - 1] == '/')
2847 s[strlen(s) - 1] = '\0';
2855 m = malloc(sizeof(struct modattr));
2857 debug(DBG_ERR, "malloc failed");
2862 m->replacement = stringcopy(t, 0);
2863 if (!m->replacement) {
2865 debug(DBG_ERR, "malloc failed");
2869 m->regex = malloc(sizeof(regex_t));
2871 free(m->replacement);
2873 debug(DBG_ERR, "malloc failed");
2877 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2879 free(m->replacement);
2881 debug(DBG_ERR, "failed to compile regular expression %s", s);
2888 struct rewrite *getrewrite(char *alt1, char *alt2) {
2891 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2893 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2898 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2899 struct rewrite *rewrite = NULL;
2901 uint8_t *rma = NULL;
2902 uint32_t *p, *rmva = NULL;
2903 struct list *adda = NULL, *moda = NULL;
2908 for (n = 0; rmattrs[n]; n++);
2909 rma = calloc(n + 1, sizeof(uint8_t));
2911 debugx(1, DBG_ERR, "malloc failed");
2913 for (i = 0; i < n; i++) {
2914 if (!(rma[i] = attrname2val(rmattrs[i])))
2915 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2923 for (n = 0; rmvattrs[n]; n++);
2924 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2926 debugx(1, DBG_ERR, "malloc failed");
2928 for (p = rmva, i = 0; i < n; i++, p += 2) {
2929 if (!vattrname2val(rmvattrs[i], p, p + 1))
2930 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2938 adda = list_create();
2940 debugx(1, DBG_ERR, "malloc failed");
2941 for (i = 0; addattrs[i]; i++) {
2942 a = extractattr(addattrs[i]);
2944 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2946 if (!list_push(adda, a))
2947 debugx(1, DBG_ERR, "malloc failed");
2953 moda = list_create();
2955 debugx(1, DBG_ERR, "malloc failed");
2956 for (i = 0; modattrs[i]; i++) {
2957 m = extractmodattr(modattrs[i]);
2959 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2961 if (!list_push(moda, m))
2962 debugx(1, DBG_ERR, "malloc failed");
2967 if (rma || rmva || adda || moda) {
2968 rewrite = malloc(sizeof(struct rewrite));
2970 debugx(1, DBG_ERR, "malloc failed");
2971 rewrite->removeattrs = rma;
2972 rewrite->removevendorattrs = rmva;
2973 rewrite->addattrs = adda;
2974 rewrite->modattrs = moda;
2977 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2978 debugx(1, DBG_ERR, "malloc failed");
2979 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2982 void freeclsrvconf(struct clsrvconf *conf) {
2988 free(conf->matchcertattr);
2989 if (conf->certcnregex)
2990 regfree(conf->certcnregex);
2991 if (conf->certuriregex)
2992 regfree(conf->certuriregex);
2993 free(conf->confrewritein);
2994 free(conf->confrewriteout);
2995 if (conf->rewriteusername) {
2996 if (conf->rewriteusername->regex)
2997 regfree(conf->rewriteusername->regex);
2998 free(conf->rewriteusername->replacement);
2999 free(conf->rewriteusername);
3001 free(conf->dynamiclookupcommand);
3002 free(conf->rewritein);
3003 free(conf->rewriteout);
3005 freeaddrinfo(conf->addrinfo);
3007 pthread_mutex_destroy(conf->lock);
3010 /* not touching ssl_ctx, clients and servers */
3014 int mergeconfstring(char **dst, char **src) {
3023 t = stringcopy(*dst, 0);
3025 debug(DBG_ERR, "malloc failed");
3033 /* assumes dst is a shallow copy */
3034 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3035 if (!mergeconfstring(&dst->name, &src->name) ||
3036 !mergeconfstring(&dst->host, &src->host) ||
3037 !mergeconfstring(&dst->port, &src->port) ||
3038 !mergeconfstring(&dst->secret, &src->secret) ||
3039 !mergeconfstring(&dst->tls, &src->tls) ||
3040 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3041 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3042 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3043 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3046 dst->pdef = src->pdef;
3047 dst->statusserver = src->statusserver;
3048 dst->certnamecheck = src->certnamecheck;
3049 if (src->retryinterval != 255)
3050 dst->retryinterval = src->retryinterval;
3051 if (src->retrycount != 255)
3052 dst->retrycount = src->retrycount;
3056 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3057 struct clsrvconf *conf;
3058 char *conftype = NULL, *rewriteinalias = NULL;
3059 long int dupinterval = LONG_MIN;
3061 debug(DBG_DBG, "confclient_cb called for %s", block);
3063 conf = malloc(sizeof(struct clsrvconf));
3065 debugx(1, DBG_ERR, "malloc failed");
3066 memset(conf, 0, sizeof(struct clsrvconf));
3067 conf->certnamecheck = 1;
3069 if (!getgenericconfig(cf, block,
3070 "type", CONF_STR, &conftype,
3071 "host", CONF_STR, &conf->host,
3072 "secret", CONF_STR, &conf->secret,
3073 "tls", CONF_STR, &conf->tls,
3074 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3075 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3076 "DuplicateInterval", CONF_LINT, &dupinterval,
3077 "rewrite", CONF_STR, &rewriteinalias,
3078 "rewriteIn", CONF_STR, &conf->confrewritein,
3079 "rewriteOut", CONF_STR, &conf->confrewriteout,
3080 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3083 debugx(1, DBG_ERR, "configuration error");
3085 conf->name = stringcopy(val, 0);
3087 conf->host = stringcopy(val, 0);
3088 if (!conf->name || !conf->host)
3089 debugx(1, DBG_ERR, "malloc failed");
3092 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3093 conf->type = protoname2int(conftype);
3094 conf->pdef = &protodefs[conf->type];
3095 if (!conf->pdef->name)
3096 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3099 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3100 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3102 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3103 if (conf->matchcertattr && !addmatchcertattr(conf))
3104 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3107 if (dupinterval != LONG_MIN) {
3108 if (dupinterval < 0 || dupinterval > 255)
3109 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3110 conf->dupinterval = (uint8_t)dupinterval;
3112 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3114 if (!conf->confrewritein)
3115 conf->confrewritein = rewriteinalias;
3117 free(rewriteinalias);
3118 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3119 if (conf->confrewriteout)
3120 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3122 if (conf->confrewriteusername) {
3123 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3124 if (!conf->rewriteusername)
3125 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3128 if (!resolvepeer(conf, 0))
3129 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3131 if (!conf->secret) {
3132 if (!conf->pdef->secretdefault)
3133 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3134 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3136 debugx(1, DBG_ERR, "malloc failed");
3139 conf->lock = malloc(sizeof(pthread_mutex_t));
3141 debugx(1, DBG_ERR, "malloc failed");
3143 pthread_mutex_init(conf->lock, NULL);
3144 if (!list_push(clconfs, conf))
3145 debugx(1, DBG_ERR, "malloc failed");
3149 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3150 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3151 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3152 if (!conf->ssl_ctx) {
3153 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3156 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3157 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3163 conf->port = stringcopy(conf->pdef->portdefault, 0);
3165 debug(DBG_ERR, "malloc failed");
3170 if (conf->retryinterval == 255)
3171 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3172 if (conf->retrycount == 255)
3173 conf->retrycount = protodefs[conf->type].retrycountdefault;
3175 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3176 if (conf->confrewriteout)
3177 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3179 if (!conf->secret) {
3180 if (!conf->pdef->secretdefault) {
3181 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3184 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3185 if (!conf->secret) {
3186 debug(DBG_ERR, "malloc failed");
3191 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3192 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3198 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3199 struct clsrvconf *conf, *resconf;
3200 char *conftype = NULL, *rewriteinalias = NULL;
3201 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3203 debug(DBG_DBG, "confserver_cb called for %s", block);
3205 conf = malloc(sizeof(struct clsrvconf));
3207 debug(DBG_ERR, "malloc failed");
3210 memset(conf, 0, sizeof(struct clsrvconf));
3211 resconf = (struct clsrvconf *)arg;
3213 conf->statusserver = resconf->statusserver;
3214 conf->certnamecheck = resconf->certnamecheck;
3216 conf->certnamecheck = 1;
3218 if (!getgenericconfig(cf, block,
3219 "type", CONF_STR, &conftype,
3220 "host", CONF_STR, &conf->host,
3221 "port", CONF_STR, &conf->port,
3222 "secret", CONF_STR, &conf->secret,
3223 "tls", CONF_STR, &conf->tls,
3224 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3225 "rewrite", CONF_STR, &rewriteinalias,
3226 "rewriteIn", CONF_STR, &conf->confrewritein,
3227 "rewriteOut", CONF_STR, &conf->confrewriteout,
3228 "StatusServer", CONF_BLN, &conf->statusserver,
3229 "RetryInterval", CONF_LINT, &retryinterval,
3230 "RetryCount", CONF_LINT, &retrycount,
3231 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3232 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3235 debug(DBG_ERR, "configuration error");
3239 conf->name = stringcopy(val, 0);
3241 debug(DBG_ERR, "malloc failed");
3245 conf->host = stringcopy(val, 0);
3247 debug(DBG_ERR, "malloc failed");
3253 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3254 conf->type = protoname2int(conftype);
3255 conf->pdef = &protodefs[conf->type];
3256 if (!conf->pdef->name) {
3257 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3263 if (!conf->confrewritein)
3264 conf->confrewritein = rewriteinalias;
3266 free(rewriteinalias);
3267 rewriteinalias = NULL;
3269 if (retryinterval != LONG_MIN) {
3270 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3271 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3274 conf->retryinterval = (uint8_t)retryinterval;
3276 conf->retryinterval = 255;
3278 if (retrycount != LONG_MIN) {
3279 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3280 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3283 conf->retrycount = (uint8_t)retrycount;
3285 conf->retrycount = 255;
3288 if (!mergesrvconf(resconf, conf))
3292 if (conf->dynamiclookupcommand) {
3293 free(conf->dynamiclookupcommand);
3294 conf->dynamiclookupcommand = NULL;
3298 if (resconf || !conf->dynamiclookupcommand) {
3299 if (!compileserverconfig(conf, block))
3306 if (!list_push(srvconfs, conf)) {
3307 debug(DBG_ERR, "malloc failed");
3314 free(rewriteinalias);
3315 freeclsrvconf(conf);
3319 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3320 char **servers = NULL, **accservers = NULL, *msg = NULL;
3321 uint8_t accresp = 0;
3323 debug(DBG_DBG, "confrealm_cb called for %s", block);
3325 if (!getgenericconfig(cf, block,
3326 "server", CONF_MSTR, &servers,
3327 "accountingServer", CONF_MSTR, &accservers,
3328 "ReplyMessage", CONF_STR, &msg,
3329 "AccountingResponse", CONF_BLN, &accresp,
3332 debugx(1, DBG_ERR, "configuration error");
3334 addrealm(realms, val, servers, accservers, msg, accresp);
3338 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3341 debug(DBG_DBG, "conftls_cb called for %s", block);
3343 conf = malloc(sizeof(struct tls));
3345 debug(DBG_ERR, "conftls_cb: malloc failed");
3348 memset(conf, 0, sizeof(struct tls));
3350 if (!getgenericconfig(cf, block,
3351 "CACertificateFile", CONF_STR, &conf->cacertfile,
3352 "CACertificatePath", CONF_STR, &conf->cacertpath,
3353 "CertificateFile", CONF_STR, &conf->certfile,
3354 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3355 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3356 "CRLCheck", CONF_BLN, &conf->crlcheck,
3359 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3362 if (!conf->certfile || !conf->certkeyfile) {
3363 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3366 if (!conf->cacertfile && !conf->cacertpath) {
3367 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3371 conf->name = stringcopy(val, 0);
3373 debug(DBG_ERR, "conftls_cb: malloc failed");
3377 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3378 debug(DBG_ERR, "conftls_cb: malloc failed");
3382 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3386 free(conf->cacertfile);
3387 free(conf->cacertpath);
3388 free(conf->certfile);
3389 free(conf->certkeyfile);
3390 free(conf->certkeypwd);
3395 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3396 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3398 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3400 if (!getgenericconfig(cf, block,
3401 "removeAttribute", CONF_MSTR, &rmattrs,
3402 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3403 "addAttribute", CONF_MSTR, &addattrs,
3404 "modifyAttribute", CONF_MSTR, &modattrs,
3407 debugx(1, DBG_ERR, "configuration error");
3408 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3412 void getmainconfig(const char *configfile) {
3413 long int loglevel = LONG_MIN;
3414 struct gconffile *cfs;
3416 cfs = openconfigfile(configfile);
3417 memset(&options, 0, sizeof(options));
3419 clconfs = list_create();
3421 debugx(1, DBG_ERR, "malloc failed");
3423 srvconfs = list_create();
3425 debugx(1, DBG_ERR, "malloc failed");
3427 realms = list_create();
3429 debugx(1, DBG_ERR, "malloc failed");
3431 tlsconfs = hash_create();
3433 debugx(1, DBG_ERR, "malloc failed");
3435 rewriteconfs = hash_create();
3437 debugx(1, DBG_ERR, "malloc failed");
3439 if (!getgenericconfig(&cfs, NULL,
3440 "ListenUDP", CONF_MSTR, &options.listenudp,
3441 "ListenTCP", CONF_MSTR, &options.listentcp,
3442 "ListenTLS", CONF_MSTR, &options.listentls,
3443 "ListenDTLS", CONF_MSTR, &options.listendtls,
3444 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3445 "SourceUDP", CONF_STR, &options.sourceudp,
3446 "SourceTCP", CONF_STR, &options.sourcetcp,
3447 "SourceTLS", CONF_STR, &options.sourcetls,
3448 "SourceDTLS", CONF_STR, &options.sourcedtls,
3449 "LogLevel", CONF_LINT, &loglevel,
3450 "LogDestination", CONF_STR, &options.logdestination,
3451 "LoopPrevention", CONF_BLN, &options.loopprevention,
3452 "Client", CONF_CBK, confclient_cb, NULL,
3453 "Server", CONF_CBK, confserver_cb, NULL,
3454 "Realm", CONF_CBK, confrealm_cb, NULL,
3455 "TLS", CONF_CBK, conftls_cb, NULL,
3456 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3459 debugx(1, DBG_ERR, "configuration error");
3461 if (loglevel != LONG_MIN) {
3462 if (loglevel < 1 || loglevel > 4)
3463 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3464 options.loglevel = (uint8_t)loglevel;
3468 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3471 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3474 *configfile = optarg;
3477 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3478 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3479 *loglevel = *optarg - '0';
3488 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3493 if (!(argc - optind))
3497 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3501 int daemon(int a, int b) {
3509 for (i = 0; i < 3; i++) {
3511 open("/dev/null", O_RDWR);
3517 void *sighandler(void *arg) {
3522 sigemptyset(&sigset);
3523 sigaddset(&sigset, SIGPIPE);
3524 sigwait(&sigset, &sig);
3525 /* only get SIGPIPE right now, so could simplify below code */
3528 /* completely ignoring this */
3531 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3534 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3539 int main(int argc, char **argv) {
3542 struct list_node *entry;
3543 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3544 char *configfile = NULL;
3545 struct clsrvconf *srvconf;
3548 debug_init("radsecproxy");
3549 debug_set_level(DEBUG_LEVEL);
3551 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3553 debug_set_level(loglevel);
3554 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3556 options.loglevel = loglevel;
3557 else if (options.loglevel)
3558 debug_set_level(options.loglevel);
3560 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3561 free(options.logdestination);
3563 if (!list_first(clconfs))
3564 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3565 if (!list_first(realms))
3566 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3569 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3571 if (!foreground && (daemon(0, 0) < 0))
3572 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3574 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3576 sigemptyset(&sigset);
3577 /* exit on all but SIGPIPE, ignore more? */
3578 sigaddset(&sigset, SIGPIPE);
3579 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3580 pthread_create(&sigth, NULL, sighandler, NULL);
3582 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3583 srvconf = (struct clsrvconf *)entry->data;
3584 if (srvconf->dynamiclookupcommand)
3586 if (!addserver(srvconf))
3587 debugx(1, DBG_ERR, "failed to add server");
3588 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3589 (void *)(srvconf->servers)))
3590 debugx(1, DBG_ERR, "pthread_create failed");
3592 /* srcprotores for UDP no longer needed */
3593 if (srcprotores[RAD_UDP]) {
3594 freeaddrinfo(srcprotores[RAD_UDP]);
3595 srcprotores[RAD_UDP] = NULL;
3598 for (i = 0; protodefs[i].name; i++)
3599 if (protodefs[i].initextra)
3600 protodefs[i].initextra();
3602 if (find_clconf_type(RAD_TCP, NULL))
3603 createlisteners(RAD_TCP, options.listentcp);
3605 if (find_clconf_type(RAD_TLS, NULL))
3606 createlisteners(RAD_TLS, options.listentls);
3608 if (find_clconf_type(RAD_DTLS, NULL))
3609 createlisteners(RAD_DTLS, options.listendtls);
3611 if (find_clconf_type(RAD_UDP, NULL)) {
3612 createlisteners(RAD_UDP, options.listenudp);
3613 if (options.listenaccudp)
3614 createlisteners(RAD_UDP, options.listenaccudp);
3617 /* just hang around doing nothing, anything to do here? */