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 * Remove expired stuff from clients request list?
40 * Multiple outgoing connections if not enough IDs? (multiple servers per conf?)
41 * Useful for TCP accounting? Now we require separate server config for alt port
45 #include <sys/socket.h>
46 #include <netinet/in.h>
55 #include <sys/types.h>
56 #include <sys/select.h>
59 #include <arpa/inet.h>
63 #include <openssl/ssl.h>
64 #include <openssl/rand.h>
65 #include <openssl/err.h>
66 #include <openssl/md5.h>
67 #include <openssl/hmac.h>
68 #include <openssl/x509v3.h>
74 #include "radsecproxy.h"
80 static struct options options;
81 static struct list *clconfs, *srvconfs;
83 struct hash *tlsconfs, *rewriteconfs;
85 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
87 static pthread_mutex_t *ssl_locks = NULL;
88 static long *ssl_lock_count;
92 /* minimum required declarations to avoid reordering code */
93 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
94 int dynamicconfig(struct server *server);
95 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
96 void freerealm(struct realm *realm);
97 void freeclsrvconf(struct clsrvconf *conf);
98 void freerq(struct request *rq);
99 void freerqoutdata(struct rqout *rqout);
100 void rmclientrq(struct request *rq, uint8_t id);
102 static const struct protodefs protodefs[] = {
103 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
104 NULL, /* secretdefault */
105 SOCK_DGRAM, /* socktype */
106 "1812", /* portdefault */
107 REQUEST_RETRY_COUNT, /* retrycountdefault */
108 10, /* retrycountmax */
109 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
110 60, /* retryintervalmax */
111 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
112 udpserverrd, /* listener */
113 &options.sourceudp, /* srcaddrport */
114 NULL, /* connecter */
115 NULL, /* clientconnreader */
116 clientradputudp, /* clientradput */
117 addclientudp, /* addclient */
118 addserverextraudp, /* addserverextra */
119 initextraudp /* initextra */
121 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
122 "mysecret", /* secretdefault */
123 SOCK_STREAM, /* socktype */
124 "2083", /* portdefault */
125 0, /* retrycountdefault */
126 0, /* retrycountmax */
127 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
128 60, /* retryintervalmax */
129 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
130 tlslistener, /* listener */
131 &options.sourcetls, /* srcaddrport */
132 tlsconnect, /* connecter */
133 tlsclientrd, /* clientconnreader */
134 clientradputtls, /* clientradput */
135 NULL, /* addclient */
136 NULL, /* addserverextra */
139 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
140 NULL, /* secretdefault */
141 SOCK_STREAM, /* socktype */
142 "1812", /* portdefault */
143 0, /* retrycountdefault */
144 0, /* retrycountmax */
145 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
146 60, /* retryintervalmax */
147 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
148 tcplistener, /* listener */
149 &options.sourcetcp, /* srcaddrport */
150 tcpconnect, /* connecter */
151 tcpclientrd, /* clientconnreader */
152 clientradputtcp, /* clientradput */
153 NULL, /* addclient */
154 NULL, /* addserverextra */
157 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
158 "mysecret", /* secretdefault */
159 SOCK_DGRAM, /* socktype */
160 "2083", /* portdefault */
161 REQUEST_RETRY_COUNT, /* retrycountdefault */
162 10, /* retrycountmax */
163 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
164 60, /* retryintervalmax */
165 DUPLICATE_INTERVAL, /* duplicateintervaldefault */
166 udpdtlsserverrd, /* listener */
167 &options.sourcedtls, /* srcaddrport */
168 dtlsconnect, /* connecter */
169 dtlsclientrd, /* clientconnreader */
170 clientradputdtls, /* clientradput */
171 NULL, /* addclient */
172 addserverextradtls, /* addserverextra */
173 initextradtls /* initextra */
179 uint8_t protoname2int(const char *name) {
182 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
186 /* callbacks for making OpenSSL thread safe */
187 unsigned long ssl_thread_id() {
188 return (unsigned long)pthread_self();
191 void ssl_locking_callback(int mode, int type, const char *file, int line) {
192 if (mode & CRYPTO_LOCK) {
193 pthread_mutex_lock(&ssl_locks[type]);
194 ssl_lock_count[type]++;
196 pthread_mutex_unlock(&ssl_locks[type]);
199 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
200 int pwdlen = strlen(userdata);
201 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
203 memcpy(buf, userdata, pwdlen);
207 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
212 err_cert = X509_STORE_CTX_get_current_cert(ctx);
213 err = X509_STORE_CTX_get_error(ctx);
214 depth = X509_STORE_CTX_get_error_depth(ctx);
216 if (depth > MAX_CERT_DEPTH) {
218 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
219 X509_STORE_CTX_set_error(ctx, err);
223 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
224 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
227 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
228 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
229 debug(DBG_WARN, "\tIssuer=%s", buf);
231 case X509_V_ERR_CERT_NOT_YET_VALID:
232 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
233 debug(DBG_WARN, "\tCertificate not yet valid");
235 case X509_V_ERR_CERT_HAS_EXPIRED:
236 debug(DBG_WARN, "Certificate has expired");
238 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
239 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
244 printf("certificate verify returns %d\n", ok);
249 struct addrinfo *getsrcprotores(uint8_t type) {
250 return srcprotores[type];
253 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
254 struct addrinfo hints, *addrinfo, *res;
258 slash = conf->host ? strchr(conf->host, '/') : NULL;
262 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
266 if (*s < '0' || *s > '9') {
267 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
270 plen = atoi(slash + 1);
271 if (plen < 0 || plen > 128) {
272 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
277 memset(&hints, 0, sizeof(hints));
278 hints.ai_socktype = conf->pdef->socktype;
279 hints.ai_family = AF_UNSPEC;
280 hints.ai_flags = ai_flags;
281 if (!conf->host && !conf->port) {
282 /* getaddrinfo() doesn't like host and port to be NULL */
283 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
284 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
287 for (res = addrinfo; res; res = res->ai_next)
288 port_set(res->ai_addr, 0);
291 hints.ai_flags |= AI_NUMERICHOST;
292 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
293 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
298 switch (addrinfo->ai_family) {
301 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
302 freeaddrinfo(addrinfo);
309 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
310 freeaddrinfo(addrinfo);
313 conf->prefixlen = plen;
315 conf->prefixlen = 255;
318 freeaddrinfo(conf->addrinfo);
319 conf->addrinfo = addrinfo;
323 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
328 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
332 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
334 debugx(1, DBG_ERR, "no ] matching initial [");
338 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
341 debugx(1, DBG_ERR, "missing host/address");
343 conf->host = stringcopy(field, p - field);
346 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
347 debugx(1, DBG_ERR, "unexpected character after ]");
350 /* port number or service name is specified */;
352 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
354 debugx(1, DBG_ERR, "syntax error, : but no following port");
355 conf->port = stringcopy(field, p - field);
357 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
361 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
362 struct clsrvconf *conf;
364 conf = malloc(sizeof(struct clsrvconf));
366 debugx(1, DBG_ERR, "malloc failed");
367 memset(conf, 0, sizeof(struct clsrvconf));
369 conf->pdef = &protodefs[conf->type];
371 parsehostport(lconf, conf, default_port);
372 if (!strcmp(conf->host, "*")) {
377 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
378 if (!resolvepeer(conf, AI_PASSIVE))
379 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
383 void freeclsrvres(struct clsrvconf *res) {
387 freeaddrinfo(res->addrinfo);
391 /* returns 1 if the len first bits are equal, else 0 */
392 int prefixmatch(void *a1, void *a2, uint8_t len) {
393 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
395 if (l && memcmp(a1, a2, l))
400 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
403 /* returns next config with matching address, or NULL */
404 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
405 struct sockaddr_in6 *sa6 = NULL;
406 struct in_addr *a4 = NULL;
407 struct addrinfo *res;
408 struct list_node *entry;
409 struct clsrvconf *conf;
411 if (addr->sa_family == AF_INET6) {
412 sa6 = (struct sockaddr_in6 *)addr;
413 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
414 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
418 a4 = &((struct sockaddr_in *)addr)->sin_addr;
420 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
421 conf = (struct clsrvconf *)entry->data;
422 if (conf->type == type) {
423 if (conf->prefixlen == 255) {
424 for (res = conf->addrinfo; res; res = res->ai_next)
425 if ((a4 && res->ai_family == AF_INET &&
426 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
427 (sa6 && res->ai_family == AF_INET6 &&
428 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
434 res = conf->addrinfo;
436 ((a4 && res->ai_family == AF_INET &&
437 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
438 (sa6 && res->ai_family == AF_INET6 &&
439 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
450 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
451 return find_conf(type, addr, clconfs, cur);
454 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
455 return find_conf(type, addr, srvconfs, cur);
458 /* returns next config of given type, or NULL */
459 struct clsrvconf *find_clconf_type(uint8_t type, struct list_node **cur) {
460 struct list_node *entry;
461 struct clsrvconf *conf;
463 for (entry = (cur && *cur ? list_next(*cur) : list_first(clconfs)); entry; entry = list_next(entry)) {
464 conf = (struct clsrvconf *)entry->data;
465 if (conf->type == type) {
474 struct queue *newqueue() {
477 q = malloc(sizeof(struct queue));
479 debugx(1, DBG_ERR, "malloc failed");
480 q->entries = list_create();
482 debugx(1, DBG_ERR, "malloc failed");
483 pthread_mutex_init(&q->mutex, NULL);
484 pthread_cond_init(&q->cond, NULL);
488 void removequeue(struct queue *q) {
489 struct list_node *entry;
493 pthread_mutex_lock(&q->mutex);
494 for (entry = list_first(q->entries); entry; entry = list_next(entry))
495 freerq((struct request *)entry);
496 list_destroy(q->entries);
497 pthread_cond_destroy(&q->cond);
498 pthread_mutex_unlock(&q->mutex);
499 pthread_mutex_destroy(&q->mutex);
503 void freebios(struct queue *q) {
506 pthread_mutex_lock(&q->mutex);
507 while ((bio = (BIO *)list_shift(q->entries)))
509 pthread_mutex_unlock(&q->mutex);
513 struct client *addclient(struct clsrvconf *conf, uint8_t lock) {
514 struct client *new = malloc(sizeof(struct client));
517 debug(DBG_ERR, "malloc failed");
522 pthread_mutex_lock(conf->lock);
523 if (!conf->clients) {
524 conf->clients = list_create();
525 if (!conf->clients) {
527 pthread_mutex_unlock(conf->lock);
528 debug(DBG_ERR, "malloc failed");
533 memset(new, 0, sizeof(struct client));
535 if (conf->pdef->addclient)
536 conf->pdef->addclient(new);
538 new->replyq = newqueue();
539 list_push(conf->clients, new);
541 pthread_mutex_unlock(conf->lock);
545 void removeclientrqs_sendrq_freeserver_lock(uint8_t wantlock) {
546 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
549 pthread_mutex_lock(&lock);
551 pthread_mutex_unlock(&lock);
554 void removeclientrqs(struct client *client) {
559 removeclientrqs_sendrq_freeserver_lock(1);
560 for (i = 0; i < MAX_REQUESTS; i++) {
565 rqout = rq->to->requests + rq->newid;
566 pthread_mutex_lock(rqout->lock);
567 if (rqout->rq == rq) /* still pointing to our request */
568 freerqoutdata(rqout);
569 pthread_mutex_unlock(rqout->lock);
573 removeclientrqs_sendrq_freeserver_lock(0);
576 void removelockedclient(struct client *client) {
577 struct clsrvconf *conf;
581 removeclientrqs(client);
582 removequeue(client->replyq);
583 list_removedata(conf->clients, client);
589 void removeclient(struct client *client) {
590 struct clsrvconf *conf;
596 pthread_mutex_lock(conf->lock);
597 removelockedclient(client);
598 pthread_mutex_unlock(conf->lock);
601 void freeserver(struct server *server, uint8_t destroymutex) {
602 struct rqout *rqout, *end;
607 removeclientrqs_sendrq_freeserver_lock(1);
608 if (server->requests) {
609 rqout = server->requests;
610 for (end = rqout + MAX_REQUESTS; rqout < end; rqout++) {
612 rqout->rq->to = NULL;
613 freerqoutdata(rqout);
614 pthread_mutex_destroy(rqout->lock);
617 free(server->requests);
620 freebios(server->rbios);
621 free(server->dynamiclookuparg);
623 SSL_free(server->ssl);
625 pthread_mutex_destroy(&server->lock);
626 pthread_cond_destroy(&server->newrq_cond);
627 pthread_mutex_destroy(&server->newrq_mutex);
629 removeclientrqs_sendrq_freeserver_lock(0);
633 int addserver(struct clsrvconf *conf) {
634 struct clsrvconf *res;
639 debug(DBG_ERR, "addserver: currently works with just one server per conf");
642 conf->servers = malloc(sizeof(struct server));
643 if (!conf->servers) {
644 debug(DBG_ERR, "malloc failed");
647 memset(conf->servers, 0, sizeof(struct server));
648 conf->servers->conf = conf;
651 if (type == RAD_DTLS)
652 conf->servers->rbios = newqueue();
654 if (!srcprotores[type]) {
655 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
656 srcprotores[type] = res->addrinfo;
657 res->addrinfo = NULL;
661 conf->servers->sock = -1;
662 if (conf->pdef->addserverextra)
663 conf->pdef->addserverextra(conf);
665 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct rqout));
666 if (!conf->servers->requests) {
667 debug(DBG_ERR, "malloc failed");
670 for (i = 0; i < MAX_REQUESTS; i++) {
671 conf->servers->requests[i].lock = malloc(sizeof(pthread_mutex_t));
672 if (!conf->servers->requests[i].lock) {
673 debug(DBG_ERR, "malloc failed");
676 if (pthread_mutex_init(conf->servers->requests[i].lock, NULL)) {
677 debug(DBG_ERR, "mutex init failed");
678 free(conf->servers->requests[i].lock);
679 conf->servers->requests[i].lock = NULL;
683 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
684 debug(DBG_ERR, "mutex init failed");
687 conf->servers->newrq = 0;
688 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
689 debug(DBG_ERR, "mutex init failed");
690 pthread_mutex_destroy(&conf->servers->lock);
693 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
694 debug(DBG_ERR, "mutex init failed");
695 pthread_mutex_destroy(&conf->servers->newrq_mutex);
696 pthread_mutex_destroy(&conf->servers->lock);
703 freeserver(conf->servers, 0);
704 conf->servers = NULL;
708 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
709 int loc, i, l, n, r = 0;
712 STACK_OF(GENERAL_NAME) *alt;
715 debug(DBG_DBG, "subjectaltnameaddr");
717 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
721 ex = X509_get_ext(cert, loc);
722 alt = X509V3_EXT_d2i(ex);
726 n = sk_GENERAL_NAME_num(alt);
727 for (i = 0; i < n; i++) {
728 gn = sk_GENERAL_NAME_value(alt, i);
729 if (gn->type != GEN_IPADD)
732 v = (char *)ASN1_STRING_data(gn->d.ia5);
733 l = ASN1_STRING_length(gn->d.ia5);
734 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
735 && !memcmp(v, &addr, l)) {
740 GENERAL_NAMES_free(alt);
744 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
751 nm = X509_get_subject_name(cert);
754 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
757 e = X509_NAME_get_entry(nm, loc);
758 t = X509_NAME_ENTRY_get_data(e);
759 v = (char *) ASN1_STRING_data(t);
760 l = ASN1_STRING_length(t);
764 if (l == strlen(exact) && !strncasecmp(exact, v, l))
767 s = stringcopy((char *)v, l);
769 debug(DBG_ERR, "malloc failed");
772 if (regexec(regex, s, 0, NULL, 0)) {
783 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
784 int loc, i, l, n, r = 0;
787 STACK_OF(GENERAL_NAME) *alt;
790 debug(DBG_DBG, "subjectaltnameregexp");
792 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
796 ex = X509_get_ext(cert, loc);
797 alt = X509V3_EXT_d2i(ex);
801 n = sk_GENERAL_NAME_num(alt);
802 for (i = 0; i < n; i++) {
803 gn = sk_GENERAL_NAME_value(alt, i);
804 if (gn->type != type)
807 v = (char *)ASN1_STRING_data(gn->d.ia5);
808 l = ASN1_STRING_length(gn->d.ia5);
812 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
815 if (memcmp(v, exact, l))
818 s = stringcopy((char *)v, l);
820 debug(DBG_ERR, "malloc failed");
823 if (regexec(regex, s, 0, NULL, 0)) {
832 GENERAL_NAMES_free(alt);
836 X509 *verifytlscert(SSL *ssl) {
840 if (SSL_get_verify_result(ssl) != X509_V_OK) {
841 debug(DBG_ERR, "verifytlscert: basic validation failed");
842 while ((error = ERR_get_error()))
843 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
847 cert = SSL_get_peer_certificate(ssl);
849 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
853 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
855 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
856 struct in6_addr addr;
858 if (conf->certnamecheck && conf->prefixlen == 255) {
859 if (inet_pton(AF_INET, conf->host, &addr))
861 else if (inet_pton(AF_INET6, conf->host, &addr))
864 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
867 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
870 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
872 if (!cnregexp(cert, conf->host, NULL)) {
873 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
876 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
879 if (conf->certcnregex) {
880 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
881 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
884 debug(DBG_DBG, "verifyconfcert: CN matching regex");
886 if (conf->certuriregex) {
887 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
888 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
891 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
896 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
898 if (ATTRTYPE(attrs) == type)
900 length -= ATTRLEN(attrs);
901 attrs += ATTRLEN(attrs);
906 struct request *newrqref(struct request *rq) {
912 void freerq(struct request *rq) {
915 debug(DBG_DBG, "freerq: called with refcount %d", rq->refcount);
918 if (rq->origusername)
919 free(rq->origusername);
925 radmsg_free(rq->msg);
929 void freerqoutdata(struct rqout *rqout) {
937 memset(&rqout->expiry, 0, sizeof(struct timeval));
940 void sendrq(struct request *rq) {
944 removeclientrqs_sendrq_freeserver_lock(1);
949 start = to->conf->statusserver ? 1 : 0;
950 pthread_mutex_lock(&to->newrq_mutex);
951 if (start && rq->msg->code == RAD_Status_Server) {
952 pthread_mutex_lock(to->requests[0].lock);
953 if (to->requests[0].rq) {
954 pthread_mutex_unlock(to->requests[0].lock);
955 debug(DBG_WARN, "sendrq: status server already in queue, dropping request");
962 /* might simplify if only try nextid, might be ok */
963 for (i = to->nextid; i < MAX_REQUESTS; i++) {
964 if (!to->requests[i].rq) {
965 pthread_mutex_lock(to->requests[i].lock);
966 if (!to->requests[i].rq)
968 pthread_mutex_unlock(to->requests[i].lock);
971 if (i == MAX_REQUESTS) {
972 for (i = start; i < to->nextid; i++) {
973 if (!to->requests[i].rq) {
974 pthread_mutex_lock(to->requests[i].lock);
975 if (!to->requests[i].rq)
977 pthread_mutex_unlock(to->requests[i].lock);
980 if (i == to->nextid) {
981 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
986 rq->newid = (uint8_t)i;
987 rq->msg->id = (uint8_t)i;
988 rq->buf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
990 pthread_mutex_unlock(to->requests[i].lock);
991 debug(DBG_ERR, "sendrq: radmsg2buf failed");
995 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
996 to->requests[i].rq = rq;
997 pthread_mutex_unlock(to->requests[i].lock);
998 if (i >= start) /* i is not reserved for statusserver */
1003 debug(DBG_DBG, "sendrq: signalling client writer");
1004 pthread_cond_signal(&to->newrq_cond);
1007 pthread_mutex_unlock(&to->newrq_mutex);
1008 removeclientrqs_sendrq_freeserver_lock(0);
1013 rmclientrq(rq, rq->msg->id);
1015 pthread_mutex_unlock(&to->newrq_mutex);
1016 removeclientrqs_sendrq_freeserver_lock(0);
1019 void sendreply(struct request *rq) {
1021 struct client *to = rq->from;
1024 rq->replybuf = radmsg2buf(rq->msg, (uint8_t *)to->conf->secret);
1025 radmsg_free(rq->msg);
1027 if (!rq->replybuf) {
1029 debug(DBG_ERR, "sendreply: radmsg2buf failed");
1033 pthread_mutex_lock(&to->replyq->mutex);
1034 first = list_first(to->replyq->entries) == NULL;
1036 if (!list_push(to->replyq->entries, rq)) {
1037 pthread_mutex_unlock(&to->replyq->mutex);
1039 debug(DBG_ERR, "sendreply: malloc failed");
1044 debug(DBG_DBG, "signalling server writer");
1045 pthread_cond_signal(&to->replyq->cond);
1047 pthread_mutex_unlock(&to->replyq->mutex);
1050 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1051 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1052 static unsigned char first = 1;
1053 static EVP_MD_CTX mdctx;
1054 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1055 unsigned int md_len;
1056 uint8_t i, offset = 0, out[128];
1058 pthread_mutex_lock(&lock);
1060 EVP_MD_CTX_init(&mdctx);
1066 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1067 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1068 !EVP_DigestUpdate(&mdctx, input, 16) ||
1069 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1071 pthread_mutex_unlock(&lock);
1074 for (i = 0; i < 16; i++)
1075 out[offset + i] = hash[i] ^ in[offset + i];
1076 input = out + offset - 16;
1081 memcpy(in, out, len);
1082 pthread_mutex_unlock(&lock);
1086 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1087 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1088 static unsigned char first = 1;
1089 static EVP_MD_CTX mdctx;
1090 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1091 unsigned int md_len;
1092 uint8_t i, offset = 0, out[128];
1094 pthread_mutex_lock(&lock);
1096 EVP_MD_CTX_init(&mdctx);
1102 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1103 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1104 !EVP_DigestUpdate(&mdctx, input, 16) ||
1105 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1107 pthread_mutex_unlock(&lock);
1110 for (i = 0; i < 16; i++)
1111 out[offset + i] = hash[i] ^ in[offset + i];
1112 input = in + offset;
1117 memcpy(in, out, len);
1118 pthread_mutex_unlock(&lock);
1122 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1123 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1124 static unsigned char first = 1;
1125 static EVP_MD_CTX mdctx;
1126 unsigned char hash[EVP_MAX_MD_SIZE];
1127 unsigned int md_len;
1130 pthread_mutex_lock(&lock);
1132 EVP_MD_CTX_init(&mdctx);
1137 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1138 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1139 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1142 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1143 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1144 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1145 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1146 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1147 pthread_mutex_unlock(&lock);
1152 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1155 for (i = 0; i < 16; i++)
1158 for (offset = 16; offset < len; offset += 16) {
1160 printf("text + offset - 16 c(%d): ", offset / 16);
1161 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1163 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1164 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1165 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1166 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1168 pthread_mutex_unlock(&lock);
1172 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1175 for (i = 0; i < 16; i++)
1176 text[offset + i] ^= hash[i];
1180 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1183 pthread_mutex_unlock(&lock);
1187 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1188 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1189 static unsigned char first = 1;
1190 static EVP_MD_CTX mdctx;
1191 unsigned char hash[EVP_MAX_MD_SIZE];
1192 unsigned int md_len;
1196 pthread_mutex_lock(&lock);
1198 EVP_MD_CTX_init(&mdctx);
1203 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1204 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1205 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1208 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1209 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1210 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1211 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1212 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1213 pthread_mutex_unlock(&lock);
1218 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1221 for (i = 0; i < 16; i++)
1222 plain[i] = text[i] ^ hash[i];
1224 for (offset = 16; offset < len; offset += 16) {
1226 printf("text + offset - 16 c(%d): ", offset / 16);
1227 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1229 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1230 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1231 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1232 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1234 pthread_mutex_unlock(&lock);
1238 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1241 for (i = 0; i < 16; i++)
1242 plain[offset + i] = text[offset + i] ^ hash[i];
1245 memcpy(text, plain, len);
1247 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1250 pthread_mutex_unlock(&lock);
1254 struct realm *newrealmref(struct realm *r) {
1260 /* returns with lock on realm */
1261 struct realm *id2realm(struct list *realmlist, char *id) {
1262 struct list_node *entry;
1263 struct realm *realm, *subrealm;
1265 /* need to do locking for subrealms and check subrealm timers */
1266 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1267 realm = (struct realm *)entry->data;
1268 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1269 pthread_mutex_lock(&realm->mutex);
1270 if (realm->subrealms) {
1271 subrealm = id2realm(realm->subrealms, id);
1273 pthread_mutex_unlock(&realm->mutex);
1277 return newrealmref(realm);
1283 /* helper function, only used by removeserversubrealms() */
1284 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1285 struct list_node *entry, *entry2;
1286 struct realm *realm;
1288 for (entry = list_first(realmlist); entry;) {
1289 realm = newrealmref((struct realm *)entry->data);
1290 pthread_mutex_lock(&realm->mutex);
1291 entry = list_next(entry);
1293 if (realm->srvconfs) {
1294 for (entry2 = list_first(realm->srvconfs); entry2; entry2 = list_next(entry2))
1295 if (entry2->data == srv)
1297 list_removedata(realm->srvconfs, srv);
1298 if (!list_first(realm->srvconfs)) {
1299 list_destroy(realm->srvconfs);
1300 realm->srvconfs = NULL;
1303 if (realm->accsrvconfs) {
1304 for (entry2 = list_first(realm->accsrvconfs); entry2; entry2 = list_next(entry2))
1305 if (entry2->data == srv)
1307 list_removedata(realm->accsrvconfs, srv);
1308 if (!list_first(realm->accsrvconfs)) {
1309 list_destroy(realm->accsrvconfs);
1310 realm->accsrvconfs = NULL;
1314 /* remove subrealm if no servers */
1315 if (!realm->srvconfs && !realm->accsrvconfs)
1316 list_removedata(realmlist, realm);
1318 pthread_mutex_unlock(&realm->mutex);
1323 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1324 struct list_node *entry;
1325 struct realm *realm;
1327 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1328 realm = (struct realm *)entry->data;
1329 pthread_mutex_lock(&realm->mutex);
1330 if (realm->subrealms) {
1331 _internal_removeserversubrealms(realm->subrealms, srv);
1332 if (!list_first(realm->subrealms)) {
1333 list_destroy(realm->subrealms);
1334 realm->subrealms = NULL;
1337 pthread_mutex_unlock(&realm->mutex);
1341 int attrvalidate(unsigned char *attrs, int length) {
1342 while (length > 1) {
1343 if (ATTRLEN(attrs) < 2) {
1344 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1347 length -= ATTRLEN(attrs);
1349 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1352 attrs += ATTRLEN(attrs);
1355 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1359 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1360 if (len < 16 || len > 128 || len % 16) {
1361 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1365 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1366 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1370 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1372 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1373 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1379 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1382 if (!msmppdecrypt(msmpp + 2, len - 2, (uint8_t *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1383 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1386 if (!msmppencrypt(msmpp + 2, len - 2, (uint8_t *)newsecret, strlen(newsecret), newauth, msmpp)) {
1387 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1393 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1394 char *oldsecret, char *newsecret) {
1395 unsigned char *attr;
1397 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1398 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1399 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->rqauth))
1405 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1409 for (; attrs[0]; attrs += 2)
1410 if (attrs[0] == vendor && attrs[1] == subattr)
1415 /* returns 1 if entire element is to be removed, else 0 */
1416 int dovendorrewriterm(struct tlv *attr, uint32_t *removevendorattrs) {
1417 uint8_t alen, sublen;
1421 if (!removevendorattrs)
1424 memcpy(&vendor, attr->v, 4);
1425 vendor = ntohl(vendor);
1426 while (*removevendorattrs && *removevendorattrs != vendor)
1427 removevendorattrs += 2;
1428 if (!*removevendorattrs)
1431 if (findvendorsubattr(removevendorattrs, vendor, -1))
1432 return 1; /* remove entire vendor attribute */
1434 sublen = attr->l - 4;
1435 subattrs = attr->v + 4;
1437 if (!attrvalidate(subattrs, sublen)) {
1438 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1442 while (sublen > 1) {
1443 alen = ATTRLEN(subattrs);
1445 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1446 memmove(subattrs, subattrs + alen, sublen);
1454 void dorewriterm(struct radmsg *msg, uint8_t *rmattrs, uint32_t *rmvattrs) {
1455 struct list_node *n, *p;
1459 n = list_first(msg->attrs);
1461 attr = (struct tlv *)n->data;
1462 if ((rmattrs && strchr((char *)rmattrs, attr->t)) ||
1463 (rmvattrs && attr->t == RAD_Attr_Vendor_Specific && dovendorrewriterm(attr, rmvattrs))) {
1464 list_removedata(msg->attrs, attr);
1466 n = p ? list_next(p) : list_first(msg->attrs);
1473 int dorewriteadd(struct radmsg *msg, struct list *addattrs) {
1474 struct list_node *n;
1477 for (n = list_first(addattrs); n; n = list_next(n)) {
1478 a = copytlv((struct tlv *)n->data);
1481 if (!radmsg_add(msg, a)) {
1489 int resizeattr(struct tlv *attr, uint8_t newlen) {
1492 if (newlen != attr->l) {
1493 newv = realloc(attr->v, newlen);
1502 int dorewritemodattr(struct tlv *attr, struct modattr *modattr) {
1503 size_t nmatch = 10, reslen = 0, start = 0;
1504 regmatch_t pmatch[10], *pfield;
1508 in = stringcopy((char *)attr->v, attr->l);
1512 if (regexec(modattr->regex, in, nmatch, pmatch, 0)) {
1517 out = modattr->replacement;
1519 for (i = start; out[i]; i++) {
1520 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1521 pfield = &pmatch[out[i + 1] - '0'];
1522 if (pfield->rm_so >= 0) {
1523 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1529 reslen += i - start;
1531 debug(DBG_WARN, "rewritten attribute length would be %d, max possible is 253, discarding message", reslen);
1536 if (!resizeattr(attr, reslen)) {
1543 for (i = start; out[i]; i++) {
1544 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1545 pfield = &pmatch[out[i + 1] - '0'];
1546 if (pfield->rm_so >= 0) {
1547 memcpy(attr->v + reslen, out + start, i - start);
1548 reslen += i - start;
1549 memcpy(attr->v + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1550 reslen += pfield->rm_eo - pfield->rm_so;
1557 memcpy(attr->v + reslen, out + start, i - start);
1561 int dorewritemod(struct radmsg *msg, struct list *modattrs) {
1562 struct list_node *n, *m;
1564 for (n = list_first(msg->attrs); n; n = list_next(n))
1565 for (m = list_first(modattrs); m; m = list_next(m))
1566 if (((struct tlv *)n->data)->t == ((struct modattr *)m->data)->t &&
1567 !dorewritemodattr((struct tlv *)n->data, (struct modattr *)m->data))
1572 int dorewrite(struct radmsg *msg, struct rewrite *rewrite) {
1575 if (rewrite->removeattrs || rewrite->removevendorattrs)
1576 dorewriterm(msg, rewrite->removeattrs, rewrite->removevendorattrs);
1577 if (rewrite->addattrs && !dorewriteadd(msg, rewrite->addattrs))
1579 if (rewrite->modattrs && !dorewritemod(msg, rewrite->modattrs))
1584 int rewriteusername(struct request *rq, struct tlv *attr) {
1585 char *orig = (char *)tlv2str(attr);
1586 if (!dorewritemodattr(attr, rq->from->conf->rewriteusername)) {
1590 if (strlen(orig) != attr->l || memcmp(orig, attr->v, attr->l))
1591 rq->origusername = (char *)orig;
1597 const char *radmsgtype2string(uint8_t code) {
1598 static const char *rad_msg_names[] = {
1599 "", "Access-Request", "Access-Accept", "Access-Reject",
1600 "Accounting-Request", "Accounting-Response", "", "",
1601 "", "", "", "Access-Challenge",
1602 "Status-Server", "Status-Client"
1604 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1607 void char2hex(char *h, unsigned char c) {
1608 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1609 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1610 h[0] = hexdigits[c / 16];
1611 h[1] = hexdigits[c % 16];
1615 uint8_t *radattr2ascii(struct tlv *attr) {
1623 for (i = 0; i < attr->l; i++)
1624 if (attr->v[i] < 32 || attr->v[i] > 126)
1627 return (uint8_t *)stringcopy((char *)attr->v, attr->l);
1634 for (i = 0; i < attr->l; i++)
1635 if (attr->v[i] < 32 || attr->v[i] > 126) {
1637 char2hex((char *)d, attr->v[i]);
1645 void acclog(struct radmsg *msg, char *host) {
1649 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1651 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1654 username = radattr2ascii(attr);
1656 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1661 void respond(struct request *rq, uint8_t code, char *message) {
1665 msg = radmsg_init(code, rq->msg->id, rq->msg->auth);
1667 debug(DBG_ERR, "respond: malloc failed");
1670 if (message && *message) {
1671 attr = maketlv(RAD_Attr_Reply_Message, strlen(message), message);
1672 if (!attr || !radmsg_add(msg, attr)) {
1675 debug(DBG_ERR, "respond: malloc failed");
1680 radmsg_free(rq->msg);
1682 debug(DBG_DBG, "respond: sending %s to %s", radmsgtype2string(msg->code), rq->from->conf->host);
1683 sendreply(newrqref(rq));
1686 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1687 struct list_node *entry;
1688 struct clsrvconf *server, *best = NULL, *first = NULL;
1690 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1691 server = (struct clsrvconf *)entry->data;
1692 if (!server->servers)
1696 if (!server->servers->connectionok)
1698 if (!server->servers->lostrqs)
1704 if (server->servers->lostrqs < best->servers->lostrqs)
1707 return best ? best : first;
1710 /* returns with lock on realm, protects from server changes while in use by radsrv/sendrq */
1711 struct server *findserver(struct realm **realm, struct tlv *username, uint8_t acc) {
1712 struct clsrvconf *srvconf;
1713 struct realm *subrealm;
1714 struct server *server = NULL;
1715 char *id = (char *)tlv2str(username);
1719 /* returns with lock on realm */
1720 *realm = id2realm(realms, id);
1723 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1724 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1727 server = srvconf->servers;
1728 if (!acc && !(*realm)->parent && !srvconf->servers) {
1729 subrealm = adddynamicrealmserver(*realm, srvconf, id);
1731 pthread_mutex_lock(&subrealm->mutex);
1732 pthread_mutex_unlock(&(*realm)->mutex);
1735 server = ((struct clsrvconf *)subrealm->srvconfs->first->data)->servers;
1744 struct request *newrequest() {
1747 rq = malloc(sizeof(struct request));
1749 debug(DBG_ERR, "newrequest: malloc failed");
1752 memset(rq, 0, sizeof(struct request));
1754 gettimeofday(&rq->created, NULL);
1758 int addclientrq(struct request *rq) {
1762 r = rq->from->rqs[rq->rqid];
1764 if (rq->udpport == r->udpport && !memcmp(rq->rqauth, r->rqauth, 16)) {
1765 gettimeofday(&now, NULL);
1766 if (now.tv_sec - r->created.tv_sec < r->from->conf->dupinterval) {
1768 debug(DBG_INFO, "addclientrq: already sent reply to request with id %d from %s, resending", rq->rqid, addr2string(r->from->addr));
1769 sendreply(newrqref(r));
1771 debug(DBG_INFO, "addclientrq: already got request with id %d from %s, ignoring", rq->rqid, addr2string(r->from->addr));
1777 rq->from->rqs[rq->rqid] = newrqref(rq);
1781 void rmclientrq(struct request *rq, uint8_t id) {
1784 r = rq->from->rqs[id];
1787 rq->from->rqs[id] = NULL;
1791 /* returns 0 if validation/authentication fails, else 1 */
1792 int radsrv(struct request *rq) {
1793 struct radmsg *msg = NULL;
1795 uint8_t *userascii = NULL;
1796 struct realm *realm = NULL;
1797 struct server *to = NULL;
1798 struct client *from = rq->from;
1800 msg = buf2radmsg(rq->buf, (uint8_t *)from->conf->secret, NULL);
1805 debug(DBG_WARN, "radsrv: message validation failed, ignoring packet");
1812 memcpy(rq->rqauth, msg->auth, 16);
1814 debug(DBG_DBG, "radsrv: code %d, id %d", msg->code, msg->id);
1815 if (msg->code != RAD_Access_Request && msg->code != RAD_Status_Server && msg->code != RAD_Accounting_Request) {
1816 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1820 if (!addclientrq(rq))
1823 if (msg->code == RAD_Status_Server) {
1824 respond(rq, RAD_Access_Accept, NULL);
1828 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
1830 if (from->conf->rewritein && !dorewrite(msg, from->conf->rewritein))
1833 attr = radmsg_gettype(msg, RAD_Attr_User_Name);
1835 if (msg->code == RAD_Accounting_Request) {
1836 acclog(msg, from->conf->host);
1837 respond(rq, RAD_Accounting_Response, NULL);
1839 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
1843 if (from->conf->rewriteusername && !rewriteusername(rq, attr)) {
1844 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1848 userascii = radattr2ascii(attr);
1851 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(msg->code), userascii);
1853 /* will return with lock on the realm */
1854 to = findserver(&realm, attr, msg->code == RAD_Accounting_Request);
1856 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1861 if (realm->message && msg->code == RAD_Access_Request) {
1862 debug(DBG_INFO, "radsrv: sending reject to %s for %s", from->conf->host, userascii);
1863 respond(rq, RAD_Access_Reject, realm->message);
1864 } else if (realm->accresp && msg->code == RAD_Accounting_Request) {
1865 acclog(msg, from->conf->host);
1866 respond(rq, RAD_Accounting_Response, NULL);
1871 if (options.loopprevention && !strcmp(from->conf->name, to->conf->name)) {
1872 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
1873 from->conf->name, to->conf->name);
1877 if (msg->code == RAD_Accounting_Request)
1878 memset(msg->auth, 0, 16);
1879 else if (!RAND_bytes(msg->auth, 16)) {
1880 debug(DBG_WARN, "radsrv: failed to generate random auth");
1885 printfchars(NULL, "auth", "%02x ", auth, 16);
1888 attr = radmsg_gettype(msg, RAD_Attr_User_Password);
1890 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", attr->l);
1891 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1895 attr = radmsg_gettype(msg, RAD_Attr_Tunnel_Password);
1897 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", attr->l);
1898 if (!pwdrecrypt(attr->v, attr->l, from->conf->secret, to->conf->secret, rq->rqauth, msg->auth))
1902 if (to->conf->rewriteout && !dorewrite(msg, to->conf->rewriteout))
1908 pthread_mutex_unlock(&realm->mutex);
1913 rmclientrq(rq, msg->id);
1918 pthread_mutex_unlock(&realm->mutex);
1924 void replyh(struct server *server, unsigned char *buf) {
1925 struct client *from;
1926 struct rqout *rqout;
1928 unsigned char *subattrs;
1929 uint8_t *username, *stationid, *replymsg;
1930 struct radmsg *msg = NULL;
1932 struct list_node *node;
1934 server->connectionok = 1;
1935 server->lostrqs = 0;
1937 rqout = server->requests + buf[1];
1938 pthread_mutex_lock(rqout->lock);
1939 if (!rqout->tries) {
1942 debug(DBG_INFO, "replyh: no outstanding request with this id, ignoring reply");
1946 msg = buf2radmsg(buf, (uint8_t *)server->conf->secret, rqout->rq->msg->auth);
1950 debug(DBG_WARN, "replyh: message validation failed, ignoring packet");
1953 if (msg->code != RAD_Access_Accept && msg->code != RAD_Access_Reject && msg->code != RAD_Access_Challenge
1954 && msg->code != RAD_Accounting_Response) {
1955 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(msg->code));
1958 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(msg->code), msg->id);
1960 gettimeofday(&server->lastrcv, NULL);
1962 if (rqout->rq->msg->code == RAD_Status_Server) {
1963 freerqoutdata(rqout);
1964 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
1968 gettimeofday(&server->lastreply, NULL);
1969 from = rqout->rq->from;
1971 if (server->conf->rewritein && !dorewrite(msg, from->conf->rewritein)) {
1972 debug(DBG_WARN, "replyh: rewritein failed");
1977 for (node = list_first(msg->attrs); node; node = list_next(node)) {
1978 attr = (struct tlv *)node->data;
1979 if (attr->t != RAD_Attr_Vendor_Specific)
1983 if (attr->v[0] != 0 || attr->v[1] != 0 || attr->v[2] != 1 || attr->v[3] != 55) /* 311 == MS */
1986 sublen = attr->l - 4;
1987 subattrs = attr->v + 4;
1988 if (!attrvalidate(subattrs, sublen) ||
1989 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1990 rqout->rq, server->conf->secret, from->conf->secret) ||
1991 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1992 rqout->rq, server->conf->secret, from->conf->secret))
1996 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2000 if (msg->code == RAD_Access_Accept || msg->code == RAD_Access_Reject || msg->code == RAD_Accounting_Response) {
2001 username = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_User_Name));
2003 stationid = radattr2ascii(radmsg_gettype(rqout->rq->msg, RAD_Attr_Calling_Station_Id));
2004 replymsg = radattr2ascii(radmsg_gettype(msg, RAD_Attr_Reply_Message));
2007 debug(DBG_INFO, "%s for user %s stationid %s from %s (%s)",
2008 radmsgtype2string(msg->code), username, stationid, server->conf->host, replymsg);
2011 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2012 radmsgtype2string(msg->code), username, stationid, server->conf->host);
2016 debug(DBG_INFO, "%s for user %s from %s (%s)",
2017 radmsgtype2string(msg->code), username, server->conf->host, replymsg);
2020 debug(DBG_INFO, "%s for user %s from %s",
2021 radmsgtype2string(msg->code), username, server->conf->host);
2027 msg->id = (char)rqout->rq->rqid;
2028 memcpy(msg->auth, rqout->rq->rqauth, 16);
2031 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2034 if (rqout->rq->origusername && (attr = radmsg_gettype(msg, RAD_Attr_User_Name))) {
2035 if (!resizeattr(attr, strlen(rqout->rq->origusername))) {
2036 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2039 memcpy(attr->v, rqout->rq->origusername, strlen(rqout->rq->origusername));
2042 if (from->conf->rewriteout && !dorewrite(msg, from->conf->rewriteout)) {
2043 debug(DBG_WARN, "replyh: rewriteout failed");
2047 debug(DBG_INFO, "replyh: passing reply to client %s (%s)", from->conf->name, addr2string(from->addr));
2048 radmsg_free(rqout->rq->msg);
2049 rqout->rq->msg = msg;
2050 sendreply(newrqref(rqout->rq));
2051 freerqoutdata(rqout);
2052 pthread_mutex_unlock(rqout->lock);
2057 pthread_mutex_unlock(rqout->lock);
2061 struct request *createstatsrvrq() {
2068 rq->msg = radmsg_init(RAD_Status_Server, 0, NULL);
2071 attr = maketlv(RAD_Attr_Message_Authenticator, 16, NULL);
2074 if (!radmsg_add(rq->msg, attr)) {
2085 /* code for removing state not finished */
2086 void *clientwr(void *arg) {
2087 struct server *server = (struct server *)arg;
2088 struct rqout *rqout = NULL;
2089 pthread_t clientrdth;
2090 int i, dynconffail = 0;
2093 struct timeval now, laststatsrv;
2094 struct timespec timeout;
2095 struct request *statsrvrq;
2096 struct clsrvconf *conf;
2098 conf = server->conf;
2100 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2105 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2106 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2110 memset(&timeout, 0, sizeof(struct timespec));
2112 if (conf->statusserver) {
2113 gettimeofday(&server->lastrcv, NULL);
2114 gettimeofday(&laststatsrv, NULL);
2117 if (conf->pdef->connecter) {
2118 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2120 server->connectionok = 1;
2121 if (pthread_create(&clientrdth, NULL, conf->pdef->clientconnreader, (void *)server)) {
2122 debug(DBG_ERR, "clientwr: pthread_create failed");
2126 server->connectionok = 1;
2129 pthread_mutex_lock(&server->newrq_mutex);
2130 if (!server->newrq) {
2131 gettimeofday(&now, NULL);
2132 /* random 0-7 seconds */
2133 RAND_bytes(&rnd, 1);
2135 if (conf->statusserver) {
2136 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2137 if (now.tv_sec - secs > STATUS_SERVER_PERIOD)
2139 if (!timeout.tv_sec || timeout.tv_sec > secs + STATUS_SERVER_PERIOD + rnd)
2140 timeout.tv_sec = secs + STATUS_SERVER_PERIOD + rnd;
2142 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2143 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2146 if (timeout.tv_sec > now.tv_sec)
2147 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2149 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2152 if (server->newrq) {
2153 debug(DBG_DBG, "clientwr: got new request");
2158 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2160 pthread_mutex_unlock(&server->newrq_mutex);
2162 for (i = 0; i < MAX_REQUESTS; i++) {
2163 if (server->clientrdgone) {
2164 pthread_join(clientrdth, NULL);
2168 for (; i < MAX_REQUESTS; i++) {
2169 rqout = server->requests + i;
2171 pthread_mutex_lock(rqout->lock);
2174 pthread_mutex_unlock(rqout->lock);
2178 if (i == MAX_REQUESTS)
2181 gettimeofday(&now, NULL);
2182 if (now.tv_sec < rqout->expiry.tv_sec) {
2183 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2184 timeout.tv_sec = rqout->expiry.tv_sec;
2185 pthread_mutex_unlock(rqout->lock);
2189 if (rqout->tries == (*rqout->rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2190 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2191 if (conf->statusserver) {
2192 if (*rqout->rq->buf == RAD_Status_Server) {
2193 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2194 if (server->lostrqs < 255)
2198 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2199 if (server->lostrqs < 255)
2202 freerqoutdata(rqout);
2203 pthread_mutex_unlock(rqout->lock);
2207 rqout->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2208 if (!timeout.tv_sec || rqout->expiry.tv_sec < timeout.tv_sec)
2209 timeout.tv_sec = rqout->expiry.tv_sec;
2211 conf->pdef->clientradput(server, rqout->rq->buf);
2212 pthread_mutex_unlock(rqout->lock);
2214 if (conf->statusserver && server->connectionok) {
2215 secs = server->lastrcv.tv_sec > laststatsrv.tv_sec ? server->lastrcv.tv_sec : laststatsrv.tv_sec;
2216 gettimeofday(&now, NULL);
2217 if (now.tv_sec - secs > STATUS_SERVER_PERIOD) {
2219 statsrvrq = createstatsrvrq();
2221 statsrvrq->to = server;
2222 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2229 conf->servers = NULL;
2230 if (server->dynamiclookuparg) {
2231 removeserversubrealms(realms, conf);
2235 freeclsrvconf(conf);
2237 freeserver(server, 1);
2238 ERR_remove_state(0);
2242 void createlistener(uint8_t type, char *arg) {
2244 struct clsrvconf *listenres;
2245 struct addrinfo *res;
2246 int s = -1, on = 1, *sp = NULL;
2248 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2250 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2252 for (res = listenres->addrinfo; res; res = res->ai_next) {
2253 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2255 debug(DBG_WARN, "createlistener: socket failed");
2258 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2260 if (res->ai_family == AF_INET6)
2261 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2263 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2264 debug(DBG_WARN, "createlistener: bind failed");
2270 sp = malloc(sizeof(int));
2272 debugx(1, DBG_ERR, "malloc failed");
2274 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2275 debugx(1, DBG_ERR, "pthread_create failed");
2279 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2281 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2282 listenres->host ? listenres->host : "*", listenres->port);
2283 freeclsrvres(listenres);
2286 void createlisteners(uint8_t type, char **args) {
2290 for (i = 0; args[i]; i++)
2291 createlistener(type, args[i]);
2293 createlistener(type, NULL);
2297 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2301 w = where & ~SSL_ST_MASK;
2303 if (w & SSL_ST_CONNECT)
2305 else if (w & SSL_ST_ACCEPT)
2310 if (where & SSL_CB_LOOP)
2311 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2312 else if (where & SSL_CB_ALERT) {
2313 s = (where & SSL_CB_READ) ? "read" : "write";
2314 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2316 else if (where & SSL_CB_EXIT) {
2318 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2320 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2330 ssl_locks = calloc(CRYPTO_num_locks(), sizeof(pthread_mutex_t));
2331 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2332 for (i = 0; i < CRYPTO_num_locks(); i++) {
2333 ssl_lock_count[i] = 0;
2334 pthread_mutex_init(&ssl_locks[i], NULL);
2336 CRYPTO_set_id_callback(ssl_thread_id);
2337 CRYPTO_set_locking_callback(ssl_locking_callback);
2339 SSL_load_error_strings();
2342 while (!RAND_status()) {
2345 RAND_seed((unsigned char *)&t, sizeof(time_t));
2346 RAND_seed((unsigned char *)&pid, sizeof(pid));
2350 int tlsaddcacrl(SSL_CTX *ctx, struct tls *conf) {
2351 STACK_OF(X509_NAME) *calist;
2353 unsigned long error;
2355 if (!SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2356 while ((error = ERR_get_error()))
2357 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2358 debug(DBG_ERR, "tlsaddcacrl: Error updating TLS context %s", conf->name);
2362 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2363 if (!conf->cacertfile || calist) {
2364 if (conf->cacertpath) {
2366 calist = sk_X509_NAME_new_null();
2367 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2368 sk_X509_NAME_free(calist);
2374 while ((error = ERR_get_error()))
2375 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2376 debug(DBG_ERR, "tlsaddcacrl: Error adding CA subjects in TLS context %s", conf->name);
2379 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
2380 SSL_CTX_set_client_CA_list(ctx, calist);
2382 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2383 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2385 if (conf->crlcheck) {
2386 x509_s = SSL_CTX_get_cert_store(ctx);
2387 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2390 debug(DBG_DBG, "tlsaddcacrl: updated TLS context %s", conf->name);
2394 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2395 SSL_CTX *ctx = NULL;
2396 unsigned long error;
2403 ctx = SSL_CTX_new(TLSv1_method());
2405 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2409 ctx = SSL_CTX_new(DTLSv1_method());
2411 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2413 SSL_CTX_set_read_ahead(ctx, 1);
2417 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2421 if (conf->certkeypwd) {
2422 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2423 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2425 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2426 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2427 !SSL_CTX_check_private_key(ctx)) {
2428 while ((error = ERR_get_error()))
2429 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2430 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2435 if (!tlsaddcacrl(ctx, conf)) {
2440 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
2444 struct tls *tlsgettls(char *alt1, char *alt2) {
2447 t = hash_read(tlsconfs, alt1, strlen(alt1));
2449 t = hash_read(tlsconfs, alt2, strlen(alt2));
2453 SSL_CTX *tlsgetctx(uint8_t type, struct tls *t) {
2458 gettimeofday(&now, NULL);
2462 if (t->tlsexpiry && t->tlsctx) {
2463 if (t->tlsexpiry < now.tv_sec) {
2464 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2465 tlsaddcacrl(t->tlsctx, t);
2469 t->tlsctx = tlscreatectx(RAD_TLS, t);
2471 t->tlsexpiry = now.tv_sec + t->cacheexpiry;
2475 if (t->dtlsexpiry && t->dtlsctx) {
2476 if (t->dtlsexpiry < now.tv_sec) {
2477 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2478 tlsaddcacrl(t->dtlsctx, t);
2482 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
2484 t->dtlsexpiry = now.tv_sec + t->cacheexpiry;
2491 struct list *addsrvconfs(char *value, char **names) {
2492 struct list *conflist;
2494 struct list_node *entry;
2495 struct clsrvconf *conf = NULL;
2497 if (!names || !*names)
2500 conflist = list_create();
2502 debug(DBG_ERR, "malloc failed");
2506 for (n = 0; names[n]; n++) {
2507 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2508 conf = (struct clsrvconf *)entry->data;
2509 if (!strcasecmp(names[n], conf->name))
2513 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2514 list_destroy(conflist);
2517 if (!list_push(conflist, conf)) {
2518 debug(DBG_ERR, "malloc failed");
2519 list_destroy(conflist);
2522 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2527 void freerealm(struct realm *realm) {
2530 debug(DBG_DBG, "freerealm: called with refcount %d", realm->refcount);
2531 if (--realm->refcount)
2535 free(realm->message);
2536 regfree(&realm->regex);
2537 pthread_mutex_destroy(&realm->mutex);
2538 /* if refcount == 0, all subrealms gone */
2539 list_destroy(realm->subrealms);
2540 /* if refcount == 0, all srvconfs gone */
2541 list_destroy(realm->srvconfs);
2542 /* if refcount == 0, all accsrvconfs gone */
2543 list_destroy(realm->accsrvconfs);
2544 freerealm(realm->parent);
2548 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2550 struct realm *realm;
2551 char *s, *regex = NULL;
2553 if (*value == '/') {
2554 /* regexp, remove optional trailing / if present */
2555 if (value[strlen(value) - 1] == '/')
2556 value[strlen(value) - 1] = '\0';
2558 /* not a regexp, let us make it one */
2559 if (*value == '*' && !value[1])
2560 regex = stringcopy(".*", 0);
2562 for (n = 0, s = value; *s;)
2565 regex = malloc(strlen(value) + n + 3);
2568 for (n = 1, s = value; *s; s++) {
2578 debug(DBG_ERR, "malloc failed");
2582 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2585 realm = malloc(sizeof(struct realm));
2587 debug(DBG_ERR, "malloc failed");
2590 memset(realm, 0, sizeof(struct realm));
2592 if (pthread_mutex_init(&realm->mutex, NULL)) {
2593 debug(DBG_ERR, "mutex init failed");
2599 realm->name = stringcopy(value, 0);
2601 debug(DBG_ERR, "malloc failed");
2604 if (message && strlen(message) > 253) {
2605 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2608 realm->message = message;
2609 realm->accresp = accresp;
2611 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2612 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2616 if (servers && *servers) {
2617 realm->srvconfs = addsrvconfs(value, servers);
2618 if (!realm->srvconfs)
2622 if (accservers && *accservers) {
2623 realm->accsrvconfs = addsrvconfs(value, accservers);
2624 if (!realm->accsrvconfs)
2628 if (!list_push(realmlist, realm)) {
2629 debug(DBG_ERR, "malloc failed");
2630 pthread_mutex_destroy(&realm->mutex);
2634 debug(DBG_DBG, "addrealm: added realm %s", value);
2638 while (list_shift(realm->srvconfs));
2639 while (list_shift(realm->accsrvconfs));
2646 for (n = 0; servers[n]; n++)
2648 for (n = 0; servers[n]; n++)
2654 for (n = 0; accservers[n]; n++)
2656 for (n = 0; accservers[n]; n++)
2657 free(accservers[n]);
2660 return newrealmref(realm);
2663 struct realm *adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
2664 struct clsrvconf *srvconf;
2665 struct realm *newrealm = NULL;
2666 char *realmname, *s;
2669 if (!conf->dynamiclookupcommand)
2672 /* create dynamic for the realm (string after last @, exit if nothing after @ */
2673 realmname = strrchr(id, '@');
2679 for (s = realmname; *s; s++)
2680 if (*s != '.' && *s != '-' && !isalnum((int)*s))
2683 srvconf = malloc(sizeof(struct clsrvconf));
2685 debug(DBG_ERR, "malloc failed");
2689 if (!addserver(srvconf))
2692 if (!realm->subrealms)
2693 realm->subrealms = list_create();
2694 if (!realm->subrealms)
2696 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
2699 newrealm->parent = newrealmref(realm);
2701 /* add server and accserver to newrealm */
2702 newrealm->srvconfs = list_create();
2703 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
2704 debug(DBG_ERR, "malloc failed");
2707 newrealmref(newrealm);
2708 newrealm->accsrvconfs = list_create();
2709 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
2710 debug(DBG_ERR, "malloc failed");
2711 list_shift(realm->srvconfs);
2712 freerealm(newrealm);
2715 newrealmref(newrealm);
2717 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
2718 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
2719 debug(DBG_ERR, "pthread_create failed");
2720 list_shift(realm->srvconfs);
2721 freerealm(newrealm);
2722 list_shift(realm->accsrvconfs);
2723 freerealm(newrealm);
2726 pthread_detach(clientth);
2731 list_removedata(realm->subrealms, newrealm);
2732 freerealm(newrealm);
2733 if (!list_first(realm->subrealms)) {
2734 list_destroy(realm->subrealms);
2735 realm->subrealms = NULL;
2738 freeserver(srvconf->servers, 1);
2740 debug(DBG_ERR, "failed to create dynamic server");
2744 int dynamicconfig(struct server *server) {
2745 int ok, fd[2], status;
2747 struct clsrvconf *conf = server->conf;
2748 struct gconffile *cf = NULL;
2750 /* for now we only learn hostname/address */
2751 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
2754 debug(DBG_ERR, "dynamicconfig: pipe error");
2759 debug(DBG_ERR, "dynamicconfig: fork error");
2763 } else if (pid == 0) {
2766 if (fd[1] != STDOUT_FILENO) {
2767 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
2768 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
2771 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
2772 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
2776 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
2777 ok = getgenericconfig(&cf, NULL,
2778 "Server", CONF_CBK, confserver_cb, (void *)conf,
2783 if (waitpid(pid, &status, 0) < 0) {
2784 debug(DBG_ERR, "dynamicconfig: wait error");
2789 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
2797 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
2801 int addmatchcertattr(struct clsrvconf *conf) {
2805 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
2806 r = &conf->certcnregex;
2807 v = conf->matchcertattr + 4;
2808 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
2809 r = &conf->certuriregex;
2810 v = conf->matchcertattr + 20;
2815 /* regexp, remove optional trailing / if present */
2816 if (v[strlen(v) - 1] == '/')
2817 v[strlen(v) - 1] = '\0';
2821 *r = malloc(sizeof(regex_t));
2823 debug(DBG_ERR, "malloc failed");
2826 if (regcomp(*r, v, REG_EXTENDED | REG_ICASE | REG_NOSUB)) {
2829 debug(DBG_ERR, "failed to compile regular expression %s", v);
2835 /* should accept both names and numeric values, only numeric right now */
2836 uint8_t attrname2val(char *attrname) {
2839 val = atoi(attrname);
2840 return val > 0 && val < 256 ? val : 0;
2843 /* should accept both names and numeric values, only numeric right now */
2844 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2847 *vendor = atoi(attrname);
2848 s = strchr(attrname, ':');
2853 *type = atoi(s + 1);
2854 return *type >= 0 && *type < 256;
2857 /* should accept both names and numeric values, only numeric right now */
2858 struct tlv *extractattr(char *nameval) {
2863 s = strchr(nameval, ':');
2864 name = atoi(nameval);
2865 if (!s || name < 1 || name > 255)
2867 len = strlen(s + 1);
2870 a = malloc(sizeof(struct tlv));
2873 a->v = (uint8_t *)stringcopy(s + 1, 0);
2883 /* should accept both names and numeric values, only numeric right now */
2884 struct modattr *extractmodattr(char *nameval) {
2889 if (!strncasecmp(nameval, "User-Name:/", 11)) {
2893 s = strchr(nameval, ':');
2894 name = atoi(nameval);
2895 if (!s || name < 1 || name > 255 || s[1] != '/')
2899 /* regexp, remove optional trailing / if present */
2900 if (s[strlen(s) - 1] == '/')
2901 s[strlen(s) - 1] = '\0';
2909 m = malloc(sizeof(struct modattr));
2911 debug(DBG_ERR, "malloc failed");
2916 m->replacement = stringcopy(t, 0);
2917 if (!m->replacement) {
2919 debug(DBG_ERR, "malloc failed");
2923 m->regex = malloc(sizeof(regex_t));
2925 free(m->replacement);
2927 debug(DBG_ERR, "malloc failed");
2931 if (regcomp(m->regex, s, REG_ICASE | REG_EXTENDED)) {
2933 free(m->replacement);
2935 debug(DBG_ERR, "failed to compile regular expression %s", s);
2942 struct rewrite *getrewrite(char *alt1, char *alt2) {
2945 if ((r = hash_read(rewriteconfs, alt1, strlen(alt1))))
2947 if ((r = hash_read(rewriteconfs, alt2, strlen(alt2))))
2952 void addrewrite(char *value, char **rmattrs, char **rmvattrs, char **addattrs, char **modattrs) {
2953 struct rewrite *rewrite = NULL;
2955 uint8_t *rma = NULL;
2956 uint32_t *p, *rmva = NULL;
2957 struct list *adda = NULL, *moda = NULL;
2962 for (n = 0; rmattrs[n]; n++);
2963 rma = calloc(n + 1, sizeof(uint8_t));
2965 debugx(1, DBG_ERR, "malloc failed");
2967 for (i = 0; i < n; i++) {
2968 if (!(rma[i] = attrname2val(rmattrs[i])))
2969 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", rmattrs[i]);
2977 for (n = 0; rmvattrs[n]; n++);
2978 rmva = calloc(2 * n + 1, sizeof(uint32_t));
2980 debugx(1, DBG_ERR, "malloc failed");
2982 for (p = rmva, i = 0; i < n; i++, p += 2) {
2983 if (!vattrname2val(rmvattrs[i], p, p + 1))
2984 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", rmvattrs[i]);
2992 adda = list_create();
2994 debugx(1, DBG_ERR, "malloc failed");
2995 for (i = 0; addattrs[i]; i++) {
2996 a = extractattr(addattrs[i]);
2998 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", addattrs[i]);
3000 if (!list_push(adda, a))
3001 debugx(1, DBG_ERR, "malloc failed");
3007 moda = list_create();
3009 debugx(1, DBG_ERR, "malloc failed");
3010 for (i = 0; modattrs[i]; i++) {
3011 m = extractmodattr(modattrs[i]);
3013 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", modattrs[i]);
3015 if (!list_push(moda, m))
3016 debugx(1, DBG_ERR, "malloc failed");
3021 if (rma || rmva || adda || moda) {
3022 rewrite = malloc(sizeof(struct rewrite));
3024 debugx(1, DBG_ERR, "malloc failed");
3025 rewrite->removeattrs = rma;
3026 rewrite->removevendorattrs = rmva;
3027 rewrite->addattrs = adda;
3028 rewrite->modattrs = moda;
3031 if (!hash_insert(rewriteconfs, value, strlen(value), rewrite))
3032 debugx(1, DBG_ERR, "malloc failed");
3033 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3036 void freeclsrvconf(struct clsrvconf *conf) {
3042 free(conf->matchcertattr);
3043 if (conf->certcnregex)
3044 regfree(conf->certcnregex);
3045 if (conf->certuriregex)
3046 regfree(conf->certuriregex);
3047 free(conf->confrewritein);
3048 free(conf->confrewriteout);
3049 if (conf->rewriteusername) {
3050 if (conf->rewriteusername->regex)
3051 regfree(conf->rewriteusername->regex);
3052 free(conf->rewriteusername->replacement);
3053 free(conf->rewriteusername);
3055 free(conf->dynamiclookupcommand);
3056 free(conf->rewritein);
3057 free(conf->rewriteout);
3059 freeaddrinfo(conf->addrinfo);
3061 pthread_mutex_destroy(conf->lock);
3064 /* not touching ssl_ctx, clients and servers */
3068 int mergeconfstring(char **dst, char **src) {
3077 t = stringcopy(*dst, 0);
3079 debug(DBG_ERR, "malloc failed");
3087 /* assumes dst is a shallow copy */
3088 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3089 if (!mergeconfstring(&dst->name, &src->name) ||
3090 !mergeconfstring(&dst->host, &src->host) ||
3091 !mergeconfstring(&dst->port, &src->port) ||
3092 !mergeconfstring(&dst->secret, &src->secret) ||
3093 !mergeconfstring(&dst->tls, &src->tls) ||
3094 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3095 !mergeconfstring(&dst->confrewritein, &src->confrewritein) ||
3096 !mergeconfstring(&dst->confrewriteout, &src->confrewriteout) ||
3097 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3100 dst->pdef = src->pdef;
3101 dst->statusserver = src->statusserver;
3102 dst->certnamecheck = src->certnamecheck;
3103 if (src->retryinterval != 255)
3104 dst->retryinterval = src->retryinterval;
3105 if (src->retrycount != 255)
3106 dst->retrycount = src->retrycount;
3110 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3111 struct clsrvconf *conf;
3112 char *conftype = NULL, *rewriteinalias = NULL;
3113 long int dupinterval = LONG_MIN;
3115 debug(DBG_DBG, "confclient_cb called for %s", block);
3117 conf = malloc(sizeof(struct clsrvconf));
3119 debugx(1, DBG_ERR, "malloc failed");
3120 memset(conf, 0, sizeof(struct clsrvconf));
3121 conf->certnamecheck = 1;
3123 if (!getgenericconfig(cf, block,
3124 "type", CONF_STR, &conftype,
3125 "host", CONF_STR, &conf->host,
3126 "secret", CONF_STR, &conf->secret,
3127 "tls", CONF_STR, &conf->tls,
3128 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3129 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3130 "DuplicateInterval", CONF_LINT, &dupinterval,
3131 "rewrite", CONF_STR, &rewriteinalias,
3132 "rewriteIn", CONF_STR, &conf->confrewritein,
3133 "rewriteOut", CONF_STR, &conf->confrewriteout,
3134 "rewriteattribute", CONF_STR, &conf->confrewriteusername,
3137 debugx(1, DBG_ERR, "configuration error");
3139 conf->name = stringcopy(val, 0);
3141 conf->host = stringcopy(val, 0);
3142 if (!conf->name || !conf->host)
3143 debugx(1, DBG_ERR, "malloc failed");
3146 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3147 conf->type = protoname2int(conftype);
3148 conf->pdef = &protodefs[conf->type];
3149 if (!conf->pdef->name)
3150 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3153 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3154 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultclient", "default");
3156 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3157 if (conf->matchcertattr && !addmatchcertattr(conf))
3158 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3161 if (dupinterval != LONG_MIN) {
3162 if (dupinterval < 0 || dupinterval > 255)
3163 debugx(1, DBG_ERR, "error in block %s, value of option DuplicateInterval is %d, must be 0-255", block, dupinterval);
3164 conf->dupinterval = (uint8_t)dupinterval;
3166 conf->dupinterval = conf->pdef->duplicateintervaldefault;
3168 if (!conf->confrewritein)
3169 conf->confrewritein = rewriteinalias;
3171 free(rewriteinalias);
3172 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultclient", "default");
3173 if (conf->confrewriteout)
3174 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3176 if (conf->confrewriteusername) {
3177 conf->rewriteusername = extractmodattr(conf->confrewriteusername);
3178 if (!conf->rewriteusername)
3179 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3182 if (!resolvepeer(conf, 0))
3183 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3185 if (!conf->secret) {
3186 if (!conf->pdef->secretdefault)
3187 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3188 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3190 debugx(1, DBG_ERR, "malloc failed");
3193 conf->lock = malloc(sizeof(pthread_mutex_t));
3195 debugx(1, DBG_ERR, "malloc failed");
3197 pthread_mutex_init(conf->lock, NULL);
3198 if (!list_push(clconfs, conf))
3199 debugx(1, DBG_ERR, "malloc failed");
3203 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3204 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3205 conf->tlsconf = conf->tls ? tlsgettls(conf->tls, NULL) : tlsgettls("defaultserver", "default");
3206 if (!conf->tlsconf) {
3207 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3210 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3211 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3217 conf->port = stringcopy(conf->pdef->portdefault, 0);
3219 debug(DBG_ERR, "malloc failed");
3224 if (conf->retryinterval == 255)
3225 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3226 if (conf->retrycount == 255)
3227 conf->retrycount = protodefs[conf->type].retrycountdefault;
3229 conf->rewritein = conf->confrewritein ? getrewrite(conf->confrewritein, NULL) : getrewrite("defaultserver", "default");
3230 if (conf->confrewriteout)
3231 conf->rewriteout = getrewrite(conf->confrewriteout, NULL);
3233 if (!conf->secret) {
3234 if (!conf->pdef->secretdefault) {
3235 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3238 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3239 if (!conf->secret) {
3240 debug(DBG_ERR, "malloc failed");
3245 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3246 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3252 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3253 struct clsrvconf *conf, *resconf;
3254 char *conftype = NULL, *rewriteinalias = NULL;
3255 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3257 debug(DBG_DBG, "confserver_cb called for %s", block);
3259 conf = malloc(sizeof(struct clsrvconf));
3261 debug(DBG_ERR, "malloc failed");
3264 memset(conf, 0, sizeof(struct clsrvconf));
3265 resconf = (struct clsrvconf *)arg;
3267 conf->statusserver = resconf->statusserver;
3268 conf->certnamecheck = resconf->certnamecheck;
3270 conf->certnamecheck = 1;
3272 if (!getgenericconfig(cf, block,
3273 "type", CONF_STR, &conftype,
3274 "host", CONF_STR, &conf->host,
3275 "port", CONF_STR, &conf->port,
3276 "secret", CONF_STR, &conf->secret,
3277 "tls", CONF_STR, &conf->tls,
3278 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3279 "rewrite", CONF_STR, &rewriteinalias,
3280 "rewriteIn", CONF_STR, &conf->confrewritein,
3281 "rewriteOut", CONF_STR, &conf->confrewriteout,
3282 "StatusServer", CONF_BLN, &conf->statusserver,
3283 "RetryInterval", CONF_LINT, &retryinterval,
3284 "RetryCount", CONF_LINT, &retrycount,
3285 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3286 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3289 debug(DBG_ERR, "configuration error");
3293 conf->name = stringcopy(val, 0);
3295 debug(DBG_ERR, "malloc failed");
3299 conf->host = stringcopy(val, 0);
3301 debug(DBG_ERR, "malloc failed");
3307 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3308 conf->type = protoname2int(conftype);
3309 conf->pdef = &protodefs[conf->type];
3310 if (!conf->pdef->name) {
3311 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3317 if (!conf->confrewritein)
3318 conf->confrewritein = rewriteinalias;
3320 free(rewriteinalias);
3321 rewriteinalias = NULL;
3323 if (retryinterval != LONG_MIN) {
3324 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3325 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3328 conf->retryinterval = (uint8_t)retryinterval;
3330 conf->retryinterval = 255;
3332 if (retrycount != LONG_MIN) {
3333 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3334 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3337 conf->retrycount = (uint8_t)retrycount;
3339 conf->retrycount = 255;
3342 if (!mergesrvconf(resconf, conf))
3346 if (conf->dynamiclookupcommand) {
3347 free(conf->dynamiclookupcommand);
3348 conf->dynamiclookupcommand = NULL;
3352 if (resconf || !conf->dynamiclookupcommand) {
3353 if (!compileserverconfig(conf, block))
3360 if (!list_push(srvconfs, conf)) {
3361 debug(DBG_ERR, "malloc failed");
3368 free(rewriteinalias);
3369 freeclsrvconf(conf);
3373 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3374 char **servers = NULL, **accservers = NULL, *msg = NULL;
3375 uint8_t accresp = 0;
3377 debug(DBG_DBG, "confrealm_cb called for %s", block);
3379 if (!getgenericconfig(cf, block,
3380 "server", CONF_MSTR, &servers,
3381 "accountingServer", CONF_MSTR, &accservers,
3382 "ReplyMessage", CONF_STR, &msg,
3383 "AccountingResponse", CONF_BLN, &accresp,
3386 debugx(1, DBG_ERR, "configuration error");
3388 addrealm(realms, val, servers, accservers, msg, accresp);
3392 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3394 long int expiry = LONG_MIN;
3396 debug(DBG_DBG, "conftls_cb called for %s", block);
3398 conf = malloc(sizeof(struct tls));
3400 debug(DBG_ERR, "conftls_cb: malloc failed");
3403 memset(conf, 0, sizeof(struct tls));
3405 if (!getgenericconfig(cf, block,
3406 "CACertificateFile", CONF_STR, &conf->cacertfile,
3407 "CACertificatePath", CONF_STR, &conf->cacertpath,
3408 "CertificateFile", CONF_STR, &conf->certfile,
3409 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3410 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3411 "CacheExpiry", CONF_LINT, &expiry,
3412 "CRLCheck", CONF_BLN, &conf->crlcheck,
3415 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3418 if (!conf->certfile || !conf->certkeyfile) {
3419 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3422 if (!conf->cacertfile && !conf->cacertpath) {
3423 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3426 if (expiry != LONG_MIN) {
3428 debug(DBG_ERR, "error in block %s, value of option CacheExpiry is %ld, may not be negative", val, expiry);
3431 conf->cacheexpiry = expiry;
3434 conf->name = stringcopy(val, 0);
3436 debug(DBG_ERR, "conftls_cb: malloc failed");
3440 if (!hash_insert(tlsconfs, val, strlen(val), conf)) {
3441 debug(DBG_ERR, "conftls_cb: malloc failed");
3444 if (!tlsgetctx(RAD_TLS, conf))
3445 debug(DBG_ERR, "conftls_cb: error creating ctx for TLS block %s", val);
3446 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3450 free(conf->cacertfile);
3451 free(conf->cacertpath);
3452 free(conf->certfile);
3453 free(conf->certkeyfile);
3454 free(conf->certkeypwd);
3459 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3460 char **rmattrs = NULL, **rmvattrs = NULL, **addattrs = NULL, **modattrs = NULL;
3462 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3464 if (!getgenericconfig(cf, block,
3465 "removeAttribute", CONF_MSTR, &rmattrs,
3466 "removeVendorAttribute", CONF_MSTR, &rmvattrs,
3467 "addAttribute", CONF_MSTR, &addattrs,
3468 "modifyAttribute", CONF_MSTR, &modattrs,
3471 debugx(1, DBG_ERR, "configuration error");
3472 addrewrite(val, rmattrs, rmvattrs, addattrs, modattrs);
3476 void getmainconfig(const char *configfile) {
3477 long int loglevel = LONG_MIN;
3478 struct gconffile *cfs;
3480 cfs = openconfigfile(configfile);
3481 memset(&options, 0, sizeof(options));
3483 clconfs = list_create();
3485 debugx(1, DBG_ERR, "malloc failed");
3487 srvconfs = list_create();
3489 debugx(1, DBG_ERR, "malloc failed");
3491 realms = list_create();
3493 debugx(1, DBG_ERR, "malloc failed");
3495 tlsconfs = hash_create();
3497 debugx(1, DBG_ERR, "malloc failed");
3499 rewriteconfs = hash_create();
3501 debugx(1, DBG_ERR, "malloc failed");
3503 if (!getgenericconfig(&cfs, NULL,
3504 "ListenUDP", CONF_MSTR, &options.listenudp,
3505 "ListenTCP", CONF_MSTR, &options.listentcp,
3506 "ListenTLS", CONF_MSTR, &options.listentls,
3507 "ListenDTLS", CONF_MSTR, &options.listendtls,
3508 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3509 "SourceUDP", CONF_STR, &options.sourceudp,
3510 "SourceTCP", CONF_STR, &options.sourcetcp,
3511 "SourceTLS", CONF_STR, &options.sourcetls,
3512 "SourceDTLS", CONF_STR, &options.sourcedtls,
3513 "LogLevel", CONF_LINT, &loglevel,
3514 "LogDestination", CONF_STR, &options.logdestination,
3515 "LoopPrevention", CONF_BLN, &options.loopprevention,
3516 "Client", CONF_CBK, confclient_cb, NULL,
3517 "Server", CONF_CBK, confserver_cb, NULL,
3518 "Realm", CONF_CBK, confrealm_cb, NULL,
3519 "TLS", CONF_CBK, conftls_cb, NULL,
3520 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3523 debugx(1, DBG_ERR, "configuration error");
3525 if (loglevel != LONG_MIN) {
3526 if (loglevel < 1 || loglevel > 4)
3527 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3528 options.loglevel = (uint8_t)loglevel;
3532 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3535 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3538 *configfile = optarg;
3541 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3542 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3543 *loglevel = *optarg - '0';
3552 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3557 if (!(argc - optind))
3561 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3565 int daemon(int a, int b) {
3573 for (i = 0; i < 3; i++) {
3575 open("/dev/null", O_RDWR);
3581 void *sighandler(void *arg) {
3586 sigemptyset(&sigset);
3587 sigaddset(&sigset, SIGPIPE);
3588 sigwait(&sigset, &sig);
3589 /* only get SIGPIPE right now, so could simplify below code */
3592 /* completely ignoring this */
3595 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3598 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3603 int main(int argc, char **argv) {
3606 struct list_node *entry;
3607 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3608 char *configfile = NULL;
3609 struct clsrvconf *srvconf;
3612 debug_init("radsecproxy");
3613 debug_set_level(DEBUG_LEVEL);
3615 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3617 debug_set_level(loglevel);
3618 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3620 options.loglevel = loglevel;
3621 else if (options.loglevel)
3622 debug_set_level(options.loglevel);
3624 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3625 free(options.logdestination);
3627 if (!list_first(clconfs))
3628 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3629 if (!list_first(realms))
3630 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3633 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3635 if (!foreground && (daemon(0, 0) < 0))
3636 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3638 debug_timestamp_on();
3639 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3641 sigemptyset(&sigset);
3642 /* exit on all but SIGPIPE, ignore more? */
3643 sigaddset(&sigset, SIGPIPE);
3644 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3645 pthread_create(&sigth, NULL, sighandler, NULL);
3647 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3648 srvconf = (struct clsrvconf *)entry->data;
3649 if (srvconf->dynamiclookupcommand)
3651 if (!addserver(srvconf))
3652 debugx(1, DBG_ERR, "failed to add server");
3653 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3654 (void *)(srvconf->servers)))
3655 debugx(1, DBG_ERR, "pthread_create failed");
3657 /* srcprotores for UDP no longer needed */
3658 if (srcprotores[RAD_UDP]) {
3659 freeaddrinfo(srcprotores[RAD_UDP]);
3660 srcprotores[RAD_UDP] = NULL;
3663 for (i = 0; protodefs[i].name; i++)
3664 if (protodefs[i].initextra)
3665 protodefs[i].initextra();
3667 if (find_clconf_type(RAD_TCP, NULL))
3668 createlisteners(RAD_TCP, options.listentcp);
3670 if (find_clconf_type(RAD_TLS, NULL))
3671 createlisteners(RAD_TLS, options.listentls);
3673 if (find_clconf_type(RAD_DTLS, NULL))
3674 createlisteners(RAD_DTLS, options.listendtls);
3676 if (find_clconf_type(RAD_UDP, NULL)) {
3677 createlisteners(RAD_UDP, options.listenudp);
3678 if (options.listenaccudp)
3679 createlisteners(RAD_UDP, options.listenaccudp);
3682 /* just hang around doing nothing, anything to do here? */