2 * Copyright (C) 2006-2008 Stig Venaas <venaas@uninett.no>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
9 /* For UDP there is one server instance consisting of udpserverrd and udpserverth
10 * rd is responsible for init and launching wr
11 * For TLS there is a server instance that launches tlsserverrd for each TLS peer
12 * each tlsserverrd launches tlsserverwr
13 * For each UDP/TLS peer there is clientrd and clientwr, clientwr is responsible
14 * for init and launching rd
16 * serverrd will receive a request, processes it and puts it in the requestq of
17 * the appropriate clientwr
18 * clientwr monitors its requestq and sends requests
19 * clientrd looks for responses, processes them and puts them in the replyq of
20 * the peer the request came from
21 * serverwr monitors its reply and sends replies
23 * In addition to the main thread, we have:
24 * If UDP peers are configured, there will be 2 + 2 * #peers UDP threads
25 * If TLS peers are configured, there will initially be 2 * #peers TLS threads
26 * For each TLS peer connecting to us there will be 2 more TLS threads
27 * This is only for connected peers
28 * Example: With 3 UDP peer and 30 TLS peers, there will be a max of
29 * 1 + (2 + 2 * 3) + (2 * 30) + (2 * 30) = 129 threads
33 * TCP accounting not yet supported
34 * We are not removing client requests from dynamic servers, see removeclientrqs()
38 #include <sys/socket.h>
39 #include <netinet/in.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
52 #include <arpa/inet.h>
56 #include <openssl/ssl.h>
57 #include <openssl/rand.h>
58 #include <openssl/err.h>
59 #include <openssl/md5.h>
60 #include <openssl/hmac.h>
61 #include <openssl/x509v3.h>
66 #include "radsecproxy.h"
68 static struct options options;
69 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
71 static struct addrinfo *srcprotores[3] = { NULL, NULL, NULL };
73 static struct replyq *udp_server_replyq = NULL;
74 static int udp_client4_sock = -1;
75 static int udp_client6_sock = -1;
76 static pthread_mutex_t tlsconfs_lock;
77 static pthread_mutex_t *ssl_locks = NULL;
78 static long *ssl_lock_count;
82 /* minimum required declarations to avoid reordering code */
83 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
84 int dynamicconfig(struct server *server);
85 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
86 void freerealm(struct realm *realm);
87 void freeclsrvconf(struct clsrvconf *conf);
88 void freerqdata(struct request *rq);
89 void *udpserverrd(void *arg);
90 void *tlslistener(void *arg);
91 void *tcplistener(void *arg);
92 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text);
93 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
94 void *udpclientrd(void *arg);
95 void *tlsclientrd(void *arg);
96 void *tcpclientrd(void *arg);
97 int clientradputudp(struct server *server, unsigned char *rad);
98 int clientradputtls(struct server *server, unsigned char *rad);
99 int clientradputtcp(struct server *server, unsigned char *rad);
101 static const struct protodefs protodefs[] = {
102 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
103 NULL, /* secretdefault */
104 SOCK_DGRAM, /* socktype */
105 "1812", /* portdefault */
106 REQUEST_RETRY_COUNT, /* retrycountdefault */
107 10, /* retrycountmax */
108 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
109 60, /* retryintervalmax */
110 udpserverrd, /* listener */
111 &options.sourceudp, /* srcaddrport */
112 NULL, /* connecter */
113 udpclientrd, /* clientreader */
114 clientradputudp /* clientradput */
116 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
117 "mysecret", /* secretdefault */
118 SOCK_STREAM, /* socktype */
119 "2083", /* portdefault */
120 0, /* retrycountdefault */
121 0, /* retrycountmax */
122 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
123 60, /* retryintervalmax */
124 tlslistener, /* listener */
125 &options.sourcetls, /* srcaddrport */
126 tlsconnect, /* connecter */
127 tlsclientrd, /* clientreader */
128 clientradputtls /* clientradput */
130 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
131 NULL, /* secretdefault */
132 SOCK_STREAM, /* socktype */
133 "1812", /* portdefault */
134 0, /* retrycountdefault */
135 0, /* retrycountmax */
136 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
137 60, /* retryintervalmax */
138 tcplistener, /* listener */
139 &options.sourcetcp, /* srcaddrport */
140 tcpconnect, /* connecter */
141 tcpclientrd, /* clientreader */
142 clientradputtcp /* clientradput */
144 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
145 NULL, /* secretdefault */
146 SOCK_DGRAM, /* socktype */
147 "1812", /* portdefault */
148 REQUEST_RETRY_COUNT, /* retrycountdefault */
149 10, /* retrycountmax */
150 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
151 60, /* retryintervalmax */
152 udpserverrd, /* listener */
153 &options.sourceudp, /* srcaddrport */
154 tlsconnect, /* connecter */
155 udpclientrd, /* clientreader */
156 clientradputudp /* clientradput */
162 uint8_t protoname2int(const char *name) {
165 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
169 /* callbacks for making OpenSSL thread safe */
170 unsigned long ssl_thread_id() {
171 return (unsigned long)pthread_self();
174 void ssl_locking_callback(int mode, int type, const char *file, int line) {
175 if (mode & CRYPTO_LOCK) {
176 pthread_mutex_lock(&ssl_locks[type]);
177 ssl_lock_count[type]++;
179 pthread_mutex_unlock(&ssl_locks[type]);
182 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
183 int pwdlen = strlen(userdata);
184 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
186 memcpy(buf, userdata, pwdlen);
190 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
195 err_cert = X509_STORE_CTX_get_current_cert(ctx);
196 err = X509_STORE_CTX_get_error(ctx);
197 depth = X509_STORE_CTX_get_error_depth(ctx);
199 if (depth > MAX_CERT_DEPTH) {
201 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
202 X509_STORE_CTX_set_error(ctx, err);
206 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
207 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
210 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
211 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
212 debug(DBG_WARN, "\tIssuer=%s", buf);
214 case X509_V_ERR_CERT_NOT_YET_VALID:
215 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
216 debug(DBG_WARN, "\tCertificate not yet valid");
218 case X509_V_ERR_CERT_HAS_EXPIRED:
219 debug(DBG_WARN, "Certificate has expired");
221 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
222 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
227 printf("certificate verify returns %d\n", ok);
232 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
233 struct addrinfo hints, *addrinfo, *res;
237 slash = conf->host ? strchr(conf->host, '/') : NULL;
241 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
245 if (*s < '0' || *s > '9') {
246 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
249 plen = atoi(slash + 1);
250 if (plen < 0 || plen > 128) {
251 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
256 memset(&hints, 0, sizeof(hints));
257 hints.ai_socktype = conf->pdef->socktype;
258 hints.ai_family = AF_UNSPEC;
259 hints.ai_flags = ai_flags;
260 if (!conf->host && !conf->port) {
261 /* getaddrinfo() doesn't like host and port to be NULL */
262 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
263 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
266 for (res = addrinfo; res; res = res->ai_next) {
267 switch (res->ai_family) {
269 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
272 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
278 hints.ai_flags |= AI_NUMERICHOST;
279 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
280 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
285 switch (addrinfo->ai_family) {
288 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
289 freeaddrinfo(addrinfo);
296 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
297 freeaddrinfo(addrinfo);
300 conf->prefixlen = plen;
302 conf->prefixlen = 255;
305 freeaddrinfo(conf->addrinfo);
306 conf->addrinfo = addrinfo;
310 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
312 struct addrinfo *res;
314 for (res = addrinfo; res; res = res->ai_next) {
315 if (family != AF_UNSPEC && family != res->ai_family)
317 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
319 debug(DBG_WARN, "bindtoaddr: socket failed");
323 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
326 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
329 if (!bind(s, res->ai_addr, res->ai_addrlen))
331 debug(DBG_WARN, "bindtoaddr: bind failed");
337 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
342 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
346 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
348 debugx(1, DBG_ERR, "no ] matching initial [");
352 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
355 debugx(1, DBG_ERR, "missing host/address");
357 conf->host = stringcopy(field, p - field);
360 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
361 debugx(1, DBG_ERR, "unexpected character after ]");
364 /* port number or service name is specified */;
366 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
368 debugx(1, DBG_ERR, "syntax error, : but no following port");
369 conf->port = stringcopy(field, p - field);
371 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
375 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
376 struct clsrvconf *conf;
378 conf = malloc(sizeof(struct clsrvconf));
380 debugx(1, DBG_ERR, "malloc failed");
381 memset(conf, 0, sizeof(struct clsrvconf));
383 conf->pdef = &protodefs[conf->type];
385 parsehostport(lconf, conf, default_port);
386 if (!strcmp(conf->host, "*")) {
391 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
392 if (!resolvepeer(conf, AI_PASSIVE))
393 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
397 void freeclsrvres(struct clsrvconf *res) {
401 freeaddrinfo(res->addrinfo);
405 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
407 struct addrinfo *res;
410 for (res = addrinfo; res; res = res->ai_next) {
411 s = bindtoaddr(src, res->ai_family, 1, 1);
413 debug(DBG_WARN, "connecttoserver: socket failed");
416 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
418 debug(DBG_WARN, "connecttoserver: connect failed");
425 /* returns 1 if the len first bits are equal, else 0 */
426 int prefixmatch(void *a1, void *a2, uint8_t len) {
427 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
429 if (l && memcmp(a1, a2, l))
434 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
437 /* check if conf has matching address */
438 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
439 struct sockaddr_in6 *sa6 = NULL;
440 struct in_addr *a4 = NULL;
441 struct addrinfo *res;
443 if (addr->sa_family == AF_INET6) {
444 sa6 = (struct sockaddr_in6 *)addr;
445 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
446 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
450 a4 = &((struct sockaddr_in *)addr)->sin_addr;
452 if (conf->type == type) {
453 if (conf->prefixlen == 255) {
454 for (res = conf->addrinfo; res; res = res->ai_next)
455 if ((a4 && res->ai_family == AF_INET &&
456 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
457 (sa6 && res->ai_family == AF_INET6 &&
458 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
461 res = conf->addrinfo;
463 ((a4 && res->ai_family == AF_INET &&
464 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
465 (sa6 && res->ai_family == AF_INET6 &&
466 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
473 /* returns next config with matching address, or NULL */
474 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
475 struct sockaddr_in6 *sa6 = NULL;
476 struct in_addr *a4 = NULL;
477 struct addrinfo *res;
478 struct list_node *entry;
479 struct clsrvconf *conf;
481 if (addr->sa_family == AF_INET6) {
482 sa6 = (struct sockaddr_in6 *)addr;
483 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
484 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
488 a4 = &((struct sockaddr_in *)addr)->sin_addr;
490 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
491 conf = (struct clsrvconf *)entry->data;
492 if (conf->type == type) {
493 if (conf->prefixlen == 255) {
494 for (res = conf->addrinfo; res; res = res->ai_next)
495 if ((a4 && res->ai_family == AF_INET &&
496 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
497 (sa6 && res->ai_family == AF_INET6 &&
498 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
504 res = conf->addrinfo;
506 ((a4 && res->ai_family == AF_INET &&
507 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
508 (sa6 && res->ai_family == AF_INET6 &&
509 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
520 /* returns next config of given type, or NULL */
521 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
522 struct list_node *entry;
523 struct clsrvconf *conf;
525 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
526 conf = (struct clsrvconf *)entry->data;
527 if (conf->type == type) {
536 struct replyq *newreplyq() {
537 struct replyq *replyq;
539 replyq = malloc(sizeof(struct replyq));
541 debugx(1, DBG_ERR, "malloc failed");
542 replyq->replies = list_create();
543 if (!replyq->replies)
544 debugx(1, DBG_ERR, "malloc failed");
545 pthread_mutex_init(&replyq->mutex, NULL);
546 pthread_cond_init(&replyq->cond, NULL);
550 struct client *addclient(struct clsrvconf *conf) {
551 struct client *new = malloc(sizeof(struct client));
554 debug(DBG_ERR, "malloc failed");
557 if (!conf->clients) {
558 conf->clients = list_create();
559 if (!conf->clients) {
560 debug(DBG_ERR, "malloc failed");
565 memset(new, 0, sizeof(struct client));
567 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
569 list_push(conf->clients, new);
573 void removeclient(struct client *client) {
574 struct list_node *entry;
576 if (!client || !client->conf->clients)
579 pthread_mutex_lock(&client->replyq->mutex);
580 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
581 free(((struct reply *)entry)->buf);
582 list_destroy(client->replyq->replies);
583 pthread_cond_destroy(&client->replyq->cond);
584 pthread_mutex_unlock(&client->replyq->mutex);
585 pthread_mutex_destroy(&client->replyq->mutex);
586 list_removedata(client->conf->clients, client);
590 void removeclientrqs(struct client *client) {
591 struct list_node *entry;
592 struct server *server;
596 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
597 server = ((struct clsrvconf *)entry->data)->servers;
600 pthread_mutex_lock(&server->newrq_mutex);
601 for (i = 0; i < MAX_REQUESTS; i++) {
602 rq = server->requests + i;
603 if (rq->from == client)
606 pthread_mutex_unlock(&server->newrq_mutex);
610 void freeserver(struct server *server, uint8_t destroymutex) {
611 struct request *rq, *end;
616 if(server->requests) {
617 rq = server->requests;
618 for (end = rq + MAX_REQUESTS; rq < end; rq++)
620 free(server->requests);
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)
651 if (!srcprotores[type]) {
652 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
653 srcprotores[type] = res->addrinfo;
654 res->addrinfo = NULL;
658 if (type == RAD_UDP) {
659 switch (conf->addrinfo->ai_family) {
661 if (udp_client4_sock < 0) {
662 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
663 if (udp_client4_sock < 0)
664 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
666 conf->servers->sock = udp_client4_sock;
669 if (udp_client6_sock < 0) {
670 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
671 if (udp_client6_sock < 0)
672 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
674 conf->servers->sock = udp_client6_sock;
677 debugx(1, DBG_ERR, "addserver: unsupported address family");
681 conf->servers->sock = -1;
683 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
684 if (!conf->servers->requests) {
685 debug(DBG_ERR, "malloc failed");
688 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
689 debug(DBG_ERR, "mutex init failed");
692 conf->servers->newrq = 0;
693 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
694 debug(DBG_ERR, "mutex init failed");
695 pthread_mutex_destroy(&conf->servers->lock);
698 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
699 debug(DBG_ERR, "mutex init failed");
700 pthread_mutex_destroy(&conf->servers->newrq_mutex);
701 pthread_mutex_destroy(&conf->servers->lock);
708 freeserver(conf->servers, 0);
709 conf->servers = NULL;
713 /* exactly one of client and server must be non-NULL */
714 /* should probably take peer list (client(s) or server(s)) as argument instead */
715 /* if *peer == NULL we return who we received from, else require it to be from peer */
716 /* return from in sa if not NULL */
717 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
719 unsigned char buf[4], *rad;
720 struct sockaddr_storage from;
721 socklen_t fromlen = sizeof(from);
723 struct list_node *node;
729 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
731 cnt = recvfrom(s, buf, 4, MSG_PEEK, (struct sockaddr *)&from, &fromlen);
733 debug(DBG_WARN, "radudpget: recv failed");
739 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
741 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
744 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
746 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
749 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
756 debug(DBG_WARN, "radudpget: length too small");
763 debug(DBG_ERR, "radudpget: malloc failed");
768 cnt = recv(s, rad, len, MSG_TRUNC);
769 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
772 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
778 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
780 if (client && !*client) {
781 node = list_first(p->clients);
782 *client = node ? (struct client *)node->data : addclient(p);
787 } else if (server && !*server)
788 *server = p->servers;
797 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
798 int loc, i, l, n, r = 0;
801 STACK_OF(GENERAL_NAME) *alt;
804 debug(DBG_DBG, "subjectaltnameaddr");
806 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
810 ex = X509_get_ext(cert, loc);
811 alt = X509V3_EXT_d2i(ex);
815 n = sk_GENERAL_NAME_num(alt);
816 for (i = 0; i < n; i++) {
817 gn = sk_GENERAL_NAME_value(alt, i);
818 if (gn->type != GEN_IPADD)
821 v = (char *)ASN1_STRING_data(gn->d.ia5);
822 l = ASN1_STRING_length(gn->d.ia5);
823 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
824 && !memcmp(v, &addr, l)) {
829 GENERAL_NAMES_free(alt);
833 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
840 nm = X509_get_subject_name(cert);
843 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
846 e = X509_NAME_get_entry(nm, loc);
847 t = X509_NAME_ENTRY_get_data(e);
848 v = (char *) ASN1_STRING_data(t);
849 l = ASN1_STRING_length(t);
853 if (l == strlen(exact) && !strncasecmp(exact, v, l))
856 s = stringcopy((char *)v, l);
858 debug(DBG_ERR, "malloc failed");
861 if (regexec(regex, s, 0, NULL, 0)) {
872 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
873 int loc, i, l, n, r = 0;
876 STACK_OF(GENERAL_NAME) *alt;
879 debug(DBG_DBG, "subjectaltnameregexp");
881 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
885 ex = X509_get_ext(cert, loc);
886 alt = X509V3_EXT_d2i(ex);
890 n = sk_GENERAL_NAME_num(alt);
891 for (i = 0; i < n; i++) {
892 gn = sk_GENERAL_NAME_value(alt, i);
893 if (gn->type != type)
896 v = (char *)ASN1_STRING_data(gn->d.ia5);
897 l = ASN1_STRING_length(gn->d.ia5);
901 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
904 if (memcmp(v, exact, l))
907 s = stringcopy((char *)v, l);
909 debug(DBG_ERR, "malloc failed");
912 if (regexec(regex, s, 0, NULL, 0)) {
921 GENERAL_NAMES_free(alt);
925 X509 *verifytlscert(SSL *ssl) {
929 if (SSL_get_verify_result(ssl) != X509_V_OK) {
930 debug(DBG_ERR, "verifytlscert: basic validation failed");
931 while ((error = ERR_get_error()))
932 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
936 cert = SSL_get_peer_certificate(ssl);
938 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
942 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
944 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
945 struct in6_addr addr;
947 if (conf->certnamecheck && conf->prefixlen == 255) {
948 if (inet_pton(AF_INET, conf->host, &addr))
950 else if (inet_pton(AF_INET6, conf->host, &addr))
953 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
956 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
959 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
961 if (!cnregexp(cert, conf->host, NULL)) {
962 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
965 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
968 if (conf->certcnregex) {
969 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
970 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
973 debug(DBG_DBG, "verifyconfcert: CN matching regex");
975 if (conf->certuriregex) {
976 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
977 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
980 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
985 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
990 debug(DBG_DBG, "tlsconnect: called from %s", text);
991 pthread_mutex_lock(&server->lock);
992 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
993 /* already reconnected, nothing to do */
994 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
995 pthread_mutex_unlock(&server->lock);
1000 gettimeofday(&now, NULL);
1001 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1002 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1003 debug(DBG_DBG, "tlsconnect: timeout");
1004 if (server->sock >= 0)
1005 close(server->sock);
1006 SSL_free(server->ssl);
1008 pthread_mutex_unlock(&server->lock);
1011 if (server->connectionok) {
1012 server->connectionok = 0;
1014 } else if (elapsed < 1)
1016 else if (elapsed < 60) {
1017 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1019 } else if (elapsed < 100000) {
1020 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1023 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1024 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1025 if (server->sock >= 0)
1026 close(server->sock);
1027 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1028 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1032 SSL_free(server->ssl);
1033 server->ssl = SSL_new(server->conf->ssl_ctx);
1034 SSL_set_fd(server->ssl, server->sock);
1035 if (SSL_connect(server->ssl) <= 0)
1037 cert = verifytlscert(server->ssl);
1040 if (verifyconfcert(cert, server->conf)) {
1046 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1047 gettimeofday(&server->lastconnecttry, NULL);
1048 pthread_mutex_unlock(&server->lock);
1052 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1056 debug(DBG_DBG, "tcpconnect: called from %s", text);
1057 pthread_mutex_lock(&server->lock);
1058 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1059 /* already reconnected, nothing to do */
1060 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1061 pthread_mutex_unlock(&server->lock);
1066 gettimeofday(&now, NULL);
1067 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1068 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1069 debug(DBG_DBG, "tcpconnect: timeout");
1070 if (server->sock >= 0)
1071 close(server->sock);
1072 pthread_mutex_unlock(&server->lock);
1075 if (server->connectionok) {
1076 server->connectionok = 0;
1078 } else if (elapsed < 1)
1080 else if (elapsed < 60) {
1081 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1083 } else if (elapsed < 100000) {
1084 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1087 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1088 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1089 if (server->sock >= 0)
1090 close(server->sock);
1091 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1093 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1095 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1096 gettimeofday(&server->lastconnecttry, NULL);
1097 pthread_mutex_unlock(&server->lock);
1101 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1102 /* returns 0 on timeout, -1 on error and num if ok */
1103 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1104 int s, ndesc, cnt, len;
1105 fd_set readfds, writefds;
1106 struct timeval timer;
1108 s = SSL_get_fd(ssl);
1111 /* make socket non-blocking? */
1112 for (len = 0; len < num; len += cnt) {
1114 FD_SET(s, &readfds);
1117 timer.tv_sec = timeout;
1120 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1124 cnt = SSL_read(ssl, buf + len, num - len);
1126 switch (SSL_get_error(ssl, cnt)) {
1127 case SSL_ERROR_WANT_READ:
1128 case SSL_ERROR_WANT_WRITE:
1131 case SSL_ERROR_ZERO_RETURN:
1132 /* remote end sent close_notify, send one back */
1142 /* timeout in seconds, 0 means no timeout (blocking) */
1143 unsigned char *radtlsget(SSL *ssl, int timeout) {
1145 unsigned char buf[4], *rad;
1148 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1150 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1157 debug(DBG_ERR, "radtlsget: malloc failed");
1160 memcpy(rad, buf, 4);
1162 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1164 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1173 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1176 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1180 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1181 /* returns 0 on timeout, -1 on error and num if ok */
1182 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1183 int ndesc, cnt, len;
1184 fd_set readfds, writefds;
1185 struct timeval timer;
1189 /* make socket non-blocking? */
1190 for (len = 0; len < num; len += cnt) {
1192 FD_SET(s, &readfds);
1195 timer.tv_sec = timeout;
1198 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1202 cnt = read(s, buf + len, num - len);
1209 /* timeout in seconds, 0 means no timeout (blocking) */
1210 unsigned char *radtcpget(int s, int timeout) {
1212 unsigned char buf[4], *rad;
1215 cnt = tcpreadtimeout(s, buf, 4, timeout);
1217 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1224 debug(DBG_ERR, "radtcpget: malloc failed");
1227 memcpy(rad, buf, 4);
1229 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1231 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1240 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1243 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1247 int clientradputudp(struct server *server, unsigned char *rad) {
1249 struct sockaddr_storage sa;
1250 struct sockaddr *sap;
1251 struct clsrvconf *conf = server->conf;
1252 in_port_t *port = NULL;
1256 if (*rad == RAD_Accounting_Request) {
1257 sap = (struct sockaddr *)&sa;
1258 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1260 sap = conf->addrinfo->ai_addr;
1262 switch (sap->sa_family) {
1264 port = &((struct sockaddr_in *)sap)->sin_port;
1267 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1273 if (*rad == RAD_Accounting_Request)
1274 *port = htons(ntohs(*port) + 1);
1276 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1277 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1281 debug(DBG_WARN, "clientradputudp: send failed");
1285 int clientradputtls(struct server *server, unsigned char *rad) {
1288 unsigned long error;
1289 struct timeval lastconnecttry;
1290 struct clsrvconf *conf = server->conf;
1293 lastconnecttry = server->lastconnecttry;
1294 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1295 while ((error = ERR_get_error()))
1296 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1297 if (server->dynamiclookuparg)
1299 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1300 lastconnecttry = server->lastconnecttry;
1303 server->connectionok = 1;
1304 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1308 int clientradputtcp(struct server *server, unsigned char *rad) {
1311 struct timeval lastconnecttry;
1312 struct clsrvconf *conf = server->conf;
1315 lastconnecttry = server->lastconnecttry;
1316 while ((cnt = write(server->sock, rad, len)) <= 0) {
1317 debug(DBG_ERR, "clientradputtcp: write error");
1318 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1319 lastconnecttry = server->lastconnecttry;
1322 server->connectionok = 1;
1323 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1327 int radsign(unsigned char *rad, unsigned char *sec) {
1328 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1329 static unsigned char first = 1;
1330 static EVP_MD_CTX mdctx;
1331 unsigned int md_len;
1334 pthread_mutex_lock(&lock);
1336 EVP_MD_CTX_init(&mdctx);
1340 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1341 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1342 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1343 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1345 pthread_mutex_unlock(&lock);
1349 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1350 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1351 static unsigned char first = 1;
1352 static EVP_MD_CTX mdctx;
1353 unsigned char hash[EVP_MAX_MD_SIZE];
1357 pthread_mutex_lock(&lock);
1359 EVP_MD_CTX_init(&mdctx);
1365 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1366 EVP_DigestUpdate(&mdctx, rad, 4) &&
1367 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1368 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1369 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1370 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1372 !memcmp(hash, rad + 4, 16));
1373 pthread_mutex_unlock(&lock);
1377 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1378 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1379 static unsigned char first = 1;
1380 static HMAC_CTX hmacctx;
1381 unsigned int md_len;
1382 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1384 pthread_mutex_lock(&lock);
1386 HMAC_CTX_init(&hmacctx);
1390 memcpy(auth, authattr, 16);
1391 memset(authattr, 0, 16);
1393 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1394 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1395 HMAC_Final(&hmacctx, hash, &md_len);
1396 memcpy(authattr, auth, 16);
1398 debug(DBG_WARN, "message auth computation failed");
1399 pthread_mutex_unlock(&lock);
1403 if (memcmp(auth, hash, 16)) {
1404 debug(DBG_WARN, "message authenticator, wrong value");
1405 pthread_mutex_unlock(&lock);
1409 pthread_mutex_unlock(&lock);
1413 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1414 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1415 static unsigned char first = 1;
1416 static HMAC_CTX hmacctx;
1417 unsigned int md_len;
1422 pthread_mutex_lock(&lock);
1424 HMAC_CTX_init(&hmacctx);
1428 memset(authattrval, 0, 16);
1430 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1431 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1432 HMAC_Final(&hmacctx, authattrval, &md_len);
1434 debug(DBG_WARN, "message auth computation failed");
1435 pthread_mutex_unlock(&lock);
1439 pthread_mutex_unlock(&lock);
1443 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1444 while (length > 1) {
1445 if (ATTRTYPE(attrs) == type)
1447 length -= ATTRLEN(attrs);
1448 attrs += ATTRLEN(attrs);
1453 void freerqdata(struct request *rq) {
1454 if (rq->origusername)
1455 free(rq->origusername);
1460 void sendrq(struct server *to, struct request *rq) {
1464 pthread_mutex_lock(&to->newrq_mutex);
1465 /* might simplify if only try nextid, might be ok */
1466 for (i = to->nextid; i < MAX_REQUESTS; i++)
1467 if (!to->requests[i].buf)
1469 if (i == MAX_REQUESTS) {
1470 for (i = 0; i < to->nextid; i++)
1471 if (!to->requests[i].buf)
1473 if (i == to->nextid) {
1474 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1480 rq->buf[1] = (char)i;
1482 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1483 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1488 if (*rq->buf == RAD_Accounting_Request) {
1489 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1490 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1496 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1497 to->requests[i] = *rq;
1502 debug(DBG_DBG, "sendrq: signalling client writer");
1503 pthread_cond_signal(&to->newrq_cond);
1506 pthread_mutex_unlock(&to->newrq_mutex);
1509 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1510 struct reply *reply;
1513 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1515 debug(DBG_WARN, "sendreply: failed to sign message");
1519 reply = malloc(sizeof(struct reply));
1522 debug(DBG_ERR, "sendreply: malloc failed");
1525 memset(reply, 0, sizeof(struct reply));
1528 reply->tosa = *tosa;
1529 reply->toudpsock = toudpsock;
1531 pthread_mutex_lock(&to->replyq->mutex);
1533 first = list_first(to->replyq->replies) == NULL;
1535 if (!list_push(to->replyq->replies, reply)) {
1536 pthread_mutex_unlock(&to->replyq->mutex);
1539 debug(DBG_ERR, "sendreply: malloc failed");
1544 debug(DBG_DBG, "signalling server writer");
1545 pthread_cond_signal(&to->replyq->cond);
1547 pthread_mutex_unlock(&to->replyq->mutex);
1550 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1551 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1552 static unsigned char first = 1;
1553 static EVP_MD_CTX mdctx;
1554 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1555 unsigned int md_len;
1556 uint8_t i, offset = 0, out[128];
1558 pthread_mutex_lock(&lock);
1560 EVP_MD_CTX_init(&mdctx);
1566 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1567 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1568 !EVP_DigestUpdate(&mdctx, input, 16) ||
1569 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1571 pthread_mutex_unlock(&lock);
1574 for (i = 0; i < 16; i++)
1575 out[offset + i] = hash[i] ^ in[offset + i];
1576 input = out + offset - 16;
1581 memcpy(in, out, len);
1582 pthread_mutex_unlock(&lock);
1586 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1587 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1588 static unsigned char first = 1;
1589 static EVP_MD_CTX mdctx;
1590 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1591 unsigned int md_len;
1592 uint8_t i, offset = 0, out[128];
1594 pthread_mutex_lock(&lock);
1596 EVP_MD_CTX_init(&mdctx);
1602 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1603 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1604 !EVP_DigestUpdate(&mdctx, input, 16) ||
1605 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1607 pthread_mutex_unlock(&lock);
1610 for (i = 0; i < 16; i++)
1611 out[offset + i] = hash[i] ^ in[offset + i];
1612 input = in + offset;
1617 memcpy(in, out, len);
1618 pthread_mutex_unlock(&lock);
1622 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1623 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1624 static unsigned char first = 1;
1625 static EVP_MD_CTX mdctx;
1626 unsigned char hash[EVP_MAX_MD_SIZE];
1627 unsigned int md_len;
1630 pthread_mutex_lock(&lock);
1632 EVP_MD_CTX_init(&mdctx);
1637 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1638 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1639 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1642 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1643 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1644 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1645 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1646 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1647 pthread_mutex_unlock(&lock);
1652 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1655 for (i = 0; i < 16; i++)
1658 for (offset = 16; offset < len; offset += 16) {
1660 printf("text + offset - 16 c(%d): ", offset / 16);
1661 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1663 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1664 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1665 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1666 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1668 pthread_mutex_unlock(&lock);
1672 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1675 for (i = 0; i < 16; i++)
1676 text[offset + i] ^= hash[i];
1680 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1683 pthread_mutex_unlock(&lock);
1687 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1688 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1689 static unsigned char first = 1;
1690 static EVP_MD_CTX mdctx;
1691 unsigned char hash[EVP_MAX_MD_SIZE];
1692 unsigned int md_len;
1696 pthread_mutex_lock(&lock);
1698 EVP_MD_CTX_init(&mdctx);
1703 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1704 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1705 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1708 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1709 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1710 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1711 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1712 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1713 pthread_mutex_unlock(&lock);
1718 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1721 for (i = 0; i < 16; i++)
1722 plain[i] = text[i] ^ hash[i];
1724 for (offset = 16; offset < len; offset += 16) {
1726 printf("text + offset - 16 c(%d): ", offset / 16);
1727 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1729 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1730 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1731 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1732 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1734 pthread_mutex_unlock(&lock);
1738 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1741 for (i = 0; i < 16; i++)
1742 plain[offset + i] = text[offset + i] ^ hash[i];
1745 memcpy(text, plain, len);
1747 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1750 pthread_mutex_unlock(&lock);
1754 struct realm *id2realm(struct list *realmlist, char *id) {
1755 struct list_node *entry;
1756 struct realm *realm, *subrealm = NULL;
1758 /* need to do locking for subrealms and check subrealm timers */
1759 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1760 realm = (struct realm *)entry->data;
1761 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1762 pthread_mutex_lock(&realm->subrealms_mutex);
1763 if (realm->subrealms)
1764 subrealm = id2realm(realm->subrealms, id);
1765 pthread_mutex_unlock(&realm->subrealms_mutex);
1766 return subrealm ? subrealm : realm;
1772 /* helper function, only used by removeserversubrealms() */
1773 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1774 struct list_node *entry;
1775 struct realm *realm;
1777 for (entry = list_first(realmlist); entry;) {
1778 realm = (struct realm *)entry->data;
1779 entry = list_next(entry);
1780 if (realm->srvconfs) {
1781 list_removedata(realm->srvconfs, srv);
1782 if (!list_first(realm->srvconfs)) {
1783 list_destroy(realm->srvconfs);
1784 realm->srvconfs = NULL;
1787 if (realm->accsrvconfs) {
1788 list_removedata(realm->accsrvconfs, srv);
1789 if (!list_first(realm->accsrvconfs)) {
1790 list_destroy(realm->accsrvconfs);
1791 realm->accsrvconfs = NULL;
1795 /* remove subrealm if no servers */
1796 if (!realm->srvconfs && !realm->accsrvconfs) {
1797 list_removedata(realmlist, realm);
1803 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1804 struct list_node *entry;
1805 struct realm *realm;
1807 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1808 realm = (struct realm *)entry->data;
1809 pthread_mutex_lock(&realm->subrealms_mutex);
1810 if (realm->subrealms) {
1811 _internal_removeserversubrealms(realm->subrealms, srv);
1812 if (!list_first(realm->subrealms)) {
1813 list_destroy(realm->subrealms);
1814 realm->subrealms = NULL;
1817 pthread_mutex_unlock(&realm->subrealms_mutex);
1821 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1822 struct request *rq = to->requests, *end;
1824 pthread_mutex_lock(&to->newrq_mutex);
1825 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1826 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1828 pthread_mutex_unlock(&to->newrq_mutex);
1833 int attrvalidate(unsigned char *attrs, int length) {
1834 while (length > 1) {
1835 if (ATTRLEN(attrs) < 2) {
1836 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1839 length -= ATTRLEN(attrs);
1841 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1844 attrs += ATTRLEN(attrs);
1847 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1851 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1852 if (len < 16 || len > 128 || len % 16) {
1853 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1857 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1858 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1862 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1864 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1865 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1871 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1874 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1875 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1878 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1879 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1885 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1886 char *oldsecret, char *newsecret) {
1887 unsigned char *attr;
1889 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1890 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1891 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1897 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1901 for (; attrs[0]; attrs += 2)
1902 if (attrs[0] == vendor && attrs[1] == subattr)
1907 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1908 uint8_t alen, sublen, rmlen = 0;
1909 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1912 if (!removevendorattrs)
1915 while (*removevendorattrs && *removevendorattrs != vendor)
1916 removevendorattrs += 2;
1917 if (!*removevendorattrs)
1920 alen = ATTRLEN(attrs);
1922 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1923 /* remove entire vendor attribute */
1924 memmove(attrs, attrs + alen, length - alen);
1929 subattrs = ATTRVAL(attrs) + 4;
1931 if (!attrvalidate(subattrs, sublen)) {
1932 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1937 while (sublen > 1) {
1938 alen = ATTRLEN(subattrs);
1941 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1942 memmove(subattrs, subattrs + alen, length);
1948 ATTRLEN(attrs) -= rmlen;
1952 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1953 uint8_t *attrs, alen;
1954 uint16_t len, rmlen = 0;
1956 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1959 len = RADLEN(buf) - 20;
1962 alen = ATTRLEN(attrs);
1964 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1965 memmove(attrs, attrs + alen, len);
1967 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1968 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1973 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1976 /* returns a pointer to the resized attribute value */
1977 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1978 uint8_t *attrs, *attr, vallen;
1982 len = RADLEN(*buf) - 20;
1985 attr = attrget(attrs, len, type);
1989 vallen = ATTRVALLEN(attr);
1990 if (vallen == newvallen)
1993 len += newvallen - vallen;
1994 if (newvallen > vallen) {
1995 new = realloc(*buf, len + 20);
1997 debug(DBG_ERR, "resizeattr: malloc failed");
2006 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
2007 attr[1] = newvallen + 2;
2008 ((uint16_t *)*buf)[1] = htons(len + 20);
2012 int rewriteusername(struct request *rq, char *in) {
2013 size_t nmatch = 10, reslen = 0, start = 0;
2014 regmatch_t pmatch[10], *pfield;
2016 unsigned char *result;
2017 char *out = rq->from->conf->rewriteattrreplacement;
2019 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2020 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2024 rq->origusername = stringcopy(in, 0);
2025 if (!rq->origusername)
2028 for (i = start; out[i]; i++) {
2029 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2030 pfield = &pmatch[out[i + 1] - '0'];
2031 if (pfield->rm_so >= 0) {
2032 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2038 reslen += i - start;
2040 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2046 for (i = start; out[i]; i++) {
2047 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2048 pfield = &pmatch[out[i + 1] - '0'];
2049 if (pfield->rm_so >= 0) {
2050 memcpy(result + reslen, out + start, i - start);
2051 reslen += i - start;
2052 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2053 reslen += pfield->rm_eo - pfield->rm_so;
2060 memcpy(result + reslen, out + start, i - start);
2061 reslen += i - start;
2062 memcpy(in, result, reslen);
2067 const char *radmsgtype2string(uint8_t code) {
2068 static const char *rad_msg_names[] = {
2069 "", "Access-Request", "Access-Accept", "Access-Reject",
2070 "Accounting-Request", "Accounting-Response", "", "",
2071 "", "", "", "Access-Challenge",
2072 "Status-Server", "Status-Client"
2074 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2077 void char2hex(char *h, unsigned char c) {
2078 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2079 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2080 h[0] = hexdigits[c / 16];
2081 h[1] = hexdigits[c % 16];
2085 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2089 if (!attr || len == 1) {
2094 l = ATTRVALLEN(attr);
2095 s = (char *)ATTRVAL(attr);
2098 for (i = 0; i < l; i++) {
2099 if (s[i] > 31 && s[i] < 127) {
2101 if (d - ascii == len - 1)
2104 if (d - ascii > len - 4)
2109 if (d - ascii == len - 1)
2117 void acclog(unsigned char *attrs, int length, char *host) {
2118 unsigned char *attr;
2121 attr = attrget(attrs, length, RAD_Attr_User_Name);
2123 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2126 radattr2ascii(username, sizeof(username), attr);
2127 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2130 void respondaccounting(struct request *rq) {
2131 unsigned char *resp;
2135 debug(DBG_ERR, "respondaccounting: malloc failed");
2138 memcpy(resp, rq->buf, 20);
2139 resp[0] = RAD_Accounting_Response;
2142 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2143 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2146 void respondstatusserver(struct request *rq) {
2147 unsigned char *resp;
2151 debug(DBG_ERR, "respondstatusserver: malloc failed");
2154 memcpy(resp, rq->buf, 20);
2155 resp[0] = RAD_Access_Accept;
2158 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2159 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2162 void respondreject(struct request *rq, char *message) {
2163 unsigned char *resp;
2166 if (message && *message)
2167 len += 2 + strlen(message);
2171 debug(DBG_ERR, "respondreject: malloc failed");
2174 memcpy(resp, rq->buf, 20);
2175 resp[0] = RAD_Access_Reject;
2176 *(uint16_t *)(resp + 2) = htons(len);
2177 if (message && *message) {
2178 resp[20] = RAD_Attr_Reply_Message;
2179 resp[21] = len - 20;
2180 memcpy(resp + 22, message, len - 22);
2182 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2185 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2186 struct list_node *entry;
2187 struct clsrvconf *server, *best = NULL, *first = NULL;
2189 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2190 server = (struct clsrvconf *)entry->data;
2191 if (!server->servers)
2195 if (!server->servers->connectionok)
2197 if (!server->servers->lostrqs)
2203 if (server->servers->lostrqs < best->servers->lostrqs)
2206 return best ? best : first;
2209 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2210 struct clsrvconf *srvconf;
2212 *realm = id2realm(realms, id);
2215 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2216 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2219 if (!acc && !srvconf->servers)
2220 adddynamicrealmserver(*realm, srvconf, id);
2221 return srvconf->servers;
2224 /* returns 0 if validation/authentication fails, else 1 */
2225 int radsrv(struct request *rq) {
2226 uint8_t code, id, *auth, *attrs, *attr;
2228 struct server *to = NULL;
2229 char username[254], userascii[760];
2230 unsigned char newauth[16];
2231 struct realm *realm = NULL;
2233 code = *(uint8_t *)rq->buf;
2234 id = *(uint8_t *)(rq->buf + 1);
2235 len = RADLEN(rq->buf);
2236 auth = (uint8_t *)(rq->buf + 4);
2238 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2240 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2241 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2246 attrs = rq->buf + 20;
2248 if (!attrvalidate(attrs, len)) {
2249 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2253 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2254 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2255 debug(DBG_WARN, "radsrv: message authentication failed");
2259 if (code == RAD_Status_Server) {
2260 respondstatusserver(rq);
2264 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2266 if (code == RAD_Accounting_Request) {
2267 memset(newauth, 0, 16);
2268 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2269 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2274 if (rq->from->conf->rewrite) {
2275 dorewrite(rq->buf, rq->from->conf->rewrite);
2276 len = RADLEN(rq->buf) - 20;
2279 attr = attrget(attrs, len, RAD_Attr_User_Name);
2281 if (code == RAD_Accounting_Request) {
2282 acclog(attrs, len, rq->from->conf->host);
2283 respondaccounting(rq);
2285 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2288 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2289 username[ATTRVALLEN(attr)] = '\0';
2290 radattr2ascii(userascii, sizeof(userascii), attr);
2292 if (rq->from->conf->rewriteattrregex) {
2293 if (!rewriteusername(rq, username)) {
2294 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2297 len = RADLEN(rq->buf) - 20;
2298 auth = (uint8_t *)(rq->buf + 4);
2299 attrs = rq->buf + 20;
2302 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2304 to = findserver(&realm, username, code == RAD_Accounting_Request);
2306 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2310 if (realm->message && code == RAD_Access_Request) {
2311 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2312 respondreject(rq, realm->message);
2313 } else if (realm->accresp && code == RAD_Accounting_Request) {
2314 acclog(attrs, len, rq->from->conf->host);
2315 respondaccounting(rq);
2320 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2321 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2322 rq->from->conf->name, to->conf->name);
2326 if (rqinqueue(to, rq->from, id, code)) {
2327 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2328 radmsgtype2string(code), rq->from->conf->host, id);
2332 if (code != RAD_Accounting_Request) {
2333 if (!RAND_bytes(newauth, 16)) {
2334 debug(DBG_WARN, "radsrv: failed to generate random auth");
2340 printfchars(NULL, "auth", "%02x ", auth, 16);
2343 attr = attrget(attrs, len, RAD_Attr_User_Password);
2345 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2346 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2350 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2352 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2353 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2358 memcpy(rq->origauth, auth, 16);
2359 memcpy(auth, newauth, 16);
2372 int replyh(struct server *server, unsigned char *buf) {
2373 struct client *from;
2376 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2377 struct sockaddr_storage fromsa;
2378 char tmp[760], stationid[760];
2380 server->connectionok = 1;
2381 server->lostrqs = 0;
2383 i = buf[1]; /* i is the id */
2385 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2386 && *buf != RAD_Accounting_Response) {
2387 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2390 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2392 rq = server->requests + i;
2394 pthread_mutex_lock(&server->newrq_mutex);
2395 if (!rq->buf || !rq->tries) {
2396 pthread_mutex_unlock(&server->newrq_mutex);
2397 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2402 pthread_mutex_unlock(&server->newrq_mutex);
2403 debug(DBG_INFO, "replyh: already received, ignoring reply");
2407 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2408 pthread_mutex_unlock(&server->newrq_mutex);
2409 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2413 len = RADLEN(buf) - 20;
2416 if (!attrvalidate(attrs, len)) {
2417 pthread_mutex_unlock(&server->newrq_mutex);
2418 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2422 /* Message Authenticator */
2423 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2425 if (ATTRVALLEN(messageauth) != 16) {
2426 pthread_mutex_unlock(&server->newrq_mutex);
2427 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2430 memcpy(tmp, buf + 4, 16);
2431 memcpy(buf + 4, rq->buf + 4, 16);
2432 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2433 pthread_mutex_unlock(&server->newrq_mutex);
2434 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2437 memcpy(buf + 4, tmp, 16);
2438 debug(DBG_DBG, "replyh: message auth ok");
2441 gettimeofday(&server->lastrcv, NULL);
2443 if (*rq->buf == RAD_Status_Server) {
2445 pthread_mutex_unlock(&server->newrq_mutex);
2446 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2450 gettimeofday(&server->lastreply, NULL);
2454 pthread_mutex_unlock(&server->newrq_mutex);
2455 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2459 if (server->conf->rewrite) {
2460 dorewrite(buf, server->conf->rewrite);
2461 len = RADLEN(buf) - 20;
2465 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2466 if (ATTRVALLEN(attr) <= 4)
2469 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2472 sublen = ATTRVALLEN(attr) - 4;
2473 subattrs = ATTRVAL(attr) + 4;
2474 if (!attrvalidate(subattrs, sublen) ||
2475 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2476 rq, server->conf->secret, from->conf->secret) ||
2477 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2478 rq, server->conf->secret, from->conf->secret))
2482 pthread_mutex_unlock(&server->newrq_mutex);
2483 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2487 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2488 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2490 radattr2ascii(tmp, sizeof(tmp), attr);
2491 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2493 radattr2ascii(stationid, sizeof(stationid), attr);
2494 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2495 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2497 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2501 buf[1] = (char)rq->origid;
2502 memcpy(buf + 4, rq->origauth, 16);
2504 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2507 if (rq->origusername) {
2508 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2510 pthread_mutex_unlock(&server->newrq_mutex);
2511 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2514 memcpy(username, rq->origusername, strlen(rq->origusername));
2515 len = RADLEN(buf) - 20;
2518 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2522 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2523 pthread_mutex_unlock(&server->newrq_mutex);
2524 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2527 debug(DBG_DBG, "replyh: computed messageauthattr");
2530 fromsa = rq->fromsa; /* only needed for UDP */
2531 /* once we set received = 1, rq may be reused */
2534 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2535 sendreply(from, buf, &fromsa, rq->fromudpsock);
2536 pthread_mutex_unlock(&server->newrq_mutex);
2540 void *udpclientrd(void *arg) {
2541 struct server *server;
2543 int *s = (int *)arg;
2547 buf = radudpget(*s, NULL, &server, NULL);
2548 if (!replyh(server, buf))
2553 void *tlsclientrd(void *arg) {
2554 struct server *server = (struct server *)arg;
2556 struct timeval now, lastconnecttry;
2559 /* yes, lastconnecttry is really necessary */
2560 lastconnecttry = server->lastconnecttry;
2561 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2563 if (server->dynamiclookuparg)
2565 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2569 if (!replyh(server, buf))
2571 if (server->dynamiclookuparg) {
2572 gettimeofday(&now, NULL);
2573 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2574 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2579 ERR_remove_state(0);
2580 server->clientrdgone = 1;
2584 void *tcpclientrd(void *arg) {
2585 struct server *server = (struct server *)arg;
2587 struct timeval lastconnecttry;
2590 /* yes, lastconnecttry is really necessary */
2591 lastconnecttry = server->lastconnecttry;
2592 buf = radtcpget(server->sock, 0);
2594 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2598 if (!replyh(server, buf))
2601 server->clientrdgone = 1;
2605 /* code for removing state not finished */
2606 void *clientwr(void *arg) {
2607 struct server *server = (struct server *)arg;
2609 pthread_t clientrdth;
2610 int i, dynconffail = 0;
2613 struct timespec timeout;
2614 struct request statsrvrq;
2615 unsigned char statsrvbuf[38];
2616 struct clsrvconf *conf;
2618 conf = server->conf;
2620 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2625 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2626 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2630 memset(&timeout, 0, sizeof(struct timespec));
2632 if (conf->statusserver) {
2633 memset(&statsrvrq, 0, sizeof(struct request));
2634 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2635 statsrvbuf[0] = RAD_Status_Server;
2637 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2638 statsrvbuf[21] = 18;
2639 gettimeofday(&server->lastrcv, NULL);
2642 if (conf->pdef->connecter) {
2643 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2645 server->connectionok = 1;
2646 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2647 debug(DBG_ERR, "clientwr: pthread_create failed");
2651 server->connectionok = 1;
2654 pthread_mutex_lock(&server->newrq_mutex);
2655 if (!server->newrq) {
2656 gettimeofday(&now, NULL);
2657 /* random 0-7 seconds */
2658 RAND_bytes(&rnd, 1);
2660 if (conf->statusserver) {
2661 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2662 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2664 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2665 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2668 if (timeout.tv_sec > now.tv_sec)
2669 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2671 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2674 if (server->newrq) {
2675 debug(DBG_DBG, "clientwr: got new request");
2680 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2682 pthread_mutex_unlock(&server->newrq_mutex);
2684 for (i = 0; i < MAX_REQUESTS; i++) {
2685 if (server->clientrdgone) {
2686 pthread_join(clientrdth, NULL);
2689 pthread_mutex_lock(&server->newrq_mutex);
2690 while (i < MAX_REQUESTS && !server->requests[i].buf)
2692 if (i == MAX_REQUESTS) {
2693 pthread_mutex_unlock(&server->newrq_mutex);
2696 rq = server->requests + i;
2699 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2701 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2703 /* setting this to NULL means that it can be reused */
2706 pthread_mutex_unlock(&server->newrq_mutex);
2710 gettimeofday(&now, NULL);
2711 if (now.tv_sec < rq->expiry.tv_sec) {
2712 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2713 timeout.tv_sec = rq->expiry.tv_sec;
2714 pthread_mutex_unlock(&server->newrq_mutex);
2718 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2719 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2720 if (conf->statusserver) {
2721 if (*rq->buf == RAD_Status_Server) {
2722 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2723 if (server->lostrqs < 255)
2727 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2728 if (server->lostrqs < 255)
2732 /* setting this to NULL means that it can be reused */
2734 pthread_mutex_unlock(&server->newrq_mutex);
2737 pthread_mutex_unlock(&server->newrq_mutex);
2739 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2740 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2741 timeout.tv_sec = rq->expiry.tv_sec;
2743 conf->pdef->clientradput(server, server->requests[i].buf);
2745 if (conf->statusserver) {
2746 gettimeofday(&now, NULL);
2747 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2748 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2749 debug(DBG_WARN, "clientwr: failed to generate random auth");
2752 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2753 if (!statsrvrq.buf) {
2754 debug(DBG_ERR, "clientwr: malloc failed");
2757 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2758 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2759 sendrq(server, &statsrvrq);
2764 conf->servers = NULL;
2765 if (server->dynamiclookuparg) {
2766 removeserversubrealms(realms, conf);
2770 freeclsrvconf(conf);
2772 freeserver(server, 1);
2773 ERR_remove_state(0);
2777 void *udpserverwr(void *arg) {
2778 struct replyq *replyq = udp_server_replyq;
2779 struct reply *reply;
2782 pthread_mutex_lock(&replyq->mutex);
2783 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2784 debug(DBG_DBG, "udp server writer, waiting for signal");
2785 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2786 debug(DBG_DBG, "udp server writer, got signal");
2788 pthread_mutex_unlock(&replyq->mutex);
2790 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2791 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2792 debug(DBG_WARN, "sendudp: send failed");
2798 void *udpserverrd(void *arg) {
2800 int *sp = (int *)arg;
2803 memset(&rq, 0, sizeof(struct request));
2804 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2805 rq.fromudpsock = *sp;
2811 void *tlsserverwr(void *arg) {
2813 unsigned long error;
2814 struct client *client = (struct client *)arg;
2815 struct replyq *replyq;
2816 struct reply *reply;
2818 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2819 replyq = client->replyq;
2821 pthread_mutex_lock(&replyq->mutex);
2822 while (!list_first(replyq->replies)) {
2824 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2825 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2826 debug(DBG_DBG, "tlsserverwr: got signal");
2829 /* ssl might have changed while waiting */
2830 pthread_mutex_unlock(&replyq->mutex);
2831 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2832 ERR_remove_state(0);
2836 reply = (struct reply *)list_shift(replyq->replies);
2837 pthread_mutex_unlock(&replyq->mutex);
2838 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2840 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2841 cnt, RADLEN(reply->buf));
2843 while ((error = ERR_get_error()))
2844 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2850 void tlsserverrd(struct client *client) {
2852 pthread_t tlsserverwrth;
2854 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2856 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2857 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2862 memset(&rq, 0, sizeof(struct request));
2863 rq.buf = radtlsget(client->ssl, 0);
2865 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2868 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2871 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2876 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2878 pthread_mutex_lock(&client->replyq->mutex);
2879 pthread_cond_signal(&client->replyq->cond);
2880 pthread_mutex_unlock(&client->replyq->mutex);
2881 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2882 pthread_join(tlsserverwrth, NULL);
2883 removeclientrqs(client);
2884 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2887 void *tlsservernew(void *arg) {
2889 struct sockaddr_storage from;
2890 size_t fromlen = sizeof(from);
2891 struct clsrvconf *conf;
2892 struct list_node *cur = NULL;
2895 unsigned long error;
2896 struct client *client;
2899 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2900 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2903 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2905 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2907 ssl = SSL_new(conf->ssl_ctx);
2910 if (SSL_accept(ssl) <= 0) {
2911 while ((error = ERR_get_error()))
2912 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2913 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2916 cert = verifytlscert(ssl);
2922 if (verifyconfcert(cert, conf)) {
2924 client = addclient(conf);
2927 tlsserverrd(client);
2928 removeclient(client);
2930 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2933 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2935 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2941 ERR_remove_state(0);
2942 shutdown(s, SHUT_RDWR);
2947 void *tlslistener(void *arg) {
2948 pthread_t tlsserverth;
2949 int s, *sp = (int *)arg;
2950 struct sockaddr_storage from;
2951 size_t fromlen = sizeof(from);
2956 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2958 debug(DBG_WARN, "accept failed");
2961 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2962 debug(DBG_ERR, "tlslistener: pthread_create failed");
2963 shutdown(s, SHUT_RDWR);
2967 pthread_detach(tlsserverth);
2973 void *tcpserverwr(void *arg) {
2975 struct client *client = (struct client *)arg;
2976 struct replyq *replyq;
2977 struct reply *reply;
2979 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2980 replyq = client->replyq;
2982 pthread_mutex_lock(&replyq->mutex);
2983 while (!list_first(replyq->replies)) {
2984 if (client->s >= 0) {
2985 debug(DBG_DBG, "tcpserverwr: waiting for signal");
2986 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2987 debug(DBG_DBG, "tcpserverwr: got signal");
2989 if (client->s < 0) {
2990 /* s might have changed while waiting */
2991 pthread_mutex_unlock(&replyq->mutex);
2992 debug(DBG_DBG, "tcpserverwr: exiting as requested");
2996 reply = (struct reply *)list_shift(replyq->replies);
2997 pthread_mutex_unlock(&replyq->mutex);
2998 cnt = write(client->s, reply->buf, RADLEN(reply->buf));
3000 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
3001 cnt, RADLEN(reply->buf));
3003 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3009 void tcpserverrd(struct client *client) {
3011 pthread_t tcpserverwrth;
3013 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3015 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3016 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3021 memset(&rq, 0, sizeof(struct request));
3022 rq.buf = radtcpget(client->s, 0);
3024 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3027 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3030 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3035 /* stop writer by setting s to -1 and give signal in case waiting for data */
3037 pthread_mutex_lock(&client->replyq->mutex);
3038 pthread_cond_signal(&client->replyq->cond);
3039 pthread_mutex_unlock(&client->replyq->mutex);
3040 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3041 pthread_join(tcpserverwrth, NULL);
3042 removeclientrqs(client);
3043 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3046 void *tcpservernew(void *arg) {
3048 struct sockaddr_storage from;
3049 size_t fromlen = sizeof(from);
3050 struct clsrvconf *conf;
3051 struct client *client;
3054 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3055 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3058 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3060 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3062 client = addclient(conf);
3065 tcpserverrd(client);
3066 removeclient(client);
3068 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3070 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3073 shutdown(s, SHUT_RDWR);
3078 void *tcplistener(void *arg) {
3079 pthread_t tcpserverth;
3080 int s, *sp = (int *)arg;
3081 struct sockaddr_storage from;
3082 size_t fromlen = sizeof(from);
3087 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3089 debug(DBG_WARN, "accept failed");
3092 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3093 debug(DBG_ERR, "tcplistener: pthread_create failed");
3094 shutdown(s, SHUT_RDWR);
3098 pthread_detach(tcpserverth);
3104 void createlistener(uint8_t type, char *arg) {
3106 struct clsrvconf *listenres;
3107 struct addrinfo *res;
3108 int s = -1, on = 1, *sp = NULL;
3110 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3112 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3114 for (res = listenres->addrinfo; res; res = res->ai_next) {
3115 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3117 debug(DBG_WARN, "createlistener: socket failed");
3120 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3122 if (res->ai_family == AF_INET6)
3123 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3125 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3126 debug(DBG_WARN, "createlistener: bind failed");
3132 sp = malloc(sizeof(int));
3134 debugx(1, DBG_ERR, "malloc failed");
3136 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3137 debugx(1, DBG_ERR, "pthread_create failed");
3141 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3143 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3144 listenres->host ? listenres->host : "*", listenres->port);
3145 freeclsrvres(listenres);
3148 void createlisteners(uint8_t type, char **args) {
3152 for (i = 0; args[i]; i++)
3153 createlistener(type, args[i]);
3155 createlistener(type, NULL);
3158 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3159 SSL_CTX *ctx = NULL;
3160 STACK_OF(X509_NAME) *calist;
3163 unsigned long error;
3166 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3167 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3168 for (i = 0; i < CRYPTO_num_locks(); i++) {
3169 ssl_lock_count[i] = 0;
3170 pthread_mutex_init(&ssl_locks[i], NULL);
3172 CRYPTO_set_id_callback(ssl_thread_id);
3173 CRYPTO_set_locking_callback(ssl_locking_callback);
3175 SSL_load_error_strings();
3178 while (!RAND_status()) {
3179 time_t t = time(NULL);
3180 pid_t pid = getpid();
3181 RAND_seed((unsigned char *)&t, sizeof(time_t));
3182 RAND_seed((unsigned char *)&pid, sizeof(pid));
3188 ctx = SSL_CTX_new(TLSv1_method());
3191 ctx = SSL_CTX_new(DTLSv1_method());
3192 SSL_CTX_set_read_ahead(ctx, 1);
3196 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3200 if (conf->certkeypwd) {
3201 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3202 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3204 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3205 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3206 !SSL_CTX_check_private_key(ctx) ||
3207 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3208 while ((error = ERR_get_error()))
3209 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3210 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3215 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3216 if (!conf->cacertfile || calist) {
3217 if (conf->cacertpath) {
3219 calist = sk_X509_NAME_new_null();
3220 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3221 sk_X509_NAME_free(calist);
3227 while ((error = ERR_get_error()))
3228 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3229 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3233 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3234 SSL_CTX_set_client_CA_list(ctx, calist);
3236 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3237 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3239 if (conf->crlcheck) {
3240 x509_s = SSL_CTX_get_cert_store(ctx);
3241 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3244 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3248 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3249 struct list_node *entry;
3250 struct tls *t, *t1 = NULL, *t2 = NULL;
3251 SSL_CTX *ctx = NULL;
3253 pthread_mutex_lock(&tlsconfs_lock);
3255 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3256 t = (struct tls *)entry->data;
3257 if (!strcasecmp(t->name, alt1)) {
3261 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3272 t->tlsctx = tlscreatectx(RAD_TLS, t);
3277 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3283 pthread_mutex_unlock(&tlsconfs_lock);
3287 struct list *addsrvconfs(char *value, char **names) {
3288 struct list *conflist;
3290 struct list_node *entry;
3291 struct clsrvconf *conf = NULL;
3293 if (!names || !*names)
3296 conflist = list_create();
3298 debug(DBG_ERR, "malloc failed");
3302 for (n = 0; names[n]; n++) {
3303 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3304 conf = (struct clsrvconf *)entry->data;
3305 if (!strcasecmp(names[n], conf->name))
3309 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3310 list_destroy(conflist);
3313 if (!list_push(conflist, conf)) {
3314 debug(DBG_ERR, "malloc failed");
3315 list_destroy(conflist);
3318 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3323 void freerealm(struct realm *realm) {
3327 free(realm->message);
3328 regfree(&realm->regex);
3329 pthread_mutex_destroy(&realm->subrealms_mutex);
3330 if (realm->subrealms)
3331 list_destroy(realm->subrealms);
3332 if (realm->srvconfs) {
3333 /* emptying list without freeing data */
3334 while (list_shift(realm->srvconfs));
3335 list_destroy(realm->srvconfs);
3337 if (realm->accsrvconfs) {
3338 /* emptying list without freeing data */
3339 while (list_shift(realm->accsrvconfs));
3340 list_destroy(realm->accsrvconfs);
3345 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3347 struct realm *realm;
3348 char *s, *regex = NULL;
3350 if (*value == '/') {
3351 /* regexp, remove optional trailing / if present */
3352 if (value[strlen(value) - 1] == '/')
3353 value[strlen(value) - 1] = '\0';
3355 /* not a regexp, let us make it one */
3356 if (*value == '*' && !value[1])
3357 regex = stringcopy(".*", 0);
3359 for (n = 0, s = value; *s;)
3362 regex = malloc(strlen(value) + n + 3);
3365 for (n = 1, s = value; *s; s++) {
3375 debug(DBG_ERR, "malloc failed");
3379 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3382 realm = malloc(sizeof(struct realm));
3384 debug(DBG_ERR, "malloc failed");
3387 memset(realm, 0, sizeof(struct realm));
3389 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3390 debug(DBG_ERR, "mutex init failed");
3396 realm->name = stringcopy(value, 0);
3398 debug(DBG_ERR, "malloc failed");
3401 if (message && strlen(message) > 253) {
3402 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3405 realm->message = message;
3406 realm->accresp = accresp;
3408 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3409 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3413 if (servers && *servers) {
3414 realm->srvconfs = addsrvconfs(value, servers);
3415 if (!realm->srvconfs)
3419 if (accservers && *accservers) {
3420 realm->accsrvconfs = addsrvconfs(value, accservers);
3421 if (!realm->accsrvconfs)
3425 if (!list_push(realmlist, realm)) {
3426 debug(DBG_ERR, "malloc failed");
3427 pthread_mutex_destroy(&realm->subrealms_mutex);
3431 debug(DBG_DBG, "addrealm: added realm %s", value);
3441 for (n = 0; servers[n]; n++)
3446 for (n = 0; accservers[n]; n++)
3447 free(accservers[n]);
3453 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3454 struct clsrvconf *srvconf;
3455 struct realm *newrealm = NULL;
3456 char *realmname, *s;
3459 if (!conf->dynamiclookupcommand)
3462 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3463 realmname = strrchr(id, '@');
3469 for (s = realmname; *s; s++)
3470 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3473 pthread_mutex_lock(&realm->subrealms_mutex);
3474 /* exit if we now already got a matching subrealm */
3475 if (id2realm(realm->subrealms, id))
3477 srvconf = malloc(sizeof(struct clsrvconf));
3479 debug(DBG_ERR, "malloc failed");
3483 if (!addserver(srvconf))
3486 if (!realm->subrealms)
3487 realm->subrealms = list_create();
3488 if (!realm->subrealms)
3490 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3494 /* add server and accserver to newrealm */
3495 newrealm->srvconfs = list_create();
3496 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3497 debug(DBG_ERR, "malloc failed");
3500 newrealm->accsrvconfs = list_create();
3501 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3502 debug(DBG_ERR, "malloc failed");
3506 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3508 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3509 debug(DBG_ERR, "pthread_create failed");
3512 pthread_detach(clientth);
3517 list_removedata(realm->subrealms, newrealm);
3518 freerealm(newrealm);
3519 if (!list_first(realm->subrealms)) {
3520 list_destroy(realm->subrealms);
3521 realm->subrealms = NULL;
3524 freeserver(srvconf->servers, 1);
3526 debug(DBG_ERR, "failed to create dynamic server");
3529 pthread_mutex_unlock(&realm->subrealms_mutex);
3532 int dynamicconfig(struct server *server) {
3533 int ok, fd[2], status;
3535 struct clsrvconf *conf = server->conf;
3536 struct gconffile *cf = NULL;
3538 /* for now we only learn hostname/address */
3539 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3542 debug(DBG_ERR, "dynamicconfig: pipe error");
3547 debug(DBG_ERR, "dynamicconfig: fork error");
3551 } else if (pid == 0) {
3554 if (fd[1] != STDOUT_FILENO) {
3555 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3556 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3559 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3560 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3564 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3565 ok = getgenericconfig(&cf, NULL,
3566 "Server", CONF_CBK, confserver_cb, (void *)conf,
3571 if (waitpid(pid, &status, 0) < 0) {
3572 debug(DBG_ERR, "dynamicconfig: wait error");
3577 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3585 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3589 int addmatchcertattr(struct clsrvconf *conf) {
3593 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3594 r = &conf->certcnregex;
3595 v = conf->matchcertattr + 4;
3596 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3597 r = &conf->certuriregex;
3598 v = conf->matchcertattr + 20;
3603 /* regexp, remove optional trailing / if present */
3604 if (v[strlen(v) - 1] == '/')
3605 v[strlen(v) - 1] = '\0';
3609 *r = malloc(sizeof(regex_t));
3611 debug(DBG_ERR, "malloc failed");
3614 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3617 debug(DBG_ERR, "failed to compile regular expression %s", v);
3623 int addrewriteattr(struct clsrvconf *conf) {
3626 v = conf->rewriteattr + 11;
3627 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3629 /* regexp, remove optional trailing / if present */
3630 if (v[strlen(v) - 1] == '/')
3631 v[strlen(v) - 1] = '\0';
3639 conf->rewriteattrregex = malloc(sizeof(regex_t));
3640 if (!conf->rewriteattrregex) {
3641 debug(DBG_ERR, "malloc failed");
3645 conf->rewriteattrreplacement = stringcopy(w, 0);
3646 if (!conf->rewriteattrreplacement) {
3647 free(conf->rewriteattrregex);
3648 conf->rewriteattrregex = NULL;
3652 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3653 free(conf->rewriteattrregex);
3654 conf->rewriteattrregex = NULL;
3655 free(conf->rewriteattrreplacement);
3656 conf->rewriteattrreplacement = NULL;
3657 debug(DBG_ERR, "failed to compile regular expression %s", v);
3664 /* should accept both names and numeric values, only numeric right now */
3665 uint8_t attrname2val(char *attrname) {
3668 val = atoi(attrname);
3669 return val > 0 && val < 256 ? val : 0;
3672 /* should accept both names and numeric values, only numeric right now */
3673 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3676 *vendor = atoi(attrname);
3677 s = strchr(attrname, ':');
3682 *type = atoi(s + 1);
3683 return *type >= 0 && *type < 256;
3686 struct rewrite *getrewrite(char *alt1, char *alt2) {
3687 struct list_node *entry;
3688 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3690 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3691 r = (struct rewriteconf *)entry->data;
3692 if (!strcasecmp(r->name, alt1)) {
3696 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3706 void addrewrite(char *value, char **attrs, char **vattrs) {
3707 struct rewriteconf *new;
3708 struct rewrite *rewrite = NULL;
3711 uint32_t *p, *va = NULL;
3715 for (; attrs[n]; n++);
3716 a = malloc((n + 1) * sizeof(uint8_t));
3718 debugx(1, DBG_ERR, "malloc failed");
3720 for (i = 0; i < n; i++) {
3721 if (!(a[i] = attrname2val(attrs[i])))
3722 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3731 for (; vattrs[n]; n++);
3732 va = malloc((2 * n + 1) * sizeof(uint32_t));
3734 debugx(1, DBG_ERR, "malloc failed");
3736 for (p = va, i = 0; i < n; i++, p += 2) {
3737 if (!vattrname2val(vattrs[i], p, p + 1))
3738 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3746 rewrite = malloc(sizeof(struct rewrite));
3748 debugx(1, DBG_ERR, "malloc failed");
3749 rewrite->removeattrs = a;
3750 rewrite->removevendorattrs = va;
3753 new = malloc(sizeof(struct rewriteconf));
3754 if (!new || !list_push(rewriteconfs, new))
3755 debugx(1, DBG_ERR, "malloc failed");
3757 memset(new, 0, sizeof(struct rewriteconf));
3758 new->name = stringcopy(value, 0);
3760 debugx(1, DBG_ERR, "malloc failed");
3762 new->rewrite = rewrite;
3763 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3766 void freeclsrvconf(struct clsrvconf *conf) {
3772 free(conf->matchcertattr);
3773 if (conf->certcnregex)
3774 regfree(conf->certcnregex);
3775 if (conf->certuriregex)
3776 regfree(conf->certuriregex);
3777 free(conf->confrewrite);
3778 free(conf->rewriteattr);
3779 if (conf->rewriteattrregex)
3780 regfree(conf->rewriteattrregex);
3781 free(conf->rewriteattrreplacement);
3782 free(conf->dynamiclookupcommand);
3783 free(conf->rewrite);
3785 freeaddrinfo(conf->addrinfo);
3786 /* not touching ssl_ctx, clients and servers */
3790 int mergeconfstring(char **dst, char **src) {
3799 t = stringcopy(*dst, 0);
3801 debug(DBG_ERR, "malloc failed");
3809 /* assumes dst is a shallow copy */
3810 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3811 if (!mergeconfstring(&dst->name, &src->name) ||
3812 !mergeconfstring(&dst->host, &src->host) ||
3813 !mergeconfstring(&dst->port, &src->port) ||
3814 !mergeconfstring(&dst->secret, &src->secret) ||
3815 !mergeconfstring(&dst->tls, &src->tls) ||
3816 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3817 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3818 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3821 dst->pdef = src->pdef;
3822 dst->statusserver = src->statusserver;
3823 dst->certnamecheck = src->certnamecheck;
3824 if (src->retryinterval != 255)
3825 dst->retryinterval = src->retryinterval;
3826 if (src->retrycount != 255)
3827 dst->retrycount = src->retrycount;
3831 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3832 struct clsrvconf *conf;
3833 char *conftype = NULL;
3835 debug(DBG_DBG, "confclient_cb called for %s", block);
3837 conf = malloc(sizeof(struct clsrvconf));
3838 if (!conf || !list_push(clconfs, conf))
3839 debugx(1, DBG_ERR, "malloc failed");
3840 memset(conf, 0, sizeof(struct clsrvconf));
3841 conf->certnamecheck = 1;
3843 if (!getgenericconfig(cf, block,
3844 "type", CONF_STR, &conftype,
3845 "host", CONF_STR, &conf->host,
3846 "secret", CONF_STR, &conf->secret,
3847 "tls", CONF_STR, &conf->tls,
3848 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3849 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3850 "rewrite", CONF_STR, &conf->confrewrite,
3851 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3854 debugx(1, DBG_ERR, "configuration error");
3856 conf->name = stringcopy(val, 0);
3858 conf->host = stringcopy(val, 0);
3859 if (!conf->name || !conf->host)
3860 debugx(1, DBG_ERR, "malloc failed");
3863 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3864 conf->type = protoname2int(conftype);
3865 conf->pdef = &protodefs[conf->type];
3866 if (!conf->pdef->name)
3867 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3870 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3871 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3873 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3874 if (conf->matchcertattr && !addmatchcertattr(conf))
3875 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3878 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3880 if (conf->rewriteattr) {
3881 if (!addrewriteattr(conf))
3882 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3885 if (!resolvepeer(conf, 0))
3886 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3888 if (!conf->secret) {
3889 if (!conf->pdef->secretdefault)
3890 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3891 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3893 debugx(1, DBG_ERR, "malloc failed");
3898 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3899 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3900 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3901 if (!conf->ssl_ctx) {
3902 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3905 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3906 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3912 conf->port = stringcopy(conf->pdef->portdefault, 0);
3914 debug(DBG_ERR, "malloc failed");
3919 if (conf->retryinterval == 255)
3920 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3921 if (conf->retrycount == 255)
3922 conf->retrycount = protodefs[conf->type].retrycountdefault;
3924 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3926 if (!conf->secret) {
3927 if (!conf->pdef->secretdefault) {
3928 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3931 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3932 if (!conf->secret) {
3933 debug(DBG_ERR, "malloc failed");
3938 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3939 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3945 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3946 struct clsrvconf *conf, *resconf;
3947 char *conftype = NULL;
3948 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3950 debug(DBG_DBG, "confserver_cb called for %s", block);
3952 conf = malloc(sizeof(struct clsrvconf));
3954 debug(DBG_ERR, "malloc failed");
3957 memset(conf, 0, sizeof(struct clsrvconf));
3958 resconf = (struct clsrvconf *)arg;
3960 conf->statusserver = resconf->statusserver;
3961 conf->certnamecheck = resconf->certnamecheck;
3963 conf->certnamecheck = 1;
3965 if (!getgenericconfig(cf, block,
3966 "type", CONF_STR, &conftype,
3967 "host", CONF_STR, &conf->host,
3968 "port", CONF_STR, &conf->port,
3969 "secret", CONF_STR, &conf->secret,
3970 "tls", CONF_STR, &conf->tls,
3971 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3972 "rewrite", CONF_STR, &conf->confrewrite,
3973 "StatusServer", CONF_BLN, &conf->statusserver,
3974 "RetryInterval", CONF_LINT, &retryinterval,
3975 "RetryCount", CONF_LINT, &retrycount,
3976 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3977 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3980 debug(DBG_ERR, "configuration error");
3984 conf->name = stringcopy(val, 0);
3986 debug(DBG_ERR, "malloc failed");
3990 conf->host = stringcopy(val, 0);
3992 debug(DBG_ERR, "malloc failed");
3998 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3999 conf->type = protoname2int(conftype);
4000 conf->pdef = &protodefs[conf->type];
4001 if (!conf->pdef->name) {
4002 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4008 if (retryinterval != LONG_MIN) {
4009 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4010 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4013 conf->retryinterval = (uint8_t)retryinterval;
4015 conf->retryinterval = 255;
4017 if (retrycount != LONG_MIN) {
4018 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4019 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4022 conf->retrycount = (uint8_t)retrycount;
4024 conf->retrycount = 255;
4027 if (!mergesrvconf(resconf, conf))
4031 if (conf->dynamiclookupcommand) {
4032 free(conf->dynamiclookupcommand);
4033 conf->dynamiclookupcommand = NULL;
4037 if (resconf || !conf->dynamiclookupcommand) {
4038 if (!compileserverconfig(conf, block))
4045 if (!list_push(srvconfs, conf)) {
4046 debug(DBG_ERR, "malloc failed");
4052 freeclsrvconf(conf);
4056 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4057 char **servers = NULL, **accservers = NULL, *msg = NULL;
4058 uint8_t accresp = 0;
4060 debug(DBG_DBG, "confrealm_cb called for %s", block);
4062 if (!getgenericconfig(cf, block,
4063 "server", CONF_MSTR, &servers,
4064 "accountingServer", CONF_MSTR, &accservers,
4065 "ReplyMessage", CONF_STR, &msg,
4066 "AccountingResponse", CONF_BLN, &accresp,
4069 debugx(1, DBG_ERR, "configuration error");
4071 addrealm(realms, val, servers, accservers, msg, accresp);
4075 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4078 debug(DBG_DBG, "conftls_cb called for %s", block);
4080 conf = malloc(sizeof(struct tls));
4082 debug(DBG_ERR, "conftls_cb: malloc failed");
4085 memset(conf, 0, sizeof(struct tls));
4087 if (!getgenericconfig(cf, block,
4088 "CACertificateFile", CONF_STR, &conf->cacertfile,
4089 "CACertificatePath", CONF_STR, &conf->cacertpath,
4090 "CertificateFile", CONF_STR, &conf->certfile,
4091 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4092 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4093 "CRLCheck", CONF_BLN, &conf->crlcheck,
4096 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4099 if (!conf->certfile || !conf->certkeyfile) {
4100 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4103 if (!conf->cacertfile && !conf->cacertpath) {
4104 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4108 conf->name = stringcopy(val, 0);
4110 debug(DBG_ERR, "conftls_cb: malloc failed");
4114 pthread_mutex_lock(&tlsconfs_lock);
4115 if (!list_push(tlsconfs, conf)) {
4116 debug(DBG_ERR, "conftls_cb: malloc failed");
4117 pthread_mutex_unlock(&tlsconfs_lock);
4120 pthread_mutex_unlock(&tlsconfs_lock);
4122 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4126 free(conf->cacertfile);
4127 free(conf->cacertpath);
4128 free(conf->certfile);
4129 free(conf->certkeyfile);
4130 free(conf->certkeypwd);
4135 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4136 char **attrs = NULL, **vattrs = NULL;
4138 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4140 if (!getgenericconfig(cf, block,
4141 "removeAttribute", CONF_MSTR, &attrs,
4142 "removeVendorAttribute", CONF_MSTR, &vattrs,
4145 debugx(1, DBG_ERR, "configuration error");
4146 addrewrite(val, attrs, vattrs);
4150 void getmainconfig(const char *configfile) {
4151 long int loglevel = LONG_MIN;
4152 struct gconffile *cfs;
4154 cfs = openconfigfile(configfile);
4155 memset(&options, 0, sizeof(options));
4157 clconfs = list_create();
4159 debugx(1, DBG_ERR, "malloc failed");
4161 srvconfs = list_create();
4163 debugx(1, DBG_ERR, "malloc failed");
4165 realms = list_create();
4167 debugx(1, DBG_ERR, "malloc failed");
4169 tlsconfs = list_create();
4171 debugx(1, DBG_ERR, "malloc failed");
4173 rewriteconfs = list_create();
4175 debugx(1, DBG_ERR, "malloc failed");
4177 if (!getgenericconfig(&cfs, NULL,
4178 "ListenUDP", CONF_MSTR, &options.listenudp,
4179 "ListenTCP", CONF_MSTR, &options.listentcp,
4180 "ListenTLS", CONF_MSTR, &options.listentls,
4181 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4182 "SourceUDP", CONF_STR, &options.sourceudp,
4183 "SourceTCP", CONF_STR, &options.sourcetcp,
4184 "SourceTLS", CONF_STR, &options.sourcetls,
4185 "LogLevel", CONF_LINT, &loglevel,
4186 "LogDestination", CONF_STR, &options.logdestination,
4187 "LoopPrevention", CONF_BLN, &options.loopprevention,
4188 "Client", CONF_CBK, confclient_cb, NULL,
4189 "Server", CONF_CBK, confserver_cb, NULL,
4190 "Realm", CONF_CBK, confrealm_cb, NULL,
4191 "TLS", CONF_CBK, conftls_cb, NULL,
4192 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4195 debugx(1, DBG_ERR, "configuration error");
4197 if (loglevel != LONG_MIN) {
4198 if (loglevel < 1 || loglevel > 4)
4199 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4200 options.loglevel = (uint8_t)loglevel;
4204 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4207 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4210 *configfile = optarg;
4213 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4214 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4215 *loglevel = *optarg - '0';
4224 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4229 if (!(argc - optind))
4233 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4237 int daemon(int a, int b) {
4245 for (i = 0; i < 3; i++) {
4247 open("/dev/null", O_RDWR);
4253 void *sighandler(void *arg) {
4258 sigemptyset(&sigset);
4259 sigaddset(&sigset, SIGPIPE);
4260 sigwait(&sigset, &sig);
4261 /* only get SIGPIPE right now, so could simplify below code */
4264 /* completely ignoring this */
4267 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4270 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4275 int main(int argc, char **argv) {
4276 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
4278 struct list_node *entry;
4279 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4280 char *configfile = NULL;
4281 struct clsrvconf *srvconf;
4283 debug_init("radsecproxy");
4284 debug_set_level(DEBUG_LEVEL);
4285 pthread_mutex_init(&tlsconfs_lock, NULL);
4287 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4289 debug_set_level(loglevel);
4290 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4292 options.loglevel = loglevel;
4293 else if (options.loglevel)
4294 debug_set_level(options.loglevel);
4296 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4297 free(options.logdestination);
4299 if (!list_first(clconfs))
4300 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4301 if (!list_first(srvconfs))
4302 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
4303 if (!list_first(realms))
4304 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4307 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4309 if (!foreground && (daemon(0, 0) < 0))
4310 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4312 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4314 sigemptyset(&sigset);
4315 /* exit on all but SIGPIPE, ignore more? */
4316 sigaddset(&sigset, SIGPIPE);
4317 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4318 pthread_create(&sigth, NULL, sighandler, NULL);
4320 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4321 udp_server_replyq = newreplyq();
4322 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4323 debugx(1, DBG_ERR, "pthread_create failed");
4324 createlisteners(RAD_UDP, options.listenudp);
4325 if (options.listenaccudp)
4326 createlisteners(RAD_UDP, options.listenaccudp);
4329 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4330 srvconf = (struct clsrvconf *)entry->data;
4331 if (srvconf->dynamiclookupcommand)
4333 if (!addserver(srvconf))
4334 debugx(1, DBG_ERR, "failed to add server");
4335 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4336 (void *)(srvconf->servers)))
4337 debugx(1, DBG_ERR, "pthread_create failed");
4339 /* srcprotores for UDP no longer needed */
4340 if (srcprotores[RAD_UDP]) {
4341 freeaddrinfo(srcprotores[RAD_UDP]);
4342 srcprotores[RAD_UDP] = NULL;
4344 if (udp_client4_sock >= 0)
4345 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4346 debugx(1, DBG_ERR, "pthread_create failed");
4347 if (udp_client6_sock >= 0)
4348 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4349 debugx(1, DBG_ERR, "pthread_create failed");
4351 if (find_conf_type(RAD_TCP, clconfs, NULL))
4352 createlisteners(RAD_TCP, options.listentcp);
4354 if (find_conf_type(RAD_TLS, clconfs, NULL))
4355 createlisteners(RAD_TLS, options.listentls);
4357 /* just hang around doing nothing, anything to do here? */