2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
66 #include "radsecproxy.h"
69 static struct options options;
70 static struct list *clconfs, *srvconfs;
71 struct list *realms, *tlsconfs, *rewriteconfs;
73 static struct addrinfo *srcprotores[4] = { NULL, NULL, NULL, NULL };
75 static struct queue *udp_server_replyq = NULL;
76 static int udp_client4_sock = -1;
77 static int udp_client6_sock = -1;
78 static int dtls_client4_sock = -1;
79 static int dtls_client6_sock = -1;
80 static pthread_mutex_t tlsconfs_lock;
81 static pthread_mutex_t *ssl_locks = NULL;
82 static long *ssl_lock_count;
86 /* minimum required declarations to avoid reordering code */
87 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
88 int dynamicconfig(struct server *server);
89 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
90 void freerealm(struct realm *realm);
91 void freeclsrvconf(struct clsrvconf *conf);
92 void freerqdata(struct request *rq);
93 void *udpserverrd(void *arg);
94 void *tlslistener(void *arg);
95 void *tcplistener(void *arg);
96 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
97 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
98 void *udpclientrd(void *arg);
99 void *tlsclientrd(void *arg);
100 void *tcpclientrd(void *arg);
101 int clientradputudp(struct server *server, unsigned char *rad);
102 int clientradputtls(struct server *server, unsigned char *rad);
103 int clientradputtcp(struct server *server, unsigned char *rad);
104 X509 *verifytlscert(SSL *ssl);
105 int radsrv(struct request *rq);
107 static const struct protodefs protodefs[] = {
108 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
109 NULL, /* secretdefault */
110 SOCK_DGRAM, /* socktype */
111 "1812", /* portdefault */
112 REQUEST_RETRY_COUNT, /* retrycountdefault */
113 10, /* retrycountmax */
114 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
115 60, /* retryintervalmax */
116 udpserverrd, /* listener */
117 &options.sourceudp, /* srcaddrport */
118 NULL, /* connecter */
119 udpclientrd, /* clientreader */
120 clientradputudp /* clientradput */
122 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
123 "mysecret", /* secretdefault */
124 SOCK_STREAM, /* socktype */
125 "2083", /* portdefault */
126 0, /* retrycountdefault */
127 0, /* retrycountmax */
128 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
129 60, /* retryintervalmax */
130 tlslistener, /* listener */
131 &options.sourcetls, /* srcaddrport */
132 tlsconnect, /* connecter */
133 tlsclientrd, /* clientreader */
134 clientradputtls /* clientradput */
136 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
137 NULL, /* secretdefault */
138 SOCK_STREAM, /* socktype */
139 "1812", /* portdefault */
140 0, /* retrycountdefault */
141 0, /* retrycountmax */
142 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
143 60, /* retryintervalmax */
144 tcplistener, /* listener */
145 &options.sourcetcp, /* srcaddrport */
146 tcpconnect, /* connecter */
147 tcpclientrd, /* clientreader */
148 clientradputtcp /* clientradput */
150 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
151 "mysecret", /* secretdefault */
152 SOCK_DGRAM, /* socktype */
153 "2083", /* portdefault */
154 REQUEST_RETRY_COUNT, /* retrycountdefault */
155 10, /* retrycountmax */
156 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
157 60, /* retryintervalmax */
158 udpdtlsserverrd, /* listener */
159 &options.sourcedtls, /* srcaddrport */
160 dtlsconnect, /* connecter */
161 dtlsclientrd, /* clientreader */
162 clientradputdtls /* clientradput */
168 uint8_t protoname2int(const char *name) {
171 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
175 /* callbacks for making OpenSSL thread safe */
176 unsigned long ssl_thread_id() {
177 return (unsigned long)pthread_self();
180 void ssl_locking_callback(int mode, int type, const char *file, int line) {
181 if (mode & CRYPTO_LOCK) {
182 pthread_mutex_lock(&ssl_locks[type]);
183 ssl_lock_count[type]++;
185 pthread_mutex_unlock(&ssl_locks[type]);
188 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
189 int pwdlen = strlen(userdata);
190 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
192 memcpy(buf, userdata, pwdlen);
196 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
201 err_cert = X509_STORE_CTX_get_current_cert(ctx);
202 err = X509_STORE_CTX_get_error(ctx);
203 depth = X509_STORE_CTX_get_error_depth(ctx);
205 if (depth > MAX_CERT_DEPTH) {
207 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
208 X509_STORE_CTX_set_error(ctx, err);
212 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
213 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
216 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
217 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
218 debug(DBG_WARN, "\tIssuer=%s", buf);
220 case X509_V_ERR_CERT_NOT_YET_VALID:
221 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
222 debug(DBG_WARN, "\tCertificate not yet valid");
224 case X509_V_ERR_CERT_HAS_EXPIRED:
225 debug(DBG_WARN, "Certificate has expired");
227 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
228 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
233 printf("certificate verify returns %d\n", ok);
238 struct addrinfo *getsrcprotores(uint8_t type) {
239 return srcprotores[type];
242 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
243 struct addrinfo hints, *addrinfo, *res;
247 slash = conf->host ? strchr(conf->host, '/') : NULL;
251 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
255 if (*s < '0' || *s > '9') {
256 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
259 plen = atoi(slash + 1);
260 if (plen < 0 || plen > 128) {
261 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
266 memset(&hints, 0, sizeof(hints));
267 hints.ai_socktype = conf->pdef->socktype;
268 hints.ai_family = AF_UNSPEC;
269 hints.ai_flags = ai_flags;
270 if (!conf->host && !conf->port) {
271 /* getaddrinfo() doesn't like host and port to be NULL */
272 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
273 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
276 for (res = addrinfo; res; res = res->ai_next) {
277 switch (res->ai_family) {
279 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
282 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
288 hints.ai_flags |= AI_NUMERICHOST;
289 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
290 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
295 switch (addrinfo->ai_family) {
298 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
299 freeaddrinfo(addrinfo);
306 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
307 freeaddrinfo(addrinfo);
310 conf->prefixlen = plen;
312 conf->prefixlen = 255;
315 freeaddrinfo(conf->addrinfo);
316 conf->addrinfo = addrinfo;
320 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
322 struct addrinfo *res;
324 for (res = addrinfo; res; res = res->ai_next) {
325 if (family != AF_UNSPEC && family != res->ai_family)
327 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
329 debug(DBG_WARN, "bindtoaddr: socket failed");
333 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
336 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
339 if (!bind(s, res->ai_addr, res->ai_addrlen))
341 debug(DBG_WARN, "bindtoaddr: bind failed");
347 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
352 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
356 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
358 debugx(1, DBG_ERR, "no ] matching initial [");
362 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
365 debugx(1, DBG_ERR, "missing host/address");
367 conf->host = stringcopy(field, p - field);
370 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
371 debugx(1, DBG_ERR, "unexpected character after ]");
374 /* port number or service name is specified */;
376 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
378 debugx(1, DBG_ERR, "syntax error, : but no following port");
379 conf->port = stringcopy(field, p - field);
381 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
385 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
386 struct clsrvconf *conf;
388 conf = malloc(sizeof(struct clsrvconf));
390 debugx(1, DBG_ERR, "malloc failed");
391 memset(conf, 0, sizeof(struct clsrvconf));
393 conf->pdef = &protodefs[conf->type];
395 parsehostport(lconf, conf, default_port);
396 if (!strcmp(conf->host, "*")) {
401 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
402 if (!resolvepeer(conf, AI_PASSIVE))
403 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
407 void freeclsrvres(struct clsrvconf *res) {
411 freeaddrinfo(res->addrinfo);
415 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
417 struct addrinfo *res;
420 for (res = addrinfo; res; res = res->ai_next) {
421 s = bindtoaddr(src, res->ai_family, 1, 1);
423 debug(DBG_WARN, "connecttoserver: socket failed");
426 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
428 debug(DBG_WARN, "connecttoserver: connect failed");
435 /* returns 1 if the len first bits are equal, else 0 */
436 int prefixmatch(void *a1, void *a2, uint8_t len) {
437 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
439 if (l && memcmp(a1, a2, l))
444 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
447 /* returns next config with matching address, or NULL */
448 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
449 struct sockaddr_in6 *sa6 = NULL;
450 struct in_addr *a4 = NULL;
451 struct addrinfo *res;
452 struct list_node *entry;
453 struct clsrvconf *conf;
455 if (addr->sa_family == AF_INET6) {
456 sa6 = (struct sockaddr_in6 *)addr;
457 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
458 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
462 a4 = &((struct sockaddr_in *)addr)->sin_addr;
464 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
465 conf = (struct clsrvconf *)entry->data;
466 if (conf->type == type) {
467 if (conf->prefixlen == 255) {
468 for (res = conf->addrinfo; res; res = res->ai_next)
469 if ((a4 && res->ai_family == AF_INET &&
470 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
471 (sa6 && res->ai_family == AF_INET6 &&
472 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
478 res = conf->addrinfo;
480 ((a4 && res->ai_family == AF_INET &&
481 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
482 (sa6 && res->ai_family == AF_INET6 &&
483 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
494 struct clsrvconf *find_clconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
495 return find_conf(type, addr, clconfs, cur);
498 struct clsrvconf *find_srvconf(uint8_t type, struct sockaddr *addr, struct list_node **cur) {
499 return find_conf(type, addr, srvconfs, cur);
502 /* returns next config of given type, or NULL */
503 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
504 struct list_node *entry;
505 struct clsrvconf *conf;
507 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
508 conf = (struct clsrvconf *)entry->data;
509 if (conf->type == type) {
518 struct queue *newqueue() {
521 q = malloc(sizeof(struct queue));
523 debugx(1, DBG_ERR, "malloc failed");
524 q->entries = list_create();
526 debugx(1, DBG_ERR, "malloc failed");
527 pthread_mutex_init(&q->mutex, NULL);
528 pthread_cond_init(&q->cond, NULL);
532 void removequeue(struct queue *q) {
533 struct list_node *entry;
535 pthread_mutex_lock(&q->mutex);
536 for (entry = list_first(q->entries); entry; entry = list_next(entry))
537 free(((struct reply *)entry)->buf);
538 list_destroy(q->entries);
539 pthread_cond_destroy(&q->cond);
540 pthread_mutex_unlock(&q->mutex);
541 pthread_mutex_destroy(&q->mutex);
544 void freebios(struct queue *q) {
547 pthread_mutex_lock(&q->mutex);
548 while ((bio = (BIO *)list_shift(q->entries)))
550 pthread_mutex_unlock(&q->mutex);
554 struct client *addclient(struct clsrvconf *conf) {
555 struct client *new = malloc(sizeof(struct client));
558 debug(DBG_ERR, "malloc failed");
561 if (!conf->clients) {
562 conf->clients = list_create();
563 if (!conf->clients) {
564 debug(DBG_ERR, "malloc failed");
569 memset(new, 0, sizeof(struct client));
571 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newqueue();
572 if (conf->type == RAD_DTLS)
573 new->rbios = newqueue();
574 list_push(conf->clients, new);
578 void removeclient(struct client *client) {
579 if (!client || !client->conf->clients)
581 removequeue(client->replyq);
583 freebios(client->rbios);
584 list_removedata(client->conf->clients, client);
588 void removeclientrqs(struct client *client) {
589 struct list_node *entry;
590 struct server *server;
594 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
595 server = ((struct clsrvconf *)entry->data)->servers;
598 pthread_mutex_lock(&server->newrq_mutex);
599 for (i = 0; i < MAX_REQUESTS; i++) {
600 rq = server->requests + i;
601 if (rq->from == client)
604 pthread_mutex_unlock(&server->newrq_mutex);
608 void freeserver(struct server *server, uint8_t destroymutex) {
609 struct request *rq, *end;
614 if (server->requests) {
615 rq = server->requests;
616 for (end = rq + MAX_REQUESTS; rq < end; rq++)
618 free(server->requests);
621 freebios(server->rbios);
622 free(server->dynamiclookuparg);
624 pthread_mutex_destroy(&server->lock);
625 pthread_cond_destroy(&server->newrq_cond);
626 pthread_mutex_destroy(&server->newrq_mutex);
631 int addserver(struct clsrvconf *conf) {
632 struct clsrvconf *res;
636 debug(DBG_ERR, "addserver: currently works with just one server per conf");
639 conf->servers = malloc(sizeof(struct server));
640 if (!conf->servers) {
641 debug(DBG_ERR, "malloc failed");
644 memset(conf->servers, 0, sizeof(struct server));
645 conf->servers->conf = conf;
648 if (type == RAD_DTLS)
649 conf->servers->rbios = newqueue();
651 if (!srcprotores[type]) {
652 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
653 srcprotores[type] = res->addrinfo;
654 res->addrinfo = NULL;
660 switch (conf->addrinfo->ai_family) {
662 if (udp_client4_sock < 0) {
663 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
664 if (udp_client4_sock < 0)
665 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
667 conf->servers->sock = udp_client4_sock;
670 if (udp_client6_sock < 0) {
671 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
672 if (udp_client6_sock < 0)
673 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
675 conf->servers->sock = udp_client6_sock;
678 debugx(1, DBG_ERR, "addserver: unsupported address family");
682 switch (conf->addrinfo->ai_family) {
684 if (dtls_client4_sock < 0) {
685 dtls_client4_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET, 0, 1);
686 if (dtls_client4_sock < 0)
687 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
689 conf->servers->sock = dtls_client4_sock;
692 if (dtls_client6_sock < 0) {
693 dtls_client6_sock = bindtoaddr(srcprotores[RAD_DTLS], AF_INET6, 0, 1);
694 if (dtls_client6_sock < 0)
695 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
697 conf->servers->sock = dtls_client6_sock;
700 debugx(1, DBG_ERR, "addserver: unsupported address family");
704 conf->servers->sock = -1;
707 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
708 if (!conf->servers->requests) {
709 debug(DBG_ERR, "malloc failed");
712 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
713 debug(DBG_ERR, "mutex init failed");
716 conf->servers->newrq = 0;
717 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
718 debug(DBG_ERR, "mutex init failed");
719 pthread_mutex_destroy(&conf->servers->lock);
722 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
723 debug(DBG_ERR, "mutex init failed");
724 pthread_mutex_destroy(&conf->servers->newrq_mutex);
725 pthread_mutex_destroy(&conf->servers->lock);
732 freeserver(conf->servers, 0);
733 conf->servers = NULL;
737 /* exactly one of client and server must be non-NULL */
738 /* return who we received from in *client or *server */
739 /* return from in sa if not NULL */
740 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
742 unsigned char buf[4], *rad = NULL;
743 struct sockaddr_storage from;
744 socklen_t fromlen = sizeof(from);
746 struct list_node *node;
756 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
758 cnt = recvfrom(s, buf, 4, MSG_PEEK | MSG_TRUNC, (struct sockaddr *)&from, &fromlen);
760 debug(DBG_WARN, "radudpget: recv failed");
764 debug(DBG_WARN, "radudpget: length too small");
769 p = find_conf(RAD_UDP, (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
771 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
778 debug(DBG_WARN, "radudpget: length too small");
785 debug(DBG_ERR, "radudpget: malloc failed");
790 cnt = recv(s, rad, len, MSG_TRUNC);
791 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
794 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
798 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
801 node = list_first(p->clients);
802 *client = node ? (struct client *)node->data : addclient(p);
806 *server = p->servers;
814 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
815 int loc, i, l, n, r = 0;
818 STACK_OF(GENERAL_NAME) *alt;
821 debug(DBG_DBG, "subjectaltnameaddr");
823 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
827 ex = X509_get_ext(cert, loc);
828 alt = X509V3_EXT_d2i(ex);
832 n = sk_GENERAL_NAME_num(alt);
833 for (i = 0; i < n; i++) {
834 gn = sk_GENERAL_NAME_value(alt, i);
835 if (gn->type != GEN_IPADD)
838 v = (char *)ASN1_STRING_data(gn->d.ia5);
839 l = ASN1_STRING_length(gn->d.ia5);
840 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
841 && !memcmp(v, &addr, l)) {
846 GENERAL_NAMES_free(alt);
850 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
857 nm = X509_get_subject_name(cert);
860 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
863 e = X509_NAME_get_entry(nm, loc);
864 t = X509_NAME_ENTRY_get_data(e);
865 v = (char *) ASN1_STRING_data(t);
866 l = ASN1_STRING_length(t);
870 if (l == strlen(exact) && !strncasecmp(exact, v, l))
873 s = stringcopy((char *)v, l);
875 debug(DBG_ERR, "malloc failed");
878 if (regexec(regex, s, 0, NULL, 0)) {
889 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
890 int loc, i, l, n, r = 0;
893 STACK_OF(GENERAL_NAME) *alt;
896 debug(DBG_DBG, "subjectaltnameregexp");
898 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
902 ex = X509_get_ext(cert, loc);
903 alt = X509V3_EXT_d2i(ex);
907 n = sk_GENERAL_NAME_num(alt);
908 for (i = 0; i < n; i++) {
909 gn = sk_GENERAL_NAME_value(alt, i);
910 if (gn->type != type)
913 v = (char *)ASN1_STRING_data(gn->d.ia5);
914 l = ASN1_STRING_length(gn->d.ia5);
918 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
921 if (memcmp(v, exact, l))
924 s = stringcopy((char *)v, l);
926 debug(DBG_ERR, "malloc failed");
929 if (regexec(regex, s, 0, NULL, 0)) {
938 GENERAL_NAMES_free(alt);
942 X509 *verifytlscert(SSL *ssl) {
946 if (SSL_get_verify_result(ssl) != X509_V_OK) {
947 debug(DBG_ERR, "verifytlscert: basic validation failed");
948 while ((error = ERR_get_error()))
949 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
953 cert = SSL_get_peer_certificate(ssl);
955 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
959 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
961 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
962 struct in6_addr addr;
964 if (conf->certnamecheck && conf->prefixlen == 255) {
965 if (inet_pton(AF_INET, conf->host, &addr))
967 else if (inet_pton(AF_INET6, conf->host, &addr))
970 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
973 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
976 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
978 if (!cnregexp(cert, conf->host, NULL)) {
979 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
982 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
985 if (conf->certcnregex) {
986 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
987 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
990 debug(DBG_DBG, "verifyconfcert: CN matching regex");
992 if (conf->certuriregex) {
993 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
994 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
997 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
1002 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1006 unsigned long error;
1008 debug(DBG_DBG, "tlsconnect: called from %s", text);
1009 pthread_mutex_lock(&server->lock);
1010 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1011 /* already reconnected, nothing to do */
1012 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
1013 pthread_mutex_unlock(&server->lock);
1018 gettimeofday(&now, NULL);
1019 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1020 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1021 debug(DBG_DBG, "tlsconnect: timeout");
1022 if (server->sock >= 0)
1023 close(server->sock);
1024 SSL_free(server->ssl);
1026 pthread_mutex_unlock(&server->lock);
1029 if (server->connectionok) {
1030 server->connectionok = 0;
1032 } else if (elapsed < 1)
1034 else if (elapsed < 60) {
1035 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1037 } else if (elapsed < 100000) {
1038 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1041 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1042 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1043 if (server->sock >= 0)
1044 close(server->sock);
1045 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1046 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1050 SSL_free(server->ssl);
1051 server->ssl = SSL_new(server->conf->ssl_ctx);
1052 SSL_set_fd(server->ssl, server->sock);
1053 if (SSL_connect(server->ssl) <= 0) {
1054 while ((error = ERR_get_error()))
1055 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
1058 cert = verifytlscert(server->ssl);
1061 if (verifyconfcert(cert, server->conf)) {
1067 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1068 gettimeofday(&server->lastconnecttry, NULL);
1069 pthread_mutex_unlock(&server->lock);
1073 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1074 /* returns 0 on timeout, -1 on error and num if ok */
1075 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1076 int s, ndesc, cnt, len;
1077 fd_set readfds, writefds;
1078 struct timeval timer;
1080 s = SSL_get_fd(ssl);
1083 /* make socket non-blocking? */
1084 for (len = 0; len < num; len += cnt) {
1086 FD_SET(s, &readfds);
1089 timer.tv_sec = timeout;
1092 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1096 cnt = SSL_read(ssl, buf + len, num - len);
1098 switch (SSL_get_error(ssl, cnt)) {
1099 case SSL_ERROR_WANT_READ:
1100 case SSL_ERROR_WANT_WRITE:
1103 case SSL_ERROR_ZERO_RETURN:
1104 /* remote end sent close_notify, send one back */
1114 /* timeout in seconds, 0 means no timeout (blocking) */
1115 unsigned char *radtlsget(SSL *ssl, int timeout) {
1117 unsigned char buf[4], *rad;
1120 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1122 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1129 debug(DBG_ERR, "radtlsget: malloc failed");
1132 memcpy(rad, buf, 4);
1134 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1136 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1145 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1148 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1152 int clientradputudp(struct server *server, unsigned char *rad) {
1154 struct sockaddr_storage sa;
1155 struct sockaddr *sap;
1156 struct clsrvconf *conf = server->conf;
1157 in_port_t *port = NULL;
1161 if (*rad == RAD_Accounting_Request) {
1162 sap = (struct sockaddr *)&sa;
1163 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1165 sap = conf->addrinfo->ai_addr;
1167 switch (sap->sa_family) {
1169 port = &((struct sockaddr_in *)sap)->sin_port;
1172 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1178 if (*rad == RAD_Accounting_Request)
1179 *port = htons(ntohs(*port) + 1);
1181 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1182 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1186 debug(DBG_WARN, "clientradputudp: send failed");
1190 int clientradputtls(struct server *server, unsigned char *rad) {
1193 unsigned long error;
1194 struct timeval lastconnecttry;
1195 struct clsrvconf *conf = server->conf;
1198 lastconnecttry = server->lastconnecttry;
1199 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1200 while ((error = ERR_get_error()))
1201 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1202 if (server->dynamiclookuparg)
1204 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1205 lastconnecttry = server->lastconnecttry;
1208 server->connectionok = 1;
1209 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1213 int radsign(unsigned char *rad, unsigned char *sec) {
1214 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1215 static unsigned char first = 1;
1216 static EVP_MD_CTX mdctx;
1217 unsigned int md_len;
1220 pthread_mutex_lock(&lock);
1222 EVP_MD_CTX_init(&mdctx);
1226 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1227 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1228 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1229 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1231 pthread_mutex_unlock(&lock);
1235 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1236 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1237 static unsigned char first = 1;
1238 static EVP_MD_CTX mdctx;
1239 unsigned char hash[EVP_MAX_MD_SIZE];
1243 pthread_mutex_lock(&lock);
1245 EVP_MD_CTX_init(&mdctx);
1251 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1252 EVP_DigestUpdate(&mdctx, rad, 4) &&
1253 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1254 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1255 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1256 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1258 !memcmp(hash, rad + 4, 16));
1259 pthread_mutex_unlock(&lock);
1263 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1264 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1265 static unsigned char first = 1;
1266 static HMAC_CTX hmacctx;
1267 unsigned int md_len;
1268 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1270 pthread_mutex_lock(&lock);
1272 HMAC_CTX_init(&hmacctx);
1276 memcpy(auth, authattr, 16);
1277 memset(authattr, 0, 16);
1279 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1280 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1281 HMAC_Final(&hmacctx, hash, &md_len);
1282 memcpy(authattr, auth, 16);
1284 debug(DBG_WARN, "message auth computation failed");
1285 pthread_mutex_unlock(&lock);
1289 if (memcmp(auth, hash, 16)) {
1290 debug(DBG_WARN, "message authenticator, wrong value");
1291 pthread_mutex_unlock(&lock);
1295 pthread_mutex_unlock(&lock);
1299 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1300 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1301 static unsigned char first = 1;
1302 static HMAC_CTX hmacctx;
1303 unsigned int md_len;
1308 pthread_mutex_lock(&lock);
1310 HMAC_CTX_init(&hmacctx);
1314 memset(authattrval, 0, 16);
1316 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1317 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1318 HMAC_Final(&hmacctx, authattrval, &md_len);
1320 debug(DBG_WARN, "message auth computation failed");
1321 pthread_mutex_unlock(&lock);
1325 pthread_mutex_unlock(&lock);
1329 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1330 while (length > 1) {
1331 if (ATTRTYPE(attrs) == type)
1333 length -= ATTRLEN(attrs);
1334 attrs += ATTRLEN(attrs);
1339 void freerqdata(struct request *rq) {
1340 if (rq->origusername)
1341 free(rq->origusername);
1346 void sendrq(struct server *to, struct request *rq) {
1350 pthread_mutex_lock(&to->newrq_mutex);
1351 /* might simplify if only try nextid, might be ok */
1352 for (i = to->nextid; i < MAX_REQUESTS; i++)
1353 if (!to->requests[i].buf)
1355 if (i == MAX_REQUESTS) {
1356 for (i = 0; i < to->nextid; i++)
1357 if (!to->requests[i].buf)
1359 if (i == to->nextid) {
1360 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1366 rq->buf[1] = (char)i;
1368 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1369 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1374 if (*rq->buf == RAD_Accounting_Request) {
1375 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1376 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1382 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1383 to->requests[i] = *rq;
1388 debug(DBG_DBG, "sendrq: signalling client writer");
1389 pthread_cond_signal(&to->newrq_cond);
1392 pthread_mutex_unlock(&to->newrq_mutex);
1395 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1396 struct reply *reply;
1399 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1401 debug(DBG_WARN, "sendreply: failed to sign message");
1405 reply = malloc(sizeof(struct reply));
1408 debug(DBG_ERR, "sendreply: malloc failed");
1411 memset(reply, 0, sizeof(struct reply));
1414 reply->tosa = *tosa;
1415 reply->toudpsock = toudpsock;
1417 pthread_mutex_lock(&to->replyq->mutex);
1419 first = list_first(to->replyq->entries) == NULL;
1421 if (!list_push(to->replyq->entries, reply)) {
1422 pthread_mutex_unlock(&to->replyq->mutex);
1425 debug(DBG_ERR, "sendreply: malloc failed");
1430 debug(DBG_DBG, "signalling server writer");
1431 pthread_cond_signal(&to->replyq->cond);
1433 pthread_mutex_unlock(&to->replyq->mutex);
1436 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1437 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1438 static unsigned char first = 1;
1439 static EVP_MD_CTX mdctx;
1440 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1441 unsigned int md_len;
1442 uint8_t i, offset = 0, out[128];
1444 pthread_mutex_lock(&lock);
1446 EVP_MD_CTX_init(&mdctx);
1452 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1453 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1454 !EVP_DigestUpdate(&mdctx, input, 16) ||
1455 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1457 pthread_mutex_unlock(&lock);
1460 for (i = 0; i < 16; i++)
1461 out[offset + i] = hash[i] ^ in[offset + i];
1462 input = out + offset - 16;
1467 memcpy(in, out, len);
1468 pthread_mutex_unlock(&lock);
1472 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1473 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1474 static unsigned char first = 1;
1475 static EVP_MD_CTX mdctx;
1476 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1477 unsigned int md_len;
1478 uint8_t i, offset = 0, out[128];
1480 pthread_mutex_lock(&lock);
1482 EVP_MD_CTX_init(&mdctx);
1488 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1489 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1490 !EVP_DigestUpdate(&mdctx, input, 16) ||
1491 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1493 pthread_mutex_unlock(&lock);
1496 for (i = 0; i < 16; i++)
1497 out[offset + i] = hash[i] ^ in[offset + i];
1498 input = in + offset;
1503 memcpy(in, out, len);
1504 pthread_mutex_unlock(&lock);
1508 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1509 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1510 static unsigned char first = 1;
1511 static EVP_MD_CTX mdctx;
1512 unsigned char hash[EVP_MAX_MD_SIZE];
1513 unsigned int md_len;
1516 pthread_mutex_lock(&lock);
1518 EVP_MD_CTX_init(&mdctx);
1523 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1524 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1525 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1528 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1529 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1530 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1531 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1532 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1533 pthread_mutex_unlock(&lock);
1538 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1541 for (i = 0; i < 16; i++)
1544 for (offset = 16; offset < len; offset += 16) {
1546 printf("text + offset - 16 c(%d): ", offset / 16);
1547 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1549 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1550 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1551 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1552 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1554 pthread_mutex_unlock(&lock);
1558 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1561 for (i = 0; i < 16; i++)
1562 text[offset + i] ^= hash[i];
1566 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1569 pthread_mutex_unlock(&lock);
1573 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1574 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1575 static unsigned char first = 1;
1576 static EVP_MD_CTX mdctx;
1577 unsigned char hash[EVP_MAX_MD_SIZE];
1578 unsigned int md_len;
1582 pthread_mutex_lock(&lock);
1584 EVP_MD_CTX_init(&mdctx);
1589 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1590 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1591 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1594 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1595 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1596 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1597 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1598 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1599 pthread_mutex_unlock(&lock);
1604 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1607 for (i = 0; i < 16; i++)
1608 plain[i] = text[i] ^ hash[i];
1610 for (offset = 16; offset < len; offset += 16) {
1612 printf("text + offset - 16 c(%d): ", offset / 16);
1613 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1615 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1616 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1617 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1618 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1620 pthread_mutex_unlock(&lock);
1624 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1627 for (i = 0; i < 16; i++)
1628 plain[offset + i] = text[offset + i] ^ hash[i];
1631 memcpy(text, plain, len);
1633 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1636 pthread_mutex_unlock(&lock);
1640 struct realm *id2realm(struct list *realmlist, char *id) {
1641 struct list_node *entry;
1642 struct realm *realm, *subrealm = NULL;
1644 /* need to do locking for subrealms and check subrealm timers */
1645 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1646 realm = (struct realm *)entry->data;
1647 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1648 pthread_mutex_lock(&realm->subrealms_mutex);
1649 if (realm->subrealms)
1650 subrealm = id2realm(realm->subrealms, id);
1651 pthread_mutex_unlock(&realm->subrealms_mutex);
1652 return subrealm ? subrealm : realm;
1658 /* helper function, only used by removeserversubrealms() */
1659 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1660 struct list_node *entry;
1661 struct realm *realm;
1663 for (entry = list_first(realmlist); entry;) {
1664 realm = (struct realm *)entry->data;
1665 entry = list_next(entry);
1666 if (realm->srvconfs) {
1667 list_removedata(realm->srvconfs, srv);
1668 if (!list_first(realm->srvconfs)) {
1669 list_destroy(realm->srvconfs);
1670 realm->srvconfs = NULL;
1673 if (realm->accsrvconfs) {
1674 list_removedata(realm->accsrvconfs, srv);
1675 if (!list_first(realm->accsrvconfs)) {
1676 list_destroy(realm->accsrvconfs);
1677 realm->accsrvconfs = NULL;
1681 /* remove subrealm if no servers */
1682 if (!realm->srvconfs && !realm->accsrvconfs) {
1683 list_removedata(realmlist, realm);
1689 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1690 struct list_node *entry;
1691 struct realm *realm;
1693 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1694 realm = (struct realm *)entry->data;
1695 pthread_mutex_lock(&realm->subrealms_mutex);
1696 if (realm->subrealms) {
1697 _internal_removeserversubrealms(realm->subrealms, srv);
1698 if (!list_first(realm->subrealms)) {
1699 list_destroy(realm->subrealms);
1700 realm->subrealms = NULL;
1703 pthread_mutex_unlock(&realm->subrealms_mutex);
1707 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1708 struct request *rq = to->requests, *end;
1710 pthread_mutex_lock(&to->newrq_mutex);
1711 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1712 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1714 pthread_mutex_unlock(&to->newrq_mutex);
1719 int attrvalidate(unsigned char *attrs, int length) {
1720 while (length > 1) {
1721 if (ATTRLEN(attrs) < 2) {
1722 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1725 length -= ATTRLEN(attrs);
1727 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1730 attrs += ATTRLEN(attrs);
1733 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1737 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1738 if (len < 16 || len > 128 || len % 16) {
1739 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1743 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1744 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1748 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1750 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1751 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1757 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1760 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1761 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1764 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1765 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1771 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1772 char *oldsecret, char *newsecret) {
1773 unsigned char *attr;
1775 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1776 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1777 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1783 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1787 for (; attrs[0]; attrs += 2)
1788 if (attrs[0] == vendor && attrs[1] == subattr)
1793 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1794 uint8_t alen, sublen, rmlen = 0;
1795 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1798 if (!removevendorattrs)
1801 while (*removevendorattrs && *removevendorattrs != vendor)
1802 removevendorattrs += 2;
1803 if (!*removevendorattrs)
1806 alen = ATTRLEN(attrs);
1808 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1809 /* remove entire vendor attribute */
1810 memmove(attrs, attrs + alen, length - alen);
1815 subattrs = ATTRVAL(attrs) + 4;
1817 if (!attrvalidate(subattrs, sublen)) {
1818 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1823 while (sublen > 1) {
1824 alen = ATTRLEN(subattrs);
1827 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1828 memmove(subattrs, subattrs + alen, length);
1834 ATTRLEN(attrs) -= rmlen;
1838 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1839 uint8_t *attrs, alen;
1840 uint16_t len, rmlen = 0;
1842 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1845 len = RADLEN(buf) - 20;
1848 alen = ATTRLEN(attrs);
1850 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1851 memmove(attrs, attrs + alen, len);
1853 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1854 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1859 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1862 /* returns a pointer to the resized attribute value */
1863 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1864 uint8_t *attrs, *attr, vallen;
1868 len = RADLEN(*buf) - 20;
1871 attr = attrget(attrs, len, type);
1875 vallen = ATTRVALLEN(attr);
1876 if (vallen == newvallen)
1879 len += newvallen - vallen;
1880 if (newvallen > vallen) {
1881 new = realloc(*buf, len + 20);
1883 debug(DBG_ERR, "resizeattr: malloc failed");
1892 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1893 attr[1] = newvallen + 2;
1894 ((uint16_t *)*buf)[1] = htons(len + 20);
1898 int rewriteusername(struct request *rq, char *in) {
1899 size_t nmatch = 10, reslen = 0, start = 0;
1900 regmatch_t pmatch[10], *pfield;
1902 unsigned char *result;
1903 char *out = rq->from->conf->rewriteattrreplacement;
1905 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1906 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1910 rq->origusername = stringcopy(in, 0);
1911 if (!rq->origusername)
1914 for (i = start; out[i]; i++) {
1915 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1916 pfield = &pmatch[out[i + 1] - '0'];
1917 if (pfield->rm_so >= 0) {
1918 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1924 reslen += i - start;
1926 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1932 for (i = start; out[i]; i++) {
1933 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1934 pfield = &pmatch[out[i + 1] - '0'];
1935 if (pfield->rm_so >= 0) {
1936 memcpy(result + reslen, out + start, i - start);
1937 reslen += i - start;
1938 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1939 reslen += pfield->rm_eo - pfield->rm_so;
1946 memcpy(result + reslen, out + start, i - start);
1947 reslen += i - start;
1948 memcpy(in, result, reslen);
1953 const char *radmsgtype2string(uint8_t code) {
1954 static const char *rad_msg_names[] = {
1955 "", "Access-Request", "Access-Accept", "Access-Reject",
1956 "Accounting-Request", "Accounting-Response", "", "",
1957 "", "", "", "Access-Challenge",
1958 "Status-Server", "Status-Client"
1960 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1963 void char2hex(char *h, unsigned char c) {
1964 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1965 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1966 h[0] = hexdigits[c / 16];
1967 h[1] = hexdigits[c % 16];
1971 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1975 if (!attr || len == 1) {
1980 l = ATTRVALLEN(attr);
1981 s = (char *)ATTRVAL(attr);
1984 for (i = 0; i < l; i++) {
1985 if (s[i] > 31 && s[i] < 127) {
1987 if (d - ascii == len - 1)
1990 if (d - ascii > len - 4)
1995 if (d - ascii == len - 1)
2003 void acclog(unsigned char *attrs, int length, char *host) {
2004 unsigned char *attr;
2007 attr = attrget(attrs, length, RAD_Attr_User_Name);
2009 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2012 radattr2ascii(username, sizeof(username), attr);
2013 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2016 void respondaccounting(struct request *rq) {
2017 unsigned char *resp;
2021 debug(DBG_ERR, "respondaccounting: malloc failed");
2024 memcpy(resp, rq->buf, 20);
2025 resp[0] = RAD_Accounting_Response;
2028 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2029 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2032 void respondstatusserver(struct request *rq) {
2033 unsigned char *resp;
2037 debug(DBG_ERR, "respondstatusserver: malloc failed");
2040 memcpy(resp, rq->buf, 20);
2041 resp[0] = RAD_Access_Accept;
2044 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2045 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2048 void respondreject(struct request *rq, char *message) {
2049 unsigned char *resp;
2052 if (message && *message)
2053 len += 2 + strlen(message);
2057 debug(DBG_ERR, "respondreject: malloc failed");
2060 memcpy(resp, rq->buf, 20);
2061 resp[0] = RAD_Access_Reject;
2062 *(uint16_t *)(resp + 2) = htons(len);
2063 if (message && *message) {
2064 resp[20] = RAD_Attr_Reply_Message;
2065 resp[21] = len - 20;
2066 memcpy(resp + 22, message, len - 22);
2068 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2071 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2072 struct list_node *entry;
2073 struct clsrvconf *server, *best = NULL, *first = NULL;
2075 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2076 server = (struct clsrvconf *)entry->data;
2077 if (!server->servers)
2081 if (!server->servers->connectionok)
2083 if (!server->servers->lostrqs)
2089 if (server->servers->lostrqs < best->servers->lostrqs)
2092 return best ? best : first;
2095 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2096 struct clsrvconf *srvconf;
2098 *realm = id2realm(realms, id);
2101 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2102 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2105 if (!acc && !srvconf->servers)
2106 adddynamicrealmserver(*realm, srvconf, id);
2107 return srvconf->servers;
2110 /* returns 0 if validation/authentication fails, else 1 */
2111 int radsrv(struct request *rq) {
2112 uint8_t code, id, *auth, *attrs, *attr;
2114 struct server *to = NULL;
2115 char username[254], userascii[760];
2116 unsigned char newauth[16];
2117 struct realm *realm = NULL;
2119 code = *(uint8_t *)rq->buf;
2120 id = *(uint8_t *)(rq->buf + 1);
2121 len = RADLEN(rq->buf);
2122 auth = (uint8_t *)(rq->buf + 4);
2124 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2126 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2127 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2132 attrs = rq->buf + 20;
2134 if (!attrvalidate(attrs, len)) {
2135 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2139 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2140 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2141 debug(DBG_WARN, "radsrv: message authentication failed");
2145 if (code == RAD_Status_Server) {
2146 respondstatusserver(rq);
2150 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2152 if (code == RAD_Accounting_Request) {
2153 memset(newauth, 0, 16);
2154 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2155 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2160 if (rq->from->conf->rewrite) {
2161 dorewrite(rq->buf, rq->from->conf->rewrite);
2162 len = RADLEN(rq->buf) - 20;
2165 attr = attrget(attrs, len, RAD_Attr_User_Name);
2167 if (code == RAD_Accounting_Request) {
2168 acclog(attrs, len, rq->from->conf->host);
2169 respondaccounting(rq);
2171 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2174 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2175 username[ATTRVALLEN(attr)] = '\0';
2176 radattr2ascii(userascii, sizeof(userascii), attr);
2178 if (rq->from->conf->rewriteattrregex) {
2179 if (!rewriteusername(rq, username)) {
2180 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2183 len = RADLEN(rq->buf) - 20;
2184 auth = (uint8_t *)(rq->buf + 4);
2185 attrs = rq->buf + 20;
2188 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2190 to = findserver(&realm, username, code == RAD_Accounting_Request);
2192 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2196 if (realm->message && code == RAD_Access_Request) {
2197 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2198 respondreject(rq, realm->message);
2199 } else if (realm->accresp && code == RAD_Accounting_Request) {
2200 acclog(attrs, len, rq->from->conf->host);
2201 respondaccounting(rq);
2206 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2207 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2208 rq->from->conf->name, to->conf->name);
2212 if (rqinqueue(to, rq->from, id, code)) {
2213 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2214 radmsgtype2string(code), rq->from->conf->host, id);
2218 if (code != RAD_Accounting_Request) {
2219 if (!RAND_bytes(newauth, 16)) {
2220 debug(DBG_WARN, "radsrv: failed to generate random auth");
2226 printfchars(NULL, "auth", "%02x ", auth, 16);
2229 attr = attrget(attrs, len, RAD_Attr_User_Password);
2231 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2232 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2236 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2238 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2239 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2244 memcpy(rq->origauth, auth, 16);
2245 memcpy(auth, newauth, 16);
2258 int replyh(struct server *server, unsigned char *buf) {
2259 struct client *from;
2262 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2263 struct sockaddr_storage fromsa;
2264 char tmp[760], stationid[760];
2266 server->connectionok = 1;
2267 server->lostrqs = 0;
2269 i = buf[1]; /* i is the id */
2271 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2272 && *buf != RAD_Accounting_Response) {
2273 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2276 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2278 rq = server->requests + i;
2280 pthread_mutex_lock(&server->newrq_mutex);
2281 if (!rq->buf || !rq->tries) {
2282 pthread_mutex_unlock(&server->newrq_mutex);
2283 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2288 pthread_mutex_unlock(&server->newrq_mutex);
2289 debug(DBG_INFO, "replyh: already received, ignoring reply");
2293 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2294 pthread_mutex_unlock(&server->newrq_mutex);
2295 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2299 len = RADLEN(buf) - 20;
2302 if (!attrvalidate(attrs, len)) {
2303 pthread_mutex_unlock(&server->newrq_mutex);
2304 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2308 /* Message Authenticator */
2309 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2311 if (ATTRVALLEN(messageauth) != 16) {
2312 pthread_mutex_unlock(&server->newrq_mutex);
2313 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2316 memcpy(tmp, buf + 4, 16);
2317 memcpy(buf + 4, rq->buf + 4, 16);
2318 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2319 pthread_mutex_unlock(&server->newrq_mutex);
2320 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2323 memcpy(buf + 4, tmp, 16);
2324 debug(DBG_DBG, "replyh: message auth ok");
2327 gettimeofday(&server->lastrcv, NULL);
2329 if (*rq->buf == RAD_Status_Server) {
2331 pthread_mutex_unlock(&server->newrq_mutex);
2332 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2336 gettimeofday(&server->lastreply, NULL);
2340 pthread_mutex_unlock(&server->newrq_mutex);
2341 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2345 if (server->conf->rewrite) {
2346 dorewrite(buf, server->conf->rewrite);
2347 len = RADLEN(buf) - 20;
2351 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2352 if (ATTRVALLEN(attr) <= 4)
2355 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2358 sublen = ATTRVALLEN(attr) - 4;
2359 subattrs = ATTRVAL(attr) + 4;
2360 if (!attrvalidate(subattrs, sublen) ||
2361 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2362 rq, server->conf->secret, from->conf->secret) ||
2363 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2364 rq, server->conf->secret, from->conf->secret))
2368 pthread_mutex_unlock(&server->newrq_mutex);
2369 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2373 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2374 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2376 radattr2ascii(tmp, sizeof(tmp), attr);
2377 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2379 radattr2ascii(stationid, sizeof(stationid), attr);
2380 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2381 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2383 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2387 buf[1] = (char)rq->origid;
2388 memcpy(buf + 4, rq->origauth, 16);
2390 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2393 if (rq->origusername) {
2394 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2396 pthread_mutex_unlock(&server->newrq_mutex);
2397 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2400 memcpy(username, rq->origusername, strlen(rq->origusername));
2401 len = RADLEN(buf) - 20;
2404 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2408 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2409 pthread_mutex_unlock(&server->newrq_mutex);
2410 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2413 debug(DBG_DBG, "replyh: computed messageauthattr");
2416 fromsa = rq->fromsa; /* only needed for UDP */
2417 /* once we set received = 1, rq may be reused */
2420 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2421 sendreply(from, buf, &fromsa, rq->fromudpsock);
2422 pthread_mutex_unlock(&server->newrq_mutex);
2426 void *udpclientrd(void *arg) {
2427 struct server *server;
2429 int *s = (int *)arg;
2433 buf = radudpget(*s, NULL, &server, NULL);
2434 if (!replyh(server, buf))
2439 void *tlsclientrd(void *arg) {
2440 struct server *server = (struct server *)arg;
2442 struct timeval now, lastconnecttry;
2445 /* yes, lastconnecttry is really necessary */
2446 lastconnecttry = server->lastconnecttry;
2447 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2449 if (server->dynamiclookuparg)
2451 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2455 if (!replyh(server, buf))
2457 if (server->dynamiclookuparg) {
2458 gettimeofday(&now, NULL);
2459 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2460 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2465 ERR_remove_state(0);
2466 server->clientrdgone = 1;
2470 /* code for removing state not finished */
2471 void *clientwr(void *arg) {
2472 struct server *server = (struct server *)arg;
2474 pthread_t clientrdth;
2475 int i, dynconffail = 0;
2478 struct timespec timeout;
2479 struct request statsrvrq;
2480 unsigned char statsrvbuf[38];
2481 struct clsrvconf *conf;
2483 conf = server->conf;
2485 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2490 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2491 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2495 memset(&timeout, 0, sizeof(struct timespec));
2497 if (conf->statusserver) {
2498 memset(&statsrvrq, 0, sizeof(struct request));
2499 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2500 statsrvbuf[0] = RAD_Status_Server;
2502 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2503 statsrvbuf[21] = 18;
2504 gettimeofday(&server->lastrcv, NULL);
2507 if (conf->pdef->connecter) {
2508 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2510 server->connectionok = 1;
2511 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2512 debug(DBG_ERR, "clientwr: pthread_create failed");
2516 server->connectionok = 1;
2519 pthread_mutex_lock(&server->newrq_mutex);
2520 if (!server->newrq) {
2521 gettimeofday(&now, NULL);
2522 /* random 0-7 seconds */
2523 RAND_bytes(&rnd, 1);
2525 if (conf->statusserver) {
2526 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2527 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2529 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2530 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2533 if (timeout.tv_sec > now.tv_sec)
2534 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2536 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2539 if (server->newrq) {
2540 debug(DBG_DBG, "clientwr: got new request");
2545 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2547 pthread_mutex_unlock(&server->newrq_mutex);
2549 for (i = 0; i < MAX_REQUESTS; i++) {
2550 if (server->clientrdgone) {
2551 pthread_join(clientrdth, NULL);
2554 pthread_mutex_lock(&server->newrq_mutex);
2555 while (i < MAX_REQUESTS && !server->requests[i].buf)
2557 if (i == MAX_REQUESTS) {
2558 pthread_mutex_unlock(&server->newrq_mutex);
2561 rq = server->requests + i;
2564 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2566 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2568 /* setting this to NULL means that it can be reused */
2571 pthread_mutex_unlock(&server->newrq_mutex);
2575 gettimeofday(&now, NULL);
2576 if (now.tv_sec < rq->expiry.tv_sec) {
2577 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2578 timeout.tv_sec = rq->expiry.tv_sec;
2579 pthread_mutex_unlock(&server->newrq_mutex);
2583 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2584 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2585 if (conf->statusserver) {
2586 if (*rq->buf == RAD_Status_Server) {
2587 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2588 if (server->lostrqs < 255)
2592 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2593 if (server->lostrqs < 255)
2597 /* setting this to NULL means that it can be reused */
2599 pthread_mutex_unlock(&server->newrq_mutex);
2602 pthread_mutex_unlock(&server->newrq_mutex);
2604 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2605 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2606 timeout.tv_sec = rq->expiry.tv_sec;
2608 conf->pdef->clientradput(server, server->requests[i].buf);
2610 if (conf->statusserver) {
2611 gettimeofday(&now, NULL);
2612 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2613 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2614 debug(DBG_WARN, "clientwr: failed to generate random auth");
2617 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2618 if (!statsrvrq.buf) {
2619 debug(DBG_ERR, "clientwr: malloc failed");
2622 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2623 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2624 sendrq(server, &statsrvrq);
2629 conf->servers = NULL;
2630 if (server->dynamiclookuparg) {
2631 removeserversubrealms(realms, conf);
2635 freeclsrvconf(conf);
2637 freeserver(server, 1);
2638 ERR_remove_state(0);
2642 void *udpserverwr(void *arg) {
2643 struct queue *replyq = udp_server_replyq;
2644 struct reply *reply;
2647 pthread_mutex_lock(&replyq->mutex);
2648 while (!(reply = (struct reply *)list_shift(replyq->entries))) {
2649 debug(DBG_DBG, "udp server writer, waiting for signal");
2650 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2651 debug(DBG_DBG, "udp server writer, got signal");
2653 pthread_mutex_unlock(&replyq->mutex);
2655 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2656 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2657 debug(DBG_WARN, "sendudp: send failed");
2663 void *udpserverrd(void *arg) {
2665 int *sp = (int *)arg;
2668 memset(&rq, 0, sizeof(struct request));
2669 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2670 rq.fromudpsock = *sp;
2676 void *tlsserverwr(void *arg) {
2678 unsigned long error;
2679 struct client *client = (struct client *)arg;
2680 struct queue *replyq;
2681 struct reply *reply;
2683 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2684 replyq = client->replyq;
2686 pthread_mutex_lock(&replyq->mutex);
2687 while (!list_first(replyq->entries)) {
2689 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2690 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2691 debug(DBG_DBG, "tlsserverwr: got signal");
2694 /* ssl might have changed while waiting */
2695 pthread_mutex_unlock(&replyq->mutex);
2696 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2697 ERR_remove_state(0);
2701 reply = (struct reply *)list_shift(replyq->entries);
2702 pthread_mutex_unlock(&replyq->mutex);
2703 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2705 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2706 cnt, RADLEN(reply->buf));
2708 while ((error = ERR_get_error()))
2709 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2715 void tlsserverrd(struct client *client) {
2717 pthread_t tlsserverwrth;
2719 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2721 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2722 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2727 memset(&rq, 0, sizeof(struct request));
2728 rq.buf = radtlsget(client->ssl, 0);
2730 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2733 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2736 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2741 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2743 pthread_mutex_lock(&client->replyq->mutex);
2744 pthread_cond_signal(&client->replyq->cond);
2745 pthread_mutex_unlock(&client->replyq->mutex);
2746 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2747 pthread_join(tlsserverwrth, NULL);
2748 removeclientrqs(client);
2749 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2752 void *tlsservernew(void *arg) {
2754 struct sockaddr_storage from;
2755 size_t fromlen = sizeof(from);
2756 struct clsrvconf *conf;
2757 struct list_node *cur = NULL;
2760 unsigned long error;
2761 struct client *client;
2764 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2765 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2768 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2770 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2772 ssl = SSL_new(conf->ssl_ctx);
2775 if (SSL_accept(ssl) <= 0) {
2776 while ((error = ERR_get_error()))
2777 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2778 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2781 cert = verifytlscert(ssl);
2787 if (verifyconfcert(cert, conf)) {
2789 client = addclient(conf);
2792 tlsserverrd(client);
2793 removeclient(client);
2795 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2798 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2800 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2806 ERR_remove_state(0);
2807 shutdown(s, SHUT_RDWR);
2812 void *tlslistener(void *arg) {
2813 pthread_t tlsserverth;
2814 int s, *sp = (int *)arg;
2815 struct sockaddr_storage from;
2816 size_t fromlen = sizeof(from);
2821 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2823 debug(DBG_WARN, "accept failed");
2826 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2827 debug(DBG_ERR, "tlslistener: pthread_create failed");
2828 shutdown(s, SHUT_RDWR);
2832 pthread_detach(tlsserverth);
2838 void createlistener(uint8_t type, char *arg) {
2840 struct clsrvconf *listenres;
2841 struct addrinfo *res;
2842 int s = -1, on = 1, *sp = NULL;
2844 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
2846 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2848 for (res = listenres->addrinfo; res; res = res->ai_next) {
2849 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2851 debug(DBG_WARN, "createlistener: socket failed");
2854 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2856 if (res->ai_family == AF_INET6)
2857 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2859 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2860 debug(DBG_WARN, "createlistener: bind failed");
2866 sp = malloc(sizeof(int));
2868 debugx(1, DBG_ERR, "malloc failed");
2870 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
2871 debugx(1, DBG_ERR, "pthread_create failed");
2875 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2877 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
2878 listenres->host ? listenres->host : "*", listenres->port);
2879 freeclsrvres(listenres);
2882 void createlisteners(uint8_t type, char **args) {
2886 for (i = 0; args[i]; i++)
2887 createlistener(type, args[i]);
2889 createlistener(type, NULL);
2893 void ssl_info_callback(const SSL *ssl, int where, int ret) {
2897 w = where & ~SSL_ST_MASK;
2899 if (w & SSL_ST_CONNECT)
2901 else if (w & SSL_ST_ACCEPT)
2906 if (where & SSL_CB_LOOP)
2907 debug(DBG_DBG, "%s:%s\n", s, SSL_state_string_long(ssl));
2908 else if (where & SSL_CB_ALERT) {
2909 s = (where & SSL_CB_READ) ? "read" : "write";
2910 debug(DBG_DBG, "SSL3 alert %s:%s:%s\n", s, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret));
2912 else if (where & SSL_CB_EXIT) {
2914 debug(DBG_DBG, "%s:failed in %s\n", s, SSL_state_string_long(ssl));
2916 debug(DBG_DBG, "%s:error in %s\n", s, SSL_state_string_long(ssl));
2921 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
2922 SSL_CTX *ctx = NULL;
2923 STACK_OF(X509_NAME) *calist;
2926 unsigned long error;
2929 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2930 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2931 for (i = 0; i < CRYPTO_num_locks(); i++) {
2932 ssl_lock_count[i] = 0;
2933 pthread_mutex_init(&ssl_locks[i], NULL);
2935 CRYPTO_set_id_callback(ssl_thread_id);
2936 CRYPTO_set_locking_callback(ssl_locking_callback);
2938 SSL_load_error_strings();
2941 while (!RAND_status()) {
2942 time_t t = time(NULL);
2943 pid_t pid = getpid();
2944 RAND_seed((unsigned char *)&t, sizeof(time_t));
2945 RAND_seed((unsigned char *)&pid, sizeof(pid));
2951 ctx = SSL_CTX_new(TLSv1_method());
2953 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2957 ctx = SSL_CTX_new(DTLSv1_method());
2959 SSL_CTX_set_info_callback(ctx, ssl_info_callback);
2961 SSL_CTX_set_read_ahead(ctx, 1);
2965 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2969 if (conf->certkeypwd) {
2970 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
2971 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2973 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
2974 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
2975 !SSL_CTX_check_private_key(ctx) ||
2976 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
2977 while ((error = ERR_get_error()))
2978 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2979 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
2984 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
2985 if (!conf->cacertfile || calist) {
2986 if (conf->cacertpath) {
2988 calist = sk_X509_NAME_new_null();
2989 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
2990 sk_X509_NAME_free(calist);
2996 while ((error = ERR_get_error()))
2997 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2998 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3002 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3003 SSL_CTX_set_client_CA_list(ctx, calist);
3005 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3006 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3008 if (conf->crlcheck) {
3009 x509_s = SSL_CTX_get_cert_store(ctx);
3010 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3013 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3017 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3018 struct list_node *entry;
3019 struct tls *t, *t1 = NULL, *t2 = NULL;
3020 SSL_CTX *ctx = NULL;
3022 pthread_mutex_lock(&tlsconfs_lock);
3024 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3025 t = (struct tls *)entry->data;
3026 if (!strcasecmp(t->name, alt1)) {
3030 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3041 t->tlsctx = tlscreatectx(RAD_TLS, t);
3046 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3052 pthread_mutex_unlock(&tlsconfs_lock);
3056 struct list *addsrvconfs(char *value, char **names) {
3057 struct list *conflist;
3059 struct list_node *entry;
3060 struct clsrvconf *conf = NULL;
3062 if (!names || !*names)
3065 conflist = list_create();
3067 debug(DBG_ERR, "malloc failed");
3071 for (n = 0; names[n]; n++) {
3072 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3073 conf = (struct clsrvconf *)entry->data;
3074 if (!strcasecmp(names[n], conf->name))
3078 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3079 list_destroy(conflist);
3082 if (!list_push(conflist, conf)) {
3083 debug(DBG_ERR, "malloc failed");
3084 list_destroy(conflist);
3087 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3092 void freerealm(struct realm *realm) {
3096 free(realm->message);
3097 regfree(&realm->regex);
3098 pthread_mutex_destroy(&realm->subrealms_mutex);
3099 if (realm->subrealms)
3100 list_destroy(realm->subrealms);
3101 if (realm->srvconfs) {
3102 /* emptying list without freeing data */
3103 while (list_shift(realm->srvconfs));
3104 list_destroy(realm->srvconfs);
3106 if (realm->accsrvconfs) {
3107 /* emptying list without freeing data */
3108 while (list_shift(realm->accsrvconfs));
3109 list_destroy(realm->accsrvconfs);
3114 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3116 struct realm *realm;
3117 char *s, *regex = NULL;
3119 if (*value == '/') {
3120 /* regexp, remove optional trailing / if present */
3121 if (value[strlen(value) - 1] == '/')
3122 value[strlen(value) - 1] = '\0';
3124 /* not a regexp, let us make it one */
3125 if (*value == '*' && !value[1])
3126 regex = stringcopy(".*", 0);
3128 for (n = 0, s = value; *s;)
3131 regex = malloc(strlen(value) + n + 3);
3134 for (n = 1, s = value; *s; s++) {
3144 debug(DBG_ERR, "malloc failed");
3148 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3151 realm = malloc(sizeof(struct realm));
3153 debug(DBG_ERR, "malloc failed");
3156 memset(realm, 0, sizeof(struct realm));
3158 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3159 debug(DBG_ERR, "mutex init failed");
3165 realm->name = stringcopy(value, 0);
3167 debug(DBG_ERR, "malloc failed");
3170 if (message && strlen(message) > 253) {
3171 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3174 realm->message = message;
3175 realm->accresp = accresp;
3177 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3178 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3182 if (servers && *servers) {
3183 realm->srvconfs = addsrvconfs(value, servers);
3184 if (!realm->srvconfs)
3188 if (accservers && *accservers) {
3189 realm->accsrvconfs = addsrvconfs(value, accservers);
3190 if (!realm->accsrvconfs)
3194 if (!list_push(realmlist, realm)) {
3195 debug(DBG_ERR, "malloc failed");
3196 pthread_mutex_destroy(&realm->subrealms_mutex);
3200 debug(DBG_DBG, "addrealm: added realm %s", value);
3210 for (n = 0; servers[n]; n++)
3215 for (n = 0; accservers[n]; n++)
3216 free(accservers[n]);
3222 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3223 struct clsrvconf *srvconf;
3224 struct realm *newrealm = NULL;
3225 char *realmname, *s;
3228 if (!conf->dynamiclookupcommand)
3231 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3232 realmname = strrchr(id, '@');
3238 for (s = realmname; *s; s++)
3239 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3242 pthread_mutex_lock(&realm->subrealms_mutex);
3243 /* exit if we now already got a matching subrealm */
3244 if (id2realm(realm->subrealms, id))
3246 srvconf = malloc(sizeof(struct clsrvconf));
3248 debug(DBG_ERR, "malloc failed");
3252 if (!addserver(srvconf))
3255 if (!realm->subrealms)
3256 realm->subrealms = list_create();
3257 if (!realm->subrealms)
3259 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3263 /* add server and accserver to newrealm */
3264 newrealm->srvconfs = list_create();
3265 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3266 debug(DBG_ERR, "malloc failed");
3269 newrealm->accsrvconfs = list_create();
3270 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3271 debug(DBG_ERR, "malloc failed");
3275 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3277 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3278 debug(DBG_ERR, "pthread_create failed");
3281 pthread_detach(clientth);
3286 list_removedata(realm->subrealms, newrealm);
3287 freerealm(newrealm);
3288 if (!list_first(realm->subrealms)) {
3289 list_destroy(realm->subrealms);
3290 realm->subrealms = NULL;
3293 freeserver(srvconf->servers, 1);
3295 debug(DBG_ERR, "failed to create dynamic server");
3298 pthread_mutex_unlock(&realm->subrealms_mutex);
3301 int dynamicconfig(struct server *server) {
3302 int ok, fd[2], status;
3304 struct clsrvconf *conf = server->conf;
3305 struct gconffile *cf = NULL;
3307 /* for now we only learn hostname/address */
3308 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3311 debug(DBG_ERR, "dynamicconfig: pipe error");
3316 debug(DBG_ERR, "dynamicconfig: fork error");
3320 } else if (pid == 0) {
3323 if (fd[1] != STDOUT_FILENO) {
3324 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3325 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3328 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3329 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3333 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3334 ok = getgenericconfig(&cf, NULL,
3335 "Server", CONF_CBK, confserver_cb, (void *)conf,
3340 if (waitpid(pid, &status, 0) < 0) {
3341 debug(DBG_ERR, "dynamicconfig: wait error");
3346 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3354 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3358 int addmatchcertattr(struct clsrvconf *conf) {
3362 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3363 r = &conf->certcnregex;
3364 v = conf->matchcertattr + 4;
3365 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3366 r = &conf->certuriregex;
3367 v = conf->matchcertattr + 20;
3372 /* regexp, remove optional trailing / if present */
3373 if (v[strlen(v) - 1] == '/')
3374 v[strlen(v) - 1] = '\0';
3378 *r = malloc(sizeof(regex_t));
3380 debug(DBG_ERR, "malloc failed");
3383 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3386 debug(DBG_ERR, "failed to compile regular expression %s", v);
3392 int addrewriteattr(struct clsrvconf *conf) {
3395 v = conf->rewriteattr + 11;
3396 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3398 /* regexp, remove optional trailing / if present */
3399 if (v[strlen(v) - 1] == '/')
3400 v[strlen(v) - 1] = '\0';
3408 conf->rewriteattrregex = malloc(sizeof(regex_t));
3409 if (!conf->rewriteattrregex) {
3410 debug(DBG_ERR, "malloc failed");
3414 conf->rewriteattrreplacement = stringcopy(w, 0);
3415 if (!conf->rewriteattrreplacement) {
3416 free(conf->rewriteattrregex);
3417 conf->rewriteattrregex = NULL;
3421 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3422 free(conf->rewriteattrregex);
3423 conf->rewriteattrregex = NULL;
3424 free(conf->rewriteattrreplacement);
3425 conf->rewriteattrreplacement = NULL;
3426 debug(DBG_ERR, "failed to compile regular expression %s", v);
3433 /* should accept both names and numeric values, only numeric right now */
3434 uint8_t attrname2val(char *attrname) {
3437 val = atoi(attrname);
3438 return val > 0 && val < 256 ? val : 0;
3441 /* should accept both names and numeric values, only numeric right now */
3442 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3445 *vendor = atoi(attrname);
3446 s = strchr(attrname, ':');
3451 *type = atoi(s + 1);
3452 return *type >= 0 && *type < 256;
3455 struct rewrite *getrewrite(char *alt1, char *alt2) {
3456 struct list_node *entry;
3457 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3459 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3460 r = (struct rewriteconf *)entry->data;
3461 if (!strcasecmp(r->name, alt1)) {
3465 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3475 void addrewrite(char *value, char **attrs, char **vattrs) {
3476 struct rewriteconf *new;
3477 struct rewrite *rewrite = NULL;
3480 uint32_t *p, *va = NULL;
3484 for (; attrs[n]; n++);
3485 a = malloc((n + 1) * sizeof(uint8_t));
3487 debugx(1, DBG_ERR, "malloc failed");
3489 for (i = 0; i < n; i++) {
3490 if (!(a[i] = attrname2val(attrs[i])))
3491 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3500 for (; vattrs[n]; n++);
3501 va = malloc((2 * n + 1) * sizeof(uint32_t));
3503 debugx(1, DBG_ERR, "malloc failed");
3505 for (p = va, i = 0; i < n; i++, p += 2) {
3506 if (!vattrname2val(vattrs[i], p, p + 1))
3507 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3515 rewrite = malloc(sizeof(struct rewrite));
3517 debugx(1, DBG_ERR, "malloc failed");
3518 rewrite->removeattrs = a;
3519 rewrite->removevendorattrs = va;
3522 new = malloc(sizeof(struct rewriteconf));
3523 if (!new || !list_push(rewriteconfs, new))
3524 debugx(1, DBG_ERR, "malloc failed");
3526 memset(new, 0, sizeof(struct rewriteconf));
3527 new->name = stringcopy(value, 0);
3529 debugx(1, DBG_ERR, "malloc failed");
3531 new->rewrite = rewrite;
3532 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3535 void freeclsrvconf(struct clsrvconf *conf) {
3541 free(conf->matchcertattr);
3542 if (conf->certcnregex)
3543 regfree(conf->certcnregex);
3544 if (conf->certuriregex)
3545 regfree(conf->certuriregex);
3546 free(conf->confrewrite);
3547 free(conf->rewriteattr);
3548 if (conf->rewriteattrregex)
3549 regfree(conf->rewriteattrregex);
3550 free(conf->rewriteattrreplacement);
3551 free(conf->dynamiclookupcommand);
3552 free(conf->rewrite);
3554 freeaddrinfo(conf->addrinfo);
3555 /* not touching ssl_ctx, clients and servers */
3559 int mergeconfstring(char **dst, char **src) {
3568 t = stringcopy(*dst, 0);
3570 debug(DBG_ERR, "malloc failed");
3578 /* assumes dst is a shallow copy */
3579 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3580 if (!mergeconfstring(&dst->name, &src->name) ||
3581 !mergeconfstring(&dst->host, &src->host) ||
3582 !mergeconfstring(&dst->port, &src->port) ||
3583 !mergeconfstring(&dst->secret, &src->secret) ||
3584 !mergeconfstring(&dst->tls, &src->tls) ||
3585 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3586 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3587 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3590 dst->pdef = src->pdef;
3591 dst->statusserver = src->statusserver;
3592 dst->certnamecheck = src->certnamecheck;
3593 if (src->retryinterval != 255)
3594 dst->retryinterval = src->retryinterval;
3595 if (src->retrycount != 255)
3596 dst->retrycount = src->retrycount;
3600 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3601 struct clsrvconf *conf;
3602 char *conftype = NULL;
3604 debug(DBG_DBG, "confclient_cb called for %s", block);
3606 conf = malloc(sizeof(struct clsrvconf));
3607 if (!conf || !list_push(clconfs, conf))
3608 debugx(1, DBG_ERR, "malloc failed");
3609 memset(conf, 0, sizeof(struct clsrvconf));
3610 conf->certnamecheck = 1;
3612 if (!getgenericconfig(cf, block,
3613 "type", CONF_STR, &conftype,
3614 "host", CONF_STR, &conf->host,
3615 "secret", CONF_STR, &conf->secret,
3616 "tls", CONF_STR, &conf->tls,
3617 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3618 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3619 "rewrite", CONF_STR, &conf->confrewrite,
3620 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3623 debugx(1, DBG_ERR, "configuration error");
3625 conf->name = stringcopy(val, 0);
3627 conf->host = stringcopy(val, 0);
3628 if (!conf->name || !conf->host)
3629 debugx(1, DBG_ERR, "malloc failed");
3632 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3633 conf->type = protoname2int(conftype);
3634 conf->pdef = &protodefs[conf->type];
3635 if (!conf->pdef->name)
3636 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3639 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3640 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3642 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3643 if (conf->matchcertattr && !addmatchcertattr(conf))
3644 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3647 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3649 if (conf->rewriteattr) {
3650 if (!addrewriteattr(conf))
3651 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3654 if (!resolvepeer(conf, 0))
3655 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3657 if (!conf->secret) {
3658 if (!conf->pdef->secretdefault)
3659 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3660 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3662 debugx(1, DBG_ERR, "malloc failed");
3667 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3668 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3669 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3670 if (!conf->ssl_ctx) {
3671 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3674 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3675 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3681 conf->port = stringcopy(conf->pdef->portdefault, 0);
3683 debug(DBG_ERR, "malloc failed");
3688 if (conf->retryinterval == 255)
3689 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3690 if (conf->retrycount == 255)
3691 conf->retrycount = protodefs[conf->type].retrycountdefault;
3693 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3695 if (!conf->secret) {
3696 if (!conf->pdef->secretdefault) {
3697 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3700 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3701 if (!conf->secret) {
3702 debug(DBG_ERR, "malloc failed");
3707 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3708 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3714 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3715 struct clsrvconf *conf, *resconf;
3716 char *conftype = NULL;
3717 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3719 debug(DBG_DBG, "confserver_cb called for %s", block);
3721 conf = malloc(sizeof(struct clsrvconf));
3723 debug(DBG_ERR, "malloc failed");
3726 memset(conf, 0, sizeof(struct clsrvconf));
3727 resconf = (struct clsrvconf *)arg;
3729 conf->statusserver = resconf->statusserver;
3730 conf->certnamecheck = resconf->certnamecheck;
3732 conf->certnamecheck = 1;
3734 if (!getgenericconfig(cf, block,
3735 "type", CONF_STR, &conftype,
3736 "host", CONF_STR, &conf->host,
3737 "port", CONF_STR, &conf->port,
3738 "secret", CONF_STR, &conf->secret,
3739 "tls", CONF_STR, &conf->tls,
3740 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3741 "rewrite", CONF_STR, &conf->confrewrite,
3742 "StatusServer", CONF_BLN, &conf->statusserver,
3743 "RetryInterval", CONF_LINT, &retryinterval,
3744 "RetryCount", CONF_LINT, &retrycount,
3745 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3746 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3749 debug(DBG_ERR, "configuration error");
3753 conf->name = stringcopy(val, 0);
3755 debug(DBG_ERR, "malloc failed");
3759 conf->host = stringcopy(val, 0);
3761 debug(DBG_ERR, "malloc failed");
3767 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3768 conf->type = protoname2int(conftype);
3769 conf->pdef = &protodefs[conf->type];
3770 if (!conf->pdef->name) {
3771 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3777 if (retryinterval != LONG_MIN) {
3778 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
3779 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
3782 conf->retryinterval = (uint8_t)retryinterval;
3784 conf->retryinterval = 255;
3786 if (retrycount != LONG_MIN) {
3787 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
3788 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
3791 conf->retrycount = (uint8_t)retrycount;
3793 conf->retrycount = 255;
3796 if (!mergesrvconf(resconf, conf))
3800 if (conf->dynamiclookupcommand) {
3801 free(conf->dynamiclookupcommand);
3802 conf->dynamiclookupcommand = NULL;
3806 if (resconf || !conf->dynamiclookupcommand) {
3807 if (!compileserverconfig(conf, block))
3814 if (!list_push(srvconfs, conf)) {
3815 debug(DBG_ERR, "malloc failed");
3821 freeclsrvconf(conf);
3825 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3826 char **servers = NULL, **accservers = NULL, *msg = NULL;
3827 uint8_t accresp = 0;
3829 debug(DBG_DBG, "confrealm_cb called for %s", block);
3831 if (!getgenericconfig(cf, block,
3832 "server", CONF_MSTR, &servers,
3833 "accountingServer", CONF_MSTR, &accservers,
3834 "ReplyMessage", CONF_STR, &msg,
3835 "AccountingResponse", CONF_BLN, &accresp,
3838 debugx(1, DBG_ERR, "configuration error");
3840 addrealm(realms, val, servers, accservers, msg, accresp);
3844 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3847 debug(DBG_DBG, "conftls_cb called for %s", block);
3849 conf = malloc(sizeof(struct tls));
3851 debug(DBG_ERR, "conftls_cb: malloc failed");
3854 memset(conf, 0, sizeof(struct tls));
3856 if (!getgenericconfig(cf, block,
3857 "CACertificateFile", CONF_STR, &conf->cacertfile,
3858 "CACertificatePath", CONF_STR, &conf->cacertpath,
3859 "CertificateFile", CONF_STR, &conf->certfile,
3860 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
3861 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
3862 "CRLCheck", CONF_BLN, &conf->crlcheck,
3865 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
3868 if (!conf->certfile || !conf->certkeyfile) {
3869 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
3872 if (!conf->cacertfile && !conf->cacertpath) {
3873 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
3877 conf->name = stringcopy(val, 0);
3879 debug(DBG_ERR, "conftls_cb: malloc failed");
3883 pthread_mutex_lock(&tlsconfs_lock);
3884 if (!list_push(tlsconfs, conf)) {
3885 debug(DBG_ERR, "conftls_cb: malloc failed");
3886 pthread_mutex_unlock(&tlsconfs_lock);
3889 pthread_mutex_unlock(&tlsconfs_lock);
3891 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
3895 free(conf->cacertfile);
3896 free(conf->cacertpath);
3897 free(conf->certfile);
3898 free(conf->certkeyfile);
3899 free(conf->certkeypwd);
3904 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3905 char **attrs = NULL, **vattrs = NULL;
3907 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3909 if (!getgenericconfig(cf, block,
3910 "removeAttribute", CONF_MSTR, &attrs,
3911 "removeVendorAttribute", CONF_MSTR, &vattrs,
3914 debugx(1, DBG_ERR, "configuration error");
3915 addrewrite(val, attrs, vattrs);
3919 void getmainconfig(const char *configfile) {
3920 long int loglevel = LONG_MIN;
3921 struct gconffile *cfs;
3923 cfs = openconfigfile(configfile);
3924 memset(&options, 0, sizeof(options));
3926 clconfs = list_create();
3928 debugx(1, DBG_ERR, "malloc failed");
3930 srvconfs = list_create();
3932 debugx(1, DBG_ERR, "malloc failed");
3934 realms = list_create();
3936 debugx(1, DBG_ERR, "malloc failed");
3938 tlsconfs = list_create();
3940 debugx(1, DBG_ERR, "malloc failed");
3942 rewriteconfs = list_create();
3944 debugx(1, DBG_ERR, "malloc failed");
3946 if (!getgenericconfig(&cfs, NULL,
3947 "ListenUDP", CONF_MSTR, &options.listenudp,
3948 "ListenTCP", CONF_MSTR, &options.listentcp,
3949 "ListenTLS", CONF_MSTR, &options.listentls,
3950 "ListenDTLS", CONF_MSTR, &options.listendtls,
3951 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3952 "SourceUDP", CONF_STR, &options.sourceudp,
3953 "SourceTCP", CONF_STR, &options.sourcetcp,
3954 "SourceTLS", CONF_STR, &options.sourcetls,
3955 "SourceDTLS", CONF_STR, &options.sourcedtls,
3956 "LogLevel", CONF_LINT, &loglevel,
3957 "LogDestination", CONF_STR, &options.logdestination,
3958 "LoopPrevention", CONF_BLN, &options.loopprevention,
3959 "Client", CONF_CBK, confclient_cb, NULL,
3960 "Server", CONF_CBK, confserver_cb, NULL,
3961 "Realm", CONF_CBK, confrealm_cb, NULL,
3962 "TLS", CONF_CBK, conftls_cb, NULL,
3963 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3966 debugx(1, DBG_ERR, "configuration error");
3968 if (loglevel != LONG_MIN) {
3969 if (loglevel < 1 || loglevel > 4)
3970 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3971 options.loglevel = (uint8_t)loglevel;
3975 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3978 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3981 *configfile = optarg;
3984 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3985 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3986 *loglevel = *optarg - '0';
3995 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4000 if (!(argc - optind))
4004 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4008 int daemon(int a, int b) {
4016 for (i = 0; i < 3; i++) {
4018 open("/dev/null", O_RDWR);
4024 void *sighandler(void *arg) {
4029 sigemptyset(&sigset);
4030 sigaddset(&sigset, SIGPIPE);
4031 sigwait(&sigset, &sig);
4032 /* only get SIGPIPE right now, so could simplify below code */
4035 /* completely ignoring this */
4038 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4041 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4046 int main(int argc, char **argv) {
4047 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth, dtlsclient4rdth, dtlsclient6rdth;
4049 struct list_node *entry;
4050 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4051 char *configfile = NULL;
4052 struct clsrvconf *srvconf;
4054 debug_init("radsecproxy");
4055 debug_set_level(DEBUG_LEVEL);
4056 pthread_mutex_init(&tlsconfs_lock, NULL);
4058 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4060 debug_set_level(loglevel);
4061 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4063 options.loglevel = loglevel;
4064 else if (options.loglevel)
4065 debug_set_level(options.loglevel);
4067 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4068 free(options.logdestination);
4070 if (!list_first(clconfs))
4071 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4072 if (!list_first(realms))
4073 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4076 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4078 if (!foreground && (daemon(0, 0) < 0))
4079 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4081 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4083 sigemptyset(&sigset);
4084 /* exit on all but SIGPIPE, ignore more? */
4085 sigaddset(&sigset, SIGPIPE);
4086 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4087 pthread_create(&sigth, NULL, sighandler, NULL);
4089 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4090 srvconf = (struct clsrvconf *)entry->data;
4091 if (srvconf->dynamiclookupcommand)
4093 if (!addserver(srvconf))
4094 debugx(1, DBG_ERR, "failed to add server");
4095 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4096 (void *)(srvconf->servers)))
4097 debugx(1, DBG_ERR, "pthread_create failed");
4099 /* srcprotores for UDP no longer needed */
4100 if (srcprotores[RAD_UDP]) {
4101 freeaddrinfo(srcprotores[RAD_UDP]);
4102 srcprotores[RAD_UDP] = NULL;
4105 if (udp_client4_sock >= 0)
4106 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4107 debugx(1, DBG_ERR, "pthread_create failed");
4108 if (udp_client6_sock >= 0)
4109 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4110 debugx(1, DBG_ERR, "pthread_create failed");
4112 if (dtls_client4_sock >= 0)
4113 if (pthread_create(&dtlsclient4rdth, NULL, udpdtlsclientrd, (void *)&dtls_client4_sock))
4114 debugx(1, DBG_ERR, "pthread_create failed");
4115 if (dtls_client6_sock >= 0)
4116 if (pthread_create(&dtlsclient6rdth, NULL, udpdtlsclientrd, (void *)&dtls_client6_sock))
4117 debugx(1, DBG_ERR, "pthread_create failed");
4119 if (find_conf_type(RAD_TCP, clconfs, NULL))
4120 createlisteners(RAD_TCP, options.listentcp);
4122 if (find_conf_type(RAD_TLS, clconfs, NULL))
4123 createlisteners(RAD_TLS, options.listentls);
4125 if (find_conf_type(RAD_DTLS, clconfs, NULL))
4126 createlisteners(RAD_DTLS, options.listendtls);
4128 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4129 udp_server_replyq = newqueue();
4130 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4131 debugx(1, DBG_ERR, "pthread_create failed");
4132 createlisteners(RAD_UDP, options.listenudp);
4133 if (options.listenaccudp)
4134 createlisteners(RAD_UDP, options.listenaccudp);
4137 /* just hang around doing nothing, anything to do here? */