2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 #include <sys/socket.h>
34 #include <netinet/in.h>
43 #include <sys/types.h>
44 #include <sys/select.h>
47 #include <arpa/inet.h>
51 #include <openssl/ssl.h>
52 #include <openssl/rand.h>
53 #include <openssl/err.h>
54 #include <openssl/md5.h>
55 #include <openssl/hmac.h>
56 #include <openssl/x509v3.h>
61 #include "radsecproxy.h"
63 static struct options options;
64 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
66 static struct addrinfo *srcudpres = NULL;
67 static struct addrinfo *srctcpres = NULL;
69 static struct replyq *udp_server_replyq = NULL;
70 static int udp_client4_sock = -1;
71 static int udp_client6_sock = -1;
72 static pthread_mutex_t *ssl_locks;
73 static long *ssl_lock_count;
77 /* minimum required declarations to avoid reordering code */
78 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
79 int dynamicconfig(struct server *server);
80 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
81 void freerealm(struct realm *realm);
82 void freeclsrvconf(struct clsrvconf *conf);
83 void freerqdata(struct request *rq);
85 static const struct protodefs protodefs[] = {
86 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
87 NULL, /* secretdefault */
88 SOCK_DGRAM, /* socktype */
89 "1812", /* portdefault */
90 REQUEST_RETRY_COUNT, /* retrycountdefault */
91 10, /* retrycountmax */
92 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
93 60 /* retryintervalmax */
95 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
96 "mysecret", /* secretdefault */
97 SOCK_STREAM, /* socktype */
98 "2083", /* portdefault */
99 0, /* retrycountdefault */
100 0, /* retrycountmax */
101 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
102 60 /* retryintervalmax */
104 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
105 NULL, /* secretdefault */
106 SOCK_STREAM, /* socktype */
107 "1812", /* portdefault */
108 0, /* retrycountdefault */
109 0, /* retrycountmax */
110 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
111 60 /* retryintervalmax */
117 uint8_t protoname2int(const char *name) {
120 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
124 /* callbacks for making OpenSSL thread safe */
125 unsigned long ssl_thread_id() {
126 return (unsigned long)pthread_self();
129 void ssl_locking_callback(int mode, int type, const char *file, int line) {
130 if (mode & CRYPTO_LOCK) {
131 pthread_mutex_lock(&ssl_locks[type]);
132 ssl_lock_count[type]++;
134 pthread_mutex_unlock(&ssl_locks[type]);
137 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
138 int pwdlen = strlen(userdata);
139 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
141 memcpy(buf, userdata, pwdlen);
145 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
150 err_cert = X509_STORE_CTX_get_current_cert(ctx);
151 err = X509_STORE_CTX_get_error(ctx);
152 depth = X509_STORE_CTX_get_error_depth(ctx);
154 if (depth > MAX_CERT_DEPTH) {
156 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
157 X509_STORE_CTX_set_error(ctx, err);
161 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
162 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
165 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
166 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
167 debug(DBG_WARN, "\tIssuer=%s", buf);
169 case X509_V_ERR_CERT_NOT_YET_VALID:
170 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
171 debug(DBG_WARN, "\tCertificate not yet valid");
173 case X509_V_ERR_CERT_HAS_EXPIRED:
174 debug(DBG_WARN, "Certificate has expired");
176 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
177 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
182 printf("certificate verify returns %d\n", ok);
187 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
188 struct addrinfo hints, *addrinfo, *res;
192 slash = conf->host ? strchr(conf->host, '/') : NULL;
196 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
200 if (*s < '0' || *s > '9') {
201 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
204 plen = atoi(slash + 1);
205 if (plen < 0 || plen > 128) {
206 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
211 memset(&hints, 0, sizeof(hints));
212 hints.ai_socktype = conf->pdef->socktype;
213 hints.ai_family = AF_UNSPEC;
214 hints.ai_flags = ai_flags;
215 if (!conf->host && !conf->port) {
216 /* getaddrinfo() doesn't like host and port to be NULL */
217 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
218 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
221 for (res = addrinfo; res; res = res->ai_next) {
222 switch (res->ai_family) {
224 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
227 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
233 hints.ai_flags |= AI_NUMERICHOST;
234 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
235 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
240 switch (addrinfo->ai_family) {
243 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
244 freeaddrinfo(addrinfo);
251 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
252 freeaddrinfo(addrinfo);
255 conf->prefixlen = plen;
257 conf->prefixlen = 255;
260 freeaddrinfo(conf->addrinfo);
261 conf->addrinfo = addrinfo;
265 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
267 struct addrinfo *res;
269 for (res = addrinfo; res; res = res->ai_next) {
270 if (family != AF_UNSPEC && family != res->ai_family)
272 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
274 debug(DBG_WARN, "bindtoaddr: socket failed");
278 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
281 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
284 if (!bind(s, res->ai_addr, res->ai_addrlen))
286 debug(DBG_WARN, "bindtoaddr: bind failed");
292 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
297 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
301 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
303 debugx(1, DBG_ERR, "no ] matching initial [");
307 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
310 debugx(1, DBG_ERR, "missing host/address");
312 conf->host = stringcopy(field, p - field);
315 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
316 debugx(1, DBG_ERR, "unexpected character after ]");
319 /* port number or service name is specified */;
321 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
323 debugx(1, DBG_ERR, "syntax error, : but no following port");
324 conf->port = stringcopy(field, p - field);
326 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
330 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
331 struct clsrvconf *conf;
333 conf = malloc(sizeof(struct clsrvconf));
335 debugx(1, DBG_ERR, "malloc failed");
336 memset(conf, 0, sizeof(struct clsrvconf));
338 conf->pdef = &protodefs[conf->type];
340 parsehostport(lconf, conf, default_port);
341 if (!strcmp(conf->host, "*")) {
346 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
347 if (!resolvepeer(conf, AI_PASSIVE))
348 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
352 void freeclsrvres(struct clsrvconf *res) {
356 freeaddrinfo(res->addrinfo);
360 int connecttcp(struct addrinfo *addrinfo) {
362 struct addrinfo *res;
365 for (res = addrinfo; res; res = res->ai_next) {
366 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
368 debug(DBG_WARN, "connecttoserver: socket failed");
371 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
373 debug(DBG_WARN, "connecttoserver: connect failed");
380 /* returns 1 if the len first bits are equal, else 0 */
381 int prefixmatch(void *a1, void *a2, uint8_t len) {
382 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
384 if (l && memcmp(a1, a2, l))
389 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
392 /* check if conf has matching address */
393 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
394 struct sockaddr_in6 *sa6 = NULL;
395 struct in_addr *a4 = NULL;
396 struct addrinfo *res;
398 if (addr->sa_family == AF_INET6) {
399 sa6 = (struct sockaddr_in6 *)addr;
400 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
401 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
405 a4 = &((struct sockaddr_in *)addr)->sin_addr;
407 if (conf->type == type) {
408 if (conf->prefixlen == 255) {
409 for (res = conf->addrinfo; res; res = res->ai_next)
410 if ((a4 && res->ai_family == AF_INET &&
411 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
412 (sa6 && res->ai_family == AF_INET6 &&
413 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
416 res = conf->addrinfo;
418 ((a4 && res->ai_family == AF_INET &&
419 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
420 (sa6 && res->ai_family == AF_INET6 &&
421 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
428 /* returns next config with matching address, or NULL */
429 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
430 struct sockaddr_in6 *sa6 = NULL;
431 struct in_addr *a4 = NULL;
432 struct addrinfo *res;
433 struct list_node *entry;
434 struct clsrvconf *conf;
436 if (addr->sa_family == AF_INET6) {
437 sa6 = (struct sockaddr_in6 *)addr;
438 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
439 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
443 a4 = &((struct sockaddr_in *)addr)->sin_addr;
445 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
446 conf = (struct clsrvconf *)entry->data;
447 if (conf->type == type) {
448 if (conf->prefixlen == 255) {
449 for (res = conf->addrinfo; res; res = res->ai_next)
450 if ((a4 && res->ai_family == AF_INET &&
451 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
452 (sa6 && res->ai_family == AF_INET6 &&
453 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
459 res = conf->addrinfo;
461 ((a4 && res->ai_family == AF_INET &&
462 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
463 (sa6 && res->ai_family == AF_INET6 &&
464 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
475 /* returns next config of given type, or NULL */
476 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
477 struct list_node *entry;
478 struct clsrvconf *conf;
480 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
481 conf = (struct clsrvconf *)entry->data;
482 if (conf->type == type) {
491 struct replyq *newreplyq() {
492 struct replyq *replyq;
494 replyq = malloc(sizeof(struct replyq));
496 debugx(1, DBG_ERR, "malloc failed");
497 replyq->replies = list_create();
498 if (!replyq->replies)
499 debugx(1, DBG_ERR, "malloc failed");
500 pthread_mutex_init(&replyq->mutex, NULL);
501 pthread_cond_init(&replyq->cond, NULL);
505 struct client *addclient(struct clsrvconf *conf) {
506 struct client *new = malloc(sizeof(struct client));
509 debug(DBG_ERR, "malloc failed");
512 if (!conf->clients) {
513 conf->clients = list_create();
514 if (!conf->clients) {
515 debug(DBG_ERR, "malloc failed");
520 memset(new, 0, sizeof(struct client));
522 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
524 list_push(conf->clients, new);
528 void removeclient(struct client *client) {
529 struct list_node *entry;
531 if (!client || !client->conf->clients)
534 pthread_mutex_lock(&client->replyq->mutex);
535 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
536 free(((struct reply *)entry)->buf);
537 list_destroy(client->replyq->replies);
538 pthread_cond_destroy(&client->replyq->cond);
539 pthread_mutex_unlock(&client->replyq->mutex);
540 pthread_mutex_destroy(&client->replyq->mutex);
541 list_removedata(client->conf->clients, client);
545 void removeclientrqs(struct client *client) {
546 struct list_node *entry;
547 struct server *server;
551 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
552 server = ((struct clsrvconf *)entry->data)->servers;
553 pthread_mutex_lock(&server->newrq_mutex);
554 for (i = 0; i < MAX_REQUESTS; i++) {
555 rq = server->requests + i;
556 if (rq->from == client)
559 pthread_mutex_unlock(&server->newrq_mutex);
563 void freeserver(struct server *server, uint8_t destroymutex) {
564 struct request *rq, *end;
569 if(server->requests) {
570 rq = server->requests;
571 for (end = rq + MAX_REQUESTS; rq < end; rq++)
573 free(server->requests);
575 free(server->dynamiclookuparg);
577 pthread_mutex_destroy(&server->lock);
578 pthread_cond_destroy(&server->newrq_cond);
579 pthread_mutex_destroy(&server->newrq_mutex);
584 int addserver(struct clsrvconf *conf) {
585 struct clsrvconf *res;
588 debug(DBG_ERR, "addserver: currently works with just one server per conf");
591 conf->servers = malloc(sizeof(struct server));
592 if (!conf->servers) {
593 debug(DBG_ERR, "malloc failed");
596 memset(conf->servers, 0, sizeof(struct server));
597 conf->servers->conf = conf;
599 if (conf->type == RAD_UDP) {
601 res = resolve_hostport(RAD_UDP, options.sourceudp, NULL);
602 srcudpres = res->addrinfo;
603 res->addrinfo = NULL;
606 switch (conf->addrinfo->ai_family) {
608 if (udp_client4_sock < 0) {
609 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
610 if (udp_client4_sock < 0)
611 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
613 conf->servers->sock = udp_client4_sock;
616 if (udp_client6_sock < 0) {
617 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
618 if (udp_client6_sock < 0)
619 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
621 conf->servers->sock = udp_client6_sock;
624 debugx(1, DBG_ERR, "addserver: unsupported address family");
629 res = resolve_hostport(RAD_TLS, options.sourcetcp, NULL);
630 srctcpres = res->addrinfo;
631 res->addrinfo = NULL;
634 conf->servers->sock = -1;
637 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
638 if (!conf->servers->requests) {
639 debug(DBG_ERR, "malloc failed");
642 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
643 debug(DBG_ERR, "mutex init failed");
646 conf->servers->newrq = 0;
647 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
648 debug(DBG_ERR, "mutex init failed");
649 pthread_mutex_destroy(&conf->servers->lock);
652 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
653 debug(DBG_ERR, "mutex init failed");
654 pthread_mutex_destroy(&conf->servers->newrq_mutex);
655 pthread_mutex_destroy(&conf->servers->lock);
662 freeserver(conf->servers, 0);
663 conf->servers = NULL;
667 /* exactly one of client and server must be non-NULL */
668 /* should probably take peer list (client(s) or server(s)) as argument instead */
669 /* if *peer == NULL we return who we received from, else require it to be from peer */
670 /* return from in sa if not NULL */
671 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
673 unsigned char buf[65536], *rad;
674 struct sockaddr_storage from;
675 socklen_t fromlen = sizeof(from);
677 struct list_node *node;
680 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
682 debug(DBG_WARN, "radudpget: recv failed");
685 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
688 debug(DBG_WARN, "radudpget: packet too small");
694 debug(DBG_WARN, "radudpget: length too small");
699 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
703 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
707 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
709 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
712 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
714 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
717 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
723 debug(DBG_ERR, "radudpget: malloc failed");
727 if (client && !*client) {
728 node = list_first(p->clients);
729 *client = node ? (struct client *)node->data : addclient(p);
734 } else if (server && !*server)
735 *server = p->servers;
739 memcpy(rad, buf, len);
745 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
746 int loc, i, l, n, r = 0;
749 STACK_OF(GENERAL_NAME) *alt;
752 debug(DBG_DBG, "subjectaltnameaddr");
754 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
758 ex = X509_get_ext(cert, loc);
759 alt = X509V3_EXT_d2i(ex);
763 n = sk_GENERAL_NAME_num(alt);
764 for (i = 0; i < n; i++) {
765 gn = sk_GENERAL_NAME_value(alt, i);
766 if (gn->type != GEN_IPADD)
769 v = (char *)ASN1_STRING_data(gn->d.ia5);
770 l = ASN1_STRING_length(gn->d.ia5);
771 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
772 && !memcmp(v, &addr, l)) {
777 GENERAL_NAMES_free(alt);
781 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
788 nm = X509_get_subject_name(cert);
791 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
794 e = X509_NAME_get_entry(nm, loc);
795 t = X509_NAME_ENTRY_get_data(e);
796 v = (char *) ASN1_STRING_data(t);
797 l = ASN1_STRING_length(t);
801 if (l == strlen(exact) && !strncasecmp(exact, v, l))
804 s = stringcopy((char *)v, l);
806 debug(DBG_ERR, "malloc failed");
809 if (regexec(regex, s, 0, NULL, 0)) {
820 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
821 int loc, i, l, n, r = 0;
824 STACK_OF(GENERAL_NAME) *alt;
827 debug(DBG_DBG, "subjectaltnameregexp");
829 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
833 ex = X509_get_ext(cert, loc);
834 alt = X509V3_EXT_d2i(ex);
838 n = sk_GENERAL_NAME_num(alt);
839 for (i = 0; i < n; i++) {
840 gn = sk_GENERAL_NAME_value(alt, i);
841 if (gn->type != type)
844 v = (char *)ASN1_STRING_data(gn->d.ia5);
845 l = ASN1_STRING_length(gn->d.ia5);
849 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
852 if (memcmp(v, exact, l))
855 s = stringcopy((char *)v, l);
857 debug(DBG_ERR, "malloc failed");
860 if (regexec(regex, s, 0, NULL, 0)) {
869 GENERAL_NAMES_free(alt);
873 X509 *verifytlscert(SSL *ssl) {
877 if (SSL_get_verify_result(ssl) != X509_V_OK) {
878 debug(DBG_ERR, "verifytlscert: basic validation failed");
879 while ((error = ERR_get_error()))
880 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
884 cert = SSL_get_peer_certificate(ssl);
886 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
890 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
892 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
893 struct in6_addr addr;
895 if (conf->certnamecheck && conf->prefixlen == 255) {
896 if (inet_pton(AF_INET, conf->host, &addr))
898 else if (inet_pton(AF_INET6, conf->host, &addr))
901 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
904 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
907 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
909 if (!cnregexp(cert, conf->host, NULL)) {
910 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
913 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
916 if (conf->certcnregex) {
917 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
918 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
921 debug(DBG_DBG, "verifyconfcert: CN matching regex");
923 if (conf->certuriregex) {
924 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
925 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
928 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
933 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
938 debug(DBG_DBG, "tlsconnect called from %s", text);
939 pthread_mutex_lock(&server->lock);
940 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
941 /* already reconnected, nothing to do */
942 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
943 pthread_mutex_unlock(&server->lock);
947 debug(DBG_DBG, "tlsconnect %s", text);
950 gettimeofday(&now, NULL);
951 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
952 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
953 debug(DBG_DBG, "tlsconnect: timeout");
954 if (server->sock >= 0)
956 SSL_free(server->ssl);
958 pthread_mutex_unlock(&server->lock);
961 if (server->connectionok) {
962 server->connectionok = 0;
964 } else if (elapsed < 1)
966 else if (elapsed < 60) {
967 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
969 } else if (elapsed < 100000) {
970 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
973 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
974 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
975 if (server->sock >= 0)
977 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
978 debug(DBG_ERR, "tlsconnect: connecttcp failed");
982 SSL_free(server->ssl);
983 server->ssl = SSL_new(server->conf->ssl_ctx);
984 SSL_set_fd(server->ssl, server->sock);
985 if (SSL_connect(server->ssl) <= 0)
987 cert = verifytlscert(server->ssl);
990 if (verifyconfcert(cert, server->conf)) {
996 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
997 gettimeofday(&server->lastconnecttry, NULL);
998 pthread_mutex_unlock(&server->lock);
1002 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1003 /* returns 0 on timeout, -1 on error and num if ok */
1004 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1005 int s, ndesc, cnt, len;
1006 fd_set readfds, writefds;
1007 struct timeval timer;
1009 s = SSL_get_fd(ssl);
1012 /* make socket non-blocking? */
1013 for (len = 0; len < num; len += cnt) {
1015 FD_SET(s, &readfds);
1018 timer.tv_sec = timeout;
1021 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1025 cnt = SSL_read(ssl, buf + len, num - len);
1027 switch (SSL_get_error(ssl, cnt)) {
1028 case SSL_ERROR_WANT_READ:
1029 case SSL_ERROR_WANT_WRITE:
1032 case SSL_ERROR_ZERO_RETURN:
1033 /* remote end sent close_notify, send one back */
1043 /* timeout in seconds, 0 means no timeout (blocking) */
1044 unsigned char *radtlsget(SSL *ssl, int timeout) {
1046 unsigned char buf[4], *rad;
1049 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1051 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1058 debug(DBG_ERR, "radtlsget: malloc failed");
1061 memcpy(rad, buf, 4);
1063 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1065 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1074 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1077 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1081 int clientradputudp(struct server *server, unsigned char *rad) {
1083 struct sockaddr_storage sa;
1084 struct sockaddr *sap;
1085 struct clsrvconf *conf = server->conf;
1086 in_port_t *port = NULL;
1090 if (*rad == RAD_Accounting_Request) {
1091 sap = (struct sockaddr *)&sa;
1092 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1094 sap = conf->addrinfo->ai_addr;
1096 switch (sap->sa_family) {
1098 port = &((struct sockaddr_in *)sap)->sin_port;
1101 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1107 if (*rad == RAD_Accounting_Request)
1108 *port = htons(ntohs(*port) + 1);
1110 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1111 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1115 debug(DBG_WARN, "clientradputudp: send failed");
1119 int clientradputtls(struct server *server, unsigned char *rad) {
1122 unsigned long error;
1123 struct timeval lastconnecttry;
1124 struct clsrvconf *conf = server->conf;
1127 lastconnecttry = server->lastconnecttry;
1128 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1129 while ((error = ERR_get_error()))
1130 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1131 if (server->dynamiclookuparg)
1133 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1134 lastconnecttry = server->lastconnecttry;
1137 server->connectionok = 1;
1138 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1142 int clientradput(struct server *server, unsigned char *rad) {
1143 switch (server->conf->type) {
1145 return clientradputudp(server, rad);
1147 return clientradputtls(server, rad);
1152 int radsign(unsigned char *rad, unsigned char *sec) {
1153 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1154 static unsigned char first = 1;
1155 static EVP_MD_CTX mdctx;
1156 unsigned int md_len;
1159 pthread_mutex_lock(&lock);
1161 EVP_MD_CTX_init(&mdctx);
1165 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1166 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1167 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1168 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1170 pthread_mutex_unlock(&lock);
1174 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1175 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1176 static unsigned char first = 1;
1177 static EVP_MD_CTX mdctx;
1178 unsigned char hash[EVP_MAX_MD_SIZE];
1182 pthread_mutex_lock(&lock);
1184 EVP_MD_CTX_init(&mdctx);
1190 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1191 EVP_DigestUpdate(&mdctx, rad, 4) &&
1192 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1193 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1194 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1195 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1197 !memcmp(hash, rad + 4, 16));
1198 pthread_mutex_unlock(&lock);
1202 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1203 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1204 static unsigned char first = 1;
1205 static HMAC_CTX hmacctx;
1206 unsigned int md_len;
1207 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1209 pthread_mutex_lock(&lock);
1211 HMAC_CTX_init(&hmacctx);
1215 memcpy(auth, authattr, 16);
1216 memset(authattr, 0, 16);
1218 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1219 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1220 HMAC_Final(&hmacctx, hash, &md_len);
1221 memcpy(authattr, auth, 16);
1223 debug(DBG_WARN, "message auth computation failed");
1224 pthread_mutex_unlock(&lock);
1228 if (memcmp(auth, hash, 16)) {
1229 debug(DBG_WARN, "message authenticator, wrong value");
1230 pthread_mutex_unlock(&lock);
1234 pthread_mutex_unlock(&lock);
1238 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1239 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1240 static unsigned char first = 1;
1241 static HMAC_CTX hmacctx;
1242 unsigned int md_len;
1247 pthread_mutex_lock(&lock);
1249 HMAC_CTX_init(&hmacctx);
1253 memset(authattrval, 0, 16);
1255 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1256 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1257 HMAC_Final(&hmacctx, authattrval, &md_len);
1259 debug(DBG_WARN, "message auth computation failed");
1260 pthread_mutex_unlock(&lock);
1264 pthread_mutex_unlock(&lock);
1268 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1269 while (length > 1) {
1270 if (ATTRTYPE(attrs) == type)
1272 length -= ATTRLEN(attrs);
1273 attrs += ATTRLEN(attrs);
1278 void freerqdata(struct request *rq) {
1279 if (rq->origusername)
1280 free(rq->origusername);
1285 void sendrq(struct server *to, struct request *rq) {
1289 pthread_mutex_lock(&to->newrq_mutex);
1290 /* might simplify if only try nextid, might be ok */
1291 for (i = to->nextid; i < MAX_REQUESTS; i++)
1292 if (!to->requests[i].buf)
1294 if (i == MAX_REQUESTS) {
1295 for (i = 0; i < to->nextid; i++)
1296 if (!to->requests[i].buf)
1298 if (i == to->nextid) {
1299 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1305 rq->buf[1] = (char)i;
1307 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1308 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1313 if (*rq->buf == RAD_Accounting_Request) {
1314 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1315 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1321 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1322 to->requests[i] = *rq;
1327 debug(DBG_DBG, "sendrq: signalling client writer");
1328 pthread_cond_signal(&to->newrq_cond);
1331 pthread_mutex_unlock(&to->newrq_mutex);
1334 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1335 struct reply *reply;
1338 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1340 debug(DBG_WARN, "sendreply: failed to sign message");
1344 reply = malloc(sizeof(struct reply));
1347 debug(DBG_ERR, "sendreply: malloc failed");
1350 memset(reply, 0, sizeof(struct reply));
1353 reply->tosa = *tosa;
1354 reply->toudpsock = toudpsock;
1356 pthread_mutex_lock(&to->replyq->mutex);
1358 first = list_first(to->replyq->replies) == NULL;
1360 if (!list_push(to->replyq->replies, reply)) {
1361 pthread_mutex_unlock(&to->replyq->mutex);
1364 debug(DBG_ERR, "sendreply: malloc failed");
1369 debug(DBG_DBG, "signalling server writer");
1370 pthread_cond_signal(&to->replyq->cond);
1372 pthread_mutex_unlock(&to->replyq->mutex);
1375 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1376 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1377 static unsigned char first = 1;
1378 static EVP_MD_CTX mdctx;
1379 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1380 unsigned int md_len;
1381 uint8_t i, offset = 0, out[128];
1383 pthread_mutex_lock(&lock);
1385 EVP_MD_CTX_init(&mdctx);
1391 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1392 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1393 !EVP_DigestUpdate(&mdctx, input, 16) ||
1394 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1396 pthread_mutex_unlock(&lock);
1399 for (i = 0; i < 16; i++)
1400 out[offset + i] = hash[i] ^ in[offset + i];
1401 input = out + offset - 16;
1406 memcpy(in, out, len);
1407 pthread_mutex_unlock(&lock);
1411 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1412 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1413 static unsigned char first = 1;
1414 static EVP_MD_CTX mdctx;
1415 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1416 unsigned int md_len;
1417 uint8_t i, offset = 0, out[128];
1419 pthread_mutex_lock(&lock);
1421 EVP_MD_CTX_init(&mdctx);
1427 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1428 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1429 !EVP_DigestUpdate(&mdctx, input, 16) ||
1430 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1432 pthread_mutex_unlock(&lock);
1435 for (i = 0; i < 16; i++)
1436 out[offset + i] = hash[i] ^ in[offset + i];
1437 input = in + offset;
1442 memcpy(in, out, len);
1443 pthread_mutex_unlock(&lock);
1447 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1448 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1449 static unsigned char first = 1;
1450 static EVP_MD_CTX mdctx;
1451 unsigned char hash[EVP_MAX_MD_SIZE];
1452 unsigned int md_len;
1455 pthread_mutex_lock(&lock);
1457 EVP_MD_CTX_init(&mdctx);
1462 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1463 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1464 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1467 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1468 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1469 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1470 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1471 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1472 pthread_mutex_unlock(&lock);
1477 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1480 for (i = 0; i < 16; i++)
1483 for (offset = 16; offset < len; offset += 16) {
1485 printf("text + offset - 16 c(%d): ", offset / 16);
1486 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1488 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1489 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1490 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1491 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1493 pthread_mutex_unlock(&lock);
1497 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1500 for (i = 0; i < 16; i++)
1501 text[offset + i] ^= hash[i];
1505 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1508 pthread_mutex_unlock(&lock);
1512 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1513 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1514 static unsigned char first = 1;
1515 static EVP_MD_CTX mdctx;
1516 unsigned char hash[EVP_MAX_MD_SIZE];
1517 unsigned int md_len;
1521 pthread_mutex_lock(&lock);
1523 EVP_MD_CTX_init(&mdctx);
1528 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1529 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1530 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1533 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1534 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1535 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1536 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1537 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1538 pthread_mutex_unlock(&lock);
1543 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1546 for (i = 0; i < 16; i++)
1547 plain[i] = text[i] ^ hash[i];
1549 for (offset = 16; offset < len; offset += 16) {
1551 printf("text + offset - 16 c(%d): ", offset / 16);
1552 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1554 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1555 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1556 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1557 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1559 pthread_mutex_unlock(&lock);
1563 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1566 for (i = 0; i < 16; i++)
1567 plain[offset + i] = text[offset + i] ^ hash[i];
1570 memcpy(text, plain, len);
1572 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1575 pthread_mutex_unlock(&lock);
1579 struct realm *id2realm(struct list *realmlist, char *id) {
1580 struct list_node *entry;
1581 struct realm *realm, *subrealm = NULL;
1583 /* need to do locking for subrealms and check subrealm timers */
1584 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1585 realm = (struct realm *)entry->data;
1586 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1587 pthread_mutex_lock(&realm->subrealms_mutex);
1588 if (realm->subrealms)
1589 subrealm = id2realm(realm->subrealms, id);
1590 pthread_mutex_unlock(&realm->subrealms_mutex);
1591 return subrealm ? subrealm : realm;
1597 /* helper function, only used by removeserversubrealms() */
1598 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1599 struct list_node *entry;
1600 struct realm *realm;
1602 for (entry = list_first(realmlist); entry;) {
1603 realm = (struct realm *)entry->data;
1604 entry = list_next(entry);
1605 if (realm->srvconfs) {
1606 list_removedata(realm->srvconfs, srv);
1607 if (!list_first(realm->srvconfs)) {
1608 list_destroy(realm->srvconfs);
1609 realm->srvconfs = NULL;
1612 if (realm->accsrvconfs) {
1613 list_removedata(realm->accsrvconfs, srv);
1614 if (!list_first(realm->accsrvconfs)) {
1615 list_destroy(realm->accsrvconfs);
1616 realm->accsrvconfs = NULL;
1620 /* remove subrealm if no servers */
1621 if (!realm->srvconfs && !realm->accsrvconfs) {
1622 list_removedata(realmlist, realm);
1628 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1629 struct list_node *entry;
1630 struct realm *realm;
1632 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1633 realm = (struct realm *)entry->data;
1634 pthread_mutex_lock(&realm->subrealms_mutex);
1635 if (realm->subrealms) {
1636 _internal_removeserversubrealms(realm->subrealms, srv);
1637 if (!list_first(realm->subrealms)) {
1638 list_destroy(realm->subrealms);
1639 realm->subrealms = NULL;
1642 pthread_mutex_unlock(&realm->subrealms_mutex);
1646 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1647 struct request *rq = to->requests, *end;
1649 pthread_mutex_lock(&to->newrq_mutex);
1650 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1651 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1653 pthread_mutex_unlock(&to->newrq_mutex);
1658 int attrvalidate(unsigned char *attrs, int length) {
1659 while (length > 1) {
1660 if (ATTRLEN(attrs) < 2) {
1661 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1664 length -= ATTRLEN(attrs);
1666 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1669 attrs += ATTRLEN(attrs);
1672 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1676 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1677 if (len < 16 || len > 128 || len % 16) {
1678 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1682 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1683 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1687 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1689 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1690 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1696 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1699 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1700 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1703 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1704 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1710 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1711 char *oldsecret, char *newsecret) {
1712 unsigned char *attr;
1714 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1715 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1716 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1722 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1726 for (; attrs[0]; attrs += 2)
1727 if (attrs[0] == vendor && attrs[1] == subattr)
1732 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1733 uint8_t alen, sublen, rmlen = 0;
1734 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1737 if (!removevendorattrs)
1740 while (*removevendorattrs && *removevendorattrs != vendor)
1741 removevendorattrs += 2;
1742 if (!*removevendorattrs)
1745 alen = ATTRLEN(attrs);
1747 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1748 /* remove entire vendor attribute */
1749 memmove(attrs, attrs + alen, length - alen);
1754 subattrs = ATTRVAL(attrs) + 4;
1756 if (!attrvalidate(subattrs, sublen)) {
1757 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1762 while (sublen > 1) {
1763 alen = ATTRLEN(subattrs);
1766 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1767 memmove(subattrs, subattrs + alen, length);
1773 ATTRLEN(attrs) -= rmlen;
1777 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1778 uint8_t *attrs, alen;
1779 uint16_t len, rmlen = 0;
1781 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1784 len = RADLEN(buf) - 20;
1787 alen = ATTRLEN(attrs);
1789 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1790 memmove(attrs, attrs + alen, len);
1792 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1793 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1798 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1801 /* returns a pointer to the resized attribute value */
1802 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1803 uint8_t *attrs, *attr, vallen;
1807 len = RADLEN(*buf) - 20;
1810 attr = attrget(attrs, len, type);
1814 vallen = ATTRVALLEN(attr);
1815 if (vallen == newvallen)
1818 len += newvallen - vallen;
1819 if (newvallen > vallen) {
1820 new = realloc(*buf, len + 20);
1822 debug(DBG_ERR, "resizeattr: malloc failed");
1831 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1832 attr[1] = newvallen + 2;
1833 ((uint16_t *)*buf)[1] = htons(len + 20);
1837 int rewriteusername(struct request *rq, char *in) {
1838 size_t nmatch = 10, reslen = 0, start = 0;
1839 regmatch_t pmatch[10], *pfield;
1841 unsigned char *result;
1842 char *out = rq->from->conf->rewriteattrreplacement;
1844 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1845 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1849 rq->origusername = stringcopy(in, 0);
1850 if (!rq->origusername)
1853 for (i = start; out[i]; i++) {
1854 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1855 pfield = &pmatch[out[i + 1] - '0'];
1856 if (pfield->rm_so >= 0) {
1857 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1863 reslen += i - start;
1865 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1871 for (i = start; out[i]; i++) {
1872 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1873 pfield = &pmatch[out[i + 1] - '0'];
1874 if (pfield->rm_so >= 0) {
1875 memcpy(result + reslen, out + start, i - start);
1876 reslen += i - start;
1877 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1878 reslen += pfield->rm_eo - pfield->rm_so;
1885 memcpy(result + reslen, out + start, i - start);
1886 reslen += i - start;
1887 memcpy(in, result, reslen);
1892 const char *radmsgtype2string(uint8_t code) {
1893 static const char *rad_msg_names[] = {
1894 "", "Access-Request", "Access-Accept", "Access-Reject",
1895 "Accounting-Request", "Accounting-Response", "", "",
1896 "", "", "", "Access-Challenge",
1897 "Status-Server", "Status-Client"
1899 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1902 void char2hex(char *h, unsigned char c) {
1903 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1904 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1905 h[0] = hexdigits[c / 16];
1906 h[1] = hexdigits[c % 16];
1910 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1914 if (!attr || len == 1) {
1919 l = ATTRVALLEN(attr);
1920 s = (char *)ATTRVAL(attr);
1923 for (i = 0; i < l; i++) {
1924 if (s[i] > 31 && s[i] < 127) {
1926 if (d - ascii == len - 1)
1929 if (d - ascii > len - 4)
1934 if (d - ascii == len - 1)
1942 void acclog(unsigned char *attrs, int length, char *host) {
1943 unsigned char *attr;
1946 attr = attrget(attrs, length, RAD_Attr_User_Name);
1948 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1951 radattr2ascii(username, sizeof(username), attr);
1952 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1955 void respondaccounting(struct request *rq) {
1956 unsigned char *resp;
1960 debug(DBG_ERR, "respondaccounting: malloc failed");
1963 memcpy(resp, rq->buf, 20);
1964 resp[0] = RAD_Accounting_Response;
1967 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1968 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1971 void respondstatusserver(struct request *rq) {
1972 unsigned char *resp;
1976 debug(DBG_ERR, "respondstatusserver: malloc failed");
1979 memcpy(resp, rq->buf, 20);
1980 resp[0] = RAD_Access_Accept;
1983 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1984 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1987 void respondreject(struct request *rq, char *message) {
1988 unsigned char *resp;
1991 if (message && *message)
1992 len += 2 + strlen(message);
1996 debug(DBG_ERR, "respondreject: malloc failed");
1999 memcpy(resp, rq->buf, 20);
2000 resp[0] = RAD_Access_Reject;
2001 *(uint16_t *)(resp + 2) = htons(len);
2002 if (message && *message) {
2003 resp[20] = RAD_Attr_Reply_Message;
2004 resp[21] = len - 20;
2005 memcpy(resp + 22, message, len - 22);
2007 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2010 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2011 struct list_node *entry;
2012 struct clsrvconf *server, *best = NULL, *first = NULL;
2014 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2015 server = (struct clsrvconf *)entry->data;
2016 if (!server->servers)
2020 if (!server->servers->connectionok)
2022 if (!server->servers->lostrqs)
2028 if (server->servers->lostrqs < best->servers->lostrqs)
2031 return best ? best : first;
2034 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2035 struct clsrvconf *srvconf;
2037 *realm = id2realm(realms, id);
2040 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2041 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2044 if (!acc && !srvconf->servers)
2045 adddynamicrealmserver(*realm, srvconf, id);
2046 return srvconf->servers;
2049 void radsrv(struct request *rq) {
2050 uint8_t code, id, *auth, *attrs, *attr;
2052 struct server *to = NULL;
2053 char username[254], userascii[760];
2054 unsigned char newauth[16];
2055 struct realm *realm = NULL;
2057 code = *(uint8_t *)rq->buf;
2058 id = *(uint8_t *)(rq->buf + 1);
2059 len = RADLEN(rq->buf);
2060 auth = (uint8_t *)(rq->buf + 4);
2062 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2064 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2065 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2070 attrs = rq->buf + 20;
2072 if (!attrvalidate(attrs, len)) {
2073 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2077 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2078 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2079 debug(DBG_WARN, "radsrv: message authentication failed");
2083 if (code == RAD_Status_Server) {
2084 respondstatusserver(rq);
2088 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2090 if (code == RAD_Accounting_Request) {
2091 memset(newauth, 0, 16);
2092 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2093 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2098 if (rq->from->conf->rewrite) {
2099 dorewrite(rq->buf, rq->from->conf->rewrite);
2100 len = RADLEN(rq->buf) - 20;
2103 attr = attrget(attrs, len, RAD_Attr_User_Name);
2105 if (code == RAD_Accounting_Request) {
2106 acclog(attrs, len, rq->from->conf->host);
2107 respondaccounting(rq);
2109 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2112 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2113 username[ATTRVALLEN(attr)] = '\0';
2114 radattr2ascii(userascii, sizeof(userascii), attr);
2116 if (rq->from->conf->rewriteattrregex) {
2117 if (!rewriteusername(rq, username)) {
2118 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2121 len = RADLEN(rq->buf) - 20;
2122 auth = (uint8_t *)(rq->buf + 4);
2123 attrs = rq->buf + 20;
2126 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2128 to = findserver(&realm, username, code == RAD_Accounting_Request);
2130 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2134 if (realm->message && code == RAD_Access_Request) {
2135 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2136 respondreject(rq, realm->message);
2137 } else if (realm->accresp && code == RAD_Accounting_Request) {
2138 acclog(attrs, len, rq->from->conf->host);
2139 respondaccounting(rq);
2144 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2145 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2146 rq->from->conf->name, to->conf->name);
2150 if (rqinqueue(to, rq->from, id, code)) {
2151 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2152 radmsgtype2string(code), rq->from->conf->host, id);
2156 if (code != RAD_Accounting_Request) {
2157 if (!RAND_bytes(newauth, 16)) {
2158 debug(DBG_WARN, "radsrv: failed to generate random auth");
2164 printfchars(NULL, "auth", "%02x ", auth, 16);
2167 attr = attrget(attrs, len, RAD_Attr_User_Password);
2169 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2170 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2174 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2176 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2177 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2182 memcpy(rq->origauth, auth, 16);
2183 memcpy(auth, newauth, 16);
2191 int replyh(struct server *server, unsigned char *buf) {
2192 struct client *from;
2195 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2196 struct sockaddr_storage fromsa;
2197 char tmp[760], stationid[760];
2199 server->connectionok = 1;
2200 server->lostrqs = 0;
2202 i = buf[1]; /* i is the id */
2204 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2205 && *buf != RAD_Accounting_Response) {
2206 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2209 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2211 rq = server->requests + i;
2213 pthread_mutex_lock(&server->newrq_mutex);
2214 if (!rq->buf || !rq->tries) {
2215 pthread_mutex_unlock(&server->newrq_mutex);
2216 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2221 pthread_mutex_unlock(&server->newrq_mutex);
2222 debug(DBG_INFO, "replyh: already received, ignoring reply");
2226 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2227 pthread_mutex_unlock(&server->newrq_mutex);
2228 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2232 len = RADLEN(buf) - 20;
2235 if (!attrvalidate(attrs, len)) {
2236 pthread_mutex_unlock(&server->newrq_mutex);
2237 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2241 /* Message Authenticator */
2242 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2244 if (ATTRVALLEN(messageauth) != 16) {
2245 pthread_mutex_unlock(&server->newrq_mutex);
2246 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2249 memcpy(tmp, buf + 4, 16);
2250 memcpy(buf + 4, rq->buf + 4, 16);
2251 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2252 pthread_mutex_unlock(&server->newrq_mutex);
2253 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2256 memcpy(buf + 4, tmp, 16);
2257 debug(DBG_DBG, "replyh: message auth ok");
2260 if (*rq->buf == RAD_Status_Server) {
2262 pthread_mutex_unlock(&server->newrq_mutex);
2263 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2267 gettimeofday(&server->lastreply, NULL);
2271 pthread_mutex_unlock(&server->newrq_mutex);
2272 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2276 if (server->conf->rewrite) {
2277 dorewrite(buf, server->conf->rewrite);
2278 len = RADLEN(buf) - 20;
2282 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2283 if (ATTRVALLEN(attr) <= 4)
2286 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2289 sublen = ATTRVALLEN(attr) - 4;
2290 subattrs = ATTRVAL(attr) + 4;
2291 if (!attrvalidate(subattrs, sublen) ||
2292 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2293 rq, server->conf->secret, from->conf->secret) ||
2294 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2295 rq, server->conf->secret, from->conf->secret))
2299 pthread_mutex_unlock(&server->newrq_mutex);
2300 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2304 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2305 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2307 radattr2ascii(tmp, sizeof(tmp), attr);
2308 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2310 radattr2ascii(stationid, sizeof(stationid), attr);
2311 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2312 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2314 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2318 buf[1] = (char)rq->origid;
2319 memcpy(buf + 4, rq->origauth, 16);
2321 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2324 if (rq->origusername) {
2325 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2327 pthread_mutex_unlock(&server->newrq_mutex);
2328 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2331 memcpy(username, rq->origusername, strlen(rq->origusername));
2332 len = RADLEN(buf) - 20;
2335 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2339 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2340 pthread_mutex_unlock(&server->newrq_mutex);
2341 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2344 debug(DBG_DBG, "replyh: computed messageauthattr");
2347 fromsa = rq->fromsa; /* only needed for UDP */
2348 /* once we set received = 1, rq may be reused */
2351 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2352 sendreply(from, buf, &fromsa, rq->fromudpsock);
2353 pthread_mutex_unlock(&server->newrq_mutex);
2357 void *udpclientrd(void *arg) {
2358 struct server *server;
2360 int *s = (int *)arg;
2364 buf = radudpget(*s, NULL, &server, NULL);
2365 if (!replyh(server, buf))
2370 void *tlsclientrd(void *arg) {
2371 struct server *server = (struct server *)arg;
2373 struct timeval now, lastconnecttry;
2376 /* yes, lastconnecttry is really necessary */
2377 lastconnecttry = server->lastconnecttry;
2378 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2380 if (server->dynamiclookuparg)
2382 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2386 if (!replyh(server, buf))
2388 if (server->dynamiclookuparg) {
2389 gettimeofday(&now, NULL);
2390 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2391 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2396 server->clientrdgone = 1;
2400 /* code for removing state not finished */
2401 void *clientwr(void *arg) {
2402 struct server *server = (struct server *)arg;
2404 pthread_t tlsclientrdth;
2405 int i, dynconffail = 0;
2407 struct timeval now, lastsend;
2408 struct timespec timeout;
2409 struct request statsrvrq;
2410 unsigned char statsrvbuf[38];
2411 struct clsrvconf *conf;
2413 conf = server->conf;
2415 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2420 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2421 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2425 memset(&timeout, 0, sizeof(struct timespec));
2427 if (conf->statusserver) {
2428 memset(&statsrvrq, 0, sizeof(struct request));
2429 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2430 statsrvbuf[0] = RAD_Status_Server;
2432 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2433 statsrvbuf[21] = 18;
2434 gettimeofday(&lastsend, NULL);
2437 if (conf->type == RAD_UDP) {
2438 server->connectionok = 1;
2440 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2442 server->connectionok = 1;
2443 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2444 debug(DBG_ERR, "clientwr: pthread_create failed");
2450 pthread_mutex_lock(&server->newrq_mutex);
2451 if (!server->newrq) {
2452 gettimeofday(&now, NULL);
2453 /* random 0-7 seconds */
2454 RAND_bytes(&rnd, 1);
2456 if (conf->statusserver) {
2457 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2458 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2460 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2461 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2464 if (timeout.tv_sec > now.tv_sec)
2465 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2467 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2470 if (server->newrq) {
2471 debug(DBG_DBG, "clientwr: got new request");
2476 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2478 pthread_mutex_unlock(&server->newrq_mutex);
2480 for (i = 0; i < MAX_REQUESTS; i++) {
2481 if (server->clientrdgone) {
2482 pthread_join(tlsclientrdth, NULL);
2485 pthread_mutex_lock(&server->newrq_mutex);
2486 while (i < MAX_REQUESTS && !server->requests[i].buf)
2488 if (i == MAX_REQUESTS) {
2489 pthread_mutex_unlock(&server->newrq_mutex);
2492 rq = server->requests + i;
2495 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2497 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2499 /* setting this to NULL means that it can be reused */
2502 pthread_mutex_unlock(&server->newrq_mutex);
2506 gettimeofday(&now, NULL);
2507 if (now.tv_sec < rq->expiry.tv_sec) {
2508 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2509 timeout.tv_sec = rq->expiry.tv_sec;
2510 pthread_mutex_unlock(&server->newrq_mutex);
2514 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2515 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2516 if (conf->statusserver) {
2517 if (*rq->buf == RAD_Status_Server) {
2518 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2519 if (server->lostrqs < 255)
2523 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2524 if (server->lostrqs < 255)
2528 /* setting this to NULL means that it can be reused */
2530 pthread_mutex_unlock(&server->newrq_mutex);
2533 pthread_mutex_unlock(&server->newrq_mutex);
2535 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2536 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2537 timeout.tv_sec = rq->expiry.tv_sec;
2539 clientradput(server, server->requests[i].buf);
2540 gettimeofday(&lastsend, NULL);
2542 if (conf->statusserver) {
2543 gettimeofday(&now, NULL);
2544 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2545 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2546 debug(DBG_WARN, "clientwr: failed to generate random auth");
2549 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2550 if (!statsrvrq.buf) {
2551 debug(DBG_ERR, "clientwr: malloc failed");
2554 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2555 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2556 lastsend.tv_sec = now.tv_sec;
2557 sendrq(server, &statsrvrq);
2562 conf->servers = NULL;
2563 if (server->dynamiclookuparg) {
2564 removeserversubrealms(realms, conf);
2568 freeclsrvconf(conf);
2570 freeserver(server, 1);
2574 void *udpserverwr(void *arg) {
2575 struct replyq *replyq = udp_server_replyq;
2576 struct reply *reply;
2579 pthread_mutex_lock(&replyq->mutex);
2580 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2581 debug(DBG_DBG, "udp server writer, waiting for signal");
2582 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2583 debug(DBG_DBG, "udp server writer, got signal");
2585 pthread_mutex_unlock(&replyq->mutex);
2587 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2588 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2589 debug(DBG_WARN, "sendudp: send failed");
2595 void *udpserverrd(void *arg) {
2597 struct listenerarg *larg = (struct listenerarg *)arg;
2600 memset(&rq, 0, sizeof(struct request));
2601 rq.buf = radudpget(larg->s, &rq.from, NULL, &rq.fromsa);
2602 if (larg->acconly && *rq.buf != RAD_Accounting_Request) {
2603 debug(DBG_INFO, "udpserverrd: got something other than accounting-request, ignoring");
2607 rq.fromudpsock = larg->s;
2612 void *tlsserverwr(void *arg) {
2614 unsigned long error;
2615 struct client *client = (struct client *)arg;
2616 struct replyq *replyq;
2617 struct reply *reply;
2619 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2620 replyq = client->replyq;
2622 pthread_mutex_lock(&replyq->mutex);
2623 while (!list_first(replyq->replies)) {
2625 debug(DBG_DBG, "tls server writer, waiting for signal");
2626 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2627 debug(DBG_DBG, "tls server writer, got signal");
2630 /* ssl might have changed while waiting */
2631 pthread_mutex_unlock(&replyq->mutex);
2632 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2636 reply = (struct reply *)list_shift(replyq->replies);
2637 pthread_mutex_unlock(&replyq->mutex);
2638 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2640 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2641 cnt, RADLEN(reply->buf));
2643 while ((error = ERR_get_error()))
2644 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2650 void tlsserverrd(struct client *client) {
2652 pthread_t tlsserverwrth;
2654 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2656 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2657 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2662 memset(&rq, 0, sizeof(struct request));
2663 rq.buf = radtlsget(client->ssl, 0);
2666 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2671 debug(DBG_ERR, "tlsserverrd: connection lost");
2672 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2674 pthread_mutex_lock(&client->replyq->mutex);
2675 pthread_cond_signal(&client->replyq->cond);
2676 pthread_mutex_unlock(&client->replyq->mutex);
2677 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2678 pthread_join(tlsserverwrth, NULL);
2679 removeclientrqs(client);
2680 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2683 void *tlsservernew(void *arg) {
2685 struct sockaddr_storage from;
2686 size_t fromlen = sizeof(from);
2687 struct clsrvconf *conf;
2688 struct list_node *cur = NULL;
2691 unsigned long error;
2692 struct client *client;
2695 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2696 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2699 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2701 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2703 ssl = SSL_new(conf->ssl_ctx);
2706 if (SSL_accept(ssl) <= 0) {
2707 while ((error = ERR_get_error()))
2708 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2709 debug(DBG_ERR, "SSL_accept failed");
2712 cert = verifytlscert(ssl);
2718 if (verifyconfcert(cert, conf)) {
2720 client = addclient(conf);
2723 tlsserverrd(client);
2724 removeclient(client);
2726 debug(DBG_WARN, "Failed to create new client instance");
2729 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2731 debug(DBG_WARN, "ignoring request, no matching TLS client");
2737 shutdown(s, SHUT_RDWR);
2742 void *tlslistener(void *arg) {
2743 pthread_t tlsserverth;
2745 struct sockaddr_storage from;
2746 size_t fromlen = sizeof(from);
2747 struct listenerarg *larg = (struct listenerarg *)arg;
2752 s = accept(larg->s, (struct sockaddr *)&from, &fromlen);
2754 debug(DBG_WARN, "accept failed");
2757 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2758 debug(DBG_ERR, "tlslistener: pthread_create failed");
2759 shutdown(s, SHUT_RDWR);
2763 pthread_detach(tlsserverth);
2768 void createlistener(uint8_t type, char *arg, uint8_t acconly) {
2770 struct clsrvconf *listenres;
2771 struct addrinfo *res;
2772 struct listenerarg *larg = NULL;
2775 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2777 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2779 for (res = listenres->addrinfo; res; res = res->ai_next) {
2780 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2782 debug(DBG_WARN, "createlistener: socket failed");
2785 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2787 if (res->ai_family == AF_INET6)
2788 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2790 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2791 debug(DBG_WARN, "createlistener: bind failed");
2797 larg = malloc(sizeof(struct listenerarg));
2799 debugx(1, DBG_ERR, "malloc failed");
2801 larg->acconly = acconly;
2802 if (pthread_create(&th, NULL, type == RAD_UDP ? udpserverrd : tlslistener, (void *)larg))
2803 debugx(1, DBG_ERR, "pthread_create failed");
2807 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2809 debug(DBG_WARN, "createlistener: listening for %s%s on %s:%s",
2810 type == RAD_UDP ? "UDP" : "TCP", acconly ? " accounting" : "",
2811 listenres->host ? listenres->host : "*", listenres->port);
2812 freeclsrvres(listenres);
2815 void createlisteners(uint8_t type, char **args, uint8_t acconly) {
2819 for (i = 0; args[i]; i++)
2820 createlistener(type, args[i], acconly);
2822 createlistener(type, NULL, acconly);
2825 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2828 STACK_OF(X509_NAME) *calist;
2831 unsigned long error;
2833 if (!certfile || !certkeyfile)
2834 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2836 if (!cacertfile && !cacertpath)
2837 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2840 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2841 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2842 for (i = 0; i < CRYPTO_num_locks(); i++) {
2843 ssl_lock_count[i] = 0;
2844 pthread_mutex_init(&ssl_locks[i], NULL);
2846 CRYPTO_set_id_callback(ssl_thread_id);
2847 CRYPTO_set_locking_callback(ssl_locking_callback);
2849 SSL_load_error_strings();
2852 while (!RAND_status()) {
2853 time_t t = time(NULL);
2854 pid_t pid = getpid();
2855 RAND_seed((unsigned char *)&t, sizeof(time_t));
2856 RAND_seed((unsigned char *)&pid, sizeof(pid));
2859 ctx = SSL_CTX_new(TLSv1_method());
2861 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2862 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2864 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2865 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2866 !SSL_CTX_check_private_key(ctx) ||
2867 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2868 while ((error = ERR_get_error()))
2869 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2870 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2873 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2874 if (!cacertfile || calist) {
2877 calist = sk_X509_NAME_new_null();
2878 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2879 sk_X509_NAME_free(calist);
2885 while ((error = ERR_get_error()))
2886 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2887 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2889 SSL_CTX_set_client_CA_list(ctx, calist);
2891 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2892 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2895 x509_s = SSL_CTX_get_cert_store(ctx);
2896 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2899 new = malloc(sizeof(struct tls));
2900 if (!new || !list_push(tlsconfs, new))
2901 debugx(1, DBG_ERR, "malloc failed");
2903 memset(new, 0, sizeof(struct tls));
2904 new->name = stringcopy(value, 0);
2906 debugx(1, DBG_ERR, "malloc failed");
2908 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2911 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2912 struct list_node *entry;
2913 struct tls *t, *t1 = NULL, *t2 = NULL;
2915 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2916 t = (struct tls *)entry->data;
2917 if (!strcasecmp(t->name, alt1)) {
2921 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2931 struct list *addsrvconfs(char *value, char **names) {
2932 struct list *conflist;
2934 struct list_node *entry;
2935 struct clsrvconf *conf = NULL;
2937 if (!names || !*names)
2940 conflist = list_create();
2942 debug(DBG_ERR, "malloc failed");
2946 for (n = 0; names[n]; n++) {
2947 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2948 conf = (struct clsrvconf *)entry->data;
2949 if (!strcasecmp(names[n], conf->name))
2953 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2954 list_destroy(conflist);
2957 if (!list_push(conflist, conf)) {
2958 debug(DBG_ERR, "malloc failed");
2959 list_destroy(conflist);
2962 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2967 void freerealm(struct realm *realm) {
2971 free(realm->message);
2972 regfree(&realm->regex);
2973 pthread_mutex_destroy(&realm->subrealms_mutex);
2974 if (realm->subrealms)
2975 list_destroy(realm->subrealms);
2976 if (realm->srvconfs) {
2977 /* emptying list without freeing data */
2978 while (list_shift(realm->srvconfs));
2979 list_destroy(realm->srvconfs);
2981 if (realm->accsrvconfs) {
2982 /* emptying list without freeing data */
2983 while (list_shift(realm->accsrvconfs));
2984 list_destroy(realm->accsrvconfs);
2989 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2991 struct realm *realm;
2992 char *s, *regex = NULL;
2994 if (*value == '/') {
2995 /* regexp, remove optional trailing / if present */
2996 if (value[strlen(value) - 1] == '/')
2997 value[strlen(value) - 1] = '\0';
2999 /* not a regexp, let us make it one */
3000 if (*value == '*' && !value[1])
3001 regex = stringcopy(".*", 0);
3003 for (n = 0, s = value; *s;)
3006 regex = malloc(strlen(value) + n + 3);
3009 for (n = 1, s = value; *s; s++) {
3019 debug(DBG_ERR, "malloc failed");
3023 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3026 realm = malloc(sizeof(struct realm));
3028 debug(DBG_ERR, "malloc failed");
3031 memset(realm, 0, sizeof(struct realm));
3033 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3034 debug(DBG_ERR, "mutex init failed");
3040 realm->name = stringcopy(value, 0);
3042 debug(DBG_ERR, "malloc failed");
3045 if (message && strlen(message) > 253) {
3046 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3049 realm->message = message;
3050 realm->accresp = accresp;
3052 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3053 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3057 if (servers && *servers) {
3058 realm->srvconfs = addsrvconfs(value, servers);
3059 if (!realm->srvconfs)
3063 if (accservers && *accservers) {
3064 realm->accsrvconfs = addsrvconfs(value, accservers);
3065 if (!realm->accsrvconfs)
3069 if (!list_push(realmlist, realm)) {
3070 debug(DBG_ERR, "malloc failed");
3071 pthread_mutex_destroy(&realm->subrealms_mutex);
3075 debug(DBG_DBG, "addrealm: added realm %s", value);
3085 for (n = 0; servers[n]; n++)
3090 for (n = 0; accservers[n]; n++)
3091 free(accservers[n]);
3097 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3098 struct clsrvconf *srvconf;
3099 struct realm *newrealm = NULL;
3100 char *realmname, *s;
3103 if (!conf->dynamiclookupcommand)
3106 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3107 realmname = strrchr(id, '@');
3113 for (s = realmname; *s; s++)
3114 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3117 pthread_mutex_lock(&realm->subrealms_mutex);
3118 /* exit if we now already got a matching subrealm */
3119 if (id2realm(realm->subrealms, id))
3121 srvconf = malloc(sizeof(struct clsrvconf));
3123 debug(DBG_ERR, "malloc failed");
3127 if (!addserver(srvconf))
3130 if (!realm->subrealms)
3131 realm->subrealms = list_create();
3132 if (!realm->subrealms)
3134 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3138 /* add server and accserver to newrealm */
3139 newrealm->srvconfs = list_create();
3140 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3141 debug(DBG_ERR, "malloc failed");
3144 newrealm->accsrvconfs = list_create();
3145 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3146 debug(DBG_ERR, "malloc failed");
3150 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3152 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3153 debug(DBG_ERR, "pthread_create failed");
3156 pthread_detach(clientth);
3161 list_removedata(realm->subrealms, newrealm);
3162 freerealm(newrealm);
3163 if (!list_first(realm->subrealms)) {
3164 list_destroy(realm->subrealms);
3165 realm->subrealms = NULL;
3168 freeserver(srvconf->servers, 1);
3170 debug(DBG_ERR, "failed to create dynamic server");
3173 pthread_mutex_unlock(&realm->subrealms_mutex);
3176 int dynamicconfig(struct server *server) {
3177 int ok, fd[2], status;
3179 struct clsrvconf *conf = server->conf;
3180 struct gconffile *cf = NULL;
3182 /* for now we only learn hostname/address */
3183 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3186 debug(DBG_ERR, "dynamicconfig: pipe error");
3191 debug(DBG_ERR, "dynamicconfig: fork error");
3195 } else if (pid == 0) {
3198 if (fd[1] != STDOUT_FILENO) {
3199 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3200 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3203 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3204 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3208 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3209 ok = getgenericconfig(&cf, NULL,
3210 "Server", CONF_CBK, confserver_cb, (void *)conf,
3215 if (waitpid(pid, &status, 0) < 0) {
3216 debug(DBG_ERR, "dynamicconfig: wait error");
3221 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3229 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3233 int addmatchcertattr(struct clsrvconf *conf) {
3237 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3238 r = &conf->certcnregex;
3239 v = conf->matchcertattr + 4;
3240 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3241 r = &conf->certuriregex;
3242 v = conf->matchcertattr + 20;
3247 /* regexp, remove optional trailing / if present */
3248 if (v[strlen(v) - 1] == '/')
3249 v[strlen(v) - 1] = '\0';
3253 *r = malloc(sizeof(regex_t));
3255 debug(DBG_ERR, "malloc failed");
3258 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3261 debug(DBG_ERR, "failed to compile regular expression %s", v);
3267 int addrewriteattr(struct clsrvconf *conf) {
3270 v = conf->rewriteattr + 11;
3271 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3273 /* regexp, remove optional trailing / if present */
3274 if (v[strlen(v) - 1] == '/')
3275 v[strlen(v) - 1] = '\0';
3283 conf->rewriteattrregex = malloc(sizeof(regex_t));
3284 if (!conf->rewriteattrregex) {
3285 debug(DBG_ERR, "malloc failed");
3289 conf->rewriteattrreplacement = stringcopy(w, 0);
3290 if (!conf->rewriteattrreplacement) {
3291 free(conf->rewriteattrregex);
3292 conf->rewriteattrregex = NULL;
3296 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3297 free(conf->rewriteattrregex);
3298 conf->rewriteattrregex = NULL;
3299 free(conf->rewriteattrreplacement);
3300 conf->rewriteattrreplacement = NULL;
3301 debug(DBG_ERR, "failed to compile regular expression %s", v);
3308 /* should accept both names and numeric values, only numeric right now */
3309 uint8_t attrname2val(char *attrname) {
3312 val = atoi(attrname);
3313 return val > 0 && val < 256 ? val : 0;
3316 /* should accept both names and numeric values, only numeric right now */
3317 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3320 *vendor = atoi(attrname);
3321 s = strchr(attrname, ':');
3326 *type = atoi(s + 1);
3327 return *type >= 0 && *type < 256;
3330 struct rewrite *getrewrite(char *alt1, char *alt2) {
3331 struct list_node *entry;
3332 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3334 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3335 r = (struct rewriteconf *)entry->data;
3336 if (!strcasecmp(r->name, alt1)) {
3340 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3350 void addrewrite(char *value, char **attrs, char **vattrs) {
3351 struct rewriteconf *new;
3352 struct rewrite *rewrite = NULL;
3355 uint32_t *p, *va = NULL;
3359 for (; attrs[n]; n++);
3360 a = malloc((n + 1) * sizeof(uint8_t));
3362 debugx(1, DBG_ERR, "malloc failed");
3364 for (i = 0; i < n; i++) {
3365 if (!(a[i] = attrname2val(attrs[i])))
3366 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3375 for (; vattrs[n]; n++);
3376 va = malloc((2 * n + 1) * sizeof(uint32_t));
3378 debugx(1, DBG_ERR, "malloc failed");
3380 for (p = va, i = 0; i < n; i++, p += 2) {
3381 if (!vattrname2val(vattrs[i], p, p + 1))
3382 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3390 rewrite = malloc(sizeof(struct rewrite));
3392 debugx(1, DBG_ERR, "malloc failed");
3393 rewrite->removeattrs = a;
3394 rewrite->removevendorattrs = va;
3397 new = malloc(sizeof(struct rewriteconf));
3398 if (!new || !list_push(rewriteconfs, new))
3399 debugx(1, DBG_ERR, "malloc failed");
3401 memset(new, 0, sizeof(struct rewriteconf));
3402 new->name = stringcopy(value, 0);
3404 debugx(1, DBG_ERR, "malloc failed");
3406 new->rewrite = rewrite;
3407 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3410 void freeclsrvconf(struct clsrvconf *conf) {
3416 free(conf->matchcertattr);
3417 if (conf->certcnregex)
3418 regfree(conf->certcnregex);
3419 if (conf->certuriregex)
3420 regfree(conf->certuriregex);
3421 free(conf->confrewrite);
3422 free(conf->rewriteattr);
3423 if (conf->rewriteattrregex)
3424 regfree(conf->rewriteattrregex);
3425 free(conf->rewriteattrreplacement);
3426 free(conf->dynamiclookupcommand);
3427 free(conf->rewrite);
3429 freeaddrinfo(conf->addrinfo);
3430 /* not touching ssl_ctx, clients and servers */
3434 int mergeconfstring(char **dst, char **src) {
3443 t = stringcopy(*dst, 0);
3445 debug(DBG_ERR, "malloc failed");
3453 /* assumes dst is a shallow copy */
3454 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3455 if (!mergeconfstring(&dst->name, &src->name) ||
3456 !mergeconfstring(&dst->host, &src->host) ||
3457 !mergeconfstring(&dst->port, &src->port) ||
3458 !mergeconfstring(&dst->secret, &src->secret) ||
3459 !mergeconfstring(&dst->tls, &src->tls) ||
3460 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3461 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3462 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3465 dst->pdef = src->pdef;
3466 dst->statusserver = src->statusserver;
3467 dst->certnamecheck = src->certnamecheck;
3468 if (src->retryinterval != 255)
3469 dst->retryinterval = src->retryinterval;
3470 if (src->retrycount != 255)
3471 dst->retrycount = src->retrycount;
3475 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3476 struct clsrvconf *conf;
3477 char *conftype = NULL;
3479 debug(DBG_DBG, "confclient_cb called for %s", block);
3481 conf = malloc(sizeof(struct clsrvconf));
3482 if (!conf || !list_push(clconfs, conf))
3483 debugx(1, DBG_ERR, "malloc failed");
3484 memset(conf, 0, sizeof(struct clsrvconf));
3485 conf->certnamecheck = 1;
3487 if (!getgenericconfig(cf, block,
3488 "type", CONF_STR, &conftype,
3489 "host", CONF_STR, &conf->host,
3490 "secret", CONF_STR, &conf->secret,
3491 "tls", CONF_STR, &conf->tls,
3492 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3493 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3494 "rewrite", CONF_STR, &conf->confrewrite,
3495 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3498 debugx(1, DBG_ERR, "configuration error");
3500 conf->name = stringcopy(val, 0);
3502 conf->host = stringcopy(val, 0);
3505 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3506 conf->type = protoname2int(conftype);
3507 conf->pdef = &protodefs[conf->type];
3508 if (!conf->pdef->name)
3509 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3512 if (conf->type == RAD_TLS) {
3513 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3515 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3516 if (conf->matchcertattr && !addmatchcertattr(conf))
3517 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3520 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3522 if (conf->rewriteattr) {
3523 if (!addrewriteattr(conf))
3524 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3527 if (!resolvepeer(conf, 0))
3528 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3530 if (!conf->secret) {
3531 if (!conf->pdef->secretdefault)
3532 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3533 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3535 debugx(1, DBG_ERR, "malloc failed");
3540 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3541 if (conf->type == RAD_TLS) {
3542 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3543 if (!conf->ssl_ctx) {
3544 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3547 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3548 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3554 conf->port = stringcopy(conf->pdef->portdefault, 0);
3556 debug(DBG_ERR, "malloc failed");
3561 if (conf->retryinterval == 255)
3562 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3563 if (conf->retrycount == 255)
3564 conf->retrycount = protodefs[conf->type].retrycountdefault;
3566 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3568 if (!conf->secret) {
3569 if (!conf->pdef->secretdefault) {
3570 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3573 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3574 if (!conf->secret) {
3575 debug(DBG_ERR, "malloc failed");
3580 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3581 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3587 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3588 struct clsrvconf *conf, *resconf;
3589 char *conftype = NULL;
3590 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3592 debug(DBG_DBG, "confserver_cb called for %s", block);
3594 conf = malloc(sizeof(struct clsrvconf));
3596 debug(DBG_ERR, "malloc failed");
3599 memset(conf, 0, sizeof(struct clsrvconf));
3600 resconf = (struct clsrvconf *)arg;
3602 conf->statusserver = resconf->statusserver;
3603 conf->certnamecheck = resconf->certnamecheck;
3605 conf->certnamecheck = 1;
3607 if (!getgenericconfig(cf, block,
3608 "type", CONF_STR, &conftype,
3609 "host", CONF_STR, &conf->host,
3610 "port", CONF_STR, &conf->port,
3611 "secret", CONF_STR, &conf->secret,
3612 "tls", CONF_STR, &conf->tls,
3613 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3614 "rewrite", CONF_STR, &conf->confrewrite,
3615 "StatusServer", CONF_BLN, &conf->statusserver,
3616 "RetryInterval", CONF_LINT, &retryinterval,
3617 "RetryCount", CONF_LINT, &retrycount,
3618 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3619 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3622 debug(DBG_ERR, "configuration error");
3626 conf->name = stringcopy(val, 0);
3628 debug(DBG_ERR, "malloc failed");
3632 conf->host = stringcopy(val, 0);
3634 debug(DBG_ERR, "malloc failed");
3640 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3641 conf->type = protoname2int(conftype);
3642 conf->pdef = &protodefs[conf->type];
3643 if (!conf->pdef->name) {
3644 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3650 if (retryinterval != LONG_MIN) {
3651 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3652 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3655 conf->retryinterval = (uint8_t)retryinterval;
3657 conf->retryinterval = 255;
3659 if (retrycount != LONG_MIN) {
3660 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3661 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3664 conf->retrycount = (uint8_t)retrycount;
3666 conf->retrycount = 255;
3669 if (!mergesrvconf(resconf, conf))
3673 if (conf->dynamiclookupcommand) {
3674 free(conf->dynamiclookupcommand);
3675 conf->dynamiclookupcommand = NULL;
3679 if (resconf || !conf->dynamiclookupcommand) {
3680 if (!compileserverconfig(conf, block))
3687 if (!list_push(srvconfs, conf)) {
3688 debug(DBG_ERR, "malloc failed");
3694 freeclsrvconf(conf);
3698 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3699 char **servers = NULL, **accservers = NULL, *msg = NULL;
3700 uint8_t accresp = 0;
3702 debug(DBG_DBG, "confrealm_cb called for %s", block);
3704 if (!getgenericconfig(cf, block,
3705 "server", CONF_MSTR, &servers,
3706 "accountingServer", CONF_MSTR, &accservers,
3707 "ReplyMessage", CONF_STR, &msg,
3708 "AccountingResponse", CONF_BLN, &accresp,
3711 debugx(1, DBG_ERR, "configuration error");
3713 addrealm(realms, val, servers, accservers, msg, accresp);
3717 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3718 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3719 uint8_t crlcheck = 0;
3721 debug(DBG_DBG, "conftls_cb called for %s", block);
3723 if (!getgenericconfig(cf, block,
3724 "CACertificateFile", CONF_STR, &cacertfile,
3725 "CACertificatePath", CONF_STR, &cacertpath,
3726 "CertificateFile", CONF_STR, &certfile,
3727 "CertificateKeyFile", CONF_STR, &certkeyfile,
3728 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3729 "CRLCheck", CONF_BLN, &crlcheck,
3732 debugx(1, DBG_ERR, "configuration error");
3734 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3743 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3744 char **attrs = NULL, **vattrs = NULL;
3746 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3748 if (!getgenericconfig(cf, block,
3749 "removeAttribute", CONF_MSTR, &attrs,
3750 "removeVendorAttribute", CONF_MSTR, &vattrs,
3753 debugx(1, DBG_ERR, "configuration error");
3754 addrewrite(val, attrs, vattrs);
3758 void getmainconfig(const char *configfile) {
3759 long int loglevel = LONG_MIN;
3760 struct gconffile *cfs;
3762 cfs = openconfigfile(configfile);
3763 memset(&options, 0, sizeof(options));
3765 clconfs = list_create();
3767 debugx(1, DBG_ERR, "malloc failed");
3769 srvconfs = list_create();
3771 debugx(1, DBG_ERR, "malloc failed");
3773 realms = list_create();
3775 debugx(1, DBG_ERR, "malloc failed");
3777 tlsconfs = list_create();
3779 debugx(1, DBG_ERR, "malloc failed");
3781 rewriteconfs = list_create();
3783 debugx(1, DBG_ERR, "malloc failed");
3785 if (!getgenericconfig(&cfs, NULL,
3786 "ListenUDP", CONF_MSTR, &options.listenudp,
3787 "ListenTCP", CONF_MSTR, &options.listentcp,
3788 "ListenTLS", CONF_MSTR, &options.listentls,
3789 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3790 "SourceUDP", CONF_STR, &options.sourceudp,
3791 "SourceTCP", CONF_STR, &options.sourcetcp,
3792 "LogLevel", CONF_LINT, &loglevel,
3793 "LogDestination", CONF_STR, &options.logdestination,
3794 "LoopPrevention", CONF_BLN, &options.loopprevention,
3795 "Client", CONF_CBK, confclient_cb, NULL,
3796 "Server", CONF_CBK, confserver_cb, NULL,
3797 "Realm", CONF_CBK, confrealm_cb, NULL,
3798 "TLS", CONF_CBK, conftls_cb, NULL,
3799 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3802 debugx(1, DBG_ERR, "configuration error");
3804 if (loglevel != LONG_MIN) {
3805 if (loglevel < 1 || loglevel > 4)
3806 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3807 options.loglevel = (uint8_t)loglevel;
3811 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3814 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3817 *configfile = optarg;
3820 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3821 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3822 *loglevel = *optarg - '0';
3831 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3836 if (!(argc - optind))
3840 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3844 int daemon(int a, int b) {
3852 for (i = 0; i < 3; i++) {
3854 open("/dev/null", O_RDWR);
3860 void *sighandler(void *arg) {
3865 sigemptyset(&sigset);
3866 sigaddset(&sigset, SIGPIPE);
3867 sigwait(&sigset, &sig);
3868 /* only get SIGPIPE right now, so could simplify below code */
3871 /* completely ignoring this */
3874 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3877 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3882 int main(int argc, char **argv) {
3883 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
3885 struct list_node *entry;
3886 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3887 char *configfile = NULL;
3888 struct clsrvconf *srvconf;
3890 debug_init("radsecproxy");
3891 debug_set_level(DEBUG_LEVEL);
3892 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3894 debug_set_level(loglevel);
3895 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3897 options.loglevel = loglevel;
3898 else if (options.loglevel)
3899 debug_set_level(options.loglevel);
3901 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3902 free(options.logdestination);
3904 if (!list_first(clconfs))
3905 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3906 if (!list_first(srvconfs))
3907 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3908 if (!list_first(realms))
3909 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3912 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3914 if (!foreground && (daemon(0, 0) < 0))
3915 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3917 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3919 sigemptyset(&sigset);
3920 /* exit on all but SIGPIPE, ignore more? */
3921 sigaddset(&sigset, SIGPIPE);
3922 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3923 pthread_create(&sigth, NULL, sighandler, NULL);
3925 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
3926 udp_server_replyq = newreplyq();
3927 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
3928 debugx(1, DBG_ERR, "pthread_create failed");
3929 createlisteners(RAD_UDP, options.listenudp, 0);
3930 if (options.listenaccudp)
3931 createlisteners(RAD_UDP, options.listenaccudp, 1);
3934 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3935 srvconf = (struct clsrvconf *)entry->data;
3936 if (srvconf->dynamiclookupcommand)
3938 if (!addserver(srvconf))
3939 debugx(1, DBG_ERR, "failed to add server");
3940 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3941 (void *)(srvconf->servers)))
3942 debugx(1, DBG_ERR, "pthread_create failed");
3944 /* srcudpres no longer needed, while srctcpres is needed later */
3946 freeaddrinfo(srcudpres);
3949 if (udp_client4_sock >= 0)
3950 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3951 debugx(1, DBG_ERR, "pthread_create failed");
3952 if (udp_client6_sock >= 0)
3953 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3954 debugx(1, DBG_ERR, "pthread_create failed");
3956 if (find_conf_type(RAD_TLS, clconfs, NULL))
3957 createlisteners(RAD_TLS, options.listentls, 0);
3959 /* just hang around doing nothing, anything to do here? */