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 * May segfault when dtls connections go down? More testing needed
39 * Need to remove UDP clients when no activity for a while...
40 * Remove expired stuff from clients request list?
41 * Need refcounting for configs? Bad if remove dynsrvconf while in radsrv()
42 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
43 * Useful for TCP accounting? Now we require separate server config for alt port
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 /* returns 1 if the len first bits are equal, else 0 */
394 int prefixmatch(void *a1, void *a2, uint8_t len) {
395 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
397 if (l && memcmp(a1, a2, l))
402 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
405 /* returns next config with matching address, or NULL */
406 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
407 struct sockaddr_in6 *sa6 = NULL;
408 struct in_addr *a4 = NULL;
409 struct addrinfo *res;
410 struct list_node *entry;
411 struct clsrvconf *conf;
413 if (addr->sa_family == AF_INET6) {
414 sa6 = (struct sockaddr_in6 *)addr;
415 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
416 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
420 a4 = &((struct sockaddr_in *)addr)->sin_addr;
422 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
423 conf = (struct clsrvconf *)entry->data;
424 if (conf->type == type) {
425 if (conf->prefixlen == 255) {
426 for (res = conf->addrinfo; res; res = res->ai_next)
427 if ((a4 && res->ai_family == AF_INET &&
428 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
429 (sa6 && res->ai_family == AF_INET6 &&
430 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
436 res = conf->addrinfo;
438 ((a4 && res->ai_family == AF_INET &&
439 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
440 (sa6 && res->ai_family == AF_INET6 &&
441 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
452 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
453 return find_conf(type, addr, clconfs, cur);
456 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
457 return find_conf(type, addr, srvconfs, cur);
460 /* returns next config of given type, or NULL */
461 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
462 struct list_node *entry;
463 struct clsrvconf *conf;
465 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
466 conf = (struct clsrvconf *)entry->data;
467 if (conf->type == type) {
476 struct queue *newqueue() {
479 q = malloc(sizeof(struct queue));
481 debugx(1, DBG_ERR, "malloc failed");
482 q->entries = list_create();
484 debugx(1, DBG_ERR, "malloc failed");
485 pthread_mutex_init(&q->mutex, NULL);
486 pthread_cond_init(&q->cond, NULL);
490 void removequeue(struct queue *q) {
491 struct list_node *entry;
495 pthread_mutex_lock(&q->mutex);
496 for (entry = list_first(q->entries); entry; entry = list_next(entry))
497 freerq((struct request *)entry);
498 list_destroy(q->entries);
499 pthread_cond_destroy(&q->cond);
500 pthread_mutex_unlock(&q->mutex);
501 pthread_mutex_destroy(&q->mutex);
505 void freebios(struct queue *q) {
508 pthread_mutex_lock(&q->mutex);
509 while ((bio = (BIO *)list_shift(q->entries)))
511 pthread_mutex_unlock(&q->mutex);
515 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
516 struct client *new = malloc(sizeof(struct client));
519 debug(DBG_ERR, "malloc failed");
524 pthread_mutex_lock(conf->lock);
525 if (!conf->clients) {
526 conf->clients = list_create();
527 if (!conf->clients) {
529 pthread_mutex_unlock(conf->lock);
530 debug(DBG_ERR, "malloc failed");
535 memset(new, 0, sizeof(struct client));
537 if (conf->pdef->addclient)
538 conf->pdef->addclient(new);
540 new->replyq = newqueue();
541 list_push(conf->clients, new);
543 pthread_mutex_unlock(conf->lock);
547 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
548 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
551 pthread_mutex_lock(&lock);
553 pthread_mutex_unlock(&lock);
556 void removeclientrqs(struct client *client) {
561 removeclientrqs_sendrq_freeserver_lock(1);
562 for (i = 0; i < MAX_REQUESTS; i++) {
567 rqout = rq->to->requests + rq->newid;
568 pthread_mutex_lock(rqout->lock);
569 if (rqout->rq == rq) /* still pointing to our request */
570 freerqoutdata(rqout);
571 pthread_mutex_unlock(rqout->lock);
575 removeclientrqs_sendrq_freeserver_lock(0);
578 void removeclient(struct client *client) {
579 struct clsrvconf *conf;
584 pthread_mutex_lock(conf->lock);
586 removeclientrqs(client);
587 removequeue(client->replyq);
588 list_removedata(conf->clients, client);
592 pthread_mutex_unlock(conf->lock);
595 void freeserver(struct server *server, uint8_t destroymutex) {
596 struct rqout *rqout, *end;
601 removeclientrqs_sendrq_freeserver_lock(1);
602 if (server->requests) {
603 rqout = server->requests;
604 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
606 rqout->rq->to = NULL;
607 freerqoutdata(rqout);
608 pthread_mutex_destroy(rqout->lock);
611 free(server->requests);
614 freebios(server->rbios);
615 free(server->dynamiclookuparg);
617 SSL_free(server->ssl);
619 pthread_mutex_destroy(&server->lock);
620 pthread_cond_destroy(&server->newrq_cond);
621 pthread_mutex_destroy(&server->newrq_mutex);
623 removeclientrqs_sendrq_freeserver_lock(0);
627 int addserver(struct clsrvconf *conf) {
628 struct clsrvconf *res;
633 debug(DBG_ERR, "addserver: currently works with just one server per conf");
636 conf->servers = malloc(sizeof(struct server));
637 if (!conf->servers) {
638 debug(DBG_ERR, "malloc failed");
641 memset(conf->servers, 0, sizeof(struct server));
642 conf->servers->conf = conf;
645 if (type == RAD_DTLS)
646 conf->servers->rbios = newqueue();
648 if (!srcprotores[type]) {
649 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
650 srcprotores[type] = res->addrinfo;
651 res->addrinfo = NULL;
655 conf->servers->sock = -1;
656 if (conf->pdef->addserverextra)
657 conf->pdef->addserverextra(conf);
659 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
660 if (!conf->servers->requests) {
661 debug(DBG_ERR, "malloc failed");
664 for (i = 0; i < MAX_REQUESTS; i++) {
665 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
666 if (!conf->servers->requests[i].lock) {
667 debug(DBG_ERR, "malloc failed");
670 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
671 debug(DBG_ERR, "mutex init failed");
672 free(conf->servers->requests[i].lock);
673 conf->servers->requests[i].lock = NULL;
677 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
678 debug(DBG_ERR, "mutex init failed");
681 conf->servers->newrq = 0;
682 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
683 debug(DBG_ERR, "mutex init failed");
684 pthread_mutex_destroy(&conf->servers->lock);
687 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
688 debug(DBG_ERR, "mutex init failed");
689 pthread_mutex_destroy(&conf->servers->newrq_mutex);
690 pthread_mutex_destroy(&conf->servers->lock);
697 freeserver(conf->servers, 0);
698 conf->servers = NULL;
702 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
703 int loc, i, l, n, r = 0;
706 STACK_OF(GENERAL_NAME) *alt;
709 debug(DBG_DBG, "subjectaltnameaddr");
711 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
715 ex = X509_get_ext(cert, loc);
716 alt = X509V3_EXT_d2i(ex);
720 n = sk_GENERAL_NAME_num(alt);
721 for (i = 0; i < n; i++) {
722 gn = sk_GENERAL_NAME_value(alt, i);
723 if (gn->type != GEN_IPADD)
726 v = (char *)ASN1_STRING_data(gn->d.ia5);
727 l = ASN1_STRING_length(gn->d.ia5);
728 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
729 && !memcmp(v, &addr, l)) {
734 GENERAL_NAMES_free(alt);
738 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
745 nm = X509_get_subject_name(cert);
748 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
751 e = X509_NAME_get_entry(nm, loc);
752 t = X509_NAME_ENTRY_get_data(e);
753 v = (char *) ASN1_STRING_data(t);
754 l = ASN1_STRING_length(t);
758 if (l == strlen(exact) && !strncasecmp(exact, v, l))
761 s = stringcopy((char *)v, l);
763 debug(DBG_ERR, "malloc failed");
766 if (regexec(regex, s, 0, NULL, 0)) {
777 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
778 int loc, i, l, n, r = 0;
781 STACK_OF(GENERAL_NAME) *alt;
784 debug(DBG_DBG, "subjectaltnameregexp");
786 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
790 ex = X509_get_ext(cert, loc);
791 alt = X509V3_EXT_d2i(ex);
795 n = sk_GENERAL_NAME_num(alt);
796 for (i = 0; i < n; i++) {
797 gn = sk_GENERAL_NAME_value(alt, i);
798 if (gn->type != type)
801 v = (char *)ASN1_STRING_data(gn->d.ia5);
802 l = ASN1_STRING_length(gn->d.ia5);
806 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
809 if (memcmp(v, exact, l))
812 s = stringcopy((char *)v, l);
814 debug(DBG_ERR, "malloc failed");
817 if (regexec(regex, s, 0, NULL, 0)) {
826 GENERAL_NAMES_free(alt);
830 X509 *verifytlscert(SSL *ssl) {
834 if (SSL_get_verify_result(ssl) != X509_V_OK) {
835 debug(DBG_ERR, "verifytlscert: basic validation failed");
836 while ((error = ERR_get_error()))
837 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
841 cert = SSL_get_peer_certificate(ssl);
843 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
847 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
849 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
850 struct in6_addr addr;
852 if (conf->certnamecheck && conf->prefixlen == 255) {
853 if (inet_pton(AF_INET, conf->host, &addr))
855 else if (inet_pton(AF_INET6, conf->host, &addr))
858 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
861 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
864 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
866 if (!cnregexp(cert, conf->host, NULL)) {
867 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
870 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
873 if (conf->certcnregex) {
874 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
875 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
878 debug(DBG_DBG, "verifyconfcert: CN matching regex");
880 if (conf->certuriregex) {
881 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
882 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
885 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
890 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
892 if (ATTRTYPE(attrs) == type)
894 length -= ATTRLEN(attrs);
895 attrs += ATTRLEN(attrs);
900 struct request *newrqref(struct request *rq) {
905 void freerq(struct request *rq) {
908 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
911 if (rq->origusername)
912 free(rq->origusername);
918 radmsg_free(rq->msg);
922 void freerqoutdata(struct rqout *rqout) {
930 memset(&rqout->expiry, 0, sizeof(struct timeval));
933 void sendrq(struct request *rq) {
937 removeclientrqs_sendrq_freeserver_lock(1);
942 start = to->conf->statusserver ? 1 : 0;
943 pthread_mutex_lock(&to->newrq_mutex);
944 if (start && rq->msg->code == RAD_Status_Server) {
945 pthread_mutex_lock(to->requests[0].lock);
946 if (to->requests[0].rq) {
947 pthread_mutex_unlock(to->requests[0].lock);
948 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
955 /* might simplify if only try nextid, might be ok */
956 for (i = to->nextid; i < MAX_REQUESTS; i++) {
957 if (!to->requests[i].rq) {
958 pthread_mutex_lock(to->requests[i].lock);
959 if (!to->requests[i].rq)
961 pthread_mutex_unlock(to->requests[i].lock);
964 if (i == MAX_REQUESTS) {
965 for (i = start; i < to->nextid; i++) {
966 if (!to->requests[i].rq) {
967 pthread_mutex_lock(to->requests[i].lock);
968 if (!to->requests[i].rq)
970 pthread_mutex_unlock(to->requests[i].lock);
973 if (i == to->nextid) {
974 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
979 rq->newid = (uint8_t)i;
980 rq->msg->id = (uint8_t)i;
981 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
983 pthread_mutex_unlock(to->requests[i].lock);
984 debug(DBG_ERR, "sendrq: radmsg2buf failed");
988 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
989 to->requests[i].rq = rq;
990 pthread_mutex_unlock(to->requests[i].lock);
991 if (i >= start) /* i is not reserved for statusserver */
996 debug(DBG_DBG, "sendrq: signalling client writer");
997 pthread_cond_signal(&to->newrq_cond);
1000 pthread_mutex_unlock(&to->newrq_mutex);
1001 removeclientrqs_sendrq_freeserver_lock(0);
1006 rmclientrq(rq, rq->msg->id);
1008 pthread_mutex_unlock(&to->newrq_mutex);
1009 removeclientrqs_sendrq_freeserver_lock(0);
1012 void sendreply(struct request *rq) {
1014 struct client *to = rq->from;
1017 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1018 radmsg_free(rq->msg);
1020 if (!rq->replybuf) {
1022 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1026 pthread_mutex_lock(&to->replyq->mutex);
1027 first = list_first(to->replyq->entries) == NULL;
1029 if (!list_push(to->replyq->entries, rq)) {
1030 pthread_mutex_unlock(&to->replyq->mutex);
1032 debug(DBG_ERR, "sendreply: malloc failed");
1037 debug(DBG_DBG, "signalling server writer");
1038 pthread_cond_signal(&to->replyq->cond);
1040 pthread_mutex_unlock(&to->replyq->mutex);
1043 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1044 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1045 static unsigned char first = 1;
1046 static EVP_MD_CTX mdctx;
1047 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1048 unsigned int md_len;
1049 uint8_t i, offset = 0, out[128];
1051 pthread_mutex_lock(&lock);
1053 EVP_MD_CTX_init(&mdctx);
1059 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1060 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1061 !EVP_DigestUpdate(&mdctx, input, 16) ||
1062 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1064 pthread_mutex_unlock(&lock);
1067 for (i = 0; i < 16; i++)
1068 out[offset + i] = hash[i] ^ in[offset + i];
1069 input = out + offset - 16;
1074 memcpy(in, out, len);
1075 pthread_mutex_unlock(&lock);
1079 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1080 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1081 static unsigned char first = 1;
1082 static EVP_MD_CTX mdctx;
1083 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1084 unsigned int md_len;
1085 uint8_t i, offset = 0, out[128];
1087 pthread_mutex_lock(&lock);
1089 EVP_MD_CTX_init(&mdctx);
1095 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1096 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1097 !EVP_DigestUpdate(&mdctx, input, 16) ||
1098 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1100 pthread_mutex_unlock(&lock);
1103 for (i = 0; i < 16; i++)
1104 out[offset + i] = hash[i] ^ in[offset + i];
1105 input = in + offset;
1110 memcpy(in, out, len);
1111 pthread_mutex_unlock(&lock);
1115 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1116 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1117 static unsigned char first = 1;
1118 static EVP_MD_CTX mdctx;
1119 unsigned char hash[EVP_MAX_MD_SIZE];
1120 unsigned int md_len;
1123 pthread_mutex_lock(&lock);
1125 EVP_MD_CTX_init(&mdctx);
1130 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1131 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1132 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1135 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1136 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1137 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1138 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1139 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1140 pthread_mutex_unlock(&lock);
1145 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1148 for (i = 0; i < 16; i++)
1151 for (offset = 16; offset < len; offset += 16) {
1153 printf("text + offset - 16 c(%d): ", offset / 16);
1154 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1156 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1157 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1158 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1159 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1161 pthread_mutex_unlock(&lock);
1165 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1168 for (i = 0; i < 16; i++)
1169 text[offset + i] ^= hash[i];
1173 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1176 pthread_mutex_unlock(&lock);
1180 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1181 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1182 static unsigned char first = 1;
1183 static EVP_MD_CTX mdctx;
1184 unsigned char hash[EVP_MAX_MD_SIZE];
1185 unsigned int md_len;
1189 pthread_mutex_lock(&lock);
1191 EVP_MD_CTX_init(&mdctx);
1196 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1197 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1198 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1201 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1202 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1203 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1204 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1205 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1206 pthread_mutex_unlock(&lock);
1211 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1214 for (i = 0; i < 16; i++)
1215 plain[i] = text[i] ^ hash[i];
1217 for (offset = 16; offset < len; offset += 16) {
1219 printf("text + offset - 16 c(%d): ", offset / 16);
1220 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1222 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1223 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1224 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1225 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1227 pthread_mutex_unlock(&lock);
1231 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1234 for (i = 0; i < 16; i++)
1235 plain[offset + i] = text[offset + i] ^ hash[i];
1238 memcpy(text, plain, len);
1240 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1243 pthread_mutex_unlock(&lock);
1247 struct realm *id2realm(struct list *realmlist, char *id) {
1248 struct list_node *entry;
1249 struct realm *realm, *subrealm = NULL;
1251 /* need to do locking for subrealms and check subrealm timers */
1252 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1253 realm = (struct realm *)entry->data;
1254 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1255 pthread_mutex_lock(&realm->subrealms_mutex);
1256 if (realm->subrealms)
1257 subrealm = id2realm(realm->subrealms, id);
1258 pthread_mutex_unlock(&realm->subrealms_mutex);
1259 return subrealm ? subrealm : realm;
1265 /* helper function, only used by removeserversubrealms() */
1266 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1267 struct list_node *entry;
1268 struct realm *realm;
1270 for (entry = list_first(realmlist); entry;) {
1271 realm = (struct realm *)entry->data;
1272 entry = list_next(entry);
1273 if (realm->srvconfs) {
1274 list_removedata(realm->srvconfs, srv);
1275 if (!list_first(realm->srvconfs)) {
1276 list_destroy(realm->srvconfs);
1277 realm->srvconfs = NULL;
1280 if (realm->accsrvconfs) {
1281 list_removedata(realm->accsrvconfs, srv);
1282 if (!list_first(realm->accsrvconfs)) {
1283 list_destroy(realm->accsrvconfs);
1284 realm->accsrvconfs = NULL;
1288 /* remove subrealm if no servers */
1289 if (!realm->srvconfs && !realm->accsrvconfs) {
1290 list_removedata(realmlist, realm);
1296 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1297 struct list_node *entry;
1298 struct realm *realm;
1300 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1301 realm = (struct realm *)entry->data;
1302 pthread_mutex_lock(&realm->subrealms_mutex);
1303 if (realm->subrealms) {
1304 _internal_removeserversubrealms(realm->subrealms, srv);
1305 if (!list_first(realm->subrealms)) {
1306 list_destroy(realm->subrealms);
1307 realm->subrealms = NULL;
1310 pthread_mutex_unlock(&realm->subrealms_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, uint8_t *oldauth, uint8_t *newauth) {
1355 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1356 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1359 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), 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 request *rq,
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, rq->buf + 4, rq->rqauth))
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 request *rq, struct tlv *attr) {
1558 char *orig = (char *)tlv2str(attr);
1559 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1563 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1564 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 respond(struct request *rq, uint8_t code, char *message) {
1638 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1640 debug(DBG_ERR, "respond: malloc failed");
1643 if (message && *message) {
1644 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1645 if (!attr || !radmsg_add(msg, attr)) {
1648 debug(DBG_ERR, "respond: malloc failed");
1653 radmsg_free(rq->msg);
1655 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1656 sendreply(newrqref(rq));
1659 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1660 struct list_node *entry;
1661 struct clsrvconf *server, *best = NULL, *first = NULL;
1663 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1664 server = (struct clsrvconf *)entry->data;
1665 if (!server->servers)
1669 if (!server->servers->connectionok)
1671 if (!server->servers->lostrqs)
1677 if (server->servers->lostrqs < best->servers->lostrqs)
1680 return best ? best : first;
1683 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1684 struct clsrvconf *srvconf;
1685 char *id = (char *)tlv2str(username);
1689 *realm = id2realm(realms, id);
1694 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1695 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1700 if (!acc && !srvconf->servers)
1701 adddynamicrealmserver(*realm, srvconf, id);
1703 return srvconf->servers;
1707 struct request *newrequest() {
1710 rq = malloc(sizeof(struct request));
1712 debug(DBG_ERR, "newrequest: malloc failed");
1715 memset(rq, 0, sizeof(struct request));
1717 gettimeofday(&rq->created, NULL);
1721 int addclientrq(struct request *rq) {
1725 r = rq->from->rqs[rq->rqid];
1727 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1728 gettimeofday(&now, NULL);
1729 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1731 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1732 sendreply(newrqref(r));
1734 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1740 rq->from->rqs[rq->rqid] = newrqref(rq);
1744 void rmclientrq(struct request *rq, uint8_t id) {
1747 r = rq->from->rqs[id];
1750 rq->from->rqs[id] = NULL;
1754 /* returns 0 if validation/authentication fails, else 1 */
1755 int radsrv(struct request *rq) {
1756 struct radmsg *msg = NULL;
1758 uint8_t *userascii = NULL;
1759 struct realm *realm = NULL;
1760 struct server *to = NULL;
1761 struct client *from = rq->from;
1763 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1768 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1775 memcpy(rq->rqauth, msg->auth, 16);
1777 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1778 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1779 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1783 if (!addclientrq(rq))
1786 if (msg->code == RAD_Status_Server) {
1787 respond(rq, RAD_Access_Accept, NULL);
1791 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1793 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1796 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1798 if (msg->code == RAD_Accounting_Request) {
1799 acclog(msg, from->conf->host);
1800 respond(rq, RAD_Accounting_Response, NULL);
1802 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1806 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1807 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1811 userascii = radattr2ascii(attr);
1814 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1816 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1818 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1823 if (realm->message && msg->code == RAD_Access_Request) {
1824 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1825 respond(rq, RAD_Access_Reject, realm->message);
1826 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1827 acclog(msg, from->conf->host);
1828 respond(rq, RAD_Accounting_Response, NULL);
1833 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1834 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1835 from->conf->name, to->conf->name);
1839 if (msg->code == RAD_Accounting_Request)
1840 memset(msg->auth, 0, 16);
1841 else if (!RAND_bytes(msg->auth, 16)) {
1842 debug(DBG_WARN, "radsrv: failed to generate random auth");
1847 printfchars(NULL, "auth", "%02x ", auth, 16);
1850 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1852 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1853 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1857 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1859 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1860 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1864 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1873 rmclientrq(rq, msg->id);
1880 void replyh(struct server *server, unsigned char *buf) {
1881 struct client *from;
1882 struct rqout *rqout;
1884 unsigned char *subattrs;
1885 uint8_t *username, *stationid, *replymsg;
1886 struct radmsg *msg = NULL;
1888 struct list_node *node;
1890 server->connectionok = 1;
1891 server->lostrqs = 0;
1893 rqout = server->requests + buf[1];
1894 pthread_mutex_lock(rqout->lock);
1895 if (!rqout->tries) {
1898 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1902 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1906 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1909 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1910 && msg->code != RAD_Accounting_Response) {
1911 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1914 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1916 gettimeofday(&server->lastrcv, NULL);
1918 if (rqout->rq->msg->code == RAD_Status_Server) {
1919 freerqoutdata(rqout);
1920 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1924 gettimeofday(&server->lastreply, NULL);
1925 from = rqout->rq->from;
1927 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1928 debug(DBG_WARN, "replyh: rewritein failed");
1933 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1934 attr = (struct tlv *)node->data;
1935 if (attr->t != RAD_Attr_Vendor_Specific)
1939 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1942 sublen = attr->l - 4;
1943 subattrs = attr->v + 4;
1944 if (!attrvalidate(subattrs, sublen) ||
1945 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1946 rqout->rq, server->conf->secret, from->conf->secret) ||
1947 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1948 rqout->rq, server->conf->secret, from->conf->secret))
1952 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1956 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1957 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1959 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1960 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
1963 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
1964 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
1967 debug(DBG_INFO, "%s for user %s stationid %s from %s",
1968 radmsgtype2string(msg->code), username, stationid, server->conf->host);
1972 debug(DBG_INFO, "%s for user %s from %s (%s)",
1973 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
1976 debug(DBG_INFO, "%s for user %s from %s",
1977 radmsgtype2string(msg->code), username, server->conf->host);
1983 msg->id = (char)rqout->rq->rqid;
1984 memcpy(msg->auth, rqout->rq->rqauth, 16);
1987 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1990 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
1991 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
1992 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1995 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
1998 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
1999 debug(DBG_WARN, "replyh: rewriteout failed");
2003 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2004 radmsg_free(rqout->rq->msg);
2005 rqout->rq->msg = msg;
2006 sendreply(newrqref(rqout->rq));
2007 freerqoutdata(rqout);
2008 pthread_mutex_unlock(rqout->lock);
2013 pthread_mutex_unlock(rqout->lock);
2017 struct request *createstatsrvrq() {
2024 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2027 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2030 if (!radmsg_add(rq->msg, attr)) {
2041 /* code for removing state not finished */
2042 void *clientwr(void *arg) {
2043 struct server *server = (struct server *)arg;
2044 struct rqout *rqout = NULL;
2045 pthread_t clientrdth;
2046 int i, dynconffail = 0;
2049 struct timeval now, laststatsrv;
2050 struct timespec timeout;
2051 struct request *statsrvrq;
2052 struct clsrvconf *conf;
2054 conf = server->conf;
2056 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2061 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2062 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2066 memset(&timeout, 0, sizeof(struct timespec));
2068 if (conf->statusserver) {
2069 gettimeofday(&server->lastrcv, NULL);
2070 gettimeofday(&laststatsrv, NULL);
2073 if (conf->pdef->connecter) {
2074 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2076 server->connectionok = 1;
2077 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2078 debug(DBG_ERR, "clientwr: pthread_create failed");
2082 server->connectionok = 1;
2085 pthread_mutex_lock(&server->newrq_mutex);
2086 if (!server->newrq) {
2087 gettimeofday(&now, NULL);
2088 /* random 0-7 seconds */
2089 RAND_bytes(&rnd, 1);
2091 if (conf->statusserver) {
2092 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2093 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2095 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2096 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2098 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2099 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2102 if (timeout.tv_sec > now.tv_sec)
2103 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2105 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2108 if (server->newrq) {
2109 debug(DBG_DBG, "clientwr: got new request");
2114 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2116 pthread_mutex_unlock(&server->newrq_mutex);
2118 for (i = 0; i < MAX_REQUESTS; i++) {
2119 if (server->clientrdgone) {
2120 pthread_join(clientrdth, NULL);
2124 for (; i < MAX_REQUESTS; i++) {
2125 rqout = server->requests + i;
2127 pthread_mutex_lock(rqout->lock);
2130 pthread_mutex_unlock(rqout->lock);
2134 if (i == MAX_REQUESTS)
2137 gettimeofday(&now, NULL);
2138 if (now.tv_sec < rqout->expiry.tv_sec) {
2139 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2140 timeout.tv_sec = rqout->expiry.tv_sec;
2141 pthread_mutex_unlock(rqout->lock);
2145 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2146 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2147 if (conf->statusserver) {
2148 if (*rqout->rq->buf == RAD_Status_Server) {
2149 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2150 if (server->lostrqs < 255)
2154 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2155 if (server->lostrqs < 255)
2158 freerqoutdata(rqout);
2159 pthread_mutex_unlock(rqout->lock);
2163 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2164 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2165 timeout.tv_sec = rqout->expiry.tv_sec;
2167 conf->pdef->clientradput(server, rqout->rq->buf);
2168 pthread_mutex_unlock(rqout->lock);
2170 if (conf->statusserver && server->connectionok) {
2171 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2172 gettimeofday(&now, NULL);
2173 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2175 statsrvrq = createstatsrvrq();
2177 statsrvrq->to = server;
2178 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
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));
2286 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2287 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2288 for (i = 0; i < CRYPTO_num_locks(); i++) {
2289 ssl_lock_count[i] = 0;
2290 pthread_mutex_init(&ssl_locks[i], NULL);
2292 CRYPTO_set_id_callback(ssl_thread_id);
2293 CRYPTO_set_locking_callback(ssl_locking_callback);
2295 SSL_load_error_strings();
2298 while (!RAND_status()) {
2301 RAND_seed((unsigned char *)&t, sizeof(time_t));
2302 RAND_seed((unsigned char *)&pid, sizeof(pid));
2306 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2307 STACK_OF(X509_NAME) *calist;
2309 unsigned long error;
2311 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2312 while ((error = ERR_get_error()))
2313 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2314 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2318 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2319 if (!conf->cacertfile || calist) {
2320 if (conf->cacertpath) {
2322 calist = sk_X509_NAME_new_null();
2323 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2324 sk_X509_NAME_free(calist);
2330 while ((error = ERR_get_error()))
2331 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2332 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2335 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2336 SSL_CTX_set_client_CA_list(ctx, calist);
2338 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2339 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2341 if (conf->crlcheck) {
2342 x509_s = SSL_CTX_get_cert_store(ctx);
2343 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2346 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2350 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2351 SSL_CTX *ctx = NULL;
2352 unsigned long error;
2359 ctx = SSL_CTX_new(TLSv1_method());
2361 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2365 ctx = SSL_CTX_new(DTLSv1_method());
2367 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2369 SSL_CTX_set_read_ahead(ctx, 1);
2373 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2377 if (conf->certkeypwd) {
2378 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2379 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2381 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2382 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2383 !SSL_CTX_check_private_key(ctx)) {
2384 while ((error = ERR_get_error()))
2385 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2386 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2391 if (!tlsaddcacrl(ctx, conf)) {
2396 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2400 struct tls *tlsgettls(char *alt1, char *alt2) {
2403 t = hash_read(tlsconfs, alt1, strlen(alt1));
2405 t = hash_read(tlsconfs, alt2, strlen(alt2));
2409 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2414 gettimeofday(&now, NULL);
2418 if (t->tlsexpiry && t->tlsctx) {
2419 if (t->tlsexpiry < now.tv_sec) {
2420 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2421 tlsaddcacrl(t->tlsctx, t);
2425 t->tlsctx = tlscreatectx(RAD_TLS, t);
2427 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2431 if (t->dtlsexpiry && t->dtlsctx) {
2432 if (t->dtlsexpiry < now.tv_sec) {
2433 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2434 tlsaddcacrl(t->dtlsctx, t);
2438 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2440 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2447 struct list *addsrvconfs(char *value, char **names) {
2448 struct list *conflist;
2450 struct list_node *entry;
2451 struct clsrvconf *conf = NULL;
2453 if (!names || !*names)
2456 conflist = list_create();
2458 debug(DBG_ERR, "malloc failed");
2462 for (n = 0; names[n]; n++) {
2463 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2464 conf = (struct clsrvconf *)entry->data;
2465 if (!strcasecmp(names[n], conf->name))
2469 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2470 list_destroy(conflist);
2473 if (!list_push(conflist, conf)) {
2474 debug(DBG_ERR, "malloc failed");
2475 list_destroy(conflist);
2478 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2483 void freerealm(struct realm *realm) {
2487 free(realm->message);
2488 regfree(&realm->regex);
2489 pthread_mutex_destroy(&realm->subrealms_mutex);
2490 if (realm->subrealms)
2491 list_destroy(realm->subrealms);
2492 if (realm->srvconfs) {
2493 /* emptying list without freeing data */
2494 while (list_shift(realm->srvconfs));
2495 list_destroy(realm->srvconfs);
2497 if (realm->accsrvconfs) {
2498 /* emptying list without freeing data */
2499 while (list_shift(realm->accsrvconfs));
2500 list_destroy(realm->accsrvconfs);
2505 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2507 struct realm *realm;
2508 char *s, *regex = NULL;
2510 if (*value == '/') {
2511 /* regexp, remove optional trailing / if present */
2512 if (value[strlen(value) - 1] == '/')
2513 value[strlen(value) - 1] = '\0';
2515 /* not a regexp, let us make it one */
2516 if (*value == '*' && !value[1])
2517 regex = stringcopy(".*", 0);
2519 for (n = 0, s = value; *s;)
2522 regex = malloc(strlen(value) + n + 3);
2525 for (n = 1, s = value; *s; s++) {
2535 debug(DBG_ERR, "malloc failed");
2539 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2542 realm = malloc(sizeof(struct realm));
2544 debug(DBG_ERR, "malloc failed");
2547 memset(realm, 0, sizeof(struct realm));
2549 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2550 debug(DBG_ERR, "mutex init failed");
2556 realm->name = stringcopy(value, 0);
2558 debug(DBG_ERR, "malloc failed");
2561 if (message && strlen(message) > 253) {
2562 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2565 realm->message = message;
2566 realm->accresp = accresp;
2568 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2569 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2573 if (servers && *servers) {
2574 realm->srvconfs = addsrvconfs(value, servers);
2575 if (!realm->srvconfs)
2579 if (accservers && *accservers) {
2580 realm->accsrvconfs = addsrvconfs(value, accservers);
2581 if (!realm->accsrvconfs)
2585 if (!list_push(realmlist, realm)) {
2586 debug(DBG_ERR, "malloc failed");
2587 pthread_mutex_destroy(&realm->subrealms_mutex);
2591 debug(DBG_DBG, "addrealm: added realm %s", value);
2601 for (n = 0; servers[n]; n++)
2606 for (n = 0; accservers[n]; n++)
2607 free(accservers[n]);
2613 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2614 struct clsrvconf *srvconf;
2615 struct realm *newrealm = NULL;
2616 char *realmname, *s;
2619 if (!conf->dynamiclookupcommand)
2622 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2623 realmname = strrchr(id, '@');
2629 for (s = realmname; *s; s++)
2630 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2633 pthread_mutex_lock(&realm->subrealms_mutex);
2634 /* exit if we now already got a matching subrealm */
2635 if (id2realm(realm->subrealms, id))
2637 srvconf = malloc(sizeof(struct clsrvconf));
2639 debug(DBG_ERR, "malloc failed");
2643 if (!addserver(srvconf))
2646 if (!realm->subrealms)
2647 realm->subrealms = list_create();
2648 if (!realm->subrealms)
2650 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2654 /* add server and accserver to newrealm */
2655 newrealm->srvconfs = list_create();
2656 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2657 debug(DBG_ERR, "malloc failed");
2660 newrealm->accsrvconfs = list_create();
2661 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2662 debug(DBG_ERR, "malloc failed");
2666 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2668 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2669 debug(DBG_ERR, "pthread_create failed");
2672 pthread_detach(clientth);
2677 list_removedata(realm->subrealms, newrealm);
2678 freerealm(newrealm);
2679 if (!list_first(realm->subrealms)) {
2680 list_destroy(realm->subrealms);
2681 realm->subrealms = NULL;
2684 freeserver(srvconf->servers, 1);
2686 debug(DBG_ERR, "failed to create dynamic server");
2689 pthread_mutex_unlock(&realm->subrealms_mutex);
2692 int dynamicconfig(struct server *server) {
2693 int ok, fd[2], status;
2695 struct clsrvconf *conf = server->conf;
2696 struct gconffile *cf = NULL;
2698 /* for now we only learn hostname/address */
2699 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2702 debug(DBG_ERR, "dynamicconfig: pipe error");
2707 debug(DBG_ERR, "dynamicconfig: fork error");
2711 } else if (pid == 0) {
2714 if (fd[1] != STDOUT_FILENO) {
2715 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2716 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2719 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2720 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2724 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2725 ok = getgenericconfig(&cf, NULL,
2726 "Server", CONF_CBK, confserver_cb, (void *)conf,
2731 if (waitpid(pid, &status, 0) < 0) {
2732 debug(DBG_ERR, "dynamicconfig: wait error");
2737 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2745 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2749 int addmatchcertattr(struct clsrvconf *conf) {
2753 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2754 r = &conf->certcnregex;
2755 v = conf->matchcertattr + 4;
2756 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2757 r = &conf->certuriregex;
2758 v = conf->matchcertattr + 20;
2763 /* regexp, remove optional trailing / if present */
2764 if (v[strlen(v) - 1] == '/')
2765 v[strlen(v) - 1] = '\0';
2769 *r = malloc(sizeof(regex_t));
2771 debug(DBG_ERR, "malloc failed");
2774 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2777 debug(DBG_ERR, "failed to compile regular expression %s", v);
2783 /* should accept both names and numeric values, only numeric right now */
2784 uint8_t attrname2val(char *attrname) {
2787 val = atoi(attrname);
2788 return val > 0 && val < 256 ? val : 0;
2791 /* should accept both names and numeric values, only numeric right now */
2792 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2795 *vendor = atoi(attrname);
2796 s = strchr(attrname, ':');
2801 *type = atoi(s + 1);
2802 return *type >= 0 && *type < 256;
2805 /* should accept both names and numeric values, only numeric right now */
2806 struct tlv *extractattr(char *nameval) {
2811 s = strchr(nameval, ':');
2812 name = atoi(nameval);
2813 if (!s || name < 1 || name > 255)
2815 len = strlen(s + 1);
2818 a = malloc(sizeof(struct tlv));
2821 a->v = (uint8_t *)stringcopy(s + 1, 0);
2831 /* should accept both names and numeric values, only numeric right now */
2832 struct modattr *extractmodattr(char *nameval) {
2837 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2841 s = strchr(nameval, ':');
2842 name = atoi(nameval);
2843 if (!s || name < 1 || name > 255 || s[1] != '/')
2847 /* regexp, remove optional trailing / if present */
2848 if (s[strlen(s) - 1] == '/')
2849 s[strlen(s) - 1] = '\0';
2857 m = malloc(sizeof(struct modattr));
2859 debug(DBG_ERR, "malloc failed");
2864 m->replacement = stringcopy(t, 0);
2865 if (!m->replacement) {
2867 debug(DBG_ERR, "malloc failed");
2871 m->regex = malloc(sizeof(regex_t));
2873 free(m->replacement);
2875 debug(DBG_ERR, "malloc failed");
2879 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2881 free(m->replacement);
2883 debug(DBG_ERR, "failed to compile regular expression %s", s);
2890 struct rewrite *getrewrite(char *alt1, char *alt2) {
2893 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2895 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2900 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2901 struct rewrite *rewrite = NULL;
2903 uint8_t *rma = NULL;
2904 uint32_t *p, *rmva = NULL;
2905 struct list *adda = NULL, *moda = NULL;
2910 for (n = 0; rmattrs[n]; n++);
2911 rma = calloc(n + 1, sizeof(uint8_t));
2913 debugx(1, DBG_ERR, "malloc failed");
2915 for (i = 0; i < n; i++) {
2916 if (!(rma[i] = attrname2val(rmattrs[i])))
2917 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2925 for (n = 0; rmvattrs[n]; n++);
2926 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2928 debugx(1, DBG_ERR, "malloc failed");
2930 for (p = rmva, i = 0; i < n; i++, p += 2) {
2931 if (!vattrname2val(rmvattrs[i], p, p + 1))
2932 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2940 adda = list_create();
2942 debugx(1, DBG_ERR, "malloc failed");
2943 for (i = 0; addattrs[i]; i++) {
2944 a = extractattr(addattrs[i]);
2946 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2948 if (!list_push(adda, a))
2949 debugx(1, DBG_ERR, "malloc failed");
2955 moda = list_create();
2957 debugx(1, DBG_ERR, "malloc failed");
2958 for (i = 0; modattrs[i]; i++) {
2959 m = extractmodattr(modattrs[i]);
2961 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
2963 if (!list_push(moda, m))
2964 debugx(1, DBG_ERR, "malloc failed");
2969 if (rma || rmva || adda || moda) {
2970 rewrite = malloc(sizeof(struct rewrite));
2972 debugx(1, DBG_ERR, "malloc failed");
2973 rewrite->removeattrs = rma;
2974 rewrite->removevendorattrs = rmva;
2975 rewrite->addattrs = adda;
2976 rewrite->modattrs = moda;
2979 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
2980 debugx(1, DBG_ERR, "malloc failed");
2981 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2984 void freeclsrvconf(struct clsrvconf *conf) {
2990 free(conf->matchcertattr);
2991 if (conf->certcnregex)
2992 regfree(conf->certcnregex);
2993 if (conf->certuriregex)
2994 regfree(conf->certuriregex);
2995 free(conf->confrewritein);
2996 free(conf->confrewriteout);
2997 if (conf->rewriteusername) {
2998 if (conf->rewriteusername->regex)
2999 regfree(conf->rewriteusername->regex);
3000 free(conf->rewriteusername->replacement);
3001 free(conf->rewriteusername);
3003 free(conf->dynamiclookupcommand);
3004 free(conf->rewritein);
3005 free(conf->rewriteout);
3007 freeaddrinfo(conf->addrinfo);
3009 pthread_mutex_destroy(conf->lock);
3012 /* not touching ssl_ctx, clients and servers */
3016 int mergeconfstring(char **dst, char **src) {
3025 t = stringcopy(*dst, 0);
3027 debug(DBG_ERR, "malloc failed");
3035 /* assumes dst is a shallow copy */
3036 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3037 if (!mergeconfstring(&dst->name, &src->name) ||
3038 !mergeconfstring(&dst->host, &src->host) ||
3039 !mergeconfstring(&dst->port, &src->port) ||
3040 !mergeconfstring(&dst->secret, &src->secret) ||
3041 !mergeconfstring(&dst->tls, &src->tls) ||
3042 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3043 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3044 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3045 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3048 dst->pdef = src->pdef;
3049 dst->statusserver = src->statusserver;
3050 dst->certnamecheck = src->certnamecheck;
3051 if (src->retryinterval != 255)
3052 dst->retryinterval = src->retryinterval;
3053 if (src->retrycount != 255)
3054 dst->retrycount = src->retrycount;
3058 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3059 struct clsrvconf *conf;
3060 char *conftype = NULL, *rewriteinalias = NULL;
3061 long int dupinterval = LONG_MIN;
3063 debug(DBG_DBG, "confclient_cb called for %s", block);
3065 conf = malloc(sizeof(struct clsrvconf));
3067 debugx(1, DBG_ERR, "malloc failed");
3068 memset(conf, 0, sizeof(struct clsrvconf));
3069 conf->certnamecheck = 1;
3071 if (!getgenericconfig(cf, block,
3072 "type", CONF_STR, &conftype,
3073 "host", CONF_STR, &conf->host,
3074 "secret", CONF_STR, &conf->secret,
3075 "tls", CONF_STR, &conf->tls,
3076 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3077 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3078 "DuplicateInterval", CONF_LINT, &dupinterval,
3079 "rewrite", CONF_STR, &rewriteinalias,
3080 "rewriteIn", CONF_STR, &conf->confrewritein,
3081 "rewriteOut", CONF_STR, &conf->confrewriteout,
3082 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3085 debugx(1, DBG_ERR, "configuration error");
3087 conf->name = stringcopy(val, 0);
3089 conf->host = stringcopy(val, 0);
3090 if (!conf->name || !conf->host)
3091 debugx(1, DBG_ERR, "malloc failed");
3094 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3095 conf->type = protoname2int(conftype);
3096 conf->pdef = &protodefs[conf->type];
3097 if (!conf->pdef->name)
3098 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3101 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3102 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3104 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3105 if (conf->matchcertattr && !addmatchcertattr(conf))
3106 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3109 if (dupinterval != LONG_MIN) {
3110 if (dupinterval < 0 || dupinterval > 255)
3111 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3112 conf->dupinterval = (uint8_t)dupinterval;
3114 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3116 if (!conf->confrewritein)
3117 conf->confrewritein = rewriteinalias;
3119 free(rewriteinalias);
3120 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3121 if (conf->confrewriteout)
3122 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3124 if (conf->confrewriteusername) {
3125 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3126 if (!conf->rewriteusername)
3127 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3130 if (!resolvepeer(conf, 0))
3131 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3133 if (!conf->secret) {
3134 if (!conf->pdef->secretdefault)
3135 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3136 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3138 debugx(1, DBG_ERR, "malloc failed");
3141 conf->lock = malloc(sizeof(pthread_mutex_t));
3143 debugx(1, DBG_ERR, "malloc failed");
3145 pthread_mutex_init(conf->lock, NULL);
3146 if (!list_push(clconfs, conf))
3147 debugx(1, DBG_ERR, "malloc failed");
3151 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3152 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3153 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3154 if (!conf->tlsconf) {
3155 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3158 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3159 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3165 conf->port = stringcopy(conf->pdef->portdefault, 0);
3167 debug(DBG_ERR, "malloc failed");
3172 if (conf->retryinterval == 255)
3173 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3174 if (conf->retrycount == 255)
3175 conf->retrycount = protodefs[conf->type].retrycountdefault;
3177 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3178 if (conf->confrewriteout)
3179 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3181 if (!conf->secret) {
3182 if (!conf->pdef->secretdefault) {
3183 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3186 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3187 if (!conf->secret) {
3188 debug(DBG_ERR, "malloc failed");
3193 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3194 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3200 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3201 struct clsrvconf *conf, *resconf;
3202 char *conftype = NULL, *rewriteinalias = NULL;
3203 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3205 debug(DBG_DBG, "confserver_cb called for %s", block);
3207 conf = malloc(sizeof(struct clsrvconf));
3209 debug(DBG_ERR, "malloc failed");
3212 memset(conf, 0, sizeof(struct clsrvconf));
3213 resconf = (struct clsrvconf *)arg;
3215 conf->statusserver = resconf->statusserver;
3216 conf->certnamecheck = resconf->certnamecheck;
3218 conf->certnamecheck = 1;
3220 if (!getgenericconfig(cf, block,
3221 "type", CONF_STR, &conftype,
3222 "host", CONF_STR, &conf->host,
3223 "port", CONF_STR, &conf->port,
3224 "secret", CONF_STR, &conf->secret,
3225 "tls", CONF_STR, &conf->tls,
3226 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3227 "rewrite", CONF_STR, &rewriteinalias,
3228 "rewriteIn", CONF_STR, &conf->confrewritein,
3229 "rewriteOut", CONF_STR, &conf->confrewriteout,
3230 "StatusServer", CONF_BLN, &conf->statusserver,
3231 "RetryInterval", CONF_LINT, &retryinterval,
3232 "RetryCount", CONF_LINT, &retrycount,
3233 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3234 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3237 debug(DBG_ERR, "configuration error");
3241 conf->name = stringcopy(val, 0);
3243 debug(DBG_ERR, "malloc failed");
3247 conf->host = stringcopy(val, 0);
3249 debug(DBG_ERR, "malloc failed");
3255 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3256 conf->type = protoname2int(conftype);
3257 conf->pdef = &protodefs[conf->type];
3258 if (!conf->pdef->name) {
3259 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3265 if (!conf->confrewritein)
3266 conf->confrewritein = rewriteinalias;
3268 free(rewriteinalias);
3269 rewriteinalias = NULL;
3271 if (retryinterval != LONG_MIN) {
3272 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3273 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3276 conf->retryinterval = (uint8_t)retryinterval;
3278 conf->retryinterval = 255;
3280 if (retrycount != LONG_MIN) {
3281 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3282 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3285 conf->retrycount = (uint8_t)retrycount;
3287 conf->retrycount = 255;
3290 if (!mergesrvconf(resconf, conf))
3294 if (conf->dynamiclookupcommand) {
3295 free(conf->dynamiclookupcommand);
3296 conf->dynamiclookupcommand = NULL;
3300 if (resconf || !conf->dynamiclookupcommand) {
3301 if (!compileserverconfig(conf, block))
3308 if (!list_push(srvconfs, conf)) {
3309 debug(DBG_ERR, "malloc failed");
3316 free(rewriteinalias);
3317 freeclsrvconf(conf);
3321 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3322 char **servers = NULL, **accservers = NULL, *msg = NULL;
3323 uint8_t accresp = 0;
3325 debug(DBG_DBG, "confrealm_cb called for %s", block);
3327 if (!getgenericconfig(cf, block,
3328 "server", CONF_MSTR, &servers,
3329 "accountingServer", CONF_MSTR, &accservers,
3330 "ReplyMessage", CONF_STR, &msg,
3331 "AccountingResponse", CONF_BLN, &accresp,
3334 debugx(1, DBG_ERR, "configuration error");
3336 addrealm(realms, val, servers, accservers, msg, accresp);
3340 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3342 long int expiry = LONG_MIN;
3344 debug(DBG_DBG, "conftls_cb called for %s", block);
3346 conf = malloc(sizeof(struct tls));
3348 debug(DBG_ERR, "conftls_cb: malloc failed");
3351 memset(conf, 0, sizeof(struct tls));
3353 if (!getgenericconfig(cf, block,
3354 "CACertificateFile", CONF_STR, &conf->cacertfile,
3355 "CACertificatePath", CONF_STR, &conf->cacertpath,
3356 "CertificateFile", CONF_STR, &conf->certfile,
3357 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3358 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3359 "CacheExpiry", CONF_LINT, &expiry,
3360 "CRLCheck", CONF_BLN, &conf->crlcheck,
3363 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3366 if (!conf->certfile || !conf->certkeyfile) {
3367 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3370 if (!conf->cacertfile && !conf->cacertpath) {
3371 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3374 if (expiry != LONG_MIN) {
3376 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3379 conf->cacheexpiry = expiry;
3382 conf->name = stringcopy(val, 0);
3384 debug(DBG_ERR, "conftls_cb: malloc failed");
3388 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3389 debug(DBG_ERR, "conftls_cb: malloc failed");
3392 if (!tlsgetctx(RAD_TLS, conf))
3393 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3394 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3398 free(conf->cacertfile);
3399 free(conf->cacertpath);
3400 free(conf->certfile);
3401 free(conf->certkeyfile);
3402 free(conf->certkeypwd);
3407 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3408 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3410 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3412 if (!getgenericconfig(cf, block,
3413 "removeAttribute", CONF_MSTR, &rmattrs,
3414 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3415 "addAttribute", CONF_MSTR, &addattrs,
3416 "modifyAttribute", CONF_MSTR, &modattrs,
3419 debugx(1, DBG_ERR, "configuration error");
3420 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3424 void getmainconfig(const char *configfile) {
3425 long int loglevel = LONG_MIN;
3426 struct gconffile *cfs;
3428 cfs = openconfigfile(configfile);
3429 memset(&options, 0, sizeof(options));
3431 clconfs = list_create();
3433 debugx(1, DBG_ERR, "malloc failed");
3435 srvconfs = list_create();
3437 debugx(1, DBG_ERR, "malloc failed");
3439 realms = list_create();
3441 debugx(1, DBG_ERR, "malloc failed");
3443 tlsconfs = hash_create();
3445 debugx(1, DBG_ERR, "malloc failed");
3447 rewriteconfs = hash_create();
3449 debugx(1, DBG_ERR, "malloc failed");
3451 if (!getgenericconfig(&cfs, NULL,
3452 "ListenUDP", CONF_MSTR, &options.listenudp,
3453 "ListenTCP", CONF_MSTR, &options.listentcp,
3454 "ListenTLS", CONF_MSTR, &options.listentls,
3455 "ListenDTLS", CONF_MSTR, &options.listendtls,
3456 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3457 "SourceUDP", CONF_STR, &options.sourceudp,
3458 "SourceTCP", CONF_STR, &options.sourcetcp,
3459 "SourceTLS", CONF_STR, &options.sourcetls,
3460 "SourceDTLS", CONF_STR, &options.sourcedtls,
3461 "LogLevel", CONF_LINT, &loglevel,
3462 "LogDestination", CONF_STR, &options.logdestination,
3463 "LoopPrevention", CONF_BLN, &options.loopprevention,
3464 "Client", CONF_CBK, confclient_cb, NULL,
3465 "Server", CONF_CBK, confserver_cb, NULL,
3466 "Realm", CONF_CBK, confrealm_cb, NULL,
3467 "TLS", CONF_CBK, conftls_cb, NULL,
3468 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3471 debugx(1, DBG_ERR, "configuration error");
3473 if (loglevel != LONG_MIN) {
3474 if (loglevel < 1 || loglevel > 4)
3475 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3476 options.loglevel = (uint8_t)loglevel;
3480 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3483 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3486 *configfile = optarg;
3489 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3490 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3491 *loglevel = *optarg - '0';
3500 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3505 if (!(argc - optind))
3509 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3513 int daemon(int a, int b) {
3521 for (i = 0; i < 3; i++) {
3523 open("/dev/null", O_RDWR);
3529 void *sighandler(void *arg) {
3534 sigemptyset(&sigset);
3535 sigaddset(&sigset, SIGPIPE);
3536 sigwait(&sigset, &sig);
3537 /* only get SIGPIPE right now, so could simplify below code */
3540 /* completely ignoring this */
3543 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3546 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3551 int main(int argc, char **argv) {
3554 struct list_node *entry;
3555 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3556 char *configfile = NULL;
3557 struct clsrvconf *srvconf;
3560 debug_init("radsecproxy");
3561 debug_set_level(DEBUG_LEVEL);
3563 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3565 debug_set_level(loglevel);
3566 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3568 options.loglevel = loglevel;
3569 else if (options.loglevel)
3570 debug_set_level(options.loglevel);
3572 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3573 free(options.logdestination);
3575 if (!list_first(clconfs))
3576 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3577 if (!list_first(realms))
3578 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3581 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3583 if (!foreground && (daemon(0, 0) < 0))
3584 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3586 debug_timestamp_on();
3587 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3589 sigemptyset(&sigset);
3590 /* exit on all but SIGPIPE, ignore more? */
3591 sigaddset(&sigset, SIGPIPE);
3592 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3593 pthread_create(&sigth, NULL, sighandler, NULL);
3595 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3596 srvconf = (struct clsrvconf *)entry->data;
3597 if (srvconf->dynamiclookupcommand)
3599 if (!addserver(srvconf))
3600 debugx(1, DBG_ERR, "failed to add server");
3601 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3602 (void *)(srvconf->servers)))
3603 debugx(1, DBG_ERR, "pthread_create failed");
3605 /* srcprotores for UDP no longer needed */
3606 if (srcprotores[RAD_UDP]) {
3607 freeaddrinfo(srcprotores[RAD_UDP]);
3608 srcprotores[RAD_UDP] = NULL;
3611 for (i = 0; protodefs[i].name; i++)
3612 if (protodefs[i].initextra)
3613 protodefs[i].initextra();
3615 if (find_clconf_type(RAD_TCP, NULL))
3616 createlisteners(RAD_TCP, options.listentcp);
3618 if (find_clconf_type(RAD_TLS, NULL))
3619 createlisteners(RAD_TLS, options.listentls);
3621 if (find_clconf_type(RAD_DTLS, NULL))
3622 createlisteners(RAD_DTLS, options.listendtls);
3624 if (find_clconf_type(RAD_UDP, NULL)) {
3625 createlisteners(RAD_UDP, options.listenudp);
3626 if (options.listenaccudp)
3627 createlisteners(RAD_UDP, options.listenaccudp);
3630 /* just hang around doing nothing, anything to do here? */