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 * We are not removing client requests from dynamic servers, see removeclientrqs()
37 #include <sys/socket.h>
38 #include <netinet/in.h>
47 #include <sys/types.h>
48 #include <sys/select.h>
51 #include <arpa/inet.h>
55 #include <openssl/ssl.h>
56 #include <openssl/rand.h>
57 #include <openssl/err.h>
58 #include <openssl/md5.h>
59 #include <openssl/hmac.h>
60 #include <openssl/x509v3.h>
65 #include "radsecproxy.h"
67 static struct options options;
68 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
70 static struct addrinfo *srcprotores[3] = { NULL, NULL, NULL };
72 static struct replyq *udp_server_replyq = NULL;
73 static int udp_client4_sock = -1;
74 static int udp_client6_sock = -1;
75 static pthread_mutex_t *ssl_locks;
76 static long *ssl_lock_count;
80 /* minimum required declarations to avoid reordering code */
81 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
82 int dynamicconfig(struct server *server);
83 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
84 void freerealm(struct realm *realm);
85 void freeclsrvconf(struct clsrvconf *conf);
86 void freerqdata(struct request *rq);
87 void *udpserverrd(void *arg);
88 void *tlslistener(void *arg);
89 void *tcplistener(void *arg);
90 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
91 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
92 void *udpclientrd(void *arg);
93 void *tlsclientrd(void *arg);
94 void *tcpclientrd(void *arg);
95 int clientradputudp(struct server *server, unsigned char *rad);
96 int clientradputtls(struct server *server, unsigned char *rad);
97 int clientradputtcp(struct server *server, unsigned char *rad);
99 static const struct protodefs protodefs[] = {
100 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
101 NULL, /* secretdefault */
102 SOCK_DGRAM, /* socktype */
103 "1812", /* portdefault */
104 REQUEST_RETRY_COUNT, /* retrycountdefault */
105 10, /* retrycountmax */
106 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
107 60, /* retryintervalmax */
108 udpserverrd, /* listener */
109 &options.sourceudp, /* srcaddrport */
110 NULL, /* connecter */
111 udpclientrd, /* clientreader */
112 clientradputudp /* clientradput */
114 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
115 "mysecret", /* secretdefault */
116 SOCK_STREAM, /* socktype */
117 "2083", /* portdefault */
118 0, /* retrycountdefault */
119 0, /* retrycountmax */
120 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
121 60, /* retryintervalmax */
122 tlslistener, /* listener */
123 &options.sourcetls, /* srcaddrport */
124 tlsconnect, /* connecter */
125 tlsclientrd, /* clientreader */
126 clientradputtls /* clientradput */
128 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
129 NULL, /* secretdefault */
130 SOCK_STREAM, /* socktype */
131 "1812", /* portdefault */
132 0, /* retrycountdefault */
133 0, /* retrycountmax */
134 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
135 60, /* retryintervalmax */
136 tcplistener, /* listener */
137 &options.sourcetcp, /* srcaddrport */
138 tcpconnect, /* connecter */
139 tcpclientrd, /* clientreader */
140 clientradputtcp /* clientradput */
146 uint8_t protoname2int(const char *name) {
149 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
153 /* callbacks for making OpenSSL thread safe */
154 unsigned long ssl_thread_id() {
155 return (unsigned long)pthread_self();
158 void ssl_locking_callback(int mode, int type, const char *file, int line) {
159 if (mode & CRYPTO_LOCK) {
160 pthread_mutex_lock(&ssl_locks[type]);
161 ssl_lock_count[type]++;
163 pthread_mutex_unlock(&ssl_locks[type]);
166 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
167 int pwdlen = strlen(userdata);
168 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
170 memcpy(buf, userdata, pwdlen);
174 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
179 err_cert = X509_STORE_CTX_get_current_cert(ctx);
180 err = X509_STORE_CTX_get_error(ctx);
181 depth = X509_STORE_CTX_get_error_depth(ctx);
183 if (depth > MAX_CERT_DEPTH) {
185 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
186 X509_STORE_CTX_set_error(ctx, err);
190 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
191 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
194 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
195 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
196 debug(DBG_WARN, "\tIssuer=%s", buf);
198 case X509_V_ERR_CERT_NOT_YET_VALID:
199 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
200 debug(DBG_WARN, "\tCertificate not yet valid");
202 case X509_V_ERR_CERT_HAS_EXPIRED:
203 debug(DBG_WARN, "Certificate has expired");
205 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
206 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
211 printf("certificate verify returns %d\n", ok);
216 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
217 struct addrinfo hints, *addrinfo, *res;
221 slash = conf->host ? strchr(conf->host, '/') : NULL;
225 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
229 if (*s < '0' || *s > '9') {
230 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
233 plen = atoi(slash + 1);
234 if (plen < 0 || plen > 128) {
235 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
240 memset(&hints, 0, sizeof(hints));
241 hints.ai_socktype = conf->pdef->socktype;
242 hints.ai_family = AF_UNSPEC;
243 hints.ai_flags = ai_flags;
244 if (!conf->host && !conf->port) {
245 /* getaddrinfo() doesn't like host and port to be NULL */
246 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
247 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
250 for (res = addrinfo; res; res = res->ai_next) {
251 switch (res->ai_family) {
253 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
256 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
262 hints.ai_flags |= AI_NUMERICHOST;
263 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
264 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
269 switch (addrinfo->ai_family) {
272 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
273 freeaddrinfo(addrinfo);
280 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
281 freeaddrinfo(addrinfo);
284 conf->prefixlen = plen;
286 conf->prefixlen = 255;
289 freeaddrinfo(conf->addrinfo);
290 conf->addrinfo = addrinfo;
294 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
296 struct addrinfo *res;
298 for (res = addrinfo; res; res = res->ai_next) {
299 if (family != AF_UNSPEC && family != res->ai_family)
301 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
303 debug(DBG_WARN, "bindtoaddr: socket failed");
307 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
310 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
313 if (!bind(s, res->ai_addr, res->ai_addrlen))
315 debug(DBG_WARN, "bindtoaddr: bind failed");
321 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
326 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
330 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
332 debugx(1, DBG_ERR, "no ] matching initial [");
336 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
339 debugx(1, DBG_ERR, "missing host/address");
341 conf->host = stringcopy(field, p - field);
344 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
345 debugx(1, DBG_ERR, "unexpected character after ]");
348 /* port number or service name is specified */;
350 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
352 debugx(1, DBG_ERR, "syntax error, : but no following port");
353 conf->port = stringcopy(field, p - field);
355 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
359 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
360 struct clsrvconf *conf;
362 conf = malloc(sizeof(struct clsrvconf));
364 debugx(1, DBG_ERR, "malloc failed");
365 memset(conf, 0, sizeof(struct clsrvconf));
367 conf->pdef = &protodefs[conf->type];
369 parsehostport(lconf, conf, default_port);
370 if (!strcmp(conf->host, "*")) {
375 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
376 if (!resolvepeer(conf, AI_PASSIVE))
377 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
381 void freeclsrvres(struct clsrvconf *res) {
385 freeaddrinfo(res->addrinfo);
389 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
391 struct addrinfo *res;
394 for (res = addrinfo; res; res = res->ai_next) {
395 s = bindtoaddr(src, res->ai_family, 1, 1);
397 debug(DBG_WARN, "connecttoserver: socket failed");
400 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
402 debug(DBG_WARN, "connecttoserver: connect failed");
409 /* returns 1 if the len first bits are equal, else 0 */
410 int prefixmatch(void *a1, void *a2, uint8_t len) {
411 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
413 if (l && memcmp(a1, a2, l))
418 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
421 /* check if conf has matching address */
422 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
423 struct sockaddr_in6 *sa6 = NULL;
424 struct in_addr *a4 = NULL;
425 struct addrinfo *res;
427 if (addr->sa_family == AF_INET6) {
428 sa6 = (struct sockaddr_in6 *)addr;
429 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
430 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
434 a4 = &((struct sockaddr_in *)addr)->sin_addr;
436 if (conf->type == type) {
437 if (conf->prefixlen == 255) {
438 for (res = conf->addrinfo; res; res = res->ai_next)
439 if ((a4 && res->ai_family == AF_INET &&
440 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
441 (sa6 && res->ai_family == AF_INET6 &&
442 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
445 res = conf->addrinfo;
447 ((a4 && res->ai_family == AF_INET &&
448 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
449 (sa6 && res->ai_family == AF_INET6 &&
450 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
457 /* returns next config with matching address, or NULL */
458 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
459 struct sockaddr_in6 *sa6 = NULL;
460 struct in_addr *a4 = NULL;
461 struct addrinfo *res;
462 struct list_node *entry;
463 struct clsrvconf *conf;
465 if (addr->sa_family == AF_INET6) {
466 sa6 = (struct sockaddr_in6 *)addr;
467 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
468 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
472 a4 = &((struct sockaddr_in *)addr)->sin_addr;
474 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
475 conf = (struct clsrvconf *)entry->data;
476 if (conf->type == type) {
477 if (conf->prefixlen == 255) {
478 for (res = conf->addrinfo; res; res = res->ai_next)
479 if ((a4 && res->ai_family == AF_INET &&
480 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
481 (sa6 && res->ai_family == AF_INET6 &&
482 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
488 res = conf->addrinfo;
490 ((a4 && res->ai_family == AF_INET &&
491 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
492 (sa6 && res->ai_family == AF_INET6 &&
493 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
504 /* returns next config of given type, or NULL */
505 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
506 struct list_node *entry;
507 struct clsrvconf *conf;
509 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
510 conf = (struct clsrvconf *)entry->data;
511 if (conf->type == type) {
520 struct replyq *newreplyq() {
521 struct replyq *replyq;
523 replyq = malloc(sizeof(struct replyq));
525 debugx(1, DBG_ERR, "malloc failed");
526 replyq->replies = list_create();
527 if (!replyq->replies)
528 debugx(1, DBG_ERR, "malloc failed");
529 pthread_mutex_init(&replyq->mutex, NULL);
530 pthread_cond_init(&replyq->cond, NULL);
534 struct client *addclient(struct clsrvconf *conf) {
535 struct client *new = malloc(sizeof(struct client));
538 debug(DBG_ERR, "malloc failed");
541 if (!conf->clients) {
542 conf->clients = list_create();
543 if (!conf->clients) {
544 debug(DBG_ERR, "malloc failed");
549 memset(new, 0, sizeof(struct client));
551 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
553 list_push(conf->clients, new);
557 void removeclient(struct client *client) {
558 struct list_node *entry;
560 if (!client || !client->conf->clients)
563 pthread_mutex_lock(&client->replyq->mutex);
564 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
565 free(((struct reply *)entry)->buf);
566 list_destroy(client->replyq->replies);
567 pthread_cond_destroy(&client->replyq->cond);
568 pthread_mutex_unlock(&client->replyq->mutex);
569 pthread_mutex_destroy(&client->replyq->mutex);
570 list_removedata(client->conf->clients, client);
574 void removeclientrqs(struct client *client) {
575 struct list_node *entry;
576 struct server *server;
580 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
581 server = ((struct clsrvconf *)entry->data)->servers;
584 pthread_mutex_lock(&server->newrq_mutex);
585 for (i = 0; i < MAX_REQUESTS; i++) {
586 rq = server->requests + i;
587 if (rq->from == client)
590 pthread_mutex_unlock(&server->newrq_mutex);
594 void freeserver(struct server *server, uint8_t destroymutex) {
595 struct request *rq, *end;
600 if(server->requests) {
601 rq = server->requests;
602 for (end = rq + MAX_REQUESTS; rq < end; rq++)
604 free(server->requests);
606 free(server->dynamiclookuparg);
608 pthread_mutex_destroy(&server->lock);
609 pthread_cond_destroy(&server->newrq_cond);
610 pthread_mutex_destroy(&server->newrq_mutex);
615 int addserver(struct clsrvconf *conf) {
616 struct clsrvconf *res;
619 debug(DBG_ERR, "addserver: currently works with just one server per conf");
622 conf->servers = malloc(sizeof(struct server));
623 if (!conf->servers) {
624 debug(DBG_ERR, "malloc failed");
627 memset(conf->servers, 0, sizeof(struct server));
628 conf->servers->conf = conf;
630 if (!srcprotores[conf->type]) {
631 res = resolve_hostport(conf->type, *conf->pdef->srcaddrport, NULL);
632 srcprotores[conf->type] = res->addrinfo;
633 res->addrinfo = NULL;
637 if (conf->type == RAD_UDP) {
638 switch (conf->addrinfo->ai_family) {
640 if (udp_client4_sock < 0) {
641 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
642 if (udp_client4_sock < 0)
643 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
645 conf->servers->sock = udp_client4_sock;
648 if (udp_client6_sock < 0) {
649 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
650 if (udp_client6_sock < 0)
651 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
653 conf->servers->sock = udp_client6_sock;
656 debugx(1, DBG_ERR, "addserver: unsupported address family");
660 conf->servers->sock = -1;
662 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
663 if (!conf->servers->requests) {
664 debug(DBG_ERR, "malloc failed");
667 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
668 debug(DBG_ERR, "mutex init failed");
671 conf->servers->newrq = 0;
672 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
673 debug(DBG_ERR, "mutex init failed");
674 pthread_mutex_destroy(&conf->servers->lock);
677 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
678 debug(DBG_ERR, "mutex init failed");
679 pthread_mutex_destroy(&conf->servers->newrq_mutex);
680 pthread_mutex_destroy(&conf->servers->lock);
687 freeserver(conf->servers, 0);
688 conf->servers = NULL;
692 /* exactly one of client and server must be non-NULL */
693 /* should probably take peer list (client(s) or server(s)) as argument instead */
694 /* if *peer == NULL we return who we received from, else require it to be from peer */
695 /* return from in sa if not NULL */
696 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
698 unsigned char buf[65536], *rad;
699 struct sockaddr_storage from;
700 socklen_t fromlen = sizeof(from);
702 struct list_node *node;
705 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
707 debug(DBG_WARN, "radudpget: recv failed");
710 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
713 debug(DBG_WARN, "radudpget: packet too small");
719 debug(DBG_WARN, "radudpget: length too small");
724 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
728 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
732 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
734 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
737 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
739 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
742 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
748 debug(DBG_ERR, "radudpget: malloc failed");
752 if (client && !*client) {
753 node = list_first(p->clients);
754 *client = node ? (struct client *)node->data : addclient(p);
759 } else if (server && !*server)
760 *server = p->servers;
764 memcpy(rad, buf, len);
770 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
771 int loc, i, l, n, r = 0;
774 STACK_OF(GENERAL_NAME) *alt;
777 debug(DBG_DBG, "subjectaltnameaddr");
779 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
783 ex = X509_get_ext(cert, loc);
784 alt = X509V3_EXT_d2i(ex);
788 n = sk_GENERAL_NAME_num(alt);
789 for (i = 0; i < n; i++) {
790 gn = sk_GENERAL_NAME_value(alt, i);
791 if (gn->type != GEN_IPADD)
794 v = (char *)ASN1_STRING_data(gn->d.ia5);
795 l = ASN1_STRING_length(gn->d.ia5);
796 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
797 && !memcmp(v, &addr, l)) {
802 GENERAL_NAMES_free(alt);
806 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
813 nm = X509_get_subject_name(cert);
816 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
819 e = X509_NAME_get_entry(nm, loc);
820 t = X509_NAME_ENTRY_get_data(e);
821 v = (char *) ASN1_STRING_data(t);
822 l = ASN1_STRING_length(t);
826 if (l == strlen(exact) && !strncasecmp(exact, v, l))
829 s = stringcopy((char *)v, l);
831 debug(DBG_ERR, "malloc failed");
834 if (regexec(regex, s, 0, NULL, 0)) {
845 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
846 int loc, i, l, n, r = 0;
849 STACK_OF(GENERAL_NAME) *alt;
852 debug(DBG_DBG, "subjectaltnameregexp");
854 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
858 ex = X509_get_ext(cert, loc);
859 alt = X509V3_EXT_d2i(ex);
863 n = sk_GENERAL_NAME_num(alt);
864 for (i = 0; i < n; i++) {
865 gn = sk_GENERAL_NAME_value(alt, i);
866 if (gn->type != type)
869 v = (char *)ASN1_STRING_data(gn->d.ia5);
870 l = ASN1_STRING_length(gn->d.ia5);
874 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
877 if (memcmp(v, exact, l))
880 s = stringcopy((char *)v, l);
882 debug(DBG_ERR, "malloc failed");
885 if (regexec(regex, s, 0, NULL, 0)) {
894 GENERAL_NAMES_free(alt);
898 X509 *verifytlscert(SSL *ssl) {
902 if (SSL_get_verify_result(ssl) != X509_V_OK) {
903 debug(DBG_ERR, "verifytlscert: basic validation failed");
904 while ((error = ERR_get_error()))
905 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
909 cert = SSL_get_peer_certificate(ssl);
911 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
915 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
917 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
918 struct in6_addr addr;
920 if (conf->certnamecheck && conf->prefixlen == 255) {
921 if (inet_pton(AF_INET, conf->host, &addr))
923 else if (inet_pton(AF_INET6, conf->host, &addr))
926 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
929 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
932 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
934 if (!cnregexp(cert, conf->host, NULL)) {
935 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
938 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
941 if (conf->certcnregex) {
942 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
943 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
946 debug(DBG_DBG, "verifyconfcert: CN matching regex");
948 if (conf->certuriregex) {
949 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
950 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
953 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
958 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
963 debug(DBG_DBG, "tlsconnect: called from %s", text);
964 pthread_mutex_lock(&server->lock);
965 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
966 /* already reconnected, nothing to do */
967 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
968 pthread_mutex_unlock(&server->lock);
973 gettimeofday(&now, NULL);
974 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
975 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
976 debug(DBG_DBG, "tlsconnect: timeout");
977 if (server->sock >= 0)
979 SSL_free(server->ssl);
981 pthread_mutex_unlock(&server->lock);
984 if (server->connectionok) {
985 server->connectionok = 0;
987 } else if (elapsed < 1)
989 else if (elapsed < 60) {
990 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
992 } else if (elapsed < 100000) {
993 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
996 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
997 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
998 if (server->sock >= 0)
1000 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1001 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1005 SSL_free(server->ssl);
1006 server->ssl = SSL_new(server->conf->ssl_ctx);
1007 SSL_set_fd(server->ssl, server->sock);
1008 if (SSL_connect(server->ssl) <= 0)
1010 cert = verifytlscert(server->ssl);
1013 if (verifyconfcert(cert, server->conf)) {
1019 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1020 gettimeofday(&server->lastconnecttry, NULL);
1021 pthread_mutex_unlock(&server->lock);
1025 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1029 debug(DBG_DBG, "tcpconnect: called from %s", text);
1030 pthread_mutex_lock(&server->lock);
1031 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1032 /* already reconnected, nothing to do */
1033 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1034 pthread_mutex_unlock(&server->lock);
1039 gettimeofday(&now, NULL);
1040 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1041 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1042 debug(DBG_DBG, "tcpconnect: timeout");
1043 if (server->sock >= 0)
1044 close(server->sock);
1045 pthread_mutex_unlock(&server->lock);
1048 if (server->connectionok) {
1049 server->connectionok = 0;
1051 } else if (elapsed < 1)
1053 else if (elapsed < 60) {
1054 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1056 } else if (elapsed < 100000) {
1057 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1060 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1061 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1062 if (server->sock >= 0)
1063 close(server->sock);
1064 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1066 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1068 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1069 gettimeofday(&server->lastconnecttry, NULL);
1070 pthread_mutex_unlock(&server->lock);
1074 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1075 /* returns 0 on timeout, -1 on error and num if ok */
1076 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1077 int s, ndesc, cnt, len;
1078 fd_set readfds, writefds;
1079 struct timeval timer;
1081 s = SSL_get_fd(ssl);
1084 /* make socket non-blocking? */
1085 for (len = 0; len < num; len += cnt) {
1087 FD_SET(s, &readfds);
1090 timer.tv_sec = timeout;
1093 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1097 cnt = SSL_read(ssl, buf + len, num - len);
1099 switch (SSL_get_error(ssl, cnt)) {
1100 case SSL_ERROR_WANT_READ:
1101 case SSL_ERROR_WANT_WRITE:
1104 case SSL_ERROR_ZERO_RETURN:
1105 /* remote end sent close_notify, send one back */
1115 /* timeout in seconds, 0 means no timeout (blocking) */
1116 unsigned char *radtlsget(SSL *ssl, int timeout) {
1118 unsigned char buf[4], *rad;
1121 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1123 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1130 debug(DBG_ERR, "radtlsget: malloc failed");
1133 memcpy(rad, buf, 4);
1135 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1137 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1146 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1149 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1153 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1154 /* returns 0 on timeout, -1 on error and num if ok */
1155 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1156 int ndesc, cnt, len;
1157 fd_set readfds, writefds;
1158 struct timeval timer;
1162 /* make socket non-blocking? */
1163 for (len = 0; len < num; len += cnt) {
1165 FD_SET(s, &readfds);
1168 timer.tv_sec = timeout;
1171 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1175 cnt = read(s, buf + len, num - len);
1182 /* timeout in seconds, 0 means no timeout (blocking) */
1183 unsigned char *radtcpget(int s, int timeout) {
1185 unsigned char buf[4], *rad;
1188 cnt = tcpreadtimeout(s, buf, 4, timeout);
1190 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1197 debug(DBG_ERR, "radtcpget: malloc failed");
1200 memcpy(rad, buf, 4);
1202 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1204 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1213 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1216 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1220 int clientradputudp(struct server *server, unsigned char *rad) {
1222 struct sockaddr_storage sa;
1223 struct sockaddr *sap;
1224 struct clsrvconf *conf = server->conf;
1225 in_port_t *port = NULL;
1229 if (*rad == RAD_Accounting_Request) {
1230 sap = (struct sockaddr *)&sa;
1231 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1233 sap = conf->addrinfo->ai_addr;
1235 switch (sap->sa_family) {
1237 port = &((struct sockaddr_in *)sap)->sin_port;
1240 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1246 if (*rad == RAD_Accounting_Request)
1247 *port = htons(ntohs(*port) + 1);
1249 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1250 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1254 debug(DBG_WARN, "clientradputudp: send failed");
1258 int clientradputtls(struct server *server, unsigned char *rad) {
1261 unsigned long error;
1262 struct timeval lastconnecttry;
1263 struct clsrvconf *conf = server->conf;
1266 lastconnecttry = server->lastconnecttry;
1267 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1268 while ((error = ERR_get_error()))
1269 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1270 if (server->dynamiclookuparg)
1272 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1273 lastconnecttry = server->lastconnecttry;
1276 server->connectionok = 1;
1277 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1281 int clientradputtcp(struct server *server, unsigned char *rad) {
1284 struct timeval lastconnecttry;
1285 struct clsrvconf *conf = server->conf;
1288 lastconnecttry = server->lastconnecttry;
1289 while ((cnt = write(server->sock, rad, len)) <= 0) {
1290 debug(DBG_ERR, "clientradputtcp: write error");
1291 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1292 lastconnecttry = server->lastconnecttry;
1295 server->connectionok = 1;
1296 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1300 int radsign(unsigned char *rad, unsigned char *sec) {
1301 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1302 static unsigned char first = 1;
1303 static EVP_MD_CTX mdctx;
1304 unsigned int md_len;
1307 pthread_mutex_lock(&lock);
1309 EVP_MD_CTX_init(&mdctx);
1313 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1314 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1315 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1316 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1318 pthread_mutex_unlock(&lock);
1322 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1323 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1324 static unsigned char first = 1;
1325 static EVP_MD_CTX mdctx;
1326 unsigned char hash[EVP_MAX_MD_SIZE];
1330 pthread_mutex_lock(&lock);
1332 EVP_MD_CTX_init(&mdctx);
1338 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1339 EVP_DigestUpdate(&mdctx, rad, 4) &&
1340 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1341 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1342 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1343 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1345 !memcmp(hash, rad + 4, 16));
1346 pthread_mutex_unlock(&lock);
1350 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1351 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1352 static unsigned char first = 1;
1353 static HMAC_CTX hmacctx;
1354 unsigned int md_len;
1355 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1357 pthread_mutex_lock(&lock);
1359 HMAC_CTX_init(&hmacctx);
1363 memcpy(auth, authattr, 16);
1364 memset(authattr, 0, 16);
1366 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1367 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1368 HMAC_Final(&hmacctx, hash, &md_len);
1369 memcpy(authattr, auth, 16);
1371 debug(DBG_WARN, "message auth computation failed");
1372 pthread_mutex_unlock(&lock);
1376 if (memcmp(auth, hash, 16)) {
1377 debug(DBG_WARN, "message authenticator, wrong value");
1378 pthread_mutex_unlock(&lock);
1382 pthread_mutex_unlock(&lock);
1386 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1387 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1388 static unsigned char first = 1;
1389 static HMAC_CTX hmacctx;
1390 unsigned int md_len;
1395 pthread_mutex_lock(&lock);
1397 HMAC_CTX_init(&hmacctx);
1401 memset(authattrval, 0, 16);
1403 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1404 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1405 HMAC_Final(&hmacctx, authattrval, &md_len);
1407 debug(DBG_WARN, "message auth computation failed");
1408 pthread_mutex_unlock(&lock);
1412 pthread_mutex_unlock(&lock);
1416 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1417 while (length > 1) {
1418 if (ATTRTYPE(attrs) == type)
1420 length -= ATTRLEN(attrs);
1421 attrs += ATTRLEN(attrs);
1426 void freerqdata(struct request *rq) {
1427 if (rq->origusername)
1428 free(rq->origusername);
1433 void sendrq(struct server *to, struct request *rq) {
1437 pthread_mutex_lock(&to->newrq_mutex);
1438 /* might simplify if only try nextid, might be ok */
1439 for (i = to->nextid; i < MAX_REQUESTS; i++)
1440 if (!to->requests[i].buf)
1442 if (i == MAX_REQUESTS) {
1443 for (i = 0; i < to->nextid; i++)
1444 if (!to->requests[i].buf)
1446 if (i == to->nextid) {
1447 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1453 rq->buf[1] = (char)i;
1455 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1456 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1461 if (*rq->buf == RAD_Accounting_Request) {
1462 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1463 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1469 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1470 to->requests[i] = *rq;
1475 debug(DBG_DBG, "sendrq: signalling client writer");
1476 pthread_cond_signal(&to->newrq_cond);
1479 pthread_mutex_unlock(&to->newrq_mutex);
1482 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1483 struct reply *reply;
1486 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1488 debug(DBG_WARN, "sendreply: failed to sign message");
1492 reply = malloc(sizeof(struct reply));
1495 debug(DBG_ERR, "sendreply: malloc failed");
1498 memset(reply, 0, sizeof(struct reply));
1501 reply->tosa = *tosa;
1502 reply->toudpsock = toudpsock;
1504 pthread_mutex_lock(&to->replyq->mutex);
1506 first = list_first(to->replyq->replies) == NULL;
1508 if (!list_push(to->replyq->replies, reply)) {
1509 pthread_mutex_unlock(&to->replyq->mutex);
1512 debug(DBG_ERR, "sendreply: malloc failed");
1517 debug(DBG_DBG, "signalling server writer");
1518 pthread_cond_signal(&to->replyq->cond);
1520 pthread_mutex_unlock(&to->replyq->mutex);
1523 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1524 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1525 static unsigned char first = 1;
1526 static EVP_MD_CTX mdctx;
1527 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1528 unsigned int md_len;
1529 uint8_t i, offset = 0, out[128];
1531 pthread_mutex_lock(&lock);
1533 EVP_MD_CTX_init(&mdctx);
1539 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1540 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1541 !EVP_DigestUpdate(&mdctx, input, 16) ||
1542 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1544 pthread_mutex_unlock(&lock);
1547 for (i = 0; i < 16; i++)
1548 out[offset + i] = hash[i] ^ in[offset + i];
1549 input = out + offset - 16;
1554 memcpy(in, out, len);
1555 pthread_mutex_unlock(&lock);
1559 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1560 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1561 static unsigned char first = 1;
1562 static EVP_MD_CTX mdctx;
1563 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1564 unsigned int md_len;
1565 uint8_t i, offset = 0, out[128];
1567 pthread_mutex_lock(&lock);
1569 EVP_MD_CTX_init(&mdctx);
1575 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1576 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1577 !EVP_DigestUpdate(&mdctx, input, 16) ||
1578 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1580 pthread_mutex_unlock(&lock);
1583 for (i = 0; i < 16; i++)
1584 out[offset + i] = hash[i] ^ in[offset + i];
1585 input = in + offset;
1590 memcpy(in, out, len);
1591 pthread_mutex_unlock(&lock);
1595 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1596 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1597 static unsigned char first = 1;
1598 static EVP_MD_CTX mdctx;
1599 unsigned char hash[EVP_MAX_MD_SIZE];
1600 unsigned int md_len;
1603 pthread_mutex_lock(&lock);
1605 EVP_MD_CTX_init(&mdctx);
1610 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1611 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1612 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1615 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1616 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1617 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1618 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1619 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1620 pthread_mutex_unlock(&lock);
1625 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1628 for (i = 0; i < 16; i++)
1631 for (offset = 16; offset < len; offset += 16) {
1633 printf("text + offset - 16 c(%d): ", offset / 16);
1634 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1636 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1637 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1638 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1639 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1641 pthread_mutex_unlock(&lock);
1645 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1648 for (i = 0; i < 16; i++)
1649 text[offset + i] ^= hash[i];
1653 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1656 pthread_mutex_unlock(&lock);
1660 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1661 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1662 static unsigned char first = 1;
1663 static EVP_MD_CTX mdctx;
1664 unsigned char hash[EVP_MAX_MD_SIZE];
1665 unsigned int md_len;
1669 pthread_mutex_lock(&lock);
1671 EVP_MD_CTX_init(&mdctx);
1676 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1677 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1678 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1681 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1682 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1683 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1684 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1685 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1686 pthread_mutex_unlock(&lock);
1691 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1694 for (i = 0; i < 16; i++)
1695 plain[i] = text[i] ^ hash[i];
1697 for (offset = 16; offset < len; offset += 16) {
1699 printf("text + offset - 16 c(%d): ", offset / 16);
1700 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1702 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1703 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1704 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1705 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1707 pthread_mutex_unlock(&lock);
1711 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1714 for (i = 0; i < 16; i++)
1715 plain[offset + i] = text[offset + i] ^ hash[i];
1718 memcpy(text, plain, len);
1720 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1723 pthread_mutex_unlock(&lock);
1727 struct realm *id2realm(struct list *realmlist, char *id) {
1728 struct list_node *entry;
1729 struct realm *realm, *subrealm = NULL;
1731 /* need to do locking for subrealms and check subrealm timers */
1732 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1733 realm = (struct realm *)entry->data;
1734 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1735 pthread_mutex_lock(&realm->subrealms_mutex);
1736 if (realm->subrealms)
1737 subrealm = id2realm(realm->subrealms, id);
1738 pthread_mutex_unlock(&realm->subrealms_mutex);
1739 return subrealm ? subrealm : realm;
1745 /* helper function, only used by removeserversubrealms() */
1746 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1747 struct list_node *entry;
1748 struct realm *realm;
1750 for (entry = list_first(realmlist); entry;) {
1751 realm = (struct realm *)entry->data;
1752 entry = list_next(entry);
1753 if (realm->srvconfs) {
1754 list_removedata(realm->srvconfs, srv);
1755 if (!list_first(realm->srvconfs)) {
1756 list_destroy(realm->srvconfs);
1757 realm->srvconfs = NULL;
1760 if (realm->accsrvconfs) {
1761 list_removedata(realm->accsrvconfs, srv);
1762 if (!list_first(realm->accsrvconfs)) {
1763 list_destroy(realm->accsrvconfs);
1764 realm->accsrvconfs = NULL;
1768 /* remove subrealm if no servers */
1769 if (!realm->srvconfs && !realm->accsrvconfs) {
1770 list_removedata(realmlist, realm);
1776 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1777 struct list_node *entry;
1778 struct realm *realm;
1780 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1781 realm = (struct realm *)entry->data;
1782 pthread_mutex_lock(&realm->subrealms_mutex);
1783 if (realm->subrealms) {
1784 _internal_removeserversubrealms(realm->subrealms, srv);
1785 if (!list_first(realm->subrealms)) {
1786 list_destroy(realm->subrealms);
1787 realm->subrealms = NULL;
1790 pthread_mutex_unlock(&realm->subrealms_mutex);
1794 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1795 struct request *rq = to->requests, *end;
1797 pthread_mutex_lock(&to->newrq_mutex);
1798 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1799 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1801 pthread_mutex_unlock(&to->newrq_mutex);
1806 int attrvalidate(unsigned char *attrs, int length) {
1807 while (length > 1) {
1808 if (ATTRLEN(attrs) < 2) {
1809 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1812 length -= ATTRLEN(attrs);
1814 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1817 attrs += ATTRLEN(attrs);
1820 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1824 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1825 if (len < 16 || len > 128 || len % 16) {
1826 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1830 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1831 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1835 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1837 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1838 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1844 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1847 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1848 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1851 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1852 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1858 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1859 char *oldsecret, char *newsecret) {
1860 unsigned char *attr;
1862 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1863 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1864 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1870 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1874 for (; attrs[0]; attrs += 2)
1875 if (attrs[0] == vendor && attrs[1] == subattr)
1880 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1881 uint8_t alen, sublen, rmlen = 0;
1882 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1885 if (!removevendorattrs)
1888 while (*removevendorattrs && *removevendorattrs != vendor)
1889 removevendorattrs += 2;
1890 if (!*removevendorattrs)
1893 alen = ATTRLEN(attrs);
1895 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1896 /* remove entire vendor attribute */
1897 memmove(attrs, attrs + alen, length - alen);
1902 subattrs = ATTRVAL(attrs) + 4;
1904 if (!attrvalidate(subattrs, sublen)) {
1905 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1910 while (sublen > 1) {
1911 alen = ATTRLEN(subattrs);
1914 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1915 memmove(subattrs, subattrs + alen, length);
1921 ATTRLEN(attrs) -= rmlen;
1925 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1926 uint8_t *attrs, alen;
1927 uint16_t len, rmlen = 0;
1929 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1932 len = RADLEN(buf) - 20;
1935 alen = ATTRLEN(attrs);
1937 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1938 memmove(attrs, attrs + alen, len);
1940 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1941 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1946 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1949 /* returns a pointer to the resized attribute value */
1950 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1951 uint8_t *attrs, *attr, vallen;
1955 len = RADLEN(*buf) - 20;
1958 attr = attrget(attrs, len, type);
1962 vallen = ATTRVALLEN(attr);
1963 if (vallen == newvallen)
1966 len += newvallen - vallen;
1967 if (newvallen > vallen) {
1968 new = realloc(*buf, len + 20);
1970 debug(DBG_ERR, "resizeattr: malloc failed");
1979 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1980 attr[1] = newvallen + 2;
1981 ((uint16_t *)*buf)[1] = htons(len + 20);
1985 int rewriteusername(struct request *rq, char *in) {
1986 size_t nmatch = 10, reslen = 0, start = 0;
1987 regmatch_t pmatch[10], *pfield;
1989 unsigned char *result;
1990 char *out = rq->from->conf->rewriteattrreplacement;
1992 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1993 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1997 rq->origusername = stringcopy(in, 0);
1998 if (!rq->origusername)
2001 for (i = start; out[i]; i++) {
2002 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2003 pfield = &pmatch[out[i + 1] - '0'];
2004 if (pfield->rm_so >= 0) {
2005 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2011 reslen += i - start;
2013 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2019 for (i = start; out[i]; i++) {
2020 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2021 pfield = &pmatch[out[i + 1] - '0'];
2022 if (pfield->rm_so >= 0) {
2023 memcpy(result + reslen, out + start, i - start);
2024 reslen += i - start;
2025 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2026 reslen += pfield->rm_eo - pfield->rm_so;
2033 memcpy(result + reslen, out + start, i - start);
2034 reslen += i - start;
2035 memcpy(in, result, reslen);
2040 const char *radmsgtype2string(uint8_t code) {
2041 static const char *rad_msg_names[] = {
2042 "", "Access-Request", "Access-Accept", "Access-Reject",
2043 "Accounting-Request", "Accounting-Response", "", "",
2044 "", "", "", "Access-Challenge",
2045 "Status-Server", "Status-Client"
2047 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2050 void char2hex(char *h, unsigned char c) {
2051 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2052 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2053 h[0] = hexdigits[c / 16];
2054 h[1] = hexdigits[c % 16];
2058 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2062 if (!attr || len == 1) {
2067 l = ATTRVALLEN(attr);
2068 s = (char *)ATTRVAL(attr);
2071 for (i = 0; i < l; i++) {
2072 if (s[i] > 31 && s[i] < 127) {
2074 if (d - ascii == len - 1)
2077 if (d - ascii > len - 4)
2082 if (d - ascii == len - 1)
2090 void acclog(unsigned char *attrs, int length, char *host) {
2091 unsigned char *attr;
2094 attr = attrget(attrs, length, RAD_Attr_User_Name);
2096 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2099 radattr2ascii(username, sizeof(username), attr);
2100 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2103 void respondaccounting(struct request *rq) {
2104 unsigned char *resp;
2108 debug(DBG_ERR, "respondaccounting: malloc failed");
2111 memcpy(resp, rq->buf, 20);
2112 resp[0] = RAD_Accounting_Response;
2115 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2116 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2119 void respondstatusserver(struct request *rq) {
2120 unsigned char *resp;
2124 debug(DBG_ERR, "respondstatusserver: malloc failed");
2127 memcpy(resp, rq->buf, 20);
2128 resp[0] = RAD_Access_Accept;
2131 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2132 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2135 void respondreject(struct request *rq, char *message) {
2136 unsigned char *resp;
2139 if (message && *message)
2140 len += 2 + strlen(message);
2144 debug(DBG_ERR, "respondreject: malloc failed");
2147 memcpy(resp, rq->buf, 20);
2148 resp[0] = RAD_Access_Reject;
2149 *(uint16_t *)(resp + 2) = htons(len);
2150 if (message && *message) {
2151 resp[20] = RAD_Attr_Reply_Message;
2152 resp[21] = len - 20;
2153 memcpy(resp + 22, message, len - 22);
2155 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2158 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2159 struct list_node *entry;
2160 struct clsrvconf *server, *best = NULL, *first = NULL;
2162 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2163 server = (struct clsrvconf *)entry->data;
2164 if (!server->servers)
2168 if (!server->servers->connectionok)
2170 if (!server->servers->lostrqs)
2176 if (server->servers->lostrqs < best->servers->lostrqs)
2179 return best ? best : first;
2182 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2183 struct clsrvconf *srvconf;
2185 *realm = id2realm(realms, id);
2188 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2189 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2192 if (!acc && !srvconf->servers)
2193 adddynamicrealmserver(*realm, srvconf, id);
2194 return srvconf->servers;
2197 void radsrv(struct request *rq) {
2198 uint8_t code, id, *auth, *attrs, *attr;
2200 struct server *to = NULL;
2201 char username[254], userascii[760];
2202 unsigned char newauth[16];
2203 struct realm *realm = NULL;
2205 code = *(uint8_t *)rq->buf;
2206 id = *(uint8_t *)(rq->buf + 1);
2207 len = RADLEN(rq->buf);
2208 auth = (uint8_t *)(rq->buf + 4);
2210 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2212 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2213 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2218 attrs = rq->buf + 20;
2220 if (!attrvalidate(attrs, len)) {
2221 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2225 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2226 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2227 debug(DBG_WARN, "radsrv: message authentication failed");
2231 if (code == RAD_Status_Server) {
2232 respondstatusserver(rq);
2236 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2238 if (code == RAD_Accounting_Request) {
2239 memset(newauth, 0, 16);
2240 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2241 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2246 if (rq->from->conf->rewrite) {
2247 dorewrite(rq->buf, rq->from->conf->rewrite);
2248 len = RADLEN(rq->buf) - 20;
2251 attr = attrget(attrs, len, RAD_Attr_User_Name);
2253 if (code == RAD_Accounting_Request) {
2254 acclog(attrs, len, rq->from->conf->host);
2255 respondaccounting(rq);
2257 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2260 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2261 username[ATTRVALLEN(attr)] = '\0';
2262 radattr2ascii(userascii, sizeof(userascii), attr);
2264 if (rq->from->conf->rewriteattrregex) {
2265 if (!rewriteusername(rq, username)) {
2266 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2269 len = RADLEN(rq->buf) - 20;
2270 auth = (uint8_t *)(rq->buf + 4);
2271 attrs = rq->buf + 20;
2274 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2276 to = findserver(&realm, username, code == RAD_Accounting_Request);
2278 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2282 if (realm->message && code == RAD_Access_Request) {
2283 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2284 respondreject(rq, realm->message);
2285 } else if (realm->accresp && code == RAD_Accounting_Request) {
2286 acclog(attrs, len, rq->from->conf->host);
2287 respondaccounting(rq);
2292 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2293 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2294 rq->from->conf->name, to->conf->name);
2298 if (rqinqueue(to, rq->from, id, code)) {
2299 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2300 radmsgtype2string(code), rq->from->conf->host, id);
2304 if (code != RAD_Accounting_Request) {
2305 if (!RAND_bytes(newauth, 16)) {
2306 debug(DBG_WARN, "radsrv: failed to generate random auth");
2312 printfchars(NULL, "auth", "%02x ", auth, 16);
2315 attr = attrget(attrs, len, RAD_Attr_User_Password);
2317 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2318 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2322 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2324 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2325 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2330 memcpy(rq->origauth, auth, 16);
2331 memcpy(auth, newauth, 16);
2339 int replyh(struct server *server, unsigned char *buf) {
2340 struct client *from;
2343 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2344 struct sockaddr_storage fromsa;
2345 char tmp[760], stationid[760];
2347 server->connectionok = 1;
2348 server->lostrqs = 0;
2350 i = buf[1]; /* i is the id */
2352 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2353 && *buf != RAD_Accounting_Response) {
2354 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2357 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2359 rq = server->requests + i;
2361 pthread_mutex_lock(&server->newrq_mutex);
2362 if (!rq->buf || !rq->tries) {
2363 pthread_mutex_unlock(&server->newrq_mutex);
2364 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2369 pthread_mutex_unlock(&server->newrq_mutex);
2370 debug(DBG_INFO, "replyh: already received, ignoring reply");
2374 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2375 pthread_mutex_unlock(&server->newrq_mutex);
2376 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2380 len = RADLEN(buf) - 20;
2383 if (!attrvalidate(attrs, len)) {
2384 pthread_mutex_unlock(&server->newrq_mutex);
2385 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2389 /* Message Authenticator */
2390 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2392 if (ATTRVALLEN(messageauth) != 16) {
2393 pthread_mutex_unlock(&server->newrq_mutex);
2394 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2397 memcpy(tmp, buf + 4, 16);
2398 memcpy(buf + 4, rq->buf + 4, 16);
2399 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2400 pthread_mutex_unlock(&server->newrq_mutex);
2401 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2404 memcpy(buf + 4, tmp, 16);
2405 debug(DBG_DBG, "replyh: message auth ok");
2408 if (*rq->buf == RAD_Status_Server) {
2410 pthread_mutex_unlock(&server->newrq_mutex);
2411 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2415 gettimeofday(&server->lastreply, NULL);
2419 pthread_mutex_unlock(&server->newrq_mutex);
2420 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2424 if (server->conf->rewrite) {
2425 dorewrite(buf, server->conf->rewrite);
2426 len = RADLEN(buf) - 20;
2430 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2431 if (ATTRVALLEN(attr) <= 4)
2434 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2437 sublen = ATTRVALLEN(attr) - 4;
2438 subattrs = ATTRVAL(attr) + 4;
2439 if (!attrvalidate(subattrs, sublen) ||
2440 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2441 rq, server->conf->secret, from->conf->secret) ||
2442 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2443 rq, server->conf->secret, from->conf->secret))
2447 pthread_mutex_unlock(&server->newrq_mutex);
2448 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2452 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2453 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2455 radattr2ascii(tmp, sizeof(tmp), attr);
2456 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2458 radattr2ascii(stationid, sizeof(stationid), attr);
2459 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2460 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2462 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2466 buf[1] = (char)rq->origid;
2467 memcpy(buf + 4, rq->origauth, 16);
2469 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2472 if (rq->origusername) {
2473 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2475 pthread_mutex_unlock(&server->newrq_mutex);
2476 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2479 memcpy(username, rq->origusername, strlen(rq->origusername));
2480 len = RADLEN(buf) - 20;
2483 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2487 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2488 pthread_mutex_unlock(&server->newrq_mutex);
2489 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2492 debug(DBG_DBG, "replyh: computed messageauthattr");
2495 fromsa = rq->fromsa; /* only needed for UDP */
2496 /* once we set received = 1, rq may be reused */
2499 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2500 sendreply(from, buf, &fromsa, rq->fromudpsock);
2501 pthread_mutex_unlock(&server->newrq_mutex);
2505 void *udpclientrd(void *arg) {
2506 struct server *server;
2508 int *s = (int *)arg;
2512 buf = radudpget(*s, NULL, &server, NULL);
2513 if (!replyh(server, buf))
2518 void *tlsclientrd(void *arg) {
2519 struct server *server = (struct server *)arg;
2521 struct timeval now, lastconnecttry;
2524 /* yes, lastconnecttry is really necessary */
2525 lastconnecttry = server->lastconnecttry;
2526 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2528 if (server->dynamiclookuparg)
2530 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2534 if (!replyh(server, buf))
2536 if (server->dynamiclookuparg) {
2537 gettimeofday(&now, NULL);
2538 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2539 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2544 server->clientrdgone = 1;
2548 void *tcpclientrd(void *arg) {
2549 struct server *server = (struct server *)arg;
2551 struct timeval lastconnecttry;
2554 /* yes, lastconnecttry is really necessary */
2555 lastconnecttry = server->lastconnecttry;
2556 buf = radtcpget(server->sock, 0);
2558 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2562 if (!replyh(server, buf))
2565 server->clientrdgone = 1;
2569 /* code for removing state not finished */
2570 void *clientwr(void *arg) {
2571 struct server *server = (struct server *)arg;
2573 pthread_t clientrdth;
2574 int i, dynconffail = 0;
2576 struct timeval now, lastsend;
2577 struct timespec timeout;
2578 struct request statsrvrq;
2579 unsigned char statsrvbuf[38];
2580 struct clsrvconf *conf;
2582 conf = server->conf;
2584 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2589 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2590 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2594 memset(&timeout, 0, sizeof(struct timespec));
2596 if (conf->statusserver) {
2597 memset(&statsrvrq, 0, sizeof(struct request));
2598 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2599 statsrvbuf[0] = RAD_Status_Server;
2601 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2602 statsrvbuf[21] = 18;
2603 gettimeofday(&lastsend, NULL);
2606 if (conf->pdef->connecter) {
2607 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2609 server->connectionok = 1;
2610 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2611 debug(DBG_ERR, "clientwr: pthread_create failed");
2615 server->connectionok = 1;
2618 pthread_mutex_lock(&server->newrq_mutex);
2619 if (!server->newrq) {
2620 gettimeofday(&now, NULL);
2621 /* random 0-7 seconds */
2622 RAND_bytes(&rnd, 1);
2624 if (conf->statusserver) {
2625 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2626 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2628 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2629 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2632 if (timeout.tv_sec > now.tv_sec)
2633 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2635 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2638 if (server->newrq) {
2639 debug(DBG_DBG, "clientwr: got new request");
2644 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2646 pthread_mutex_unlock(&server->newrq_mutex);
2648 for (i = 0; i < MAX_REQUESTS; i++) {
2649 if (server->clientrdgone) {
2650 pthread_join(clientrdth, NULL);
2653 pthread_mutex_lock(&server->newrq_mutex);
2654 while (i < MAX_REQUESTS && !server->requests[i].buf)
2656 if (i == MAX_REQUESTS) {
2657 pthread_mutex_unlock(&server->newrq_mutex);
2660 rq = server->requests + i;
2663 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2665 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2667 /* setting this to NULL means that it can be reused */
2670 pthread_mutex_unlock(&server->newrq_mutex);
2674 gettimeofday(&now, NULL);
2675 if (now.tv_sec < rq->expiry.tv_sec) {
2676 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2677 timeout.tv_sec = rq->expiry.tv_sec;
2678 pthread_mutex_unlock(&server->newrq_mutex);
2682 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2683 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2684 if (conf->statusserver) {
2685 if (*rq->buf == RAD_Status_Server) {
2686 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2687 if (server->lostrqs < 255)
2691 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2692 if (server->lostrqs < 255)
2696 /* setting this to NULL means that it can be reused */
2698 pthread_mutex_unlock(&server->newrq_mutex);
2701 pthread_mutex_unlock(&server->newrq_mutex);
2703 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2704 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2705 timeout.tv_sec = rq->expiry.tv_sec;
2707 conf->pdef->clientradput(server, server->requests[i].buf);
2708 gettimeofday(&lastsend, NULL);
2710 if (conf->statusserver) {
2711 gettimeofday(&now, NULL);
2712 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2713 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2714 debug(DBG_WARN, "clientwr: failed to generate random auth");
2717 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2718 if (!statsrvrq.buf) {
2719 debug(DBG_ERR, "clientwr: malloc failed");
2722 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2723 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2724 lastsend.tv_sec = now.tv_sec;
2725 sendrq(server, &statsrvrq);
2730 conf->servers = NULL;
2731 if (server->dynamiclookuparg) {
2732 removeserversubrealms(realms, conf);
2736 freeclsrvconf(conf);
2738 freeserver(server, 1);
2742 void *udpserverwr(void *arg) {
2743 struct replyq *replyq = udp_server_replyq;
2744 struct reply *reply;
2747 pthread_mutex_lock(&replyq->mutex);
2748 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2749 debug(DBG_DBG, "udp server writer, waiting for signal");
2750 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2751 debug(DBG_DBG, "udp server writer, got signal");
2753 pthread_mutex_unlock(&replyq->mutex);
2755 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2756 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2757 debug(DBG_WARN, "sendudp: send failed");
2763 void *udpserverrd(void *arg) {
2765 struct listenerarg *larg = (struct listenerarg *)arg;
2768 memset(&rq, 0, sizeof(struct request));
2769 rq.buf = radudpget(larg->s, &rq.from, NULL, &rq.fromsa);
2770 if (larg->acconly && *rq.buf != RAD_Accounting_Request) {
2771 debug(DBG_INFO, "udpserverrd: got something other than accounting-request, ignoring");
2775 rq.fromudpsock = larg->s;
2780 void *tlsserverwr(void *arg) {
2782 unsigned long error;
2783 struct client *client = (struct client *)arg;
2784 struct replyq *replyq;
2785 struct reply *reply;
2787 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2788 replyq = client->replyq;
2790 pthread_mutex_lock(&replyq->mutex);
2791 while (!list_first(replyq->replies)) {
2793 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2794 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2795 debug(DBG_DBG, "tlsserverwr: got signal");
2798 /* ssl might have changed while waiting */
2799 pthread_mutex_unlock(&replyq->mutex);
2800 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2804 reply = (struct reply *)list_shift(replyq->replies);
2805 pthread_mutex_unlock(&replyq->mutex);
2806 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2808 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2809 cnt, RADLEN(reply->buf));
2811 while ((error = ERR_get_error()))
2812 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2818 void tlsserverrd(struct client *client) {
2820 pthread_t tlsserverwrth;
2822 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2824 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2825 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2830 memset(&rq, 0, sizeof(struct request));
2831 rq.buf = radtlsget(client->ssl, 0);
2834 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2839 debug(DBG_ERR, "tlsserverrd: connection lost");
2840 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2842 pthread_mutex_lock(&client->replyq->mutex);
2843 pthread_cond_signal(&client->replyq->cond);
2844 pthread_mutex_unlock(&client->replyq->mutex);
2845 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2846 pthread_join(tlsserverwrth, NULL);
2847 removeclientrqs(client);
2848 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2851 void *tlsservernew(void *arg) {
2853 struct sockaddr_storage from;
2854 size_t fromlen = sizeof(from);
2855 struct clsrvconf *conf;
2856 struct list_node *cur = NULL;
2859 unsigned long error;
2860 struct client *client;
2863 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2864 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2867 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2869 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2871 ssl = SSL_new(conf->ssl_ctx);
2874 if (SSL_accept(ssl) <= 0) {
2875 while ((error = ERR_get_error()))
2876 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2877 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2880 cert = verifytlscert(ssl);
2886 if (verifyconfcert(cert, conf)) {
2888 client = addclient(conf);
2891 tlsserverrd(client);
2892 removeclient(client);
2894 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2897 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2899 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2905 shutdown(s, SHUT_RDWR);
2910 void *tlslistener(void *arg) {
2911 pthread_t tlsserverth;
2913 struct sockaddr_storage from;
2914 size_t fromlen = sizeof(from);
2915 struct listenerarg *larg = (struct listenerarg *)arg;
2920 s = accept(larg->s, (struct sockaddr *)&from, &fromlen);
2922 debug(DBG_WARN, "accept failed");
2925 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2926 debug(DBG_ERR, "tlslistener: pthread_create failed");
2927 shutdown(s, SHUT_RDWR);
2931 pthread_detach(tlsserverth);
2936 void *tcpserverwr(void *arg) {
2938 struct client *client = (struct client *)arg;
2939 struct replyq *replyq;
2940 struct reply *reply;
2942 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2943 replyq = client->replyq;
2945 pthread_mutex_lock(&replyq->mutex);
2946 while (!list_first(replyq->replies)) {
2947 if (client->s >= 0) {
2948 debug(DBG_DBG, "tcpserverwr: waiting for signal");
2949 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2950 debug(DBG_DBG, "tcpserverwr: got signal");
2952 if (client->s < 0) {
2953 /* s might have changed while waiting */
2954 pthread_mutex_unlock(&replyq->mutex);
2955 debug(DBG_DBG, "tcpserverwr: exiting as requested");
2959 reply = (struct reply *)list_shift(replyq->replies);
2960 pthread_mutex_unlock(&replyq->mutex);
2961 cnt = write(client->s, reply->buf, RADLEN(reply->buf));
2963 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
2964 cnt, RADLEN(reply->buf));
2966 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
2972 void tcpserverrd(struct client *client) {
2974 pthread_t tcpserverwrth;
2976 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
2978 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
2979 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
2984 memset(&rq, 0, sizeof(struct request));
2985 rq.buf = radtcpget(client->s, 0);
2988 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
2993 debug(DBG_ERR, "tcpserverrd: connection lost");
2994 /* stop writer by setting s to -1 and give signal in case waiting for data */
2996 pthread_mutex_lock(&client->replyq->mutex);
2997 pthread_cond_signal(&client->replyq->cond);
2998 pthread_mutex_unlock(&client->replyq->mutex);
2999 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3000 pthread_join(tcpserverwrth, NULL);
3001 removeclientrqs(client);
3002 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3005 void *tcpservernew(void *arg) {
3007 struct sockaddr_storage from;
3008 size_t fromlen = sizeof(from);
3009 struct clsrvconf *conf;
3010 struct client *client;
3013 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3014 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3017 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3019 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3021 client = addclient(conf);
3024 tcpserverrd(client);
3025 removeclient(client);
3027 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3029 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3032 shutdown(s, SHUT_RDWR);
3037 void *tcplistener(void *arg) {
3038 pthread_t tcpserverth;
3040 struct sockaddr_storage from;
3041 size_t fromlen = sizeof(from);
3042 struct listenerarg *larg = (struct listenerarg *)arg;
3047 s = accept(larg->s, (struct sockaddr *)&from, &fromlen);
3049 debug(DBG_WARN, "accept failed");
3052 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3053 debug(DBG_ERR, "tcplistener: pthread_create failed");
3054 shutdown(s, SHUT_RDWR);
3058 pthread_detach(tcpserverth);
3063 void createlistener(uint8_t type, char *arg, uint8_t acconly) {
3065 struct clsrvconf *listenres;
3066 struct addrinfo *res;
3067 struct listenerarg *larg = NULL;
3070 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3072 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3074 for (res = listenres->addrinfo; res; res = res->ai_next) {
3075 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3077 debug(DBG_WARN, "createlistener: socket failed");
3080 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3082 if (res->ai_family == AF_INET6)
3083 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3085 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3086 debug(DBG_WARN, "createlistener: bind failed");
3092 larg = malloc(sizeof(struct listenerarg));
3094 debugx(1, DBG_ERR, "malloc failed");
3096 larg->acconly = acconly;
3097 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)larg))
3098 debugx(1, DBG_ERR, "pthread_create failed");
3102 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3104 debug(DBG_WARN, "createlistener: listening for %s%s on %s:%s", protodefs[type].name,
3105 acconly ? " accounting" : "",
3106 listenres->host ? listenres->host : "*", listenres->port);
3107 freeclsrvres(listenres);
3110 void createlisteners(uint8_t type, char **args, uint8_t acconly) {
3114 for (i = 0; args[i]; i++)
3115 createlistener(type, args[i], acconly);
3117 createlistener(type, NULL, acconly);
3120 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
3123 STACK_OF(X509_NAME) *calist;
3126 unsigned long error;
3128 if (!certfile || !certkeyfile)
3129 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
3131 if (!cacertfile && !cacertpath)
3132 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
3135 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3136 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3137 for (i = 0; i < CRYPTO_num_locks(); i++) {
3138 ssl_lock_count[i] = 0;
3139 pthread_mutex_init(&ssl_locks[i], NULL);
3141 CRYPTO_set_id_callback(ssl_thread_id);
3142 CRYPTO_set_locking_callback(ssl_locking_callback);
3144 SSL_load_error_strings();
3147 while (!RAND_status()) {
3148 time_t t = time(NULL);
3149 pid_t pid = getpid();
3150 RAND_seed((unsigned char *)&t, sizeof(time_t));
3151 RAND_seed((unsigned char *)&pid, sizeof(pid));
3154 ctx = SSL_CTX_new(TLSv1_method());
3156 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
3157 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3159 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
3160 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
3161 !SSL_CTX_check_private_key(ctx) ||
3162 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
3163 while ((error = ERR_get_error()))
3164 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3165 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
3168 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
3169 if (!cacertfile || calist) {
3172 calist = sk_X509_NAME_new_null();
3173 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
3174 sk_X509_NAME_free(calist);
3180 while ((error = ERR_get_error()))
3181 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3182 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
3184 SSL_CTX_set_client_CA_list(ctx, calist);
3186 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3187 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3190 x509_s = SSL_CTX_get_cert_store(ctx);
3191 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3194 new = malloc(sizeof(struct tls));
3195 if (!new || !list_push(tlsconfs, new))
3196 debugx(1, DBG_ERR, "malloc failed");
3198 memset(new, 0, sizeof(struct tls));
3199 new->name = stringcopy(value, 0);
3201 debugx(1, DBG_ERR, "malloc failed");
3203 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
3206 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
3207 struct list_node *entry;
3208 struct tls *t, *t1 = NULL, *t2 = NULL;
3210 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3211 t = (struct tls *)entry->data;
3212 if (!strcasecmp(t->name, alt1)) {
3216 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3226 struct list *addsrvconfs(char *value, char **names) {
3227 struct list *conflist;
3229 struct list_node *entry;
3230 struct clsrvconf *conf = NULL;
3232 if (!names || !*names)
3235 conflist = list_create();
3237 debug(DBG_ERR, "malloc failed");
3241 for (n = 0; names[n]; n++) {
3242 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3243 conf = (struct clsrvconf *)entry->data;
3244 if (!strcasecmp(names[n], conf->name))
3248 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3249 list_destroy(conflist);
3252 if (!list_push(conflist, conf)) {
3253 debug(DBG_ERR, "malloc failed");
3254 list_destroy(conflist);
3257 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3262 void freerealm(struct realm *realm) {
3266 free(realm->message);
3267 regfree(&realm->regex);
3268 pthread_mutex_destroy(&realm->subrealms_mutex);
3269 if (realm->subrealms)
3270 list_destroy(realm->subrealms);
3271 if (realm->srvconfs) {
3272 /* emptying list without freeing data */
3273 while (list_shift(realm->srvconfs));
3274 list_destroy(realm->srvconfs);
3276 if (realm->accsrvconfs) {
3277 /* emptying list without freeing data */
3278 while (list_shift(realm->accsrvconfs));
3279 list_destroy(realm->accsrvconfs);
3284 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3286 struct realm *realm;
3287 char *s, *regex = NULL;
3289 if (*value == '/') {
3290 /* regexp, remove optional trailing / if present */
3291 if (value[strlen(value) - 1] == '/')
3292 value[strlen(value) - 1] = '\0';
3294 /* not a regexp, let us make it one */
3295 if (*value == '*' && !value[1])
3296 regex = stringcopy(".*", 0);
3298 for (n = 0, s = value; *s;)
3301 regex = malloc(strlen(value) + n + 3);
3304 for (n = 1, s = value; *s; s++) {
3314 debug(DBG_ERR, "malloc failed");
3318 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3321 realm = malloc(sizeof(struct realm));
3323 debug(DBG_ERR, "malloc failed");
3326 memset(realm, 0, sizeof(struct realm));
3328 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3329 debug(DBG_ERR, "mutex init failed");
3335 realm->name = stringcopy(value, 0);
3337 debug(DBG_ERR, "malloc failed");
3340 if (message && strlen(message) > 253) {
3341 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3344 realm->message = message;
3345 realm->accresp = accresp;
3347 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3348 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3352 if (servers && *servers) {
3353 realm->srvconfs = addsrvconfs(value, servers);
3354 if (!realm->srvconfs)
3358 if (accservers && *accservers) {
3359 realm->accsrvconfs = addsrvconfs(value, accservers);
3360 if (!realm->accsrvconfs)
3364 if (!list_push(realmlist, realm)) {
3365 debug(DBG_ERR, "malloc failed");
3366 pthread_mutex_destroy(&realm->subrealms_mutex);
3370 debug(DBG_DBG, "addrealm: added realm %s", value);
3380 for (n = 0; servers[n]; n++)
3385 for (n = 0; accservers[n]; n++)
3386 free(accservers[n]);
3392 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3393 struct clsrvconf *srvconf;
3394 struct realm *newrealm = NULL;
3395 char *realmname, *s;
3398 if (!conf->dynamiclookupcommand)
3401 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3402 realmname = strrchr(id, '@');
3408 for (s = realmname; *s; s++)
3409 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3412 pthread_mutex_lock(&realm->subrealms_mutex);
3413 /* exit if we now already got a matching subrealm */
3414 if (id2realm(realm->subrealms, id))
3416 srvconf = malloc(sizeof(struct clsrvconf));
3418 debug(DBG_ERR, "malloc failed");
3422 if (!addserver(srvconf))
3425 if (!realm->subrealms)
3426 realm->subrealms = list_create();
3427 if (!realm->subrealms)
3429 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3433 /* add server and accserver to newrealm */
3434 newrealm->srvconfs = list_create();
3435 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3436 debug(DBG_ERR, "malloc failed");
3439 newrealm->accsrvconfs = list_create();
3440 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3441 debug(DBG_ERR, "malloc failed");
3445 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3447 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3448 debug(DBG_ERR, "pthread_create failed");
3451 pthread_detach(clientth);
3456 list_removedata(realm->subrealms, newrealm);
3457 freerealm(newrealm);
3458 if (!list_first(realm->subrealms)) {
3459 list_destroy(realm->subrealms);
3460 realm->subrealms = NULL;
3463 freeserver(srvconf->servers, 1);
3465 debug(DBG_ERR, "failed to create dynamic server");
3468 pthread_mutex_unlock(&realm->subrealms_mutex);
3471 int dynamicconfig(struct server *server) {
3472 int ok, fd[2], status;
3474 struct clsrvconf *conf = server->conf;
3475 struct gconffile *cf = NULL;
3477 /* for now we only learn hostname/address */
3478 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3481 debug(DBG_ERR, "dynamicconfig: pipe error");
3486 debug(DBG_ERR, "dynamicconfig: fork error");
3490 } else if (pid == 0) {
3493 if (fd[1] != STDOUT_FILENO) {
3494 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3495 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3498 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3499 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3503 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3504 ok = getgenericconfig(&cf, NULL,
3505 "Server", CONF_CBK, confserver_cb, (void *)conf,
3510 if (waitpid(pid, &status, 0) < 0) {
3511 debug(DBG_ERR, "dynamicconfig: wait error");
3516 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3524 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3528 int addmatchcertattr(struct clsrvconf *conf) {
3532 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3533 r = &conf->certcnregex;
3534 v = conf->matchcertattr + 4;
3535 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3536 r = &conf->certuriregex;
3537 v = conf->matchcertattr + 20;
3542 /* regexp, remove optional trailing / if present */
3543 if (v[strlen(v) - 1] == '/')
3544 v[strlen(v) - 1] = '\0';
3548 *r = malloc(sizeof(regex_t));
3550 debug(DBG_ERR, "malloc failed");
3553 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3556 debug(DBG_ERR, "failed to compile regular expression %s", v);
3562 int addrewriteattr(struct clsrvconf *conf) {
3565 v = conf->rewriteattr + 11;
3566 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3568 /* regexp, remove optional trailing / if present */
3569 if (v[strlen(v) - 1] == '/')
3570 v[strlen(v) - 1] = '\0';
3578 conf->rewriteattrregex = malloc(sizeof(regex_t));
3579 if (!conf->rewriteattrregex) {
3580 debug(DBG_ERR, "malloc failed");
3584 conf->rewriteattrreplacement = stringcopy(w, 0);
3585 if (!conf->rewriteattrreplacement) {
3586 free(conf->rewriteattrregex);
3587 conf->rewriteattrregex = NULL;
3591 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3592 free(conf->rewriteattrregex);
3593 conf->rewriteattrregex = NULL;
3594 free(conf->rewriteattrreplacement);
3595 conf->rewriteattrreplacement = NULL;
3596 debug(DBG_ERR, "failed to compile regular expression %s", v);
3603 /* should accept both names and numeric values, only numeric right now */
3604 uint8_t attrname2val(char *attrname) {
3607 val = atoi(attrname);
3608 return val > 0 && val < 256 ? val : 0;
3611 /* should accept both names and numeric values, only numeric right now */
3612 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3615 *vendor = atoi(attrname);
3616 s = strchr(attrname, ':');
3621 *type = atoi(s + 1);
3622 return *type >= 0 && *type < 256;
3625 struct rewrite *getrewrite(char *alt1, char *alt2) {
3626 struct list_node *entry;
3627 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3629 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3630 r = (struct rewriteconf *)entry->data;
3631 if (!strcasecmp(r->name, alt1)) {
3635 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3645 void addrewrite(char *value, char **attrs, char **vattrs) {
3646 struct rewriteconf *new;
3647 struct rewrite *rewrite = NULL;
3650 uint32_t *p, *va = NULL;
3654 for (; attrs[n]; n++);
3655 a = malloc((n + 1) * sizeof(uint8_t));
3657 debugx(1, DBG_ERR, "malloc failed");
3659 for (i = 0; i < n; i++) {
3660 if (!(a[i] = attrname2val(attrs[i])))
3661 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3670 for (; vattrs[n]; n++);
3671 va = malloc((2 * n + 1) * sizeof(uint32_t));
3673 debugx(1, DBG_ERR, "malloc failed");
3675 for (p = va, i = 0; i < n; i++, p += 2) {
3676 if (!vattrname2val(vattrs[i], p, p + 1))
3677 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3685 rewrite = malloc(sizeof(struct rewrite));
3687 debugx(1, DBG_ERR, "malloc failed");
3688 rewrite->removeattrs = a;
3689 rewrite->removevendorattrs = va;
3692 new = malloc(sizeof(struct rewriteconf));
3693 if (!new || !list_push(rewriteconfs, new))
3694 debugx(1, DBG_ERR, "malloc failed");
3696 memset(new, 0, sizeof(struct rewriteconf));
3697 new->name = stringcopy(value, 0);
3699 debugx(1, DBG_ERR, "malloc failed");
3701 new->rewrite = rewrite;
3702 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3705 void freeclsrvconf(struct clsrvconf *conf) {
3711 free(conf->matchcertattr);
3712 if (conf->certcnregex)
3713 regfree(conf->certcnregex);
3714 if (conf->certuriregex)
3715 regfree(conf->certuriregex);
3716 free(conf->confrewrite);
3717 free(conf->rewriteattr);
3718 if (conf->rewriteattrregex)
3719 regfree(conf->rewriteattrregex);
3720 free(conf->rewriteattrreplacement);
3721 free(conf->dynamiclookupcommand);
3722 free(conf->rewrite);
3724 freeaddrinfo(conf->addrinfo);
3725 /* not touching ssl_ctx, clients and servers */
3729 int mergeconfstring(char **dst, char **src) {
3738 t = stringcopy(*dst, 0);
3740 debug(DBG_ERR, "malloc failed");
3748 /* assumes dst is a shallow copy */
3749 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3750 if (!mergeconfstring(&dst->name, &src->name) ||
3751 !mergeconfstring(&dst->host, &src->host) ||
3752 !mergeconfstring(&dst->port, &src->port) ||
3753 !mergeconfstring(&dst->secret, &src->secret) ||
3754 !mergeconfstring(&dst->tls, &src->tls) ||
3755 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3756 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3757 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3760 dst->pdef = src->pdef;
3761 dst->statusserver = src->statusserver;
3762 dst->certnamecheck = src->certnamecheck;
3763 if (src->retryinterval != 255)
3764 dst->retryinterval = src->retryinterval;
3765 if (src->retrycount != 255)
3766 dst->retrycount = src->retrycount;
3770 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3771 struct clsrvconf *conf;
3772 char *conftype = NULL;
3774 debug(DBG_DBG, "confclient_cb called for %s", block);
3776 conf = malloc(sizeof(struct clsrvconf));
3777 if (!conf || !list_push(clconfs, conf))
3778 debugx(1, DBG_ERR, "malloc failed");
3779 memset(conf, 0, sizeof(struct clsrvconf));
3780 conf->certnamecheck = 1;
3782 if (!getgenericconfig(cf, block,
3783 "type", CONF_STR, &conftype,
3784 "host", CONF_STR, &conf->host,
3785 "secret", CONF_STR, &conf->secret,
3786 "tls", CONF_STR, &conf->tls,
3787 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3788 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3789 "rewrite", CONF_STR, &conf->confrewrite,
3790 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3793 debugx(1, DBG_ERR, "configuration error");
3795 conf->name = stringcopy(val, 0);
3797 conf->host = stringcopy(val, 0);
3800 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3801 conf->type = protoname2int(conftype);
3802 conf->pdef = &protodefs[conf->type];
3803 if (!conf->pdef->name)
3804 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3807 if (conf->type == RAD_TLS) {
3808 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3810 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3811 if (conf->matchcertattr && !addmatchcertattr(conf))
3812 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3815 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3817 if (conf->rewriteattr) {
3818 if (!addrewriteattr(conf))
3819 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3822 if (!resolvepeer(conf, 0))
3823 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3825 if (!conf->secret) {
3826 if (!conf->pdef->secretdefault)
3827 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3828 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3830 debugx(1, DBG_ERR, "malloc failed");
3835 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3836 if (conf->type == RAD_TLS) {
3837 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3838 if (!conf->ssl_ctx) {
3839 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3842 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3843 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3849 conf->port = stringcopy(conf->pdef->portdefault, 0);
3851 debug(DBG_ERR, "malloc failed");
3856 if (conf->retryinterval == 255)
3857 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3858 if (conf->retrycount == 255)
3859 conf->retrycount = protodefs[conf->type].retrycountdefault;
3861 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3863 if (!conf->secret) {
3864 if (!conf->pdef->secretdefault) {
3865 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3868 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3869 if (!conf->secret) {
3870 debug(DBG_ERR, "malloc failed");
3875 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3876 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3882 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3883 struct clsrvconf *conf, *resconf;
3884 char *conftype = NULL;
3885 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3887 debug(DBG_DBG, "confserver_cb called for %s", block);
3889 conf = malloc(sizeof(struct clsrvconf));
3891 debug(DBG_ERR, "malloc failed");
3894 memset(conf, 0, sizeof(struct clsrvconf));
3895 resconf = (struct clsrvconf *)arg;
3897 conf->statusserver = resconf->statusserver;
3898 conf->certnamecheck = resconf->certnamecheck;
3900 conf->certnamecheck = 1;
3902 if (!getgenericconfig(cf, block,
3903 "type", CONF_STR, &conftype,
3904 "host", CONF_STR, &conf->host,
3905 "port", CONF_STR, &conf->port,
3906 "secret", CONF_STR, &conf->secret,
3907 "tls", CONF_STR, &conf->tls,
3908 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3909 "rewrite", CONF_STR, &conf->confrewrite,
3910 "StatusServer", CONF_BLN, &conf->statusserver,
3911 "RetryInterval", CONF_LINT, &retryinterval,
3912 "RetryCount", CONF_LINT, &retrycount,
3913 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3914 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3917 debug(DBG_ERR, "configuration error");
3921 conf->name = stringcopy(val, 0);
3923 debug(DBG_ERR, "malloc failed");
3927 conf->host = stringcopy(val, 0);
3929 debug(DBG_ERR, "malloc failed");
3935 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3936 conf->type = protoname2int(conftype);
3937 conf->pdef = &protodefs[conf->type];
3938 if (!conf->pdef->name) {
3939 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3945 if (retryinterval != LONG_MIN) {
3946 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3947 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3950 conf->retryinterval = (uint8_t)retryinterval;
3952 conf->retryinterval = 255;
3954 if (retrycount != LONG_MIN) {
3955 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3956 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3959 conf->retrycount = (uint8_t)retrycount;
3961 conf->retrycount = 255;
3964 if (!mergesrvconf(resconf, conf))
3968 if (conf->dynamiclookupcommand) {
3969 free(conf->dynamiclookupcommand);
3970 conf->dynamiclookupcommand = NULL;
3974 if (resconf || !conf->dynamiclookupcommand) {
3975 if (!compileserverconfig(conf, block))
3982 if (!list_push(srvconfs, conf)) {
3983 debug(DBG_ERR, "malloc failed");
3989 freeclsrvconf(conf);
3993 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3994 char **servers = NULL, **accservers = NULL, *msg = NULL;
3995 uint8_t accresp = 0;
3997 debug(DBG_DBG, "confrealm_cb called for %s", block);
3999 if (!getgenericconfig(cf, block,
4000 "server", CONF_MSTR, &servers,
4001 "accountingServer", CONF_MSTR, &accservers,
4002 "ReplyMessage", CONF_STR, &msg,
4003 "AccountingResponse", CONF_BLN, &accresp,
4006 debugx(1, DBG_ERR, "configuration error");
4008 addrealm(realms, val, servers, accservers, msg, accresp);
4012 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4013 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
4014 uint8_t crlcheck = 0;
4016 debug(DBG_DBG, "conftls_cb called for %s", block);
4018 if (!getgenericconfig(cf, block,
4019 "CACertificateFile", CONF_STR, &cacertfile,
4020 "CACertificatePath", CONF_STR, &cacertpath,
4021 "CertificateFile", CONF_STR, &certfile,
4022 "CertificateKeyFile", CONF_STR, &certkeyfile,
4023 "CertificateKeyPassword", CONF_STR, &certkeypwd,
4024 "CRLCheck", CONF_BLN, &crlcheck,
4027 debugx(1, DBG_ERR, "configuration error");
4029 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
4038 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4039 char **attrs = NULL, **vattrs = NULL;
4041 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4043 if (!getgenericconfig(cf, block,
4044 "removeAttribute", CONF_MSTR, &attrs,
4045 "removeVendorAttribute", CONF_MSTR, &vattrs,
4048 debugx(1, DBG_ERR, "configuration error");
4049 addrewrite(val, attrs, vattrs);
4053 void getmainconfig(const char *configfile) {
4054 long int loglevel = LONG_MIN;
4055 struct gconffile *cfs;
4057 cfs = openconfigfile(configfile);
4058 memset(&options, 0, sizeof(options));
4060 clconfs = list_create();
4062 debugx(1, DBG_ERR, "malloc failed");
4064 srvconfs = list_create();
4066 debugx(1, DBG_ERR, "malloc failed");
4068 realms = list_create();
4070 debugx(1, DBG_ERR, "malloc failed");
4072 tlsconfs = list_create();
4074 debugx(1, DBG_ERR, "malloc failed");
4076 rewriteconfs = list_create();
4078 debugx(1, DBG_ERR, "malloc failed");
4080 if (!getgenericconfig(&cfs, NULL,
4081 "ListenUDP", CONF_MSTR, &options.listenudp,
4082 "ListenTCP", CONF_MSTR, &options.listentcp,
4083 "ListenTLS", CONF_MSTR, &options.listentls,
4084 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4085 "SourceUDP", CONF_STR, &options.sourceudp,
4086 "SourceTCP", CONF_STR, &options.sourcetcp,
4087 "SourceTLS", CONF_STR, &options.sourcetls,
4088 "LogLevel", CONF_LINT, &loglevel,
4089 "LogDestination", CONF_STR, &options.logdestination,
4090 "LoopPrevention", CONF_BLN, &options.loopprevention,
4091 "Client", CONF_CBK, confclient_cb, NULL,
4092 "Server", CONF_CBK, confserver_cb, NULL,
4093 "Realm", CONF_CBK, confrealm_cb, NULL,
4094 "TLS", CONF_CBK, conftls_cb, NULL,
4095 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4098 debugx(1, DBG_ERR, "configuration error");
4100 if (loglevel != LONG_MIN) {
4101 if (loglevel < 1 || loglevel > 4)
4102 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4103 options.loglevel = (uint8_t)loglevel;
4107 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4110 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4113 *configfile = optarg;
4116 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4117 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4118 *loglevel = *optarg - '0';
4127 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4132 if (!(argc - optind))
4136 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4140 int daemon(int a, int b) {
4148 for (i = 0; i < 3; i++) {
4150 open("/dev/null", O_RDWR);
4156 void *sighandler(void *arg) {
4161 sigemptyset(&sigset);
4162 sigaddset(&sigset, SIGPIPE);
4163 sigwait(&sigset, &sig);
4164 /* only get SIGPIPE right now, so could simplify below code */
4167 /* completely ignoring this */
4170 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4173 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4178 int main(int argc, char **argv) {
4179 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
4181 struct list_node *entry;
4182 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4183 char *configfile = NULL;
4184 struct clsrvconf *srvconf;
4186 debug_init("radsecproxy");
4187 debug_set_level(DEBUG_LEVEL);
4188 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4190 debug_set_level(loglevel);
4191 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4193 options.loglevel = loglevel;
4194 else if (options.loglevel)
4195 debug_set_level(options.loglevel);
4197 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4198 free(options.logdestination);
4200 if (!list_first(clconfs))
4201 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4202 if (!list_first(srvconfs))
4203 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
4204 if (!list_first(realms))
4205 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4208 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4210 if (!foreground && (daemon(0, 0) < 0))
4211 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4213 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4215 sigemptyset(&sigset);
4216 /* exit on all but SIGPIPE, ignore more? */
4217 sigaddset(&sigset, SIGPIPE);
4218 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4219 pthread_create(&sigth, NULL, sighandler, NULL);
4221 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4222 udp_server_replyq = newreplyq();
4223 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4224 debugx(1, DBG_ERR, "pthread_create failed");
4225 createlisteners(RAD_UDP, options.listenudp, 0);
4226 if (options.listenaccudp)
4227 createlisteners(RAD_UDP, options.listenaccudp, 1);
4230 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4231 srvconf = (struct clsrvconf *)entry->data;
4232 if (srvconf->dynamiclookupcommand)
4234 if (!addserver(srvconf))
4235 debugx(1, DBG_ERR, "failed to add server");
4236 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4237 (void *)(srvconf->servers)))
4238 debugx(1, DBG_ERR, "pthread_create failed");
4240 /* srcprotores for UDP no longer needed */
4241 if (srcprotores[RAD_UDP]) {
4242 freeaddrinfo(srcprotores[RAD_UDP]);
4243 srcprotores[RAD_UDP] = NULL;
4245 if (udp_client4_sock >= 0)
4246 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4247 debugx(1, DBG_ERR, "pthread_create failed");
4248 if (udp_client6_sock >= 0)
4249 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4250 debugx(1, DBG_ERR, "pthread_create failed");
4252 if (find_conf_type(RAD_TCP, clconfs, NULL))
4253 createlisteners(RAD_TCP, options.listentcp, 0);
4255 if (find_conf_type(RAD_TLS, clconfs, NULL))
4256 createlisteners(RAD_TLS, options.listentls, 0);
4258 /* just hang around doing nothing, anything to do here? */