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 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
42 * Useful for TCP accounting? Now we require separate server config for alt port
46 #include <sys/socket.h>
47 #include <netinet/in.h>
56 #include <sys/types.h>
57 #include <sys/select.h>
60 #include <arpa/inet.h>
64 #include <openssl/ssl.h>
65 #include <openssl/rand.h>
66 #include <openssl/err.h>
67 #include <openssl/md5.h>
68 #include <openssl/hmac.h>
69 #include <openssl/x509v3.h>
75 #include "radsecproxy.h"
81 static struct options options;
82 static struct list *clconfs, *srvconfs;
84 struct hash *tlsconfs, *rewriteconfs;
86 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
88 static pthread_mutex_t *ssl_locks = NULL;
89 static long *ssl_lock_count;
93 /* minimum required declarations to avoid reordering code */
94 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
95 int dynamicconfig(struct server *server);
96 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
97 void freerealm(struct realm *realm);
98 void freeclsrvconf(struct clsrvconf *conf);
99 void freerq(struct request *rq);
100 void freerqoutdata(struct rqout *rqout);
101 void rmclientrq(struct request *rq, uint8_t id);
103 static const struct protodefs protodefs[] = {
104 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
105 NULL, /* secretdefault */
106 SOCK_DGRAM, /* socktype */
107 "1812", /* portdefault */
108 REQUEST_RETRY_COUNT, /* retrycountdefault */
109 10, /* retrycountmax */
110 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
111 60, /* retryintervalmax */
112 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
113 udpserverrd, /* listener */
114 &options.sourceudp, /* srcaddrport */
115 NULL, /* connecter */
116 NULL, /* clientconnreader */
117 clientradputudp, /* clientradput */
118 addclientudp, /* addclient */
119 addserverextraudp, /* addserverextra */
120 initextraudp /* initextra */
122 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
123 "mysecret", /* secretdefault */
124 SOCK_STREAM, /* socktype */
125 "2083", /* portdefault */
126 0, /* retrycountdefault */
127 0, /* retrycountmax */
128 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
129 60, /* retryintervalmax */
130 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
131 tlslistener, /* listener */
132 &options.sourcetls, /* srcaddrport */
133 tlsconnect, /* connecter */
134 tlsclientrd, /* clientconnreader */
135 clientradputtls, /* clientradput */
136 NULL, /* addclient */
137 NULL, /* addserverextra */
140 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
141 NULL, /* secretdefault */
142 SOCK_STREAM, /* socktype */
143 "1812", /* portdefault */
144 0, /* retrycountdefault */
145 0, /* retrycountmax */
146 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
147 60, /* retryintervalmax */
148 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
149 tcplistener, /* listener */
150 &options.sourcetcp, /* srcaddrport */
151 tcpconnect, /* connecter */
152 tcpclientrd, /* clientconnreader */
153 clientradputtcp, /* clientradput */
154 NULL, /* addclient */
155 NULL, /* addserverextra */
158 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
159 "mysecret", /* secretdefault */
160 SOCK_DGRAM, /* socktype */
161 "2083", /* portdefault */
162 REQUEST_RETRY_COUNT, /* retrycountdefault */
163 10, /* retrycountmax */
164 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
165 60, /* retryintervalmax */
166 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
167 udpdtlsserverrd, /* listener */
168 &options.sourcedtls, /* srcaddrport */
169 dtlsconnect, /* connecter */
170 dtlsclientrd, /* clientconnreader */
171 clientradputdtls, /* clientradput */
172 NULL, /* addclient */
173 addserverextradtls, /* addserverextra */
174 initextradtls /* initextra */
180 uint8_t protoname2int(const char *name) {
183 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
187 /* callbacks for making OpenSSL thread safe */
188 unsigned long ssl_thread_id() {
189 return (unsigned long)pthread_self();
192 void ssl_locking_callback(int mode, int type, const char *file, int line) {
193 if (mode & CRYPTO_LOCK) {
194 pthread_mutex_lock(&ssl_locks[type]);
195 ssl_lock_count[type]++;
197 pthread_mutex_unlock(&ssl_locks[type]);
200 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
201 int pwdlen = strlen(userdata);
202 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
204 memcpy(buf, userdata, pwdlen);
208 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
213 err_cert = X509_STORE_CTX_get_current_cert(ctx);
214 err = X509_STORE_CTX_get_error(ctx);
215 depth = X509_STORE_CTX_get_error_depth(ctx);
217 if (depth > MAX_CERT_DEPTH) {
219 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
220 X509_STORE_CTX_set_error(ctx, err);
224 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
225 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
228 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
229 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
230 debug(DBG_WARN, "\tIssuer=%s", buf);
232 case X509_V_ERR_CERT_NOT_YET_VALID:
233 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
234 debug(DBG_WARN, "\tCertificate not yet valid");
236 case X509_V_ERR_CERT_HAS_EXPIRED:
237 debug(DBG_WARN, "Certificate has expired");
239 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
240 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
245 printf("certificate verify returns %d\n", ok);
250 struct addrinfo *getsrcprotores(uint8_t type) {
251 return srcprotores[type];
254 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
255 struct addrinfo hints, *addrinfo, *res;
259 slash = conf->host ? strchr(conf->host, '/') : NULL;
263 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
267 if (*s < '0' || *s > '9') {
268 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
271 plen = atoi(slash + 1);
272 if (plen < 0 || plen > 128) {
273 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
278 memset(&hints, 0, sizeof(hints));
279 hints.ai_socktype = conf->pdef->socktype;
280 hints.ai_family = AF_UNSPEC;
281 hints.ai_flags = ai_flags;
282 if (!conf->host && !conf->port) {
283 /* getaddrinfo() doesn't like host and port to be NULL */
284 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
285 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
288 for (res = addrinfo; res; res = res->ai_next)
289 port_set(res->ai_addr, 0);
292 hints.ai_flags |= AI_NUMERICHOST;
293 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
294 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
299 switch (addrinfo->ai_family) {
302 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
303 freeaddrinfo(addrinfo);
310 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
311 freeaddrinfo(addrinfo);
314 conf->prefixlen = plen;
316 conf->prefixlen = 255;
319 freeaddrinfo(conf->addrinfo);
320 conf->addrinfo = addrinfo;
324 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
329 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
333 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
335 debugx(1, DBG_ERR, "no ] matching initial [");
339 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
342 debugx(1, DBG_ERR, "missing host/address");
344 conf->host = stringcopy(field, p - field);
347 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
348 debugx(1, DBG_ERR, "unexpected character after ]");
351 /* port number or service name is specified */;
353 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
355 debugx(1, DBG_ERR, "syntax error, : but no following port");
356 conf->port = stringcopy(field, p - field);
358 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
362 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
363 struct clsrvconf *conf;
365 conf = malloc(sizeof(struct clsrvconf));
367 debugx(1, DBG_ERR, "malloc failed");
368 memset(conf, 0, sizeof(struct clsrvconf));
370 conf->pdef = &protodefs[conf->type];
372 parsehostport(lconf, conf, default_port);
373 if (!strcmp(conf->host, "*")) {
378 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
379 if (!resolvepeer(conf, AI_PASSIVE))
380 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
384 void freeclsrvres(struct clsrvconf *res) {
388 freeaddrinfo(res->addrinfo);
392 /* returns 1 if the len first bits are equal, else 0 */
393 int prefixmatch(void *a1, void *a2, uint8_t len) {
394 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
396 if (l && memcmp(a1, a2, l))
401 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
404 /* returns next config with matching address, or NULL */
405 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
406 struct sockaddr_in6 *sa6 = NULL;
407 struct in_addr *a4 = NULL;
408 struct addrinfo *res;
409 struct list_node *entry;
410 struct clsrvconf *conf;
412 if (addr->sa_family == AF_INET6) {
413 sa6 = (struct sockaddr_in6 *)addr;
414 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
415 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
419 a4 = &((struct sockaddr_in *)addr)->sin_addr;
421 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
422 conf = (struct clsrvconf *)entry->data;
423 if (conf->type == type) {
424 if (conf->prefixlen == 255) {
425 for (res = conf->addrinfo; res; res = res->ai_next)
426 if ((a4 && res->ai_family == AF_INET &&
427 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
428 (sa6 && res->ai_family == AF_INET6 &&
429 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
435 res = conf->addrinfo;
437 ((a4 && res->ai_family == AF_INET &&
438 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
439 (sa6 && res->ai_family == AF_INET6 &&
440 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
451 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
452 return find_conf(type, addr, clconfs, cur);
455 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
456 return find_conf(type, addr, srvconfs, cur);
459 /* returns next config of given type, or NULL */
460 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
461 struct list_node *entry;
462 struct clsrvconf *conf;
464 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
465 conf = (struct clsrvconf *)entry->data;
466 if (conf->type == type) {
475 struct queue *newqueue() {
478 q = malloc(sizeof(struct queue));
480 debugx(1, DBG_ERR, "malloc failed");
481 q->entries = list_create();
483 debugx(1, DBG_ERR, "malloc failed");
484 pthread_mutex_init(&q->mutex, NULL);
485 pthread_cond_init(&q->cond, NULL);
489 void removequeue(struct queue *q) {
490 struct list_node *entry;
494 pthread_mutex_lock(&q->mutex);
495 for (entry = list_first(q->entries); entry; entry = list_next(entry))
496 freerq((struct request *)entry);
497 list_destroy(q->entries);
498 pthread_cond_destroy(&q->cond);
499 pthread_mutex_unlock(&q->mutex);
500 pthread_mutex_destroy(&q->mutex);
504 void freebios(struct queue *q) {
507 pthread_mutex_lock(&q->mutex);
508 while ((bio = (BIO *)list_shift(q->entries)))
510 pthread_mutex_unlock(&q->mutex);
514 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
515 struct client *new = malloc(sizeof(struct client));
518 debug(DBG_ERR, "malloc failed");
523 pthread_mutex_lock(conf->lock);
524 if (!conf->clients) {
525 conf->clients = list_create();
526 if (!conf->clients) {
528 pthread_mutex_unlock(conf->lock);
529 debug(DBG_ERR, "malloc failed");
534 memset(new, 0, sizeof(struct client));
536 if (conf->pdef->addclient)
537 conf->pdef->addclient(new);
539 new->replyq = newqueue();
540 list_push(conf->clients, new);
542 pthread_mutex_unlock(conf->lock);
546 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
547 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
550 pthread_mutex_lock(&lock);
552 pthread_mutex_unlock(&lock);
555 void removeclientrqs(struct client *client) {
560 removeclientrqs_sendrq_freeserver_lock(1);
561 for (i = 0; i < MAX_REQUESTS; i++) {
566 rqout = rq->to->requests + rq->newid;
567 pthread_mutex_lock(rqout->lock);
568 if (rqout->rq == rq) /* still pointing to our request */
569 freerqoutdata(rqout);
570 pthread_mutex_unlock(rqout->lock);
574 removeclientrqs_sendrq_freeserver_lock(0);
577 void removeclient(struct client *client) {
578 struct clsrvconf *conf;
583 pthread_mutex_lock(conf->lock);
585 removeclientrqs(client);
586 removequeue(client->replyq);
587 list_removedata(conf->clients, client);
591 pthread_mutex_unlock(conf->lock);
594 void freeserver(struct server *server, uint8_t destroymutex) {
595 struct rqout *rqout, *end;
600 removeclientrqs_sendrq_freeserver_lock(1);
601 if (server->requests) {
602 rqout = server->requests;
603 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
605 rqout->rq->to = NULL;
606 freerqoutdata(rqout);
607 pthread_mutex_destroy(rqout->lock);
610 free(server->requests);
613 freebios(server->rbios);
614 free(server->dynamiclookuparg);
616 SSL_free(server->ssl);
618 pthread_mutex_destroy(&server->lock);
619 pthread_cond_destroy(&server->newrq_cond);
620 pthread_mutex_destroy(&server->newrq_mutex);
622 removeclientrqs_sendrq_freeserver_lock(0);
626 int addserver(struct clsrvconf *conf) {
627 struct clsrvconf *res;
632 debug(DBG_ERR, "addserver: currently works with just one server per conf");
635 conf->servers = malloc(sizeof(struct server));
636 if (!conf->servers) {
637 debug(DBG_ERR, "malloc failed");
640 memset(conf->servers, 0, sizeof(struct server));
641 conf->servers->conf = conf;
644 if (type == RAD_DTLS)
645 conf->servers->rbios = newqueue();
647 if (!srcprotores[type]) {
648 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
649 srcprotores[type] = res->addrinfo;
650 res->addrinfo = NULL;
654 conf->servers->sock = -1;
655 if (conf->pdef->addserverextra)
656 conf->pdef->addserverextra(conf);
658 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
659 if (!conf->servers->requests) {
660 debug(DBG_ERR, "malloc failed");
663 for (i = 0; i < MAX_REQUESTS; i++) {
664 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
665 if (!conf->servers->requests[i].lock) {
666 debug(DBG_ERR, "malloc failed");
669 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
670 debug(DBG_ERR, "mutex init failed");
671 free(conf->servers->requests[i].lock);
672 conf->servers->requests[i].lock = NULL;
676 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
677 debug(DBG_ERR, "mutex init failed");
680 conf->servers->newrq = 0;
681 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
682 debug(DBG_ERR, "mutex init failed");
683 pthread_mutex_destroy(&conf->servers->lock);
686 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
687 debug(DBG_ERR, "mutex init failed");
688 pthread_mutex_destroy(&conf->servers->newrq_mutex);
689 pthread_mutex_destroy(&conf->servers->lock);
696 freeserver(conf->servers, 0);
697 conf->servers = NULL;
701 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
702 int loc, i, l, n, r = 0;
705 STACK_OF(GENERAL_NAME) *alt;
708 debug(DBG_DBG, "subjectaltnameaddr");
710 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
714 ex = X509_get_ext(cert, loc);
715 alt = X509V3_EXT_d2i(ex);
719 n = sk_GENERAL_NAME_num(alt);
720 for (i = 0; i < n; i++) {
721 gn = sk_GENERAL_NAME_value(alt, i);
722 if (gn->type != GEN_IPADD)
725 v = (char *)ASN1_STRING_data(gn->d.ia5);
726 l = ASN1_STRING_length(gn->d.ia5);
727 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
728 && !memcmp(v, &addr, l)) {
733 GENERAL_NAMES_free(alt);
737 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
744 nm = X509_get_subject_name(cert);
747 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
750 e = X509_NAME_get_entry(nm, loc);
751 t = X509_NAME_ENTRY_get_data(e);
752 v = (char *) ASN1_STRING_data(t);
753 l = ASN1_STRING_length(t);
757 if (l == strlen(exact) && !strncasecmp(exact, v, l))
760 s = stringcopy((char *)v, l);
762 debug(DBG_ERR, "malloc failed");
765 if (regexec(regex, s, 0, NULL, 0)) {
776 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
777 int loc, i, l, n, r = 0;
780 STACK_OF(GENERAL_NAME) *alt;
783 debug(DBG_DBG, "subjectaltnameregexp");
785 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
789 ex = X509_get_ext(cert, loc);
790 alt = X509V3_EXT_d2i(ex);
794 n = sk_GENERAL_NAME_num(alt);
795 for (i = 0; i < n; i++) {
796 gn = sk_GENERAL_NAME_value(alt, i);
797 if (gn->type != type)
800 v = (char *)ASN1_STRING_data(gn->d.ia5);
801 l = ASN1_STRING_length(gn->d.ia5);
805 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
808 if (memcmp(v, exact, l))
811 s = stringcopy((char *)v, l);
813 debug(DBG_ERR, "malloc failed");
816 if (regexec(regex, s, 0, NULL, 0)) {
825 GENERAL_NAMES_free(alt);
829 X509 *verifytlscert(SSL *ssl) {
833 if (SSL_get_verify_result(ssl) != X509_V_OK) {
834 debug(DBG_ERR, "verifytlscert: basic validation failed");
835 while ((error = ERR_get_error()))
836 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
840 cert = SSL_get_peer_certificate(ssl);
842 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
846 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
848 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
849 struct in6_addr addr;
851 if (conf->certnamecheck && conf->prefixlen == 255) {
852 if (inet_pton(AF_INET, conf->host, &addr))
854 else if (inet_pton(AF_INET6, conf->host, &addr))
857 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
860 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
863 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
865 if (!cnregexp(cert, conf->host, NULL)) {
866 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
869 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
872 if (conf->certcnregex) {
873 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
874 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
877 debug(DBG_DBG, "verifyconfcert: CN matching regex");
879 if (conf->certuriregex) {
880 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
881 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
884 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
889 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
891 if (ATTRTYPE(attrs) == type)
893 length -= ATTRLEN(attrs);
894 attrs += ATTRLEN(attrs);
899 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 *newrealmref(struct realm *r) {
1253 /* returns with lock on realm */
1254 struct realm *id2realm(struct list *realmlist, char *id) {
1255 struct list_node *entry;
1256 struct realm *realm, *subrealm;
1258 /* need to do locking for subrealms and check subrealm timers */
1259 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1260 realm = (struct realm *)entry->data;
1261 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1262 pthread_mutex_lock(&realm->mutex);
1263 if (realm->subrealms) {
1264 subrealm = id2realm(realm->subrealms, id);
1266 pthread_mutex_unlock(&realm->mutex);
1270 return newrealmref(realm);
1276 /* helper function, only used by removeserversubrealms() */
1277 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1278 struct list_node *entry, *entry2;
1279 struct realm *realm;
1281 for (entry = list_first(realmlist); entry;) {
1282 realm = newrealmref((struct realm *)entry->data);
1283 pthread_mutex_lock(&realm->mutex);
1284 entry = list_next(entry);
1286 if (realm->srvconfs) {
1287 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1288 if (entry2->data == srv)
1290 list_removedata(realm->srvconfs, srv);
1291 if (!list_first(realm->srvconfs)) {
1292 list_destroy(realm->srvconfs);
1293 realm->srvconfs = NULL;
1296 if (realm->accsrvconfs) {
1297 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1298 if (entry2->data == srv)
1300 list_removedata(realm->accsrvconfs, srv);
1301 if (!list_first(realm->accsrvconfs)) {
1302 list_destroy(realm->accsrvconfs);
1303 realm->accsrvconfs = NULL;
1307 /* remove subrealm if no servers */
1308 if (!realm->srvconfs && !realm->accsrvconfs)
1309 list_removedata(realmlist, realm);
1311 pthread_mutex_unlock(&realm->mutex);
1316 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1317 struct list_node *entry;
1318 struct realm *realm;
1320 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1321 realm = (struct realm *)entry->data;
1322 pthread_mutex_lock(&realm->mutex);
1323 if (realm->subrealms) {
1324 _internal_removeserversubrealms(realm->subrealms, srv);
1325 if (!list_first(realm->subrealms)) {
1326 list_destroy(realm->subrealms);
1327 realm->subrealms = NULL;
1330 pthread_mutex_unlock(&realm->mutex);
1334 int attrvalidate(unsigned char *attrs, int length) {
1335 while (length > 1) {
1336 if (ATTRLEN(attrs) < 2) {
1337 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1340 length -= ATTRLEN(attrs);
1342 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1345 attrs += ATTRLEN(attrs);
1348 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1352 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1353 if (len < 16 || len > 128 || len % 16) {
1354 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1358 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1359 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1363 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1365 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1366 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1372 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1375 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1376 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1379 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1380 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1386 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1387 char *oldsecret, char *newsecret) {
1388 unsigned char *attr;
1390 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1391 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1392 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1398 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1402 for (; attrs[0]; attrs += 2)
1403 if (attrs[0] == vendor && attrs[1] == subattr)
1408 /* returns 1 if entire element is to be removed, else 0 */
1409 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1410 uint8_t alen, sublen;
1414 if (!removevendorattrs)
1417 memcpy(&vendor, attr->v, 4);
1418 vendor = ntohl(vendor);
1419 while (*removevendorattrs && *removevendorattrs != vendor)
1420 removevendorattrs += 2;
1421 if (!*removevendorattrs)
1424 if (findvendorsubattr(removevendorattrs, vendor, -1))
1425 return 1; /* remove entire vendor attribute */
1427 sublen = attr->l - 4;
1428 subattrs = attr->v + 4;
1430 if (!attrvalidate(subattrs, sublen)) {
1431 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1435 while (sublen > 1) {
1436 alen = ATTRLEN(subattrs);
1438 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1439 memmove(subattrs, subattrs + alen, sublen);
1447 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1448 struct list_node *n, *p;
1452 n = list_first(msg->attrs);
1454 attr = (struct tlv *)n->data;
1455 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1456 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1457 list_removedata(msg->attrs, attr);
1459 n = p ? list_next(p) : list_first(msg->attrs);
1466 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1467 struct list_node *n;
1470 for (n = list_first(addattrs); n; n = list_next(n)) {
1471 a = copytlv((struct tlv *)n->data);
1474 if (!radmsg_add(msg, a)) {
1482 int resizeattr(struct tlv *attr, uint8_t newlen) {
1485 if (newlen != attr->l) {
1486 newv = realloc(attr->v, newlen);
1495 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1496 size_t nmatch = 10, reslen = 0, start = 0;
1497 regmatch_t pmatch[10], *pfield;
1501 in = stringcopy((char *)attr->v, attr->l);
1505 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1510 out = modattr->replacement;
1512 for (i = start; out[i]; i++) {
1513 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1514 pfield = &pmatch[out[i + 1] - '0'];
1515 if (pfield->rm_so >= 0) {
1516 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1522 reslen += i - start;
1524 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1529 if (!resizeattr(attr, reslen)) {
1536 for (i = start; out[i]; i++) {
1537 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1538 pfield = &pmatch[out[i + 1] - '0'];
1539 if (pfield->rm_so >= 0) {
1540 memcpy(attr->v + reslen, out + start, i - start);
1541 reslen += i - start;
1542 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1543 reslen += pfield->rm_eo - pfield->rm_so;
1550 memcpy(attr->v + reslen, out + start, i - start);
1554 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1555 struct list_node *n, *m;
1557 for (n = list_first(msg->attrs); n; n = list_next(n))
1558 for (m = list_first(modattrs); m; m = list_next(m))
1559 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1560 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1565 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1568 if (rewrite->removeattrs || rewrite->removevendorattrs)
1569 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1570 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1572 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1577 int rewriteusername(struct request *rq, struct tlv *attr) {
1578 char *orig = (char *)tlv2str(attr);
1579 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1583 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1584 rq->origusername = (char *)orig;
1590 const char *radmsgtype2string(uint8_t code) {
1591 static const char *rad_msg_names[] = {
1592 "", "Access-Request", "Access-Accept", "Access-Reject",
1593 "Accounting-Request", "Accounting-Response", "", "",
1594 "", "", "", "Access-Challenge",
1595 "Status-Server", "Status-Client"
1597 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1600 void char2hex(char *h, unsigned char c) {
1601 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1602 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1603 h[0] = hexdigits[c / 16];
1604 h[1] = hexdigits[c % 16];
1608 uint8_t *radattr2ascii(struct tlv *attr) {
1616 for (i = 0; i < attr->l; i++)
1617 if (attr->v[i] < 32 || attr->v[i] > 126)
1620 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1627 for (i = 0; i < attr->l; i++)
1628 if (attr->v[i] < 32 || attr->v[i] > 126) {
1630 char2hex((char *)d, attr->v[i]);
1638 void acclog(struct radmsg *msg, char *host) {
1642 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1644 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1647 username = radattr2ascii(attr);
1649 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1654 void respond(struct request *rq, uint8_t code, char *message) {
1658 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1660 debug(DBG_ERR, "respond: malloc failed");
1663 if (message && *message) {
1664 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1665 if (!attr || !radmsg_add(msg, attr)) {
1668 debug(DBG_ERR, "respond: malloc failed");
1673 radmsg_free(rq->msg);
1675 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1676 sendreply(newrqref(rq));
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 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1704 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1705 struct clsrvconf *srvconf;
1706 struct realm *subrealm;
1707 struct server *server = NULL;
1708 char *id = (char *)tlv2str(username);
1712 /* returns with lock on realm */
1713 *realm = id2realm(realms, id);
1716 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1717 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1720 server = srvconf->servers;
1721 if (!acc && !(*realm)->parent && !srvconf->servers) {
1722 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1724 pthread_mutex_lock(&subrealm->mutex);
1725 pthread_mutex_unlock(&(*realm)->mutex);
1728 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1737 struct request *newrequest() {
1740 rq = malloc(sizeof(struct request));
1742 debug(DBG_ERR, "newrequest: malloc failed");
1745 memset(rq, 0, sizeof(struct request));
1747 gettimeofday(&rq->created, NULL);
1751 int addclientrq(struct request *rq) {
1755 r = rq->from->rqs[rq->rqid];
1757 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1758 gettimeofday(&now, NULL);
1759 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1761 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1762 sendreply(newrqref(r));
1764 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1770 rq->from->rqs[rq->rqid] = newrqref(rq);
1774 void rmclientrq(struct request *rq, uint8_t id) {
1777 r = rq->from->rqs[id];
1780 rq->from->rqs[id] = NULL;
1784 /* returns 0 if validation/authentication fails, else 1 */
1785 int radsrv(struct request *rq) {
1786 struct radmsg *msg = NULL;
1788 uint8_t *userascii = NULL;
1789 struct realm *realm = NULL;
1790 struct server *to = NULL;
1791 struct client *from = rq->from;
1793 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1798 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1805 memcpy(rq->rqauth, msg->auth, 16);
1807 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1808 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1809 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1813 if (!addclientrq(rq))
1816 if (msg->code == RAD_Status_Server) {
1817 respond(rq, RAD_Access_Accept, NULL);
1821 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1823 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1826 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1828 if (msg->code == RAD_Accounting_Request) {
1829 acclog(msg, from->conf->host);
1830 respond(rq, RAD_Accounting_Response, NULL);
1832 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1836 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1837 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1841 userascii = radattr2ascii(attr);
1844 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1846 /* will return with lock on the realm */
1847 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1849 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1854 if (realm->message && msg->code == RAD_Access_Request) {
1855 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1856 respond(rq, RAD_Access_Reject, realm->message);
1857 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1858 acclog(msg, from->conf->host);
1859 respond(rq, RAD_Accounting_Response, NULL);
1864 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1865 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1866 from->conf->name, to->conf->name);
1870 if (msg->code == RAD_Accounting_Request)
1871 memset(msg->auth, 0, 16);
1872 else if (!RAND_bytes(msg->auth, 16)) {
1873 debug(DBG_WARN, "radsrv: failed to generate random auth");
1878 printfchars(NULL, "auth", "%02x ", auth, 16);
1881 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1883 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1884 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1888 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1890 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1891 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1895 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1901 pthread_mutex_unlock(&realm->mutex);
1906 rmclientrq(rq, msg->id);
1911 pthread_mutex_unlock(&realm->mutex);
1917 void replyh(struct server *server, unsigned char *buf) {
1918 struct client *from;
1919 struct rqout *rqout;
1921 unsigned char *subattrs;
1922 uint8_t *username, *stationid, *replymsg;
1923 struct radmsg *msg = NULL;
1925 struct list_node *node;
1927 server->connectionok = 1;
1928 server->lostrqs = 0;
1930 rqout = server->requests + buf[1];
1931 pthread_mutex_lock(rqout->lock);
1932 if (!rqout->tries) {
1935 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1939 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->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));
1951 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1953 gettimeofday(&server->lastrcv, NULL);
1955 if (rqout->rq->msg->code == RAD_Status_Server) {
1956 freerqoutdata(rqout);
1957 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1961 gettimeofday(&server->lastreply, NULL);
1962 from = rqout->rq->from;
1964 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1965 debug(DBG_WARN, "replyh: rewritein failed");
1970 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1971 attr = (struct tlv *)node->data;
1972 if (attr->t != RAD_Attr_Vendor_Specific)
1976 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1979 sublen = attr->l - 4;
1980 subattrs = attr->v + 4;
1981 if (!attrvalidate(subattrs, sublen) ||
1982 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1983 rqout->rq, server->conf->secret, from->conf->secret) ||
1984 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1985 rqout->rq, server->conf->secret, from->conf->secret))
1989 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1993 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
1994 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
1996 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
1997 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2000 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2001 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2004 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2005 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2009 debug(DBG_INFO, "%s for user %s from %s (%s)",
2010 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2013 debug(DBG_INFO, "%s for user %s from %s",
2014 radmsgtype2string(msg->code), username, server->conf->host);
2020 msg->id = (char)rqout->rq->rqid;
2021 memcpy(msg->auth, rqout->rq->rqauth, 16);
2024 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2027 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2028 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2029 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2032 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2035 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2036 debug(DBG_WARN, "replyh: rewriteout failed");
2040 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2041 radmsg_free(rqout->rq->msg);
2042 rqout->rq->msg = msg;
2043 sendreply(newrqref(rqout->rq));
2044 freerqoutdata(rqout);
2045 pthread_mutex_unlock(rqout->lock);
2050 pthread_mutex_unlock(rqout->lock);
2054 struct request *createstatsrvrq() {
2061 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2064 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2067 if (!radmsg_add(rq->msg, attr)) {
2078 /* code for removing state not finished */
2079 void *clientwr(void *arg) {
2080 struct server *server = (struct server *)arg;
2081 struct rqout *rqout = NULL;
2082 pthread_t clientrdth;
2083 int i, dynconffail = 0;
2086 struct timeval now, laststatsrv;
2087 struct timespec timeout;
2088 struct request *statsrvrq;
2089 struct clsrvconf *conf;
2091 conf = server->conf;
2093 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2098 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2099 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2103 memset(&timeout, 0, sizeof(struct timespec));
2105 if (conf->statusserver) {
2106 gettimeofday(&server->lastrcv, NULL);
2107 gettimeofday(&laststatsrv, NULL);
2110 if (conf->pdef->connecter) {
2111 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2113 server->connectionok = 1;
2114 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2115 debug(DBG_ERR, "clientwr: pthread_create failed");
2119 server->connectionok = 1;
2122 pthread_mutex_lock(&server->newrq_mutex);
2123 if (!server->newrq) {
2124 gettimeofday(&now, NULL);
2125 /* random 0-7 seconds */
2126 RAND_bytes(&rnd, 1);
2128 if (conf->statusserver) {
2129 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2130 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2132 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2133 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2135 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2136 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2139 if (timeout.tv_sec > now.tv_sec)
2140 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2142 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2145 if (server->newrq) {
2146 debug(DBG_DBG, "clientwr: got new request");
2151 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2153 pthread_mutex_unlock(&server->newrq_mutex);
2155 for (i = 0; i < MAX_REQUESTS; i++) {
2156 if (server->clientrdgone) {
2157 pthread_join(clientrdth, NULL);
2161 for (; i < MAX_REQUESTS; i++) {
2162 rqout = server->requests + i;
2164 pthread_mutex_lock(rqout->lock);
2167 pthread_mutex_unlock(rqout->lock);
2171 if (i == MAX_REQUESTS)
2174 gettimeofday(&now, NULL);
2175 if (now.tv_sec < rqout->expiry.tv_sec) {
2176 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2177 timeout.tv_sec = rqout->expiry.tv_sec;
2178 pthread_mutex_unlock(rqout->lock);
2182 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2183 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2184 if (conf->statusserver) {
2185 if (*rqout->rq->buf == RAD_Status_Server) {
2186 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2187 if (server->lostrqs < 255)
2191 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2192 if (server->lostrqs < 255)
2195 freerqoutdata(rqout);
2196 pthread_mutex_unlock(rqout->lock);
2200 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2201 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2202 timeout.tv_sec = rqout->expiry.tv_sec;
2204 conf->pdef->clientradput(server, rqout->rq->buf);
2205 pthread_mutex_unlock(rqout->lock);
2207 if (conf->statusserver && server->connectionok) {
2208 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2209 gettimeofday(&now, NULL);
2210 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2212 statsrvrq = createstatsrvrq();
2214 statsrvrq->to = server;
2215 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2222 conf->servers = NULL;
2223 if (server->dynamiclookuparg) {
2224 removeserversubrealms(realms, conf);
2228 freeclsrvconf(conf);
2230 freeserver(server, 1);
2231 ERR_remove_state(0);
2235 void createlistener(uint8_t type, char *arg) {
2237 struct clsrvconf *listenres;
2238 struct addrinfo *res;
2239 int s = -1, on = 1, *sp = NULL;
2241 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2243 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2245 for (res = listenres->addrinfo; res; res = res->ai_next) {
2246 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2248 debug(DBG_WARN, "createlistener: socket failed");
2251 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2253 if (res->ai_family == AF_INET6)
2254 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2256 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2257 debug(DBG_WARN, "createlistener: bind failed");
2263 sp = malloc(sizeof(int));
2265 debugx(1, DBG_ERR, "malloc failed");
2267 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2268 debugx(1, DBG_ERR, "pthread_create failed");
2272 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2274 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2275 listenres->host ? listenres->host : "*", listenres->port);
2276 freeclsrvres(listenres);
2279 void createlisteners(uint8_t type, char **args) {
2283 for (i = 0; args[i]; i++)
2284 createlistener(type, args[i]);
2286 createlistener(type, NULL);
2290 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2294 w = where & ~SSL_ST_MASK;
2296 if (w & SSL_ST_CONNECT)
2298 else if (w & SSL_ST_ACCEPT)
2303 if (where & SSL_CB_LOOP)
2304 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2305 else if (where & SSL_CB_ALERT) {
2306 s = (where & SSL_CB_READ) ? "read" : "write";
2307 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2309 else if (where & SSL_CB_EXIT) {
2311 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2313 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2323 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2324 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2325 for (i = 0; i < CRYPTO_num_locks(); i++) {
2326 ssl_lock_count[i] = 0;
2327 pthread_mutex_init(&ssl_locks[i], NULL);
2329 CRYPTO_set_id_callback(ssl_thread_id);
2330 CRYPTO_set_locking_callback(ssl_locking_callback);
2332 SSL_load_error_strings();
2335 while (!RAND_status()) {
2338 RAND_seed((unsigned char *)&t, sizeof(time_t));
2339 RAND_seed((unsigned char *)&pid, sizeof(pid));
2343 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2344 STACK_OF(X509_NAME) *calist;
2346 unsigned long error;
2348 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2349 while ((error = ERR_get_error()))
2350 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2351 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2355 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2356 if (!conf->cacertfile || calist) {
2357 if (conf->cacertpath) {
2359 calist = sk_X509_NAME_new_null();
2360 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2361 sk_X509_NAME_free(calist);
2367 while ((error = ERR_get_error()))
2368 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2369 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2372 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2373 SSL_CTX_set_client_CA_list(ctx, calist);
2375 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2376 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2378 if (conf->crlcheck) {
2379 x509_s = SSL_CTX_get_cert_store(ctx);
2380 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2383 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2387 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2388 SSL_CTX *ctx = NULL;
2389 unsigned long error;
2396 ctx = SSL_CTX_new(TLSv1_method());
2398 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2402 ctx = SSL_CTX_new(DTLSv1_method());
2404 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2406 SSL_CTX_set_read_ahead(ctx, 1);
2410 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2414 if (conf->certkeypwd) {
2415 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2416 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2418 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2419 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2420 !SSL_CTX_check_private_key(ctx)) {
2421 while ((error = ERR_get_error()))
2422 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2423 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2428 if (!tlsaddcacrl(ctx, conf)) {
2433 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2437 struct tls *tlsgettls(char *alt1, char *alt2) {
2440 t = hash_read(tlsconfs, alt1, strlen(alt1));
2442 t = hash_read(tlsconfs, alt2, strlen(alt2));
2446 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2451 gettimeofday(&now, NULL);
2455 if (t->tlsexpiry && t->tlsctx) {
2456 if (t->tlsexpiry < now.tv_sec) {
2457 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2458 tlsaddcacrl(t->tlsctx, t);
2462 t->tlsctx = tlscreatectx(RAD_TLS, t);
2464 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2468 if (t->dtlsexpiry && t->dtlsctx) {
2469 if (t->dtlsexpiry < now.tv_sec) {
2470 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2471 tlsaddcacrl(t->dtlsctx, t);
2475 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2477 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2484 struct list *addsrvconfs(char *value, char **names) {
2485 struct list *conflist;
2487 struct list_node *entry;
2488 struct clsrvconf *conf = NULL;
2490 if (!names || !*names)
2493 conflist = list_create();
2495 debug(DBG_ERR, "malloc failed");
2499 for (n = 0; names[n]; n++) {
2500 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2501 conf = (struct clsrvconf *)entry->data;
2502 if (!strcasecmp(names[n], conf->name))
2506 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2507 list_destroy(conflist);
2510 if (!list_push(conflist, conf)) {
2511 debug(DBG_ERR, "malloc failed");
2512 list_destroy(conflist);
2515 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2520 void freerealm(struct realm *realm) {
2523 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2524 if (--realm->refcount)
2528 free(realm->message);
2529 regfree(&realm->regex);
2530 pthread_mutex_destroy(&realm->mutex);
2531 /* if refcount == 0, all subrealms gone */
2532 list_destroy(realm->subrealms);
2533 /* if refcount == 0, all srvconfs gone */
2534 list_destroy(realm->srvconfs);
2535 /* if refcount == 0, all accsrvconfs gone */
2536 list_destroy(realm->accsrvconfs);
2537 freerealm(realm->parent);
2541 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2543 struct realm *realm;
2544 char *s, *regex = NULL;
2546 if (*value == '/') {
2547 /* regexp, remove optional trailing / if present */
2548 if (value[strlen(value) - 1] == '/')
2549 value[strlen(value) - 1] = '\0';
2551 /* not a regexp, let us make it one */
2552 if (*value == '*' && !value[1])
2553 regex = stringcopy(".*", 0);
2555 for (n = 0, s = value; *s;)
2558 regex = malloc(strlen(value) + n + 3);
2561 for (n = 1, s = value; *s; s++) {
2571 debug(DBG_ERR, "malloc failed");
2575 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2578 realm = malloc(sizeof(struct realm));
2580 debug(DBG_ERR, "malloc failed");
2583 memset(realm, 0, sizeof(struct realm));
2585 if (pthread_mutex_init(&realm->mutex, NULL)) {
2586 debug(DBG_ERR, "mutex init failed");
2592 realm->name = stringcopy(value, 0);
2594 debug(DBG_ERR, "malloc failed");
2597 if (message && strlen(message) > 253) {
2598 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2601 realm->message = message;
2602 realm->accresp = accresp;
2604 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2605 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2609 if (servers && *servers) {
2610 realm->srvconfs = addsrvconfs(value, servers);
2611 if (!realm->srvconfs)
2615 if (accservers && *accservers) {
2616 realm->accsrvconfs = addsrvconfs(value, accservers);
2617 if (!realm->accsrvconfs)
2621 if (!list_push(realmlist, realm)) {
2622 debug(DBG_ERR, "malloc failed");
2623 pthread_mutex_destroy(&realm->mutex);
2627 debug(DBG_DBG, "addrealm: added realm %s", value);
2631 while (list_shift(realm->srvconfs));
2632 while (list_shift(realm->accsrvconfs));
2639 for (n = 0; servers[n]; n++)
2641 for (n = 0; servers[n]; n++)
2647 for (n = 0; accservers[n]; n++)
2649 for (n = 0; accservers[n]; n++)
2650 free(accservers[n]);
2653 return newrealmref(realm);
2656 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2657 struct clsrvconf *srvconf;
2658 struct realm *newrealm = NULL;
2659 char *realmname, *s;
2662 if (!conf->dynamiclookupcommand)
2665 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2666 realmname = strrchr(id, '@');
2672 for (s = realmname; *s; s++)
2673 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2676 srvconf = malloc(sizeof(struct clsrvconf));
2678 debug(DBG_ERR, "malloc failed");
2682 if (!addserver(srvconf))
2685 if (!realm->subrealms)
2686 realm->subrealms = list_create();
2687 if (!realm->subrealms)
2689 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2692 newrealm->parent = newrealmref(realm);
2694 /* add server and accserver to newrealm */
2695 newrealm->srvconfs = list_create();
2696 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2697 debug(DBG_ERR, "malloc failed");
2700 newrealmref(newrealm);
2701 newrealm->accsrvconfs = list_create();
2702 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2703 debug(DBG_ERR, "malloc failed");
2704 list_shift(realm->srvconfs);
2705 freerealm(newrealm);
2708 newrealmref(newrealm);
2710 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2711 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2712 debug(DBG_ERR, "pthread_create failed");
2713 list_shift(realm->srvconfs);
2714 freerealm(newrealm);
2715 list_shift(realm->accsrvconfs);
2716 freerealm(newrealm);
2719 pthread_detach(clientth);
2724 list_removedata(realm->subrealms, newrealm);
2725 freerealm(newrealm);
2726 if (!list_first(realm->subrealms)) {
2727 list_destroy(realm->subrealms);
2728 realm->subrealms = NULL;
2731 freeserver(srvconf->servers, 1);
2733 debug(DBG_ERR, "failed to create dynamic server");
2737 int dynamicconfig(struct server *server) {
2738 int ok, fd[2], status;
2740 struct clsrvconf *conf = server->conf;
2741 struct gconffile *cf = NULL;
2743 /* for now we only learn hostname/address */
2744 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2747 debug(DBG_ERR, "dynamicconfig: pipe error");
2752 debug(DBG_ERR, "dynamicconfig: fork error");
2756 } else if (pid == 0) {
2759 if (fd[1] != STDOUT_FILENO) {
2760 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2761 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2764 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2765 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2769 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2770 ok = getgenericconfig(&cf, NULL,
2771 "Server", CONF_CBK, confserver_cb, (void *)conf,
2776 if (waitpid(pid, &status, 0) < 0) {
2777 debug(DBG_ERR, "dynamicconfig: wait error");
2782 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2790 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2794 int addmatchcertattr(struct clsrvconf *conf) {
2798 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2799 r = &conf->certcnregex;
2800 v = conf->matchcertattr + 4;
2801 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2802 r = &conf->certuriregex;
2803 v = conf->matchcertattr + 20;
2808 /* regexp, remove optional trailing / if present */
2809 if (v[strlen(v) - 1] == '/')
2810 v[strlen(v) - 1] = '\0';
2814 *r = malloc(sizeof(regex_t));
2816 debug(DBG_ERR, "malloc failed");
2819 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2822 debug(DBG_ERR, "failed to compile regular expression %s", v);
2828 /* should accept both names and numeric values, only numeric right now */
2829 uint8_t attrname2val(char *attrname) {
2832 val = atoi(attrname);
2833 return val > 0 && val < 256 ? val : 0;
2836 /* should accept both names and numeric values, only numeric right now */
2837 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2840 *vendor = atoi(attrname);
2841 s = strchr(attrname, ':');
2846 *type = atoi(s + 1);
2847 return *type >= 0 && *type < 256;
2850 /* should accept both names and numeric values, only numeric right now */
2851 struct tlv *extractattr(char *nameval) {
2856 s = strchr(nameval, ':');
2857 name = atoi(nameval);
2858 if (!s || name < 1 || name > 255)
2860 len = strlen(s + 1);
2863 a = malloc(sizeof(struct tlv));
2866 a->v = (uint8_t *)stringcopy(s + 1, 0);
2876 /* should accept both names and numeric values, only numeric right now */
2877 struct modattr *extractmodattr(char *nameval) {
2882 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2886 s = strchr(nameval, ':');
2887 name = atoi(nameval);
2888 if (!s || name < 1 || name > 255 || s[1] != '/')
2892 /* regexp, remove optional trailing / if present */
2893 if (s[strlen(s) - 1] == '/')
2894 s[strlen(s) - 1] = '\0';
2902 m = malloc(sizeof(struct modattr));
2904 debug(DBG_ERR, "malloc failed");
2909 m->replacement = stringcopy(t, 0);
2910 if (!m->replacement) {
2912 debug(DBG_ERR, "malloc failed");
2916 m->regex = malloc(sizeof(regex_t));
2918 free(m->replacement);
2920 debug(DBG_ERR, "malloc failed");
2924 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2926 free(m->replacement);
2928 debug(DBG_ERR, "failed to compile regular expression %s", s);
2935 struct rewrite *getrewrite(char *alt1, char *alt2) {
2938 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2940 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2945 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2946 struct rewrite *rewrite = NULL;
2948 uint8_t *rma = NULL;
2949 uint32_t *p, *rmva = NULL;
2950 struct list *adda = NULL, *moda = NULL;
2955 for (n = 0; rmattrs[n]; n++);
2956 rma = calloc(n + 1, sizeof(uint8_t));
2958 debugx(1, DBG_ERR, "malloc failed");
2960 for (i = 0; i < n; i++) {
2961 if (!(rma[i] = attrname2val(rmattrs[i])))
2962 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2970 for (n = 0; rmvattrs[n]; n++);
2971 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2973 debugx(1, DBG_ERR, "malloc failed");
2975 for (p = rmva, i = 0; i < n; i++, p += 2) {
2976 if (!vattrname2val(rmvattrs[i], p, p + 1))
2977 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2985 adda = list_create();
2987 debugx(1, DBG_ERR, "malloc failed");
2988 for (i = 0; addattrs[i]; i++) {
2989 a = extractattr(addattrs[i]);
2991 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
2993 if (!list_push(adda, a))
2994 debugx(1, DBG_ERR, "malloc failed");
3000 moda = list_create();
3002 debugx(1, DBG_ERR, "malloc failed");
3003 for (i = 0; modattrs[i]; i++) {
3004 m = extractmodattr(modattrs[i]);
3006 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3008 if (!list_push(moda, m))
3009 debugx(1, DBG_ERR, "malloc failed");
3014 if (rma || rmva || adda || moda) {
3015 rewrite = malloc(sizeof(struct rewrite));
3017 debugx(1, DBG_ERR, "malloc failed");
3018 rewrite->removeattrs = rma;
3019 rewrite->removevendorattrs = rmva;
3020 rewrite->addattrs = adda;
3021 rewrite->modattrs = moda;
3024 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3025 debugx(1, DBG_ERR, "malloc failed");
3026 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3029 void freeclsrvconf(struct clsrvconf *conf) {
3035 free(conf->matchcertattr);
3036 if (conf->certcnregex)
3037 regfree(conf->certcnregex);
3038 if (conf->certuriregex)
3039 regfree(conf->certuriregex);
3040 free(conf->confrewritein);
3041 free(conf->confrewriteout);
3042 if (conf->rewriteusername) {
3043 if (conf->rewriteusername->regex)
3044 regfree(conf->rewriteusername->regex);
3045 free(conf->rewriteusername->replacement);
3046 free(conf->rewriteusername);
3048 free(conf->dynamiclookupcommand);
3049 free(conf->rewritein);
3050 free(conf->rewriteout);
3052 freeaddrinfo(conf->addrinfo);
3054 pthread_mutex_destroy(conf->lock);
3057 /* not touching ssl_ctx, clients and servers */
3061 int mergeconfstring(char **dst, char **src) {
3070 t = stringcopy(*dst, 0);
3072 debug(DBG_ERR, "malloc failed");
3080 /* assumes dst is a shallow copy */
3081 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3082 if (!mergeconfstring(&dst->name, &src->name) ||
3083 !mergeconfstring(&dst->host, &src->host) ||
3084 !mergeconfstring(&dst->port, &src->port) ||
3085 !mergeconfstring(&dst->secret, &src->secret) ||
3086 !mergeconfstring(&dst->tls, &src->tls) ||
3087 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3088 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3089 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3090 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3093 dst->pdef = src->pdef;
3094 dst->statusserver = src->statusserver;
3095 dst->certnamecheck = src->certnamecheck;
3096 if (src->retryinterval != 255)
3097 dst->retryinterval = src->retryinterval;
3098 if (src->retrycount != 255)
3099 dst->retrycount = src->retrycount;
3103 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3104 struct clsrvconf *conf;
3105 char *conftype = NULL, *rewriteinalias = NULL;
3106 long int dupinterval = LONG_MIN;
3108 debug(DBG_DBG, "confclient_cb called for %s", block);
3110 conf = malloc(sizeof(struct clsrvconf));
3112 debugx(1, DBG_ERR, "malloc failed");
3113 memset(conf, 0, sizeof(struct clsrvconf));
3114 conf->certnamecheck = 1;
3116 if (!getgenericconfig(cf, block,
3117 "type", CONF_STR, &conftype,
3118 "host", CONF_STR, &conf->host,
3119 "secret", CONF_STR, &conf->secret,
3120 "tls", CONF_STR, &conf->tls,
3121 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3122 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3123 "DuplicateInterval", CONF_LINT, &dupinterval,
3124 "rewrite", CONF_STR, &rewriteinalias,
3125 "rewriteIn", CONF_STR, &conf->confrewritein,
3126 "rewriteOut", CONF_STR, &conf->confrewriteout,
3127 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3130 debugx(1, DBG_ERR, "configuration error");
3132 conf->name = stringcopy(val, 0);
3134 conf->host = stringcopy(val, 0);
3135 if (!conf->name || !conf->host)
3136 debugx(1, DBG_ERR, "malloc failed");
3139 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3140 conf->type = protoname2int(conftype);
3141 conf->pdef = &protodefs[conf->type];
3142 if (!conf->pdef->name)
3143 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3146 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3147 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3149 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3150 if (conf->matchcertattr && !addmatchcertattr(conf))
3151 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3154 if (dupinterval != LONG_MIN) {
3155 if (dupinterval < 0 || dupinterval > 255)
3156 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3157 conf->dupinterval = (uint8_t)dupinterval;
3159 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3161 if (!conf->confrewritein)
3162 conf->confrewritein = rewriteinalias;
3164 free(rewriteinalias);
3165 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3166 if (conf->confrewriteout)
3167 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3169 if (conf->confrewriteusername) {
3170 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3171 if (!conf->rewriteusername)
3172 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3175 if (!resolvepeer(conf, 0))
3176 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3178 if (!conf->secret) {
3179 if (!conf->pdef->secretdefault)
3180 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3181 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3183 debugx(1, DBG_ERR, "malloc failed");
3186 conf->lock = malloc(sizeof(pthread_mutex_t));
3188 debugx(1, DBG_ERR, "malloc failed");
3190 pthread_mutex_init(conf->lock, NULL);
3191 if (!list_push(clconfs, conf))
3192 debugx(1, DBG_ERR, "malloc failed");
3196 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3197 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3198 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3199 if (!conf->tlsconf) {
3200 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3203 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3204 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3210 conf->port = stringcopy(conf->pdef->portdefault, 0);
3212 debug(DBG_ERR, "malloc failed");
3217 if (conf->retryinterval == 255)
3218 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3219 if (conf->retrycount == 255)
3220 conf->retrycount = protodefs[conf->type].retrycountdefault;
3222 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3223 if (conf->confrewriteout)
3224 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3226 if (!conf->secret) {
3227 if (!conf->pdef->secretdefault) {
3228 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3231 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3232 if (!conf->secret) {
3233 debug(DBG_ERR, "malloc failed");
3238 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3239 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3245 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3246 struct clsrvconf *conf, *resconf;
3247 char *conftype = NULL, *rewriteinalias = NULL;
3248 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3250 debug(DBG_DBG, "confserver_cb called for %s", block);
3252 conf = malloc(sizeof(struct clsrvconf));
3254 debug(DBG_ERR, "malloc failed");
3257 memset(conf, 0, sizeof(struct clsrvconf));
3258 resconf = (struct clsrvconf *)arg;
3260 conf->statusserver = resconf->statusserver;
3261 conf->certnamecheck = resconf->certnamecheck;
3263 conf->certnamecheck = 1;
3265 if (!getgenericconfig(cf, block,
3266 "type", CONF_STR, &conftype,
3267 "host", CONF_STR, &conf->host,
3268 "port", CONF_STR, &conf->port,
3269 "secret", CONF_STR, &conf->secret,
3270 "tls", CONF_STR, &conf->tls,
3271 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3272 "rewrite", CONF_STR, &rewriteinalias,
3273 "rewriteIn", CONF_STR, &conf->confrewritein,
3274 "rewriteOut", CONF_STR, &conf->confrewriteout,
3275 "StatusServer", CONF_BLN, &conf->statusserver,
3276 "RetryInterval", CONF_LINT, &retryinterval,
3277 "RetryCount", CONF_LINT, &retrycount,
3278 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3279 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3282 debug(DBG_ERR, "configuration error");
3286 conf->name = stringcopy(val, 0);
3288 debug(DBG_ERR, "malloc failed");
3292 conf->host = stringcopy(val, 0);
3294 debug(DBG_ERR, "malloc failed");
3300 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3301 conf->type = protoname2int(conftype);
3302 conf->pdef = &protodefs[conf->type];
3303 if (!conf->pdef->name) {
3304 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3310 if (!conf->confrewritein)
3311 conf->confrewritein = rewriteinalias;
3313 free(rewriteinalias);
3314 rewriteinalias = NULL;
3316 if (retryinterval != LONG_MIN) {
3317 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3318 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3321 conf->retryinterval = (uint8_t)retryinterval;
3323 conf->retryinterval = 255;
3325 if (retrycount != LONG_MIN) {
3326 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3327 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3330 conf->retrycount = (uint8_t)retrycount;
3332 conf->retrycount = 255;
3335 if (!mergesrvconf(resconf, conf))
3339 if (conf->dynamiclookupcommand) {
3340 free(conf->dynamiclookupcommand);
3341 conf->dynamiclookupcommand = NULL;
3345 if (resconf || !conf->dynamiclookupcommand) {
3346 if (!compileserverconfig(conf, block))
3353 if (!list_push(srvconfs, conf)) {
3354 debug(DBG_ERR, "malloc failed");
3361 free(rewriteinalias);
3362 freeclsrvconf(conf);
3366 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3367 char **servers = NULL, **accservers = NULL, *msg = NULL;
3368 uint8_t accresp = 0;
3370 debug(DBG_DBG, "confrealm_cb called for %s", block);
3372 if (!getgenericconfig(cf, block,
3373 "server", CONF_MSTR, &servers,
3374 "accountingServer", CONF_MSTR, &accservers,
3375 "ReplyMessage", CONF_STR, &msg,
3376 "AccountingResponse", CONF_BLN, &accresp,
3379 debugx(1, DBG_ERR, "configuration error");
3381 addrealm(realms, val, servers, accservers, msg, accresp);
3385 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3387 long int expiry = LONG_MIN;
3389 debug(DBG_DBG, "conftls_cb called for %s", block);
3391 conf = malloc(sizeof(struct tls));
3393 debug(DBG_ERR, "conftls_cb: malloc failed");
3396 memset(conf, 0, sizeof(struct tls));
3398 if (!getgenericconfig(cf, block,
3399 "CACertificateFile", CONF_STR, &conf->cacertfile,
3400 "CACertificatePath", CONF_STR, &conf->cacertpath,
3401 "CertificateFile", CONF_STR, &conf->certfile,
3402 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3403 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3404 "CacheExpiry", CONF_LINT, &expiry,
3405 "CRLCheck", CONF_BLN, &conf->crlcheck,
3408 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3411 if (!conf->certfile || !conf->certkeyfile) {
3412 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3415 if (!conf->cacertfile && !conf->cacertpath) {
3416 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3419 if (expiry != LONG_MIN) {
3421 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3424 conf->cacheexpiry = expiry;
3427 conf->name = stringcopy(val, 0);
3429 debug(DBG_ERR, "conftls_cb: malloc failed");
3433 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3434 debug(DBG_ERR, "conftls_cb: malloc failed");
3437 if (!tlsgetctx(RAD_TLS, conf))
3438 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3439 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3443 free(conf->cacertfile);
3444 free(conf->cacertpath);
3445 free(conf->certfile);
3446 free(conf->certkeyfile);
3447 free(conf->certkeypwd);
3452 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3453 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3455 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3457 if (!getgenericconfig(cf, block,
3458 "removeAttribute", CONF_MSTR, &rmattrs,
3459 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3460 "addAttribute", CONF_MSTR, &addattrs,
3461 "modifyAttribute", CONF_MSTR, &modattrs,
3464 debugx(1, DBG_ERR, "configuration error");
3465 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3469 void getmainconfig(const char *configfile) {
3470 long int loglevel = LONG_MIN;
3471 struct gconffile *cfs;
3473 cfs = openconfigfile(configfile);
3474 memset(&options, 0, sizeof(options));
3476 clconfs = list_create();
3478 debugx(1, DBG_ERR, "malloc failed");
3480 srvconfs = list_create();
3482 debugx(1, DBG_ERR, "malloc failed");
3484 realms = list_create();
3486 debugx(1, DBG_ERR, "malloc failed");
3488 tlsconfs = hash_create();
3490 debugx(1, DBG_ERR, "malloc failed");
3492 rewriteconfs = hash_create();
3494 debugx(1, DBG_ERR, "malloc failed");
3496 if (!getgenericconfig(&cfs, NULL,
3497 "ListenUDP", CONF_MSTR, &options.listenudp,
3498 "ListenTCP", CONF_MSTR, &options.listentcp,
3499 "ListenTLS", CONF_MSTR, &options.listentls,
3500 "ListenDTLS", CONF_MSTR, &options.listendtls,
3501 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3502 "SourceUDP", CONF_STR, &options.sourceudp,
3503 "SourceTCP", CONF_STR, &options.sourcetcp,
3504 "SourceTLS", CONF_STR, &options.sourcetls,
3505 "SourceDTLS", CONF_STR, &options.sourcedtls,
3506 "LogLevel", CONF_LINT, &loglevel,
3507 "LogDestination", CONF_STR, &options.logdestination,
3508 "LoopPrevention", CONF_BLN, &options.loopprevention,
3509 "Client", CONF_CBK, confclient_cb, NULL,
3510 "Server", CONF_CBK, confserver_cb, NULL,
3511 "Realm", CONF_CBK, confrealm_cb, NULL,
3512 "TLS", CONF_CBK, conftls_cb, NULL,
3513 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3516 debugx(1, DBG_ERR, "configuration error");
3518 if (loglevel != LONG_MIN) {
3519 if (loglevel < 1 || loglevel > 4)
3520 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3521 options.loglevel = (uint8_t)loglevel;
3525 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3528 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3531 *configfile = optarg;
3534 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3535 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3536 *loglevel = *optarg - '0';
3545 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3550 if (!(argc - optind))
3554 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3558 int daemon(int a, int b) {
3566 for (i = 0; i < 3; i++) {
3568 open("/dev/null", O_RDWR);
3574 void *sighandler(void *arg) {
3579 sigemptyset(&sigset);
3580 sigaddset(&sigset, SIGPIPE);
3581 sigwait(&sigset, &sig);
3582 /* only get SIGPIPE right now, so could simplify below code */
3585 /* completely ignoring this */
3588 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3591 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3596 int main(int argc, char **argv) {
3599 struct list_node *entry;
3600 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3601 char *configfile = NULL;
3602 struct clsrvconf *srvconf;
3605 debug_init("radsecproxy");
3606 debug_set_level(DEBUG_LEVEL);
3608 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3610 debug_set_level(loglevel);
3611 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3613 options.loglevel = loglevel;
3614 else if (options.loglevel)
3615 debug_set_level(options.loglevel);
3617 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3618 free(options.logdestination);
3620 if (!list_first(clconfs))
3621 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3622 if (!list_first(realms))
3623 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3626 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3628 if (!foreground && (daemon(0, 0) < 0))
3629 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3631 debug_timestamp_on();
3632 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3634 sigemptyset(&sigset);
3635 /* exit on all but SIGPIPE, ignore more? */
3636 sigaddset(&sigset, SIGPIPE);
3637 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3638 pthread_create(&sigth, NULL, sighandler, NULL);
3640 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3641 srvconf = (struct clsrvconf *)entry->data;
3642 if (srvconf->dynamiclookupcommand)
3644 if (!addserver(srvconf))
3645 debugx(1, DBG_ERR, "failed to add server");
3646 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3647 (void *)(srvconf->servers)))
3648 debugx(1, DBG_ERR, "pthread_create failed");
3650 /* srcprotores for UDP no longer needed */
3651 if (srcprotores[RAD_UDP]) {
3652 freeaddrinfo(srcprotores[RAD_UDP]);
3653 srcprotores[RAD_UDP] = NULL;
3656 for (i = 0; protodefs[i].name; i++)
3657 if (protodefs[i].initextra)
3658 protodefs[i].initextra();
3660 if (find_clconf_type(RAD_TCP, NULL))
3661 createlisteners(RAD_TCP, options.listentcp);
3663 if (find_clconf_type(RAD_TLS, NULL))
3664 createlisteners(RAD_TLS, options.listentls);
3666 if (find_clconf_type(RAD_DTLS, NULL))
3667 createlisteners(RAD_DTLS, options.listendtls);
3669 if (find_clconf_type(RAD_UDP, NULL)) {
3670 createlisteners(RAD_UDP, options.listenudp);
3671 if (options.listenaccudp)
3672 createlisteners(RAD_UDP, options.listenaccudp);
3675 /* just hang around doing nothing, anything to do here? */