2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
66 #include "radsecproxy.h"
68 static struct options options;
69 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
71 static struct addrinfo *srcprotores[3] = { NULL, NULL, NULL };
73 static struct replyq *udp_server_replyq = NULL;
74 static int udp_client4_sock = -1;
75 static int udp_client6_sock = -1;
76 static pthread_mutex_t *ssl_locks;
77 static long *ssl_lock_count;
81 /* minimum required declarations to avoid reordering code */
82 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
83 int dynamicconfig(struct server *server);
84 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
85 void freerealm(struct realm *realm);
86 void freeclsrvconf(struct clsrvconf *conf);
87 void freerqdata(struct request *rq);
88 void *udpserverrd(void *arg);
89 void *tlslistener(void *arg);
90 void *tcplistener(void *arg);
91 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
92 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
93 void *udpclientrd(void *arg);
94 void *tlsclientrd(void *arg);
95 void *tcpclientrd(void *arg);
96 int clientradputudp(struct server *server, unsigned char *rad);
97 int clientradputtls(struct server *server, unsigned char *rad);
98 int clientradputtcp(struct server *server, unsigned char *rad);
100 static const struct protodefs protodefs[] = {
101 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
102 NULL, /* secretdefault */
103 SOCK_DGRAM, /* socktype */
104 "1812", /* portdefault */
105 REQUEST_RETRY_COUNT, /* retrycountdefault */
106 10, /* retrycountmax */
107 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
108 60, /* retryintervalmax */
109 udpserverrd, /* listener */
110 &options.sourceudp, /* srcaddrport */
111 NULL, /* connecter */
112 udpclientrd, /* clientreader */
113 clientradputudp /* clientradput */
115 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
116 "mysecret", /* secretdefault */
117 SOCK_STREAM, /* socktype */
118 "2083", /* portdefault */
119 0, /* retrycountdefault */
120 0, /* retrycountmax */
121 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
122 60, /* retryintervalmax */
123 tlslistener, /* listener */
124 &options.sourcetls, /* srcaddrport */
125 tlsconnect, /* connecter */
126 tlsclientrd, /* clientreader */
127 clientradputtls /* clientradput */
129 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
130 NULL, /* secretdefault */
131 SOCK_STREAM, /* socktype */
132 "1812", /* portdefault */
133 0, /* retrycountdefault */
134 0, /* retrycountmax */
135 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
136 60, /* retryintervalmax */
137 tcplistener, /* listener */
138 &options.sourcetcp, /* srcaddrport */
139 tcpconnect, /* connecter */
140 tcpclientrd, /* clientreader */
141 clientradputtcp /* clientradput */
147 uint8_t protoname2int(const char *name) {
150 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
154 /* callbacks for making OpenSSL thread safe */
155 unsigned long ssl_thread_id() {
156 return (unsigned long)pthread_self();
159 void ssl_locking_callback(int mode, int type, const char *file, int line) {
160 if (mode & CRYPTO_LOCK) {
161 pthread_mutex_lock(&ssl_locks[type]);
162 ssl_lock_count[type]++;
164 pthread_mutex_unlock(&ssl_locks[type]);
167 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
168 int pwdlen = strlen(userdata);
169 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
171 memcpy(buf, userdata, pwdlen);
175 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
180 err_cert = X509_STORE_CTX_get_current_cert(ctx);
181 err = X509_STORE_CTX_get_error(ctx);
182 depth = X509_STORE_CTX_get_error_depth(ctx);
184 if (depth > MAX_CERT_DEPTH) {
186 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
187 X509_STORE_CTX_set_error(ctx, err);
191 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
192 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
195 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
196 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
197 debug(DBG_WARN, "\tIssuer=%s", buf);
199 case X509_V_ERR_CERT_NOT_YET_VALID:
200 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
201 debug(DBG_WARN, "\tCertificate not yet valid");
203 case X509_V_ERR_CERT_HAS_EXPIRED:
204 debug(DBG_WARN, "Certificate has expired");
206 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
207 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
212 printf("certificate verify returns %d\n", ok);
217 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
218 struct addrinfo hints, *addrinfo, *res;
222 slash = conf->host ? strchr(conf->host, '/') : NULL;
226 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
230 if (*s < '0' || *s > '9') {
231 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
234 plen = atoi(slash + 1);
235 if (plen < 0 || plen > 128) {
236 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
241 memset(&hints, 0, sizeof(hints));
242 hints.ai_socktype = conf->pdef->socktype;
243 hints.ai_family = AF_UNSPEC;
244 hints.ai_flags = ai_flags;
245 if (!conf->host && !conf->port) {
246 /* getaddrinfo() doesn't like host and port to be NULL */
247 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
248 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
251 for (res = addrinfo; res; res = res->ai_next) {
252 switch (res->ai_family) {
254 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
257 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
263 hints.ai_flags |= AI_NUMERICHOST;
264 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
265 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
270 switch (addrinfo->ai_family) {
273 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
274 freeaddrinfo(addrinfo);
281 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
282 freeaddrinfo(addrinfo);
285 conf->prefixlen = plen;
287 conf->prefixlen = 255;
290 freeaddrinfo(conf->addrinfo);
291 conf->addrinfo = addrinfo;
295 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
297 struct addrinfo *res;
299 for (res = addrinfo; res; res = res->ai_next) {
300 if (family != AF_UNSPEC && family != res->ai_family)
302 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
304 debug(DBG_WARN, "bindtoaddr: socket failed");
308 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
311 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
314 if (!bind(s, res->ai_addr, res->ai_addrlen))
316 debug(DBG_WARN, "bindtoaddr: bind failed");
322 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
327 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
331 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
333 debugx(1, DBG_ERR, "no ] matching initial [");
337 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
340 debugx(1, DBG_ERR, "missing host/address");
342 conf->host = stringcopy(field, p - field);
345 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
346 debugx(1, DBG_ERR, "unexpected character after ]");
349 /* port number or service name is specified */;
351 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
353 debugx(1, DBG_ERR, "syntax error, : but no following port");
354 conf->port = stringcopy(field, p - field);
356 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
360 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
361 struct clsrvconf *conf;
363 conf = malloc(sizeof(struct clsrvconf));
365 debugx(1, DBG_ERR, "malloc failed");
366 memset(conf, 0, sizeof(struct clsrvconf));
368 conf->pdef = &protodefs[conf->type];
370 parsehostport(lconf, conf, default_port);
371 if (!strcmp(conf->host, "*")) {
376 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
377 if (!resolvepeer(conf, AI_PASSIVE))
378 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
382 void freeclsrvres(struct clsrvconf *res) {
386 freeaddrinfo(res->addrinfo);
390 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
392 struct addrinfo *res;
395 for (res = addrinfo; res; res = res->ai_next) {
396 s = bindtoaddr(src, res->ai_family, 1, 1);
398 debug(DBG_WARN, "connecttoserver: socket failed");
401 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
403 debug(DBG_WARN, "connecttoserver: connect failed");
410 /* returns 1 if the len first bits are equal, else 0 */
411 int prefixmatch(void *a1, void *a2, uint8_t len) {
412 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
414 if (l && memcmp(a1, a2, l))
419 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
422 /* check if conf has matching address */
423 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
424 struct sockaddr_in6 *sa6 = NULL;
425 struct in_addr *a4 = NULL;
426 struct addrinfo *res;
428 if (addr->sa_family == AF_INET6) {
429 sa6 = (struct sockaddr_in6 *)addr;
430 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
431 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
435 a4 = &((struct sockaddr_in *)addr)->sin_addr;
437 if (conf->type == type) {
438 if (conf->prefixlen == 255) {
439 for (res = conf->addrinfo; res; res = res->ai_next)
440 if ((a4 && res->ai_family == AF_INET &&
441 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
442 (sa6 && res->ai_family == AF_INET6 &&
443 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
446 res = conf->addrinfo;
448 ((a4 && res->ai_family == AF_INET &&
449 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
450 (sa6 && res->ai_family == AF_INET6 &&
451 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
458 /* returns next config with matching address, or NULL */
459 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
460 struct sockaddr_in6 *sa6 = NULL;
461 struct in_addr *a4 = NULL;
462 struct addrinfo *res;
463 struct list_node *entry;
464 struct clsrvconf *conf;
466 if (addr->sa_family == AF_INET6) {
467 sa6 = (struct sockaddr_in6 *)addr;
468 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
469 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
473 a4 = &((struct sockaddr_in *)addr)->sin_addr;
475 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
476 conf = (struct clsrvconf *)entry->data;
477 if (conf->type == type) {
478 if (conf->prefixlen == 255) {
479 for (res = conf->addrinfo; res; res = res->ai_next)
480 if ((a4 && res->ai_family == AF_INET &&
481 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
482 (sa6 && res->ai_family == AF_INET6 &&
483 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
489 res = conf->addrinfo;
491 ((a4 && res->ai_family == AF_INET &&
492 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
493 (sa6 && res->ai_family == AF_INET6 &&
494 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
505 /* returns next config of given type, or NULL */
506 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
507 struct list_node *entry;
508 struct clsrvconf *conf;
510 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
511 conf = (struct clsrvconf *)entry->data;
512 if (conf->type == type) {
521 struct replyq *newreplyq() {
522 struct replyq *replyq;
524 replyq = malloc(sizeof(struct replyq));
526 debugx(1, DBG_ERR, "malloc failed");
527 replyq->replies = list_create();
528 if (!replyq->replies)
529 debugx(1, DBG_ERR, "malloc failed");
530 pthread_mutex_init(&replyq->mutex, NULL);
531 pthread_cond_init(&replyq->cond, NULL);
535 struct client *addclient(struct clsrvconf *conf) {
536 struct client *new = malloc(sizeof(struct client));
539 debug(DBG_ERR, "malloc failed");
542 if (!conf->clients) {
543 conf->clients = list_create();
544 if (!conf->clients) {
545 debug(DBG_ERR, "malloc failed");
550 memset(new, 0, sizeof(struct client));
552 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
554 list_push(conf->clients, new);
558 void removeclient(struct client *client) {
559 struct list_node *entry;
561 if (!client || !client->conf->clients)
564 pthread_mutex_lock(&client->replyq->mutex);
565 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
566 free(((struct reply *)entry)->buf);
567 list_destroy(client->replyq->replies);
568 pthread_cond_destroy(&client->replyq->cond);
569 pthread_mutex_unlock(&client->replyq->mutex);
570 pthread_mutex_destroy(&client->replyq->mutex);
571 list_removedata(client->conf->clients, client);
575 void removeclientrqs(struct client *client) {
576 struct list_node *entry;
577 struct server *server;
581 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
582 server = ((struct clsrvconf *)entry->data)->servers;
585 pthread_mutex_lock(&server->newrq_mutex);
586 for (i = 0; i < MAX_REQUESTS; i++) {
587 rq = server->requests + i;
588 if (rq->from == client)
591 pthread_mutex_unlock(&server->newrq_mutex);
595 void freeserver(struct server *server, uint8_t destroymutex) {
596 struct request *rq, *end;
601 if(server->requests) {
602 rq = server->requests;
603 for (end = rq + MAX_REQUESTS; rq < end; rq++)
605 free(server->requests);
607 free(server->dynamiclookuparg);
609 pthread_mutex_destroy(&server->lock);
610 pthread_cond_destroy(&server->newrq_cond);
611 pthread_mutex_destroy(&server->newrq_mutex);
616 int addserver(struct clsrvconf *conf) {
617 struct clsrvconf *res;
620 debug(DBG_ERR, "addserver: currently works with just one server per conf");
623 conf->servers = malloc(sizeof(struct server));
624 if (!conf->servers) {
625 debug(DBG_ERR, "malloc failed");
628 memset(conf->servers, 0, sizeof(struct server));
629 conf->servers->conf = conf;
631 if (!srcprotores[conf->type]) {
632 res = resolve_hostport(conf->type, *conf->pdef->srcaddrport, NULL);
633 srcprotores[conf->type] = res->addrinfo;
634 res->addrinfo = NULL;
638 if (conf->type == RAD_UDP) {
639 switch (conf->addrinfo->ai_family) {
641 if (udp_client4_sock < 0) {
642 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
643 if (udp_client4_sock < 0)
644 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
646 conf->servers->sock = udp_client4_sock;
649 if (udp_client6_sock < 0) {
650 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
651 if (udp_client6_sock < 0)
652 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
654 conf->servers->sock = udp_client6_sock;
657 debugx(1, DBG_ERR, "addserver: unsupported address family");
661 conf->servers->sock = -1;
663 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
664 if (!conf->servers->requests) {
665 debug(DBG_ERR, "malloc failed");
668 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
669 debug(DBG_ERR, "mutex init failed");
672 conf->servers->newrq = 0;
673 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
674 debug(DBG_ERR, "mutex init failed");
675 pthread_mutex_destroy(&conf->servers->lock);
678 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
679 debug(DBG_ERR, "mutex init failed");
680 pthread_mutex_destroy(&conf->servers->newrq_mutex);
681 pthread_mutex_destroy(&conf->servers->lock);
688 freeserver(conf->servers, 0);
689 conf->servers = NULL;
693 /* exactly one of client and server must be non-NULL */
694 /* should probably take peer list (client(s) or server(s)) as argument instead */
695 /* if *peer == NULL we return who we received from, else require it to be from peer */
696 /* return from in sa if not NULL */
697 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
699 unsigned char buf[65536], *rad;
700 struct sockaddr_storage from;
701 socklen_t fromlen = sizeof(from);
703 struct list_node *node;
706 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
708 debug(DBG_WARN, "radudpget: recv failed");
711 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
714 debug(DBG_WARN, "radudpget: packet too small");
720 debug(DBG_WARN, "radudpget: length too small");
725 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
729 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
733 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
735 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
738 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
740 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
743 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
749 debug(DBG_ERR, "radudpget: malloc failed");
753 if (client && !*client) {
754 node = list_first(p->clients);
755 *client = node ? (struct client *)node->data : addclient(p);
760 } else if (server && !*server)
761 *server = p->servers;
765 memcpy(rad, buf, len);
771 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
772 int loc, i, l, n, r = 0;
775 STACK_OF(GENERAL_NAME) *alt;
778 debug(DBG_DBG, "subjectaltnameaddr");
780 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
784 ex = X509_get_ext(cert, loc);
785 alt = X509V3_EXT_d2i(ex);
789 n = sk_GENERAL_NAME_num(alt);
790 for (i = 0; i < n; i++) {
791 gn = sk_GENERAL_NAME_value(alt, i);
792 if (gn->type != GEN_IPADD)
795 v = (char *)ASN1_STRING_data(gn->d.ia5);
796 l = ASN1_STRING_length(gn->d.ia5);
797 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
798 && !memcmp(v, &addr, l)) {
803 GENERAL_NAMES_free(alt);
807 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
814 nm = X509_get_subject_name(cert);
817 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
820 e = X509_NAME_get_entry(nm, loc);
821 t = X509_NAME_ENTRY_get_data(e);
822 v = (char *) ASN1_STRING_data(t);
823 l = ASN1_STRING_length(t);
827 if (l == strlen(exact) && !strncasecmp(exact, v, l))
830 s = stringcopy((char *)v, l);
832 debug(DBG_ERR, "malloc failed");
835 if (regexec(regex, s, 0, NULL, 0)) {
846 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
847 int loc, i, l, n, r = 0;
850 STACK_OF(GENERAL_NAME) *alt;
853 debug(DBG_DBG, "subjectaltnameregexp");
855 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
859 ex = X509_get_ext(cert, loc);
860 alt = X509V3_EXT_d2i(ex);
864 n = sk_GENERAL_NAME_num(alt);
865 for (i = 0; i < n; i++) {
866 gn = sk_GENERAL_NAME_value(alt, i);
867 if (gn->type != type)
870 v = (char *)ASN1_STRING_data(gn->d.ia5);
871 l = ASN1_STRING_length(gn->d.ia5);
875 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
878 if (memcmp(v, exact, l))
881 s = stringcopy((char *)v, l);
883 debug(DBG_ERR, "malloc failed");
886 if (regexec(regex, s, 0, NULL, 0)) {
895 GENERAL_NAMES_free(alt);
899 X509 *verifytlscert(SSL *ssl) {
903 if (SSL_get_verify_result(ssl) != X509_V_OK) {
904 debug(DBG_ERR, "verifytlscert: basic validation failed");
905 while ((error = ERR_get_error()))
906 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
910 cert = SSL_get_peer_certificate(ssl);
912 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
916 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
918 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
919 struct in6_addr addr;
921 if (conf->certnamecheck && conf->prefixlen == 255) {
922 if (inet_pton(AF_INET, conf->host, &addr))
924 else if (inet_pton(AF_INET6, conf->host, &addr))
927 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
930 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
933 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
935 if (!cnregexp(cert, conf->host, NULL)) {
936 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
939 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
942 if (conf->certcnregex) {
943 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
944 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
947 debug(DBG_DBG, "verifyconfcert: CN matching regex");
949 if (conf->certuriregex) {
950 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
951 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
954 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
959 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
964 debug(DBG_DBG, "tlsconnect: called from %s", text);
965 pthread_mutex_lock(&server->lock);
966 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
967 /* already reconnected, nothing to do */
968 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
969 pthread_mutex_unlock(&server->lock);
974 gettimeofday(&now, NULL);
975 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
976 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
977 debug(DBG_DBG, "tlsconnect: timeout");
978 if (server->sock >= 0)
980 SSL_free(server->ssl);
982 pthread_mutex_unlock(&server->lock);
985 if (server->connectionok) {
986 server->connectionok = 0;
988 } else if (elapsed < 1)
990 else if (elapsed < 60) {
991 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
993 } else if (elapsed < 100000) {
994 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
997 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
998 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
999 if (server->sock >= 0)
1000 close(server->sock);
1001 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1002 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1006 SSL_free(server->ssl);
1007 server->ssl = SSL_new(server->conf->ssl_ctx);
1008 SSL_set_fd(server->ssl, server->sock);
1009 if (SSL_connect(server->ssl) <= 0)
1011 cert = verifytlscert(server->ssl);
1014 if (verifyconfcert(cert, server->conf)) {
1020 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1021 gettimeofday(&server->lastconnecttry, NULL);
1022 pthread_mutex_unlock(&server->lock);
1026 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1030 debug(DBG_DBG, "tcpconnect: called from %s", text);
1031 pthread_mutex_lock(&server->lock);
1032 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1033 /* already reconnected, nothing to do */
1034 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1035 pthread_mutex_unlock(&server->lock);
1040 gettimeofday(&now, NULL);
1041 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1042 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1043 debug(DBG_DBG, "tcpconnect: timeout");
1044 if (server->sock >= 0)
1045 close(server->sock);
1046 pthread_mutex_unlock(&server->lock);
1049 if (server->connectionok) {
1050 server->connectionok = 0;
1052 } else if (elapsed < 1)
1054 else if (elapsed < 60) {
1055 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1057 } else if (elapsed < 100000) {
1058 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1061 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1062 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1063 if (server->sock >= 0)
1064 close(server->sock);
1065 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1067 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1069 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1070 gettimeofday(&server->lastconnecttry, NULL);
1071 pthread_mutex_unlock(&server->lock);
1075 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1076 /* returns 0 on timeout, -1 on error and num if ok */
1077 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1078 int s, ndesc, cnt, len;
1079 fd_set readfds, writefds;
1080 struct timeval timer;
1082 s = SSL_get_fd(ssl);
1085 /* make socket non-blocking? */
1086 for (len = 0; len < num; len += cnt) {
1088 FD_SET(s, &readfds);
1091 timer.tv_sec = timeout;
1094 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1098 cnt = SSL_read(ssl, buf + len, num - len);
1100 switch (SSL_get_error(ssl, cnt)) {
1101 case SSL_ERROR_WANT_READ:
1102 case SSL_ERROR_WANT_WRITE:
1105 case SSL_ERROR_ZERO_RETURN:
1106 /* remote end sent close_notify, send one back */
1116 /* timeout in seconds, 0 means no timeout (blocking) */
1117 unsigned char *radtlsget(SSL *ssl, int timeout) {
1119 unsigned char buf[4], *rad;
1122 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1124 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1131 debug(DBG_ERR, "radtlsget: malloc failed");
1134 memcpy(rad, buf, 4);
1136 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1138 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1147 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1150 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1154 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1155 /* returns 0 on timeout, -1 on error and num if ok */
1156 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1157 int ndesc, cnt, len;
1158 fd_set readfds, writefds;
1159 struct timeval timer;
1163 /* make socket non-blocking? */
1164 for (len = 0; len < num; len += cnt) {
1166 FD_SET(s, &readfds);
1169 timer.tv_sec = timeout;
1172 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1176 cnt = read(s, buf + len, num - len);
1183 /* timeout in seconds, 0 means no timeout (blocking) */
1184 unsigned char *radtcpget(int s, int timeout) {
1186 unsigned char buf[4], *rad;
1189 cnt = tcpreadtimeout(s, buf, 4, timeout);
1191 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1198 debug(DBG_ERR, "radtcpget: malloc failed");
1201 memcpy(rad, buf, 4);
1203 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1205 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1214 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1217 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1221 int clientradputudp(struct server *server, unsigned char *rad) {
1223 struct sockaddr_storage sa;
1224 struct sockaddr *sap;
1225 struct clsrvconf *conf = server->conf;
1226 in_port_t *port = NULL;
1230 if (*rad == RAD_Accounting_Request) {
1231 sap = (struct sockaddr *)&sa;
1232 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1234 sap = conf->addrinfo->ai_addr;
1236 switch (sap->sa_family) {
1238 port = &((struct sockaddr_in *)sap)->sin_port;
1241 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1247 if (*rad == RAD_Accounting_Request)
1248 *port = htons(ntohs(*port) + 1);
1250 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1251 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1255 debug(DBG_WARN, "clientradputudp: send failed");
1259 int clientradputtls(struct server *server, unsigned char *rad) {
1262 unsigned long error;
1263 struct timeval lastconnecttry;
1264 struct clsrvconf *conf = server->conf;
1267 lastconnecttry = server->lastconnecttry;
1268 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1269 while ((error = ERR_get_error()))
1270 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1271 if (server->dynamiclookuparg)
1273 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1274 lastconnecttry = server->lastconnecttry;
1277 server->connectionok = 1;
1278 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1282 int clientradputtcp(struct server *server, unsigned char *rad) {
1285 struct timeval lastconnecttry;
1286 struct clsrvconf *conf = server->conf;
1289 lastconnecttry = server->lastconnecttry;
1290 while ((cnt = write(server->sock, rad, len)) <= 0) {
1291 debug(DBG_ERR, "clientradputtcp: write error");
1292 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1293 lastconnecttry = server->lastconnecttry;
1296 server->connectionok = 1;
1297 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1301 int radsign(unsigned char *rad, unsigned char *sec) {
1302 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1303 static unsigned char first = 1;
1304 static EVP_MD_CTX mdctx;
1305 unsigned int md_len;
1308 pthread_mutex_lock(&lock);
1310 EVP_MD_CTX_init(&mdctx);
1314 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1315 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1316 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1317 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1319 pthread_mutex_unlock(&lock);
1323 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1324 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1325 static unsigned char first = 1;
1326 static EVP_MD_CTX mdctx;
1327 unsigned char hash[EVP_MAX_MD_SIZE];
1331 pthread_mutex_lock(&lock);
1333 EVP_MD_CTX_init(&mdctx);
1339 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1340 EVP_DigestUpdate(&mdctx, rad, 4) &&
1341 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1342 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1343 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1344 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1346 !memcmp(hash, rad + 4, 16));
1347 pthread_mutex_unlock(&lock);
1351 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1352 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1353 static unsigned char first = 1;
1354 static HMAC_CTX hmacctx;
1355 unsigned int md_len;
1356 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1358 pthread_mutex_lock(&lock);
1360 HMAC_CTX_init(&hmacctx);
1364 memcpy(auth, authattr, 16);
1365 memset(authattr, 0, 16);
1367 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1368 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1369 HMAC_Final(&hmacctx, hash, &md_len);
1370 memcpy(authattr, auth, 16);
1372 debug(DBG_WARN, "message auth computation failed");
1373 pthread_mutex_unlock(&lock);
1377 if (memcmp(auth, hash, 16)) {
1378 debug(DBG_WARN, "message authenticator, wrong value");
1379 pthread_mutex_unlock(&lock);
1383 pthread_mutex_unlock(&lock);
1387 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1388 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1389 static unsigned char first = 1;
1390 static HMAC_CTX hmacctx;
1391 unsigned int md_len;
1396 pthread_mutex_lock(&lock);
1398 HMAC_CTX_init(&hmacctx);
1402 memset(authattrval, 0, 16);
1404 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1405 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1406 HMAC_Final(&hmacctx, authattrval, &md_len);
1408 debug(DBG_WARN, "message auth computation failed");
1409 pthread_mutex_unlock(&lock);
1413 pthread_mutex_unlock(&lock);
1417 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1418 while (length > 1) {
1419 if (ATTRTYPE(attrs) == type)
1421 length -= ATTRLEN(attrs);
1422 attrs += ATTRLEN(attrs);
1427 void freerqdata(struct request *rq) {
1428 if (rq->origusername)
1429 free(rq->origusername);
1434 void sendrq(struct server *to, struct request *rq) {
1438 pthread_mutex_lock(&to->newrq_mutex);
1439 /* might simplify if only try nextid, might be ok */
1440 for (i = to->nextid; i < MAX_REQUESTS; i++)
1441 if (!to->requests[i].buf)
1443 if (i == MAX_REQUESTS) {
1444 for (i = 0; i < to->nextid; i++)
1445 if (!to->requests[i].buf)
1447 if (i == to->nextid) {
1448 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1454 rq->buf[1] = (char)i;
1456 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1457 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1462 if (*rq->buf == RAD_Accounting_Request) {
1463 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1464 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1470 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1471 to->requests[i] = *rq;
1476 debug(DBG_DBG, "sendrq: signalling client writer");
1477 pthread_cond_signal(&to->newrq_cond);
1480 pthread_mutex_unlock(&to->newrq_mutex);
1483 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1484 struct reply *reply;
1487 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1489 debug(DBG_WARN, "sendreply: failed to sign message");
1493 reply = malloc(sizeof(struct reply));
1496 debug(DBG_ERR, "sendreply: malloc failed");
1499 memset(reply, 0, sizeof(struct reply));
1502 reply->tosa = *tosa;
1503 reply->toudpsock = toudpsock;
1505 pthread_mutex_lock(&to->replyq->mutex);
1507 first = list_first(to->replyq->replies) == NULL;
1509 if (!list_push(to->replyq->replies, reply)) {
1510 pthread_mutex_unlock(&to->replyq->mutex);
1513 debug(DBG_ERR, "sendreply: malloc failed");
1518 debug(DBG_DBG, "signalling server writer");
1519 pthread_cond_signal(&to->replyq->cond);
1521 pthread_mutex_unlock(&to->replyq->mutex);
1524 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1525 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1526 static unsigned char first = 1;
1527 static EVP_MD_CTX mdctx;
1528 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1529 unsigned int md_len;
1530 uint8_t i, offset = 0, out[128];
1532 pthread_mutex_lock(&lock);
1534 EVP_MD_CTX_init(&mdctx);
1540 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1541 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1542 !EVP_DigestUpdate(&mdctx, input, 16) ||
1543 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1545 pthread_mutex_unlock(&lock);
1548 for (i = 0; i < 16; i++)
1549 out[offset + i] = hash[i] ^ in[offset + i];
1550 input = out + offset - 16;
1555 memcpy(in, out, len);
1556 pthread_mutex_unlock(&lock);
1560 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1561 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1562 static unsigned char first = 1;
1563 static EVP_MD_CTX mdctx;
1564 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1565 unsigned int md_len;
1566 uint8_t i, offset = 0, out[128];
1568 pthread_mutex_lock(&lock);
1570 EVP_MD_CTX_init(&mdctx);
1576 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1577 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1578 !EVP_DigestUpdate(&mdctx, input, 16) ||
1579 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1581 pthread_mutex_unlock(&lock);
1584 for (i = 0; i < 16; i++)
1585 out[offset + i] = hash[i] ^ in[offset + i];
1586 input = in + offset;
1591 memcpy(in, out, len);
1592 pthread_mutex_unlock(&lock);
1596 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1597 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1598 static unsigned char first = 1;
1599 static EVP_MD_CTX mdctx;
1600 unsigned char hash[EVP_MAX_MD_SIZE];
1601 unsigned int md_len;
1604 pthread_mutex_lock(&lock);
1606 EVP_MD_CTX_init(&mdctx);
1611 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1612 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1613 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1616 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1617 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1618 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1619 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1620 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1621 pthread_mutex_unlock(&lock);
1626 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1629 for (i = 0; i < 16; i++)
1632 for (offset = 16; offset < len; offset += 16) {
1634 printf("text + offset - 16 c(%d): ", offset / 16);
1635 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1637 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1638 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1639 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1640 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1642 pthread_mutex_unlock(&lock);
1646 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1649 for (i = 0; i < 16; i++)
1650 text[offset + i] ^= hash[i];
1654 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1657 pthread_mutex_unlock(&lock);
1661 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1662 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1663 static unsigned char first = 1;
1664 static EVP_MD_CTX mdctx;
1665 unsigned char hash[EVP_MAX_MD_SIZE];
1666 unsigned int md_len;
1670 pthread_mutex_lock(&lock);
1672 EVP_MD_CTX_init(&mdctx);
1677 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1678 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1679 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1682 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1683 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1684 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1685 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1686 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1687 pthread_mutex_unlock(&lock);
1692 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1695 for (i = 0; i < 16; i++)
1696 plain[i] = text[i] ^ hash[i];
1698 for (offset = 16; offset < len; offset += 16) {
1700 printf("text + offset - 16 c(%d): ", offset / 16);
1701 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1703 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1704 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1705 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1706 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1708 pthread_mutex_unlock(&lock);
1712 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1715 for (i = 0; i < 16; i++)
1716 plain[offset + i] = text[offset + i] ^ hash[i];
1719 memcpy(text, plain, len);
1721 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1724 pthread_mutex_unlock(&lock);
1728 struct realm *id2realm(struct list *realmlist, char *id) {
1729 struct list_node *entry;
1730 struct realm *realm, *subrealm = NULL;
1732 /* need to do locking for subrealms and check subrealm timers */
1733 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1734 realm = (struct realm *)entry->data;
1735 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1736 pthread_mutex_lock(&realm->subrealms_mutex);
1737 if (realm->subrealms)
1738 subrealm = id2realm(realm->subrealms, id);
1739 pthread_mutex_unlock(&realm->subrealms_mutex);
1740 return subrealm ? subrealm : realm;
1746 /* helper function, only used by removeserversubrealms() */
1747 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1748 struct list_node *entry;
1749 struct realm *realm;
1751 for (entry = list_first(realmlist); entry;) {
1752 realm = (struct realm *)entry->data;
1753 entry = list_next(entry);
1754 if (realm->srvconfs) {
1755 list_removedata(realm->srvconfs, srv);
1756 if (!list_first(realm->srvconfs)) {
1757 list_destroy(realm->srvconfs);
1758 realm->srvconfs = NULL;
1761 if (realm->accsrvconfs) {
1762 list_removedata(realm->accsrvconfs, srv);
1763 if (!list_first(realm->accsrvconfs)) {
1764 list_destroy(realm->accsrvconfs);
1765 realm->accsrvconfs = NULL;
1769 /* remove subrealm if no servers */
1770 if (!realm->srvconfs && !realm->accsrvconfs) {
1771 list_removedata(realmlist, realm);
1777 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1778 struct list_node *entry;
1779 struct realm *realm;
1781 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1782 realm = (struct realm *)entry->data;
1783 pthread_mutex_lock(&realm->subrealms_mutex);
1784 if (realm->subrealms) {
1785 _internal_removeserversubrealms(realm->subrealms, srv);
1786 if (!list_first(realm->subrealms)) {
1787 list_destroy(realm->subrealms);
1788 realm->subrealms = NULL;
1791 pthread_mutex_unlock(&realm->subrealms_mutex);
1795 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1796 struct request *rq = to->requests, *end;
1798 pthread_mutex_lock(&to->newrq_mutex);
1799 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1800 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1802 pthread_mutex_unlock(&to->newrq_mutex);
1807 int attrvalidate(unsigned char *attrs, int length) {
1808 while (length > 1) {
1809 if (ATTRLEN(attrs) < 2) {
1810 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1813 length -= ATTRLEN(attrs);
1815 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1818 attrs += ATTRLEN(attrs);
1821 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1825 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1826 if (len < 16 || len > 128 || len % 16) {
1827 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1831 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1832 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1836 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1838 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1839 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1845 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1848 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1849 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1852 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1853 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1859 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1860 char *oldsecret, char *newsecret) {
1861 unsigned char *attr;
1863 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1864 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1865 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1871 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1875 for (; attrs[0]; attrs += 2)
1876 if (attrs[0] == vendor && attrs[1] == subattr)
1881 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1882 uint8_t alen, sublen, rmlen = 0;
1883 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1886 if (!removevendorattrs)
1889 while (*removevendorattrs && *removevendorattrs != vendor)
1890 removevendorattrs += 2;
1891 if (!*removevendorattrs)
1894 alen = ATTRLEN(attrs);
1896 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1897 /* remove entire vendor attribute */
1898 memmove(attrs, attrs + alen, length - alen);
1903 subattrs = ATTRVAL(attrs) + 4;
1905 if (!attrvalidate(subattrs, sublen)) {
1906 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1911 while (sublen > 1) {
1912 alen = ATTRLEN(subattrs);
1915 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1916 memmove(subattrs, subattrs + alen, length);
1922 ATTRLEN(attrs) -= rmlen;
1926 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1927 uint8_t *attrs, alen;
1928 uint16_t len, rmlen = 0;
1930 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1933 len = RADLEN(buf) - 20;
1936 alen = ATTRLEN(attrs);
1938 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1939 memmove(attrs, attrs + alen, len);
1941 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1942 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1947 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1950 /* returns a pointer to the resized attribute value */
1951 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1952 uint8_t *attrs, *attr, vallen;
1956 len = RADLEN(*buf) - 20;
1959 attr = attrget(attrs, len, type);
1963 vallen = ATTRVALLEN(attr);
1964 if (vallen == newvallen)
1967 len += newvallen - vallen;
1968 if (newvallen > vallen) {
1969 new = realloc(*buf, len + 20);
1971 debug(DBG_ERR, "resizeattr: malloc failed");
1980 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1981 attr[1] = newvallen + 2;
1982 ((uint16_t *)*buf)[1] = htons(len + 20);
1986 int rewriteusername(struct request *rq, char *in) {
1987 size_t nmatch = 10, reslen = 0, start = 0;
1988 regmatch_t pmatch[10], *pfield;
1990 unsigned char *result;
1991 char *out = rq->from->conf->rewriteattrreplacement;
1993 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1994 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1998 rq->origusername = stringcopy(in, 0);
1999 if (!rq->origusername)
2002 for (i = start; out[i]; i++) {
2003 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2004 pfield = &pmatch[out[i + 1] - '0'];
2005 if (pfield->rm_so >= 0) {
2006 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2012 reslen += i - start;
2014 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2020 for (i = start; out[i]; i++) {
2021 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2022 pfield = &pmatch[out[i + 1] - '0'];
2023 if (pfield->rm_so >= 0) {
2024 memcpy(result + reslen, out + start, i - start);
2025 reslen += i - start;
2026 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2027 reslen += pfield->rm_eo - pfield->rm_so;
2034 memcpy(result + reslen, out + start, i - start);
2035 reslen += i - start;
2036 memcpy(in, result, reslen);
2041 const char *radmsgtype2string(uint8_t code) {
2042 static const char *rad_msg_names[] = {
2043 "", "Access-Request", "Access-Accept", "Access-Reject",
2044 "Accounting-Request", "Accounting-Response", "", "",
2045 "", "", "", "Access-Challenge",
2046 "Status-Server", "Status-Client"
2048 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2051 void char2hex(char *h, unsigned char c) {
2052 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2053 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2054 h[0] = hexdigits[c / 16];
2055 h[1] = hexdigits[c % 16];
2059 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2063 if (!attr || len == 1) {
2068 l = ATTRVALLEN(attr);
2069 s = (char *)ATTRVAL(attr);
2072 for (i = 0; i < l; i++) {
2073 if (s[i] > 31 && s[i] < 127) {
2075 if (d - ascii == len - 1)
2078 if (d - ascii > len - 4)
2083 if (d - ascii == len - 1)
2091 void acclog(unsigned char *attrs, int length, char *host) {
2092 unsigned char *attr;
2095 attr = attrget(attrs, length, RAD_Attr_User_Name);
2097 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2100 radattr2ascii(username, sizeof(username), attr);
2101 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2104 void respondaccounting(struct request *rq) {
2105 unsigned char *resp;
2109 debug(DBG_ERR, "respondaccounting: malloc failed");
2112 memcpy(resp, rq->buf, 20);
2113 resp[0] = RAD_Accounting_Response;
2116 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2117 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2120 void respondstatusserver(struct request *rq) {
2121 unsigned char *resp;
2125 debug(DBG_ERR, "respondstatusserver: malloc failed");
2128 memcpy(resp, rq->buf, 20);
2129 resp[0] = RAD_Access_Accept;
2132 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2133 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2136 void respondreject(struct request *rq, char *message) {
2137 unsigned char *resp;
2140 if (message && *message)
2141 len += 2 + strlen(message);
2145 debug(DBG_ERR, "respondreject: malloc failed");
2148 memcpy(resp, rq->buf, 20);
2149 resp[0] = RAD_Access_Reject;
2150 *(uint16_t *)(resp + 2) = htons(len);
2151 if (message && *message) {
2152 resp[20] = RAD_Attr_Reply_Message;
2153 resp[21] = len - 20;
2154 memcpy(resp + 22, message, len - 22);
2156 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2159 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2160 struct list_node *entry;
2161 struct clsrvconf *server, *best = NULL, *first = NULL;
2163 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2164 server = (struct clsrvconf *)entry->data;
2165 if (!server->servers)
2169 if (!server->servers->connectionok)
2171 if (!server->servers->lostrqs)
2177 if (server->servers->lostrqs < best->servers->lostrqs)
2180 return best ? best : first;
2183 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2184 struct clsrvconf *srvconf;
2186 *realm = id2realm(realms, id);
2189 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2190 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2193 if (!acc && !srvconf->servers)
2194 adddynamicrealmserver(*realm, srvconf, id);
2195 return srvconf->servers;
2198 /* returns 0 if validation/authentication fails, else 1 */
2199 int radsrv(struct request *rq) {
2200 uint8_t code, id, *auth, *attrs, *attr;
2202 struct server *to = NULL;
2203 char username[254], userascii[760];
2204 unsigned char newauth[16];
2205 struct realm *realm = NULL;
2207 code = *(uint8_t *)rq->buf;
2208 id = *(uint8_t *)(rq->buf + 1);
2209 len = RADLEN(rq->buf);
2210 auth = (uint8_t *)(rq->buf + 4);
2212 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2214 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2215 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2220 attrs = rq->buf + 20;
2222 if (!attrvalidate(attrs, len)) {
2223 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2227 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2228 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2229 debug(DBG_WARN, "radsrv: message authentication failed");
2233 if (code == RAD_Status_Server) {
2234 respondstatusserver(rq);
2238 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2240 if (code == RAD_Accounting_Request) {
2241 memset(newauth, 0, 16);
2242 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2243 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2248 if (rq->from->conf->rewrite) {
2249 dorewrite(rq->buf, rq->from->conf->rewrite);
2250 len = RADLEN(rq->buf) - 20;
2253 attr = attrget(attrs, len, RAD_Attr_User_Name);
2255 if (code == RAD_Accounting_Request) {
2256 acclog(attrs, len, rq->from->conf->host);
2257 respondaccounting(rq);
2259 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2262 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2263 username[ATTRVALLEN(attr)] = '\0';
2264 radattr2ascii(userascii, sizeof(userascii), attr);
2266 if (rq->from->conf->rewriteattrregex) {
2267 if (!rewriteusername(rq, username)) {
2268 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2271 len = RADLEN(rq->buf) - 20;
2272 auth = (uint8_t *)(rq->buf + 4);
2273 attrs = rq->buf + 20;
2276 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2278 to = findserver(&realm, username, code == RAD_Accounting_Request);
2280 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2284 if (realm->message && code == RAD_Access_Request) {
2285 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2286 respondreject(rq, realm->message);
2287 } else if (realm->accresp && code == RAD_Accounting_Request) {
2288 acclog(attrs, len, rq->from->conf->host);
2289 respondaccounting(rq);
2294 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2295 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2296 rq->from->conf->name, to->conf->name);
2300 if (rqinqueue(to, rq->from, id, code)) {
2301 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2302 radmsgtype2string(code), rq->from->conf->host, id);
2306 if (code != RAD_Accounting_Request) {
2307 if (!RAND_bytes(newauth, 16)) {
2308 debug(DBG_WARN, "radsrv: failed to generate random auth");
2314 printfchars(NULL, "auth", "%02x ", auth, 16);
2317 attr = attrget(attrs, len, RAD_Attr_User_Password);
2319 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2320 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2324 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2326 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2327 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2332 memcpy(rq->origauth, auth, 16);
2333 memcpy(auth, newauth, 16);
2346 int replyh(struct server *server, unsigned char *buf) {
2347 struct client *from;
2350 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2351 struct sockaddr_storage fromsa;
2352 char tmp[760], stationid[760];
2354 server->connectionok = 1;
2355 server->lostrqs = 0;
2357 i = buf[1]; /* i is the id */
2359 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2360 && *buf != RAD_Accounting_Response) {
2361 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2364 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2366 rq = server->requests + i;
2368 pthread_mutex_lock(&server->newrq_mutex);
2369 if (!rq->buf || !rq->tries) {
2370 pthread_mutex_unlock(&server->newrq_mutex);
2371 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2376 pthread_mutex_unlock(&server->newrq_mutex);
2377 debug(DBG_INFO, "replyh: already received, ignoring reply");
2381 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2382 pthread_mutex_unlock(&server->newrq_mutex);
2383 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2387 len = RADLEN(buf) - 20;
2390 if (!attrvalidate(attrs, len)) {
2391 pthread_mutex_unlock(&server->newrq_mutex);
2392 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2396 /* Message Authenticator */
2397 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2399 if (ATTRVALLEN(messageauth) != 16) {
2400 pthread_mutex_unlock(&server->newrq_mutex);
2401 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2404 memcpy(tmp, buf + 4, 16);
2405 memcpy(buf + 4, rq->buf + 4, 16);
2406 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2407 pthread_mutex_unlock(&server->newrq_mutex);
2408 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2411 memcpy(buf + 4, tmp, 16);
2412 debug(DBG_DBG, "replyh: message auth ok");
2415 if (*rq->buf == RAD_Status_Server) {
2417 pthread_mutex_unlock(&server->newrq_mutex);
2418 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2422 gettimeofday(&server->lastreply, NULL);
2426 pthread_mutex_unlock(&server->newrq_mutex);
2427 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2431 if (server->conf->rewrite) {
2432 dorewrite(buf, server->conf->rewrite);
2433 len = RADLEN(buf) - 20;
2437 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2438 if (ATTRVALLEN(attr) <= 4)
2441 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2444 sublen = ATTRVALLEN(attr) - 4;
2445 subattrs = ATTRVAL(attr) + 4;
2446 if (!attrvalidate(subattrs, sublen) ||
2447 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2448 rq, server->conf->secret, from->conf->secret) ||
2449 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2450 rq, server->conf->secret, from->conf->secret))
2454 pthread_mutex_unlock(&server->newrq_mutex);
2455 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2459 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2460 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2462 radattr2ascii(tmp, sizeof(tmp), attr);
2463 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2465 radattr2ascii(stationid, sizeof(stationid), attr);
2466 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2467 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2469 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2473 buf[1] = (char)rq->origid;
2474 memcpy(buf + 4, rq->origauth, 16);
2476 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2479 if (rq->origusername) {
2480 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2482 pthread_mutex_unlock(&server->newrq_mutex);
2483 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2486 memcpy(username, rq->origusername, strlen(rq->origusername));
2487 len = RADLEN(buf) - 20;
2490 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2494 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2495 pthread_mutex_unlock(&server->newrq_mutex);
2496 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2499 debug(DBG_DBG, "replyh: computed messageauthattr");
2502 fromsa = rq->fromsa; /* only needed for UDP */
2503 /* once we set received = 1, rq may be reused */
2506 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2507 sendreply(from, buf, &fromsa, rq->fromudpsock);
2508 pthread_mutex_unlock(&server->newrq_mutex);
2512 void *udpclientrd(void *arg) {
2513 struct server *server;
2515 int *s = (int *)arg;
2519 buf = radudpget(*s, NULL, &server, NULL);
2520 if (!replyh(server, buf))
2525 void *tlsclientrd(void *arg) {
2526 struct server *server = (struct server *)arg;
2528 struct timeval now, lastconnecttry;
2531 /* yes, lastconnecttry is really necessary */
2532 lastconnecttry = server->lastconnecttry;
2533 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2535 if (server->dynamiclookuparg)
2537 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2541 if (!replyh(server, buf))
2543 if (server->dynamiclookuparg) {
2544 gettimeofday(&now, NULL);
2545 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2546 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2551 server->clientrdgone = 1;
2555 void *tcpclientrd(void *arg) {
2556 struct server *server = (struct server *)arg;
2558 struct timeval lastconnecttry;
2561 /* yes, lastconnecttry is really necessary */
2562 lastconnecttry = server->lastconnecttry;
2563 buf = radtcpget(server->sock, 0);
2565 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2569 if (!replyh(server, buf))
2572 server->clientrdgone = 1;
2576 /* code for removing state not finished */
2577 void *clientwr(void *arg) {
2578 struct server *server = (struct server *)arg;
2580 pthread_t clientrdth;
2581 int i, dynconffail = 0;
2583 struct timeval now, lastsend;
2584 struct timespec timeout;
2585 struct request statsrvrq;
2586 unsigned char statsrvbuf[38];
2587 struct clsrvconf *conf;
2589 conf = server->conf;
2591 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2596 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2597 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2601 memset(&timeout, 0, sizeof(struct timespec));
2603 if (conf->statusserver) {
2604 memset(&statsrvrq, 0, sizeof(struct request));
2605 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2606 statsrvbuf[0] = RAD_Status_Server;
2608 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2609 statsrvbuf[21] = 18;
2610 gettimeofday(&lastsend, NULL);
2613 if (conf->pdef->connecter) {
2614 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2616 server->connectionok = 1;
2617 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2618 debug(DBG_ERR, "clientwr: pthread_create failed");
2622 server->connectionok = 1;
2625 pthread_mutex_lock(&server->newrq_mutex);
2626 if (!server->newrq) {
2627 gettimeofday(&now, NULL);
2628 /* random 0-7 seconds */
2629 RAND_bytes(&rnd, 1);
2631 if (conf->statusserver) {
2632 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2633 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2635 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2636 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2639 if (timeout.tv_sec > now.tv_sec)
2640 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2642 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2645 if (server->newrq) {
2646 debug(DBG_DBG, "clientwr: got new request");
2651 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2653 pthread_mutex_unlock(&server->newrq_mutex);
2655 for (i = 0; i < MAX_REQUESTS; i++) {
2656 if (server->clientrdgone) {
2657 pthread_join(clientrdth, NULL);
2660 pthread_mutex_lock(&server->newrq_mutex);
2661 while (i < MAX_REQUESTS && !server->requests[i].buf)
2663 if (i == MAX_REQUESTS) {
2664 pthread_mutex_unlock(&server->newrq_mutex);
2667 rq = server->requests + i;
2670 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2672 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2674 /* setting this to NULL means that it can be reused */
2677 pthread_mutex_unlock(&server->newrq_mutex);
2681 gettimeofday(&now, NULL);
2682 if (now.tv_sec < rq->expiry.tv_sec) {
2683 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2684 timeout.tv_sec = rq->expiry.tv_sec;
2685 pthread_mutex_unlock(&server->newrq_mutex);
2689 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2690 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2691 if (conf->statusserver) {
2692 if (*rq->buf == RAD_Status_Server) {
2693 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2694 if (server->lostrqs < 255)
2698 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2699 if (server->lostrqs < 255)
2703 /* setting this to NULL means that it can be reused */
2705 pthread_mutex_unlock(&server->newrq_mutex);
2708 pthread_mutex_unlock(&server->newrq_mutex);
2710 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2711 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2712 timeout.tv_sec = rq->expiry.tv_sec;
2714 conf->pdef->clientradput(server, server->requests[i].buf);
2715 gettimeofday(&lastsend, NULL);
2717 if (conf->statusserver) {
2718 gettimeofday(&now, NULL);
2719 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2720 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2721 debug(DBG_WARN, "clientwr: failed to generate random auth");
2724 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2725 if (!statsrvrq.buf) {
2726 debug(DBG_ERR, "clientwr: malloc failed");
2729 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2730 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2731 lastsend.tv_sec = now.tv_sec;
2732 sendrq(server, &statsrvrq);
2737 conf->servers = NULL;
2738 if (server->dynamiclookuparg) {
2739 removeserversubrealms(realms, conf);
2743 freeclsrvconf(conf);
2745 freeserver(server, 1);
2749 void *udpserverwr(void *arg) {
2750 struct replyq *replyq = udp_server_replyq;
2751 struct reply *reply;
2754 pthread_mutex_lock(&replyq->mutex);
2755 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2756 debug(DBG_DBG, "udp server writer, waiting for signal");
2757 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2758 debug(DBG_DBG, "udp server writer, got signal");
2760 pthread_mutex_unlock(&replyq->mutex);
2762 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2763 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2764 debug(DBG_WARN, "sendudp: send failed");
2770 void *udpserverrd(void *arg) {
2772 int *sp = (int *)arg;
2775 memset(&rq, 0, sizeof(struct request));
2776 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2777 rq.fromudpsock = *sp;
2783 void *tlsserverwr(void *arg) {
2785 unsigned long error;
2786 struct client *client = (struct client *)arg;
2787 struct replyq *replyq;
2788 struct reply *reply;
2790 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2791 replyq = client->replyq;
2793 pthread_mutex_lock(&replyq->mutex);
2794 while (!list_first(replyq->replies)) {
2796 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2797 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2798 debug(DBG_DBG, "tlsserverwr: got signal");
2801 /* ssl might have changed while waiting */
2802 pthread_mutex_unlock(&replyq->mutex);
2803 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2807 reply = (struct reply *)list_shift(replyq->replies);
2808 pthread_mutex_unlock(&replyq->mutex);
2809 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2811 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2812 cnt, RADLEN(reply->buf));
2814 while ((error = ERR_get_error()))
2815 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2821 void tlsserverrd(struct client *client) {
2823 pthread_t tlsserverwrth;
2825 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2827 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2828 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2833 memset(&rq, 0, sizeof(struct request));
2834 rq.buf = radtlsget(client->ssl, 0);
2836 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2839 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2842 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2847 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2849 pthread_mutex_lock(&client->replyq->mutex);
2850 pthread_cond_signal(&client->replyq->cond);
2851 pthread_mutex_unlock(&client->replyq->mutex);
2852 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2853 pthread_join(tlsserverwrth, NULL);
2854 removeclientrqs(client);
2855 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2858 void *tlsservernew(void *arg) {
2860 struct sockaddr_storage from;
2861 size_t fromlen = sizeof(from);
2862 struct clsrvconf *conf;
2863 struct list_node *cur = NULL;
2866 unsigned long error;
2867 struct client *client;
2870 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2871 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2874 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2876 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2878 ssl = SSL_new(conf->ssl_ctx);
2881 if (SSL_accept(ssl) <= 0) {
2882 while ((error = ERR_get_error()))
2883 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2884 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2887 cert = verifytlscert(ssl);
2893 if (verifyconfcert(cert, conf)) {
2895 client = addclient(conf);
2898 tlsserverrd(client);
2899 removeclient(client);
2901 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2904 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2906 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2912 shutdown(s, SHUT_RDWR);
2917 void *tlslistener(void *arg) {
2918 pthread_t tlsserverth;
2919 int s, *sp = (int *)arg;
2920 struct sockaddr_storage from;
2921 size_t fromlen = sizeof(from);
2926 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2928 debug(DBG_WARN, "accept failed");
2931 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2932 debug(DBG_ERR, "tlslistener: pthread_create failed");
2933 shutdown(s, SHUT_RDWR);
2937 pthread_detach(tlsserverth);
2943 void *tcpserverwr(void *arg) {
2945 struct client *client = (struct client *)arg;
2946 struct replyq *replyq;
2947 struct reply *reply;
2949 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2950 replyq = client->replyq;
2952 pthread_mutex_lock(&replyq->mutex);
2953 while (!list_first(replyq->replies)) {
2954 if (client->s >= 0) {
2955 debug(DBG_DBG, "tcpserverwr: waiting for signal");
2956 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2957 debug(DBG_DBG, "tcpserverwr: got signal");
2959 if (client->s < 0) {
2960 /* s might have changed while waiting */
2961 pthread_mutex_unlock(&replyq->mutex);
2962 debug(DBG_DBG, "tcpserverwr: exiting as requested");
2966 reply = (struct reply *)list_shift(replyq->replies);
2967 pthread_mutex_unlock(&replyq->mutex);
2968 cnt = write(client->s, reply->buf, RADLEN(reply->buf));
2970 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
2971 cnt, RADLEN(reply->buf));
2973 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
2979 void tcpserverrd(struct client *client) {
2981 pthread_t tcpserverwrth;
2983 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
2985 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
2986 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
2991 memset(&rq, 0, sizeof(struct request));
2992 rq.buf = radtcpget(client->s, 0);
2994 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
2997 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3000 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3005 /* stop writer by setting s to -1 and give signal in case waiting for data */
3007 pthread_mutex_lock(&client->replyq->mutex);
3008 pthread_cond_signal(&client->replyq->cond);
3009 pthread_mutex_unlock(&client->replyq->mutex);
3010 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3011 pthread_join(tcpserverwrth, NULL);
3012 removeclientrqs(client);
3013 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3016 void *tcpservernew(void *arg) {
3018 struct sockaddr_storage from;
3019 size_t fromlen = sizeof(from);
3020 struct clsrvconf *conf;
3021 struct client *client;
3024 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3025 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3028 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3030 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3032 client = addclient(conf);
3035 tcpserverrd(client);
3036 removeclient(client);
3038 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3040 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3043 shutdown(s, SHUT_RDWR);
3048 void *tcplistener(void *arg) {
3049 pthread_t tcpserverth;
3050 int s, *sp = (int *)arg;
3051 struct sockaddr_storage from;
3052 size_t fromlen = sizeof(from);
3057 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3059 debug(DBG_WARN, "accept failed");
3062 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3063 debug(DBG_ERR, "tcplistener: pthread_create failed");
3064 shutdown(s, SHUT_RDWR);
3068 pthread_detach(tcpserverth);
3074 void createlistener(uint8_t type, char *arg) {
3076 struct clsrvconf *listenres;
3077 struct addrinfo *res;
3078 int s = -1, on = 1, *sp = NULL;
3080 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3082 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3084 for (res = listenres->addrinfo; res; res = res->ai_next) {
3085 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3087 debug(DBG_WARN, "createlistener: socket failed");
3090 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3092 if (res->ai_family == AF_INET6)
3093 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3095 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3096 debug(DBG_WARN, "createlistener: bind failed");
3102 sp = malloc(sizeof(int));
3104 debugx(1, DBG_ERR, "malloc failed");
3105 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3106 debugx(1, DBG_ERR, "pthread_create failed");
3110 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3112 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3113 listenres->host ? listenres->host : "*", listenres->port);
3114 freeclsrvres(listenres);
3117 void createlisteners(uint8_t type, char **args) {
3121 for (i = 0; args[i]; i++)
3122 createlistener(type, args[i]);
3124 createlistener(type, NULL);
3127 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
3130 STACK_OF(X509_NAME) *calist;
3133 unsigned long error;
3135 if (!certfile || !certkeyfile)
3136 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
3138 if (!cacertfile && !cacertpath)
3139 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
3142 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3143 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3144 for (i = 0; i < CRYPTO_num_locks(); i++) {
3145 ssl_lock_count[i] = 0;
3146 pthread_mutex_init(&ssl_locks[i], NULL);
3148 CRYPTO_set_id_callback(ssl_thread_id);
3149 CRYPTO_set_locking_callback(ssl_locking_callback);
3151 SSL_load_error_strings();
3154 while (!RAND_status()) {
3155 time_t t = time(NULL);
3156 pid_t pid = getpid();
3157 RAND_seed((unsigned char *)&t, sizeof(time_t));
3158 RAND_seed((unsigned char *)&pid, sizeof(pid));
3161 ctx = SSL_CTX_new(TLSv1_method());
3163 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
3164 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3166 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
3167 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
3168 !SSL_CTX_check_private_key(ctx) ||
3169 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
3170 while ((error = ERR_get_error()))
3171 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3172 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
3175 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
3176 if (!cacertfile || calist) {
3179 calist = sk_X509_NAME_new_null();
3180 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
3181 sk_X509_NAME_free(calist);
3187 while ((error = ERR_get_error()))
3188 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3189 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
3191 SSL_CTX_set_client_CA_list(ctx, calist);
3193 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3194 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3197 x509_s = SSL_CTX_get_cert_store(ctx);
3198 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3201 new = malloc(sizeof(struct tls));
3202 if (!new || !list_push(tlsconfs, new))
3203 debugx(1, DBG_ERR, "malloc failed");
3205 memset(new, 0, sizeof(struct tls));
3206 new->name = stringcopy(value, 0);
3208 debugx(1, DBG_ERR, "malloc failed");
3210 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
3213 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
3214 struct list_node *entry;
3215 struct tls *t, *t1 = NULL, *t2 = NULL;
3217 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3218 t = (struct tls *)entry->data;
3219 if (!strcasecmp(t->name, alt1)) {
3223 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3233 struct list *addsrvconfs(char *value, char **names) {
3234 struct list *conflist;
3236 struct list_node *entry;
3237 struct clsrvconf *conf = NULL;
3239 if (!names || !*names)
3242 conflist = list_create();
3244 debug(DBG_ERR, "malloc failed");
3248 for (n = 0; names[n]; n++) {
3249 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3250 conf = (struct clsrvconf *)entry->data;
3251 if (!strcasecmp(names[n], conf->name))
3255 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3256 list_destroy(conflist);
3259 if (!list_push(conflist, conf)) {
3260 debug(DBG_ERR, "malloc failed");
3261 list_destroy(conflist);
3264 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3269 void freerealm(struct realm *realm) {
3273 free(realm->message);
3274 regfree(&realm->regex);
3275 pthread_mutex_destroy(&realm->subrealms_mutex);
3276 if (realm->subrealms)
3277 list_destroy(realm->subrealms);
3278 if (realm->srvconfs) {
3279 /* emptying list without freeing data */
3280 while (list_shift(realm->srvconfs));
3281 list_destroy(realm->srvconfs);
3283 if (realm->accsrvconfs) {
3284 /* emptying list without freeing data */
3285 while (list_shift(realm->accsrvconfs));
3286 list_destroy(realm->accsrvconfs);
3291 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3293 struct realm *realm;
3294 char *s, *regex = NULL;
3296 if (*value == '/') {
3297 /* regexp, remove optional trailing / if present */
3298 if (value[strlen(value) - 1] == '/')
3299 value[strlen(value) - 1] = '\0';
3301 /* not a regexp, let us make it one */
3302 if (*value == '*' && !value[1])
3303 regex = stringcopy(".*", 0);
3305 for (n = 0, s = value; *s;)
3308 regex = malloc(strlen(value) + n + 3);
3311 for (n = 1, s = value; *s; s++) {
3321 debug(DBG_ERR, "malloc failed");
3325 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3328 realm = malloc(sizeof(struct realm));
3330 debug(DBG_ERR, "malloc failed");
3333 memset(realm, 0, sizeof(struct realm));
3335 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3336 debug(DBG_ERR, "mutex init failed");
3342 realm->name = stringcopy(value, 0);
3344 debug(DBG_ERR, "malloc failed");
3347 if (message && strlen(message) > 253) {
3348 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3351 realm->message = message;
3352 realm->accresp = accresp;
3354 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3355 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3359 if (servers && *servers) {
3360 realm->srvconfs = addsrvconfs(value, servers);
3361 if (!realm->srvconfs)
3365 if (accservers && *accservers) {
3366 realm->accsrvconfs = addsrvconfs(value, accservers);
3367 if (!realm->accsrvconfs)
3371 if (!list_push(realmlist, realm)) {
3372 debug(DBG_ERR, "malloc failed");
3373 pthread_mutex_destroy(&realm->subrealms_mutex);
3377 debug(DBG_DBG, "addrealm: added realm %s", value);
3387 for (n = 0; servers[n]; n++)
3392 for (n = 0; accservers[n]; n++)
3393 free(accservers[n]);
3399 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3400 struct clsrvconf *srvconf;
3401 struct realm *newrealm = NULL;
3402 char *realmname, *s;
3405 if (!conf->dynamiclookupcommand)
3408 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3409 realmname = strrchr(id, '@');
3415 for (s = realmname; *s; s++)
3416 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3419 pthread_mutex_lock(&realm->subrealms_mutex);
3420 /* exit if we now already got a matching subrealm */
3421 if (id2realm(realm->subrealms, id))
3423 srvconf = malloc(sizeof(struct clsrvconf));
3425 debug(DBG_ERR, "malloc failed");
3429 if (!addserver(srvconf))
3432 if (!realm->subrealms)
3433 realm->subrealms = list_create();
3434 if (!realm->subrealms)
3436 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3440 /* add server and accserver to newrealm */
3441 newrealm->srvconfs = list_create();
3442 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3443 debug(DBG_ERR, "malloc failed");
3446 newrealm->accsrvconfs = list_create();
3447 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3448 debug(DBG_ERR, "malloc failed");
3452 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3454 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3455 debug(DBG_ERR, "pthread_create failed");
3458 pthread_detach(clientth);
3463 list_removedata(realm->subrealms, newrealm);
3464 freerealm(newrealm);
3465 if (!list_first(realm->subrealms)) {
3466 list_destroy(realm->subrealms);
3467 realm->subrealms = NULL;
3470 freeserver(srvconf->servers, 1);
3472 debug(DBG_ERR, "failed to create dynamic server");
3475 pthread_mutex_unlock(&realm->subrealms_mutex);
3478 int dynamicconfig(struct server *server) {
3479 int ok, fd[2], status;
3481 struct clsrvconf *conf = server->conf;
3482 struct gconffile *cf = NULL;
3484 /* for now we only learn hostname/address */
3485 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3488 debug(DBG_ERR, "dynamicconfig: pipe error");
3493 debug(DBG_ERR, "dynamicconfig: fork error");
3497 } else if (pid == 0) {
3500 if (fd[1] != STDOUT_FILENO) {
3501 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3502 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3505 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3506 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3510 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3511 ok = getgenericconfig(&cf, NULL,
3512 "Server", CONF_CBK, confserver_cb, (void *)conf,
3517 if (waitpid(pid, &status, 0) < 0) {
3518 debug(DBG_ERR, "dynamicconfig: wait error");
3523 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3531 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3535 int addmatchcertattr(struct clsrvconf *conf) {
3539 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3540 r = &conf->certcnregex;
3541 v = conf->matchcertattr + 4;
3542 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3543 r = &conf->certuriregex;
3544 v = conf->matchcertattr + 20;
3549 /* regexp, remove optional trailing / if present */
3550 if (v[strlen(v) - 1] == '/')
3551 v[strlen(v) - 1] = '\0';
3555 *r = malloc(sizeof(regex_t));
3557 debug(DBG_ERR, "malloc failed");
3560 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3563 debug(DBG_ERR, "failed to compile regular expression %s", v);
3569 int addrewriteattr(struct clsrvconf *conf) {
3572 v = conf->rewriteattr + 11;
3573 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3575 /* regexp, remove optional trailing / if present */
3576 if (v[strlen(v) - 1] == '/')
3577 v[strlen(v) - 1] = '\0';
3585 conf->rewriteattrregex = malloc(sizeof(regex_t));
3586 if (!conf->rewriteattrregex) {
3587 debug(DBG_ERR, "malloc failed");
3591 conf->rewriteattrreplacement = stringcopy(w, 0);
3592 if (!conf->rewriteattrreplacement) {
3593 free(conf->rewriteattrregex);
3594 conf->rewriteattrregex = NULL;
3598 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3599 free(conf->rewriteattrregex);
3600 conf->rewriteattrregex = NULL;
3601 free(conf->rewriteattrreplacement);
3602 conf->rewriteattrreplacement = NULL;
3603 debug(DBG_ERR, "failed to compile regular expression %s", v);
3610 /* should accept both names and numeric values, only numeric right now */
3611 uint8_t attrname2val(char *attrname) {
3614 val = atoi(attrname);
3615 return val > 0 && val < 256 ? val : 0;
3618 /* should accept both names and numeric values, only numeric right now */
3619 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3622 *vendor = atoi(attrname);
3623 s = strchr(attrname, ':');
3628 *type = atoi(s + 1);
3629 return *type >= 0 && *type < 256;
3632 struct rewrite *getrewrite(char *alt1, char *alt2) {
3633 struct list_node *entry;
3634 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3636 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3637 r = (struct rewriteconf *)entry->data;
3638 if (!strcasecmp(r->name, alt1)) {
3642 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3652 void addrewrite(char *value, char **attrs, char **vattrs) {
3653 struct rewriteconf *new;
3654 struct rewrite *rewrite = NULL;
3657 uint32_t *p, *va = NULL;
3661 for (; attrs[n]; n++);
3662 a = malloc((n + 1) * sizeof(uint8_t));
3664 debugx(1, DBG_ERR, "malloc failed");
3666 for (i = 0; i < n; i++) {
3667 if (!(a[i] = attrname2val(attrs[i])))
3668 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3677 for (; vattrs[n]; n++);
3678 va = malloc((2 * n + 1) * sizeof(uint32_t));
3680 debugx(1, DBG_ERR, "malloc failed");
3682 for (p = va, i = 0; i < n; i++, p += 2) {
3683 if (!vattrname2val(vattrs[i], p, p + 1))
3684 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3692 rewrite = malloc(sizeof(struct rewrite));
3694 debugx(1, DBG_ERR, "malloc failed");
3695 rewrite->removeattrs = a;
3696 rewrite->removevendorattrs = va;
3699 new = malloc(sizeof(struct rewriteconf));
3700 if (!new || !list_push(rewriteconfs, new))
3701 debugx(1, DBG_ERR, "malloc failed");
3703 memset(new, 0, sizeof(struct rewriteconf));
3704 new->name = stringcopy(value, 0);
3706 debugx(1, DBG_ERR, "malloc failed");
3708 new->rewrite = rewrite;
3709 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3712 void freeclsrvconf(struct clsrvconf *conf) {
3718 free(conf->matchcertattr);
3719 if (conf->certcnregex)
3720 regfree(conf->certcnregex);
3721 if (conf->certuriregex)
3722 regfree(conf->certuriregex);
3723 free(conf->confrewrite);
3724 free(conf->rewriteattr);
3725 if (conf->rewriteattrregex)
3726 regfree(conf->rewriteattrregex);
3727 free(conf->rewriteattrreplacement);
3728 free(conf->dynamiclookupcommand);
3729 free(conf->rewrite);
3731 freeaddrinfo(conf->addrinfo);
3732 /* not touching ssl_ctx, clients and servers */
3736 int mergeconfstring(char **dst, char **src) {
3745 t = stringcopy(*dst, 0);
3747 debug(DBG_ERR, "malloc failed");
3755 /* assumes dst is a shallow copy */
3756 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3757 if (!mergeconfstring(&dst->name, &src->name) ||
3758 !mergeconfstring(&dst->host, &src->host) ||
3759 !mergeconfstring(&dst->port, &src->port) ||
3760 !mergeconfstring(&dst->secret, &src->secret) ||
3761 !mergeconfstring(&dst->tls, &src->tls) ||
3762 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3763 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3764 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3767 dst->pdef = src->pdef;
3768 dst->statusserver = src->statusserver;
3769 dst->certnamecheck = src->certnamecheck;
3770 if (src->retryinterval != 255)
3771 dst->retryinterval = src->retryinterval;
3772 if (src->retrycount != 255)
3773 dst->retrycount = src->retrycount;
3777 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3778 struct clsrvconf *conf;
3779 char *conftype = NULL;
3781 debug(DBG_DBG, "confclient_cb called for %s", block);
3783 conf = malloc(sizeof(struct clsrvconf));
3784 if (!conf || !list_push(clconfs, conf))
3785 debugx(1, DBG_ERR, "malloc failed");
3786 memset(conf, 0, sizeof(struct clsrvconf));
3787 conf->certnamecheck = 1;
3789 if (!getgenericconfig(cf, block,
3790 "type", CONF_STR, &conftype,
3791 "host", CONF_STR, &conf->host,
3792 "secret", CONF_STR, &conf->secret,
3793 "tls", CONF_STR, &conf->tls,
3794 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3795 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3796 "rewrite", CONF_STR, &conf->confrewrite,
3797 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3800 debugx(1, DBG_ERR, "configuration error");
3802 conf->name = stringcopy(val, 0);
3804 conf->host = stringcopy(val, 0);
3807 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3808 conf->type = protoname2int(conftype);
3809 conf->pdef = &protodefs[conf->type];
3810 if (!conf->pdef->name)
3811 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3814 if (conf->type == RAD_TLS) {
3815 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3817 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3818 if (conf->matchcertattr && !addmatchcertattr(conf))
3819 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3822 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3824 if (conf->rewriteattr) {
3825 if (!addrewriteattr(conf))
3826 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3829 if (!resolvepeer(conf, 0))
3830 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3832 if (!conf->secret) {
3833 if (!conf->pdef->secretdefault)
3834 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3835 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3837 debugx(1, DBG_ERR, "malloc failed");
3842 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3843 if (conf->type == RAD_TLS) {
3844 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3845 if (!conf->ssl_ctx) {
3846 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3849 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3850 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3856 conf->port = stringcopy(conf->pdef->portdefault, 0);
3858 debug(DBG_ERR, "malloc failed");
3863 if (conf->retryinterval == 255)
3864 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3865 if (conf->retrycount == 255)
3866 conf->retrycount = protodefs[conf->type].retrycountdefault;
3868 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3870 if (!conf->secret) {
3871 if (!conf->pdef->secretdefault) {
3872 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3875 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3876 if (!conf->secret) {
3877 debug(DBG_ERR, "malloc failed");
3882 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3883 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3889 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3890 struct clsrvconf *conf, *resconf;
3891 char *conftype = NULL;
3892 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3894 debug(DBG_DBG, "confserver_cb called for %s", block);
3896 conf = malloc(sizeof(struct clsrvconf));
3898 debug(DBG_ERR, "malloc failed");
3901 memset(conf, 0, sizeof(struct clsrvconf));
3902 resconf = (struct clsrvconf *)arg;
3904 conf->statusserver = resconf->statusserver;
3905 conf->certnamecheck = resconf->certnamecheck;
3907 conf->certnamecheck = 1;
3909 if (!getgenericconfig(cf, block,
3910 "type", CONF_STR, &conftype,
3911 "host", CONF_STR, &conf->host,
3912 "port", CONF_STR, &conf->port,
3913 "secret", CONF_STR, &conf->secret,
3914 "tls", CONF_STR, &conf->tls,
3915 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3916 "rewrite", CONF_STR, &conf->confrewrite,
3917 "StatusServer", CONF_BLN, &conf->statusserver,
3918 "RetryInterval", CONF_LINT, &retryinterval,
3919 "RetryCount", CONF_LINT, &retrycount,
3920 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3921 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3924 debug(DBG_ERR, "configuration error");
3928 conf->name = stringcopy(val, 0);
3930 debug(DBG_ERR, "malloc failed");
3934 conf->host = stringcopy(val, 0);
3936 debug(DBG_ERR, "malloc failed");
3942 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3943 conf->type = protoname2int(conftype);
3944 conf->pdef = &protodefs[conf->type];
3945 if (!conf->pdef->name) {
3946 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3952 if (retryinterval != LONG_MIN) {
3953 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3954 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3957 conf->retryinterval = (uint8_t)retryinterval;
3959 conf->retryinterval = 255;
3961 if (retrycount != LONG_MIN) {
3962 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3963 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3966 conf->retrycount = (uint8_t)retrycount;
3968 conf->retrycount = 255;
3971 if (!mergesrvconf(resconf, conf))
3975 if (conf->dynamiclookupcommand) {
3976 free(conf->dynamiclookupcommand);
3977 conf->dynamiclookupcommand = NULL;
3981 if (resconf || !conf->dynamiclookupcommand) {
3982 if (!compileserverconfig(conf, block))
3989 if (!list_push(srvconfs, conf)) {
3990 debug(DBG_ERR, "malloc failed");
3996 freeclsrvconf(conf);
4000 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4001 char **servers = NULL, **accservers = NULL, *msg = NULL;
4002 uint8_t accresp = 0;
4004 debug(DBG_DBG, "confrealm_cb called for %s", block);
4006 if (!getgenericconfig(cf, block,
4007 "server", CONF_MSTR, &servers,
4008 "accountingServer", CONF_MSTR, &accservers,
4009 "ReplyMessage", CONF_STR, &msg,
4010 "AccountingResponse", CONF_BLN, &accresp,
4013 debugx(1, DBG_ERR, "configuration error");
4015 addrealm(realms, val, servers, accservers, msg, accresp);
4019 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4020 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
4021 uint8_t crlcheck = 0;
4023 debug(DBG_DBG, "conftls_cb called for %s", block);
4025 if (!getgenericconfig(cf, block,
4026 "CACertificateFile", CONF_STR, &cacertfile,
4027 "CACertificatePath", CONF_STR, &cacertpath,
4028 "CertificateFile", CONF_STR, &certfile,
4029 "CertificateKeyFile", CONF_STR, &certkeyfile,
4030 "CertificateKeyPassword", CONF_STR, &certkeypwd,
4031 "CRLCheck", CONF_BLN, &crlcheck,
4034 debugx(1, DBG_ERR, "configuration error");
4036 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
4045 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4046 char **attrs = NULL, **vattrs = NULL;
4048 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4050 if (!getgenericconfig(cf, block,
4051 "removeAttribute", CONF_MSTR, &attrs,
4052 "removeVendorAttribute", CONF_MSTR, &vattrs,
4055 debugx(1, DBG_ERR, "configuration error");
4056 addrewrite(val, attrs, vattrs);
4060 void getmainconfig(const char *configfile) {
4061 long int loglevel = LONG_MIN;
4062 struct gconffile *cfs;
4064 cfs = openconfigfile(configfile);
4065 memset(&options, 0, sizeof(options));
4067 clconfs = list_create();
4069 debugx(1, DBG_ERR, "malloc failed");
4071 srvconfs = list_create();
4073 debugx(1, DBG_ERR, "malloc failed");
4075 realms = list_create();
4077 debugx(1, DBG_ERR, "malloc failed");
4079 tlsconfs = list_create();
4081 debugx(1, DBG_ERR, "malloc failed");
4083 rewriteconfs = list_create();
4085 debugx(1, DBG_ERR, "malloc failed");
4087 if (!getgenericconfig(&cfs, NULL,
4088 "ListenUDP", CONF_MSTR, &options.listenudp,
4089 "ListenTCP", CONF_MSTR, &options.listentcp,
4090 "ListenTLS", CONF_MSTR, &options.listentls,
4091 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4092 "SourceUDP", CONF_STR, &options.sourceudp,
4093 "SourceTCP", CONF_STR, &options.sourcetcp,
4094 "SourceTLS", CONF_STR, &options.sourcetls,
4095 "LogLevel", CONF_LINT, &loglevel,
4096 "LogDestination", CONF_STR, &options.logdestination,
4097 "LoopPrevention", CONF_BLN, &options.loopprevention,
4098 "Client", CONF_CBK, confclient_cb, NULL,
4099 "Server", CONF_CBK, confserver_cb, NULL,
4100 "Realm", CONF_CBK, confrealm_cb, NULL,
4101 "TLS", CONF_CBK, conftls_cb, NULL,
4102 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4105 debugx(1, DBG_ERR, "configuration error");
4107 if (loglevel != LONG_MIN) {
4108 if (loglevel < 1 || loglevel > 4)
4109 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4110 options.loglevel = (uint8_t)loglevel;
4114 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4117 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4120 *configfile = optarg;
4123 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4124 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4125 *loglevel = *optarg - '0';
4134 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4139 if (!(argc - optind))
4143 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4147 int daemon(int a, int b) {
4155 for (i = 0; i < 3; i++) {
4157 open("/dev/null", O_RDWR);
4163 void *sighandler(void *arg) {
4168 sigemptyset(&sigset);
4169 sigaddset(&sigset, SIGPIPE);
4170 sigwait(&sigset, &sig);
4171 /* only get SIGPIPE right now, so could simplify below code */
4174 /* completely ignoring this */
4177 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4180 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4185 int main(int argc, char **argv) {
4186 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
4188 struct list_node *entry;
4189 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4190 char *configfile = NULL;
4191 struct clsrvconf *srvconf;
4193 debug_init("radsecproxy");
4194 debug_set_level(DEBUG_LEVEL);
4195 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4197 debug_set_level(loglevel);
4198 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4200 options.loglevel = loglevel;
4201 else if (options.loglevel)
4202 debug_set_level(options.loglevel);
4204 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4205 free(options.logdestination);
4207 if (!list_first(clconfs))
4208 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4209 if (!list_first(srvconfs))
4210 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
4211 if (!list_first(realms))
4212 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4215 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4217 if (!foreground && (daemon(0, 0) < 0))
4218 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4220 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4222 sigemptyset(&sigset);
4223 /* exit on all but SIGPIPE, ignore more? */
4224 sigaddset(&sigset, SIGPIPE);
4225 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4226 pthread_create(&sigth, NULL, sighandler, NULL);
4228 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4229 udp_server_replyq = newreplyq();
4230 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4231 debugx(1, DBG_ERR, "pthread_create failed");
4232 createlisteners(RAD_UDP, options.listenudp);
4233 if (options.listenaccudp)
4234 createlisteners(RAD_UDP, options.listenaccudp);
4237 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4238 srvconf = (struct clsrvconf *)entry->data;
4239 if (srvconf->dynamiclookupcommand)
4241 if (!addserver(srvconf))
4242 debugx(1, DBG_ERR, "failed to add server");
4243 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4244 (void *)(srvconf->servers)))
4245 debugx(1, DBG_ERR, "pthread_create failed");
4247 /* srcprotores for UDP no longer needed */
4248 if (srcprotores[RAD_UDP]) {
4249 freeaddrinfo(srcprotores[RAD_UDP]);
4250 srcprotores[RAD_UDP] = NULL;
4252 if (udp_client4_sock >= 0)
4253 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4254 debugx(1, DBG_ERR, "pthread_create failed");
4255 if (udp_client6_sock >= 0)
4256 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4257 debugx(1, DBG_ERR, "pthread_create failed");
4259 if (find_conf_type(RAD_TCP, clconfs, NULL))
4260 createlisteners(RAD_TCP, options.listentcp);
4262 if (find_conf_type(RAD_TLS, clconfs, NULL))
4263 createlisteners(RAD_TLS, options.listentls);
4265 /* just hang around doing nothing, anything to do here? */