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;
726 cnt = recvfrom(s, buf, 4, MSG_PEEK, (struct sockaddr *)&from, &fromlen);
728 debug(DBG_WARN, "radudpget: recv failed");
734 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
736 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
739 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
741 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
744 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
751 debug(DBG_WARN, "radudpget: length too small");
758 debug(DBG_ERR, "radudpget: malloc failed");
763 cnt = recv(s, rad, len, MSG_TRUNC);
764 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
767 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
773 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
775 if (client && !*client) {
776 node = list_first(p->clients);
777 *client = node ? (struct client *)node->data : addclient(p);
782 } else if (server && !*server)
783 *server = p->servers;
792 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
793 int loc, i, l, n, r = 0;
796 STACK_OF(GENERAL_NAME) *alt;
799 debug(DBG_DBG, "subjectaltnameaddr");
801 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
805 ex = X509_get_ext(cert, loc);
806 alt = X509V3_EXT_d2i(ex);
810 n = sk_GENERAL_NAME_num(alt);
811 for (i = 0; i < n; i++) {
812 gn = sk_GENERAL_NAME_value(alt, i);
813 if (gn->type != GEN_IPADD)
816 v = (char *)ASN1_STRING_data(gn->d.ia5);
817 l = ASN1_STRING_length(gn->d.ia5);
818 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
819 && !memcmp(v, &addr, l)) {
824 GENERAL_NAMES_free(alt);
828 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
835 nm = X509_get_subject_name(cert);
838 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
841 e = X509_NAME_get_entry(nm, loc);
842 t = X509_NAME_ENTRY_get_data(e);
843 v = (char *) ASN1_STRING_data(t);
844 l = ASN1_STRING_length(t);
848 if (l == strlen(exact) && !strncasecmp(exact, v, l))
851 s = stringcopy((char *)v, l);
853 debug(DBG_ERR, "malloc failed");
856 if (regexec(regex, s, 0, NULL, 0)) {
867 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
868 int loc, i, l, n, r = 0;
871 STACK_OF(GENERAL_NAME) *alt;
874 debug(DBG_DBG, "subjectaltnameregexp");
876 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
880 ex = X509_get_ext(cert, loc);
881 alt = X509V3_EXT_d2i(ex);
885 n = sk_GENERAL_NAME_num(alt);
886 for (i = 0; i < n; i++) {
887 gn = sk_GENERAL_NAME_value(alt, i);
888 if (gn->type != type)
891 v = (char *)ASN1_STRING_data(gn->d.ia5);
892 l = ASN1_STRING_length(gn->d.ia5);
896 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
899 if (memcmp(v, exact, l))
902 s = stringcopy((char *)v, l);
904 debug(DBG_ERR, "malloc failed");
907 if (regexec(regex, s, 0, NULL, 0)) {
916 GENERAL_NAMES_free(alt);
920 X509 *verifytlscert(SSL *ssl) {
924 if (SSL_get_verify_result(ssl) != X509_V_OK) {
925 debug(DBG_ERR, "verifytlscert: basic validation failed");
926 while ((error = ERR_get_error()))
927 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
931 cert = SSL_get_peer_certificate(ssl);
933 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
937 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
939 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
940 struct in6_addr addr;
942 if (conf->certnamecheck && conf->prefixlen == 255) {
943 if (inet_pton(AF_INET, conf->host, &addr))
945 else if (inet_pton(AF_INET6, conf->host, &addr))
948 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
951 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
954 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
956 if (!cnregexp(cert, conf->host, NULL)) {
957 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
960 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
963 if (conf->certcnregex) {
964 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
965 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
968 debug(DBG_DBG, "verifyconfcert: CN matching regex");
970 if (conf->certuriregex) {
971 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
972 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
975 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
980 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
985 debug(DBG_DBG, "tlsconnect: called from %s", text);
986 pthread_mutex_lock(&server->lock);
987 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
988 /* already reconnected, nothing to do */
989 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
990 pthread_mutex_unlock(&server->lock);
995 gettimeofday(&now, NULL);
996 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
997 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
998 debug(DBG_DBG, "tlsconnect: timeout");
999 if (server->sock >= 0)
1000 close(server->sock);
1001 SSL_free(server->ssl);
1003 pthread_mutex_unlock(&server->lock);
1006 if (server->connectionok) {
1007 server->connectionok = 0;
1009 } else if (elapsed < 1)
1011 else if (elapsed < 60) {
1012 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
1014 } else if (elapsed < 100000) {
1015 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
1018 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1019 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
1020 if (server->sock >= 0)
1021 close(server->sock);
1022 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
1023 debug(DBG_ERR, "tlsconnect: connecttcp failed");
1027 SSL_free(server->ssl);
1028 server->ssl = SSL_new(server->conf->ssl_ctx);
1029 SSL_set_fd(server->ssl, server->sock);
1030 if (SSL_connect(server->ssl) <= 0)
1032 cert = verifytlscert(server->ssl);
1035 if (verifyconfcert(cert, server->conf)) {
1041 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1042 gettimeofday(&server->lastconnecttry, NULL);
1043 pthread_mutex_unlock(&server->lock);
1047 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1051 debug(DBG_DBG, "tcpconnect: called from %s", text);
1052 pthread_mutex_lock(&server->lock);
1053 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1054 /* already reconnected, nothing to do */
1055 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1056 pthread_mutex_unlock(&server->lock);
1061 gettimeofday(&now, NULL);
1062 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1063 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1064 debug(DBG_DBG, "tcpconnect: timeout");
1065 if (server->sock >= 0)
1066 close(server->sock);
1067 pthread_mutex_unlock(&server->lock);
1070 if (server->connectionok) {
1071 server->connectionok = 0;
1073 } else if (elapsed < 1)
1075 else if (elapsed < 60) {
1076 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1078 } else if (elapsed < 100000) {
1079 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1082 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1083 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1084 if (server->sock >= 0)
1085 close(server->sock);
1086 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1088 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1090 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1091 gettimeofday(&server->lastconnecttry, NULL);
1092 pthread_mutex_unlock(&server->lock);
1096 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1097 /* returns 0 on timeout, -1 on error and num if ok */
1098 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1099 int s, ndesc, cnt, len;
1100 fd_set readfds, writefds;
1101 struct timeval timer;
1103 s = SSL_get_fd(ssl);
1106 /* make socket non-blocking? */
1107 for (len = 0; len < num; len += cnt) {
1109 FD_SET(s, &readfds);
1112 timer.tv_sec = timeout;
1115 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1119 cnt = SSL_read(ssl, buf + len, num - len);
1121 switch (SSL_get_error(ssl, cnt)) {
1122 case SSL_ERROR_WANT_READ:
1123 case SSL_ERROR_WANT_WRITE:
1126 case SSL_ERROR_ZERO_RETURN:
1127 /* remote end sent close_notify, send one back */
1137 /* timeout in seconds, 0 means no timeout (blocking) */
1138 unsigned char *radtlsget(SSL *ssl, int timeout) {
1140 unsigned char buf[4], *rad;
1143 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1145 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1152 debug(DBG_ERR, "radtlsget: malloc failed");
1155 memcpy(rad, buf, 4);
1157 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1159 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1168 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1171 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1175 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1176 /* returns 0 on timeout, -1 on error and num if ok */
1177 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1178 int ndesc, cnt, len;
1179 fd_set readfds, writefds;
1180 struct timeval timer;
1184 /* make socket non-blocking? */
1185 for (len = 0; len < num; len += cnt) {
1187 FD_SET(s, &readfds);
1190 timer.tv_sec = timeout;
1193 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1197 cnt = read(s, buf + len, num - len);
1204 /* timeout in seconds, 0 means no timeout (blocking) */
1205 unsigned char *radtcpget(int s, int timeout) {
1207 unsigned char buf[4], *rad;
1210 cnt = tcpreadtimeout(s, buf, 4, timeout);
1212 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1219 debug(DBG_ERR, "radtcpget: malloc failed");
1222 memcpy(rad, buf, 4);
1224 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1226 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1235 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1238 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1242 int clientradputudp(struct server *server, unsigned char *rad) {
1244 struct sockaddr_storage sa;
1245 struct sockaddr *sap;
1246 struct clsrvconf *conf = server->conf;
1247 in_port_t *port = NULL;
1251 if (*rad == RAD_Accounting_Request) {
1252 sap = (struct sockaddr *)&sa;
1253 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1255 sap = conf->addrinfo->ai_addr;
1257 switch (sap->sa_family) {
1259 port = &((struct sockaddr_in *)sap)->sin_port;
1262 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1268 if (*rad == RAD_Accounting_Request)
1269 *port = htons(ntohs(*port) + 1);
1271 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1272 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1276 debug(DBG_WARN, "clientradputudp: send failed");
1280 int clientradputtls(struct server *server, unsigned char *rad) {
1283 unsigned long error;
1284 struct timeval lastconnecttry;
1285 struct clsrvconf *conf = server->conf;
1288 lastconnecttry = server->lastconnecttry;
1289 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1290 while ((error = ERR_get_error()))
1291 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1292 if (server->dynamiclookuparg)
1294 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1295 lastconnecttry = server->lastconnecttry;
1298 server->connectionok = 1;
1299 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1303 int clientradputtcp(struct server *server, unsigned char *rad) {
1306 struct timeval lastconnecttry;
1307 struct clsrvconf *conf = server->conf;
1310 lastconnecttry = server->lastconnecttry;
1311 while ((cnt = write(server->sock, rad, len)) <= 0) {
1312 debug(DBG_ERR, "clientradputtcp: write error");
1313 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1314 lastconnecttry = server->lastconnecttry;
1317 server->connectionok = 1;
1318 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1322 int radsign(unsigned char *rad, unsigned char *sec) {
1323 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1324 static unsigned char first = 1;
1325 static EVP_MD_CTX mdctx;
1326 unsigned int md_len;
1329 pthread_mutex_lock(&lock);
1331 EVP_MD_CTX_init(&mdctx);
1335 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1336 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1337 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1338 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1340 pthread_mutex_unlock(&lock);
1344 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1345 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1346 static unsigned char first = 1;
1347 static EVP_MD_CTX mdctx;
1348 unsigned char hash[EVP_MAX_MD_SIZE];
1352 pthread_mutex_lock(&lock);
1354 EVP_MD_CTX_init(&mdctx);
1360 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1361 EVP_DigestUpdate(&mdctx, rad, 4) &&
1362 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1363 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1364 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1365 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1367 !memcmp(hash, rad + 4, 16));
1368 pthread_mutex_unlock(&lock);
1372 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1373 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1374 static unsigned char first = 1;
1375 static HMAC_CTX hmacctx;
1376 unsigned int md_len;
1377 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1379 pthread_mutex_lock(&lock);
1381 HMAC_CTX_init(&hmacctx);
1385 memcpy(auth, authattr, 16);
1386 memset(authattr, 0, 16);
1388 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1389 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1390 HMAC_Final(&hmacctx, hash, &md_len);
1391 memcpy(authattr, auth, 16);
1393 debug(DBG_WARN, "message auth computation failed");
1394 pthread_mutex_unlock(&lock);
1398 if (memcmp(auth, hash, 16)) {
1399 debug(DBG_WARN, "message authenticator, wrong value");
1400 pthread_mutex_unlock(&lock);
1404 pthread_mutex_unlock(&lock);
1408 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1409 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1410 static unsigned char first = 1;
1411 static HMAC_CTX hmacctx;
1412 unsigned int md_len;
1417 pthread_mutex_lock(&lock);
1419 HMAC_CTX_init(&hmacctx);
1423 memset(authattrval, 0, 16);
1425 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1426 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1427 HMAC_Final(&hmacctx, authattrval, &md_len);
1429 debug(DBG_WARN, "message auth computation failed");
1430 pthread_mutex_unlock(&lock);
1434 pthread_mutex_unlock(&lock);
1438 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1439 while (length > 1) {
1440 if (ATTRTYPE(attrs) == type)
1442 length -= ATTRLEN(attrs);
1443 attrs += ATTRLEN(attrs);
1448 void freerqdata(struct request *rq) {
1449 if (rq->origusername)
1450 free(rq->origusername);
1455 void sendrq(struct server *to, struct request *rq) {
1459 pthread_mutex_lock(&to->newrq_mutex);
1460 /* might simplify if only try nextid, might be ok */
1461 for (i = to->nextid; i < MAX_REQUESTS; i++)
1462 if (!to->requests[i].buf)
1464 if (i == MAX_REQUESTS) {
1465 for (i = 0; i < to->nextid; i++)
1466 if (!to->requests[i].buf)
1468 if (i == to->nextid) {
1469 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1475 rq->buf[1] = (char)i;
1477 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1478 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1483 if (*rq->buf == RAD_Accounting_Request) {
1484 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1485 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1491 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1492 to->requests[i] = *rq;
1497 debug(DBG_DBG, "sendrq: signalling client writer");
1498 pthread_cond_signal(&to->newrq_cond);
1501 pthread_mutex_unlock(&to->newrq_mutex);
1504 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1505 struct reply *reply;
1508 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1510 debug(DBG_WARN, "sendreply: failed to sign message");
1514 reply = malloc(sizeof(struct reply));
1517 debug(DBG_ERR, "sendreply: malloc failed");
1520 memset(reply, 0, sizeof(struct reply));
1523 reply->tosa = *tosa;
1524 reply->toudpsock = toudpsock;
1526 pthread_mutex_lock(&to->replyq->mutex);
1528 first = list_first(to->replyq->replies) == NULL;
1530 if (!list_push(to->replyq->replies, reply)) {
1531 pthread_mutex_unlock(&to->replyq->mutex);
1534 debug(DBG_ERR, "sendreply: malloc failed");
1539 debug(DBG_DBG, "signalling server writer");
1540 pthread_cond_signal(&to->replyq->cond);
1542 pthread_mutex_unlock(&to->replyq->mutex);
1545 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1546 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1547 static unsigned char first = 1;
1548 static EVP_MD_CTX mdctx;
1549 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1550 unsigned int md_len;
1551 uint8_t i, offset = 0, out[128];
1553 pthread_mutex_lock(&lock);
1555 EVP_MD_CTX_init(&mdctx);
1561 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1562 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1563 !EVP_DigestUpdate(&mdctx, input, 16) ||
1564 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1566 pthread_mutex_unlock(&lock);
1569 for (i = 0; i < 16; i++)
1570 out[offset + i] = hash[i] ^ in[offset + i];
1571 input = out + offset - 16;
1576 memcpy(in, out, len);
1577 pthread_mutex_unlock(&lock);
1581 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1582 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1583 static unsigned char first = 1;
1584 static EVP_MD_CTX mdctx;
1585 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1586 unsigned int md_len;
1587 uint8_t i, offset = 0, out[128];
1589 pthread_mutex_lock(&lock);
1591 EVP_MD_CTX_init(&mdctx);
1597 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1598 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1599 !EVP_DigestUpdate(&mdctx, input, 16) ||
1600 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1602 pthread_mutex_unlock(&lock);
1605 for (i = 0; i < 16; i++)
1606 out[offset + i] = hash[i] ^ in[offset + i];
1607 input = in + offset;
1612 memcpy(in, out, len);
1613 pthread_mutex_unlock(&lock);
1617 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1618 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1619 static unsigned char first = 1;
1620 static EVP_MD_CTX mdctx;
1621 unsigned char hash[EVP_MAX_MD_SIZE];
1622 unsigned int md_len;
1625 pthread_mutex_lock(&lock);
1627 EVP_MD_CTX_init(&mdctx);
1632 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1633 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1634 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1637 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1638 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1639 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1640 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1641 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1642 pthread_mutex_unlock(&lock);
1647 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1650 for (i = 0; i < 16; i++)
1653 for (offset = 16; offset < len; offset += 16) {
1655 printf("text + offset - 16 c(%d): ", offset / 16);
1656 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1658 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1659 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1660 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1661 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1663 pthread_mutex_unlock(&lock);
1667 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1670 for (i = 0; i < 16; i++)
1671 text[offset + i] ^= hash[i];
1675 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1678 pthread_mutex_unlock(&lock);
1682 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1683 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1684 static unsigned char first = 1;
1685 static EVP_MD_CTX mdctx;
1686 unsigned char hash[EVP_MAX_MD_SIZE];
1687 unsigned int md_len;
1691 pthread_mutex_lock(&lock);
1693 EVP_MD_CTX_init(&mdctx);
1698 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1699 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1700 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1703 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1704 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1705 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1706 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1707 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1708 pthread_mutex_unlock(&lock);
1713 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1716 for (i = 0; i < 16; i++)
1717 plain[i] = text[i] ^ hash[i];
1719 for (offset = 16; offset < len; offset += 16) {
1721 printf("text + offset - 16 c(%d): ", offset / 16);
1722 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1724 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1725 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1726 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1727 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1729 pthread_mutex_unlock(&lock);
1733 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1736 for (i = 0; i < 16; i++)
1737 plain[offset + i] = text[offset + i] ^ hash[i];
1740 memcpy(text, plain, len);
1742 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1745 pthread_mutex_unlock(&lock);
1749 struct realm *id2realm(struct list *realmlist, char *id) {
1750 struct list_node *entry;
1751 struct realm *realm, *subrealm = NULL;
1753 /* need to do locking for subrealms and check subrealm timers */
1754 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1755 realm = (struct realm *)entry->data;
1756 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1757 pthread_mutex_lock(&realm->subrealms_mutex);
1758 if (realm->subrealms)
1759 subrealm = id2realm(realm->subrealms, id);
1760 pthread_mutex_unlock(&realm->subrealms_mutex);
1761 return subrealm ? subrealm : realm;
1767 /* helper function, only used by removeserversubrealms() */
1768 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1769 struct list_node *entry;
1770 struct realm *realm;
1772 for (entry = list_first(realmlist); entry;) {
1773 realm = (struct realm *)entry->data;
1774 entry = list_next(entry);
1775 if (realm->srvconfs) {
1776 list_removedata(realm->srvconfs, srv);
1777 if (!list_first(realm->srvconfs)) {
1778 list_destroy(realm->srvconfs);
1779 realm->srvconfs = NULL;
1782 if (realm->accsrvconfs) {
1783 list_removedata(realm->accsrvconfs, srv);
1784 if (!list_first(realm->accsrvconfs)) {
1785 list_destroy(realm->accsrvconfs);
1786 realm->accsrvconfs = NULL;
1790 /* remove subrealm if no servers */
1791 if (!realm->srvconfs && !realm->accsrvconfs) {
1792 list_removedata(realmlist, realm);
1798 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1799 struct list_node *entry;
1800 struct realm *realm;
1802 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1803 realm = (struct realm *)entry->data;
1804 pthread_mutex_lock(&realm->subrealms_mutex);
1805 if (realm->subrealms) {
1806 _internal_removeserversubrealms(realm->subrealms, srv);
1807 if (!list_first(realm->subrealms)) {
1808 list_destroy(realm->subrealms);
1809 realm->subrealms = NULL;
1812 pthread_mutex_unlock(&realm->subrealms_mutex);
1816 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1817 struct request *rq = to->requests, *end;
1819 pthread_mutex_lock(&to->newrq_mutex);
1820 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1821 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1823 pthread_mutex_unlock(&to->newrq_mutex);
1828 int attrvalidate(unsigned char *attrs, int length) {
1829 while (length > 1) {
1830 if (ATTRLEN(attrs) < 2) {
1831 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1834 length -= ATTRLEN(attrs);
1836 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1839 attrs += ATTRLEN(attrs);
1842 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1846 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1847 if (len < 16 || len > 128 || len % 16) {
1848 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1852 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1853 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1857 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1859 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1860 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1866 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1869 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1870 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1873 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1874 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1880 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1881 char *oldsecret, char *newsecret) {
1882 unsigned char *attr;
1884 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1885 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1886 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1892 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1896 for (; attrs[0]; attrs += 2)
1897 if (attrs[0] == vendor && attrs[1] == subattr)
1902 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1903 uint8_t alen, sublen, rmlen = 0;
1904 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1907 if (!removevendorattrs)
1910 while (*removevendorattrs && *removevendorattrs != vendor)
1911 removevendorattrs += 2;
1912 if (!*removevendorattrs)
1915 alen = ATTRLEN(attrs);
1917 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1918 /* remove entire vendor attribute */
1919 memmove(attrs, attrs + alen, length - alen);
1924 subattrs = ATTRVAL(attrs) + 4;
1926 if (!attrvalidate(subattrs, sublen)) {
1927 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1932 while (sublen > 1) {
1933 alen = ATTRLEN(subattrs);
1936 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1937 memmove(subattrs, subattrs + alen, length);
1943 ATTRLEN(attrs) -= rmlen;
1947 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1948 uint8_t *attrs, alen;
1949 uint16_t len, rmlen = 0;
1951 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1954 len = RADLEN(buf) - 20;
1957 alen = ATTRLEN(attrs);
1959 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1960 memmove(attrs, attrs + alen, len);
1962 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1963 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1968 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1971 /* returns a pointer to the resized attribute value */
1972 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1973 uint8_t *attrs, *attr, vallen;
1977 len = RADLEN(*buf) - 20;
1980 attr = attrget(attrs, len, type);
1984 vallen = ATTRVALLEN(attr);
1985 if (vallen == newvallen)
1988 len += newvallen - vallen;
1989 if (newvallen > vallen) {
1990 new = realloc(*buf, len + 20);
1992 debug(DBG_ERR, "resizeattr: malloc failed");
2001 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
2002 attr[1] = newvallen + 2;
2003 ((uint16_t *)*buf)[1] = htons(len + 20);
2007 int rewriteusername(struct request *rq, char *in) {
2008 size_t nmatch = 10, reslen = 0, start = 0;
2009 regmatch_t pmatch[10], *pfield;
2011 unsigned char *result;
2012 char *out = rq->from->conf->rewriteattrreplacement;
2014 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2015 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2019 rq->origusername = stringcopy(in, 0);
2020 if (!rq->origusername)
2023 for (i = start; out[i]; i++) {
2024 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2025 pfield = &pmatch[out[i + 1] - '0'];
2026 if (pfield->rm_so >= 0) {
2027 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2033 reslen += i - start;
2035 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2041 for (i = start; out[i]; i++) {
2042 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2043 pfield = &pmatch[out[i + 1] - '0'];
2044 if (pfield->rm_so >= 0) {
2045 memcpy(result + reslen, out + start, i - start);
2046 reslen += i - start;
2047 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2048 reslen += pfield->rm_eo - pfield->rm_so;
2055 memcpy(result + reslen, out + start, i - start);
2056 reslen += i - start;
2057 memcpy(in, result, reslen);
2062 const char *radmsgtype2string(uint8_t code) {
2063 static const char *rad_msg_names[] = {
2064 "", "Access-Request", "Access-Accept", "Access-Reject",
2065 "Accounting-Request", "Accounting-Response", "", "",
2066 "", "", "", "Access-Challenge",
2067 "Status-Server", "Status-Client"
2069 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2072 void char2hex(char *h, unsigned char c) {
2073 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2074 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2075 h[0] = hexdigits[c / 16];
2076 h[1] = hexdigits[c % 16];
2080 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2084 if (!attr || len == 1) {
2089 l = ATTRVALLEN(attr);
2090 s = (char *)ATTRVAL(attr);
2093 for (i = 0; i < l; i++) {
2094 if (s[i] > 31 && s[i] < 127) {
2096 if (d - ascii == len - 1)
2099 if (d - ascii > len - 4)
2104 if (d - ascii == len - 1)
2112 void acclog(unsigned char *attrs, int length, char *host) {
2113 unsigned char *attr;
2116 attr = attrget(attrs, length, RAD_Attr_User_Name);
2118 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2121 radattr2ascii(username, sizeof(username), attr);
2122 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2125 void respondaccounting(struct request *rq) {
2126 unsigned char *resp;
2130 debug(DBG_ERR, "respondaccounting: malloc failed");
2133 memcpy(resp, rq->buf, 20);
2134 resp[0] = RAD_Accounting_Response;
2137 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2138 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2141 void respondstatusserver(struct request *rq) {
2142 unsigned char *resp;
2146 debug(DBG_ERR, "respondstatusserver: malloc failed");
2149 memcpy(resp, rq->buf, 20);
2150 resp[0] = RAD_Access_Accept;
2153 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2154 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2157 void respondreject(struct request *rq, char *message) {
2158 unsigned char *resp;
2161 if (message && *message)
2162 len += 2 + strlen(message);
2166 debug(DBG_ERR, "respondreject: malloc failed");
2169 memcpy(resp, rq->buf, 20);
2170 resp[0] = RAD_Access_Reject;
2171 *(uint16_t *)(resp + 2) = htons(len);
2172 if (message && *message) {
2173 resp[20] = RAD_Attr_Reply_Message;
2174 resp[21] = len - 20;
2175 memcpy(resp + 22, message, len - 22);
2177 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2180 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2181 struct list_node *entry;
2182 struct clsrvconf *server, *best = NULL, *first = NULL;
2184 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2185 server = (struct clsrvconf *)entry->data;
2186 if (!server->servers)
2190 if (!server->servers->connectionok)
2192 if (!server->servers->lostrqs)
2198 if (server->servers->lostrqs < best->servers->lostrqs)
2201 return best ? best : first;
2204 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2205 struct clsrvconf *srvconf;
2207 *realm = id2realm(realms, id);
2210 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2211 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2214 if (!acc && !srvconf->servers)
2215 adddynamicrealmserver(*realm, srvconf, id);
2216 return srvconf->servers;
2219 /* returns 0 if validation/authentication fails, else 1 */
2220 int radsrv(struct request *rq) {
2221 uint8_t code, id, *auth, *attrs, *attr;
2223 struct server *to = NULL;
2224 char username[254], userascii[760];
2225 unsigned char newauth[16];
2226 struct realm *realm = NULL;
2228 code = *(uint8_t *)rq->buf;
2229 id = *(uint8_t *)(rq->buf + 1);
2230 len = RADLEN(rq->buf);
2231 auth = (uint8_t *)(rq->buf + 4);
2233 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2235 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2236 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2241 attrs = rq->buf + 20;
2243 if (!attrvalidate(attrs, len)) {
2244 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2248 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2249 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2250 debug(DBG_WARN, "radsrv: message authentication failed");
2254 if (code == RAD_Status_Server) {
2255 respondstatusserver(rq);
2259 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2261 if (code == RAD_Accounting_Request) {
2262 memset(newauth, 0, 16);
2263 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2264 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2269 if (rq->from->conf->rewrite) {
2270 dorewrite(rq->buf, rq->from->conf->rewrite);
2271 len = RADLEN(rq->buf) - 20;
2274 attr = attrget(attrs, len, RAD_Attr_User_Name);
2276 if (code == RAD_Accounting_Request) {
2277 acclog(attrs, len, rq->from->conf->host);
2278 respondaccounting(rq);
2280 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2283 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2284 username[ATTRVALLEN(attr)] = '\0';
2285 radattr2ascii(userascii, sizeof(userascii), attr);
2287 if (rq->from->conf->rewriteattrregex) {
2288 if (!rewriteusername(rq, username)) {
2289 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2292 len = RADLEN(rq->buf) - 20;
2293 auth = (uint8_t *)(rq->buf + 4);
2294 attrs = rq->buf + 20;
2297 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2299 to = findserver(&realm, username, code == RAD_Accounting_Request);
2301 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2305 if (realm->message && code == RAD_Access_Request) {
2306 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2307 respondreject(rq, realm->message);
2308 } else if (realm->accresp && code == RAD_Accounting_Request) {
2309 acclog(attrs, len, rq->from->conf->host);
2310 respondaccounting(rq);
2315 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2316 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2317 rq->from->conf->name, to->conf->name);
2321 if (rqinqueue(to, rq->from, id, code)) {
2322 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2323 radmsgtype2string(code), rq->from->conf->host, id);
2327 if (code != RAD_Accounting_Request) {
2328 if (!RAND_bytes(newauth, 16)) {
2329 debug(DBG_WARN, "radsrv: failed to generate random auth");
2335 printfchars(NULL, "auth", "%02x ", auth, 16);
2338 attr = attrget(attrs, len, RAD_Attr_User_Password);
2340 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2341 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2345 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2347 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2348 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2353 memcpy(rq->origauth, auth, 16);
2354 memcpy(auth, newauth, 16);
2367 int replyh(struct server *server, unsigned char *buf) {
2368 struct client *from;
2371 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2372 struct sockaddr_storage fromsa;
2373 char tmp[760], stationid[760];
2375 server->connectionok = 1;
2376 server->lostrqs = 0;
2378 i = buf[1]; /* i is the id */
2380 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2381 && *buf != RAD_Accounting_Response) {
2382 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2385 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2387 rq = server->requests + i;
2389 pthread_mutex_lock(&server->newrq_mutex);
2390 if (!rq->buf || !rq->tries) {
2391 pthread_mutex_unlock(&server->newrq_mutex);
2392 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2397 pthread_mutex_unlock(&server->newrq_mutex);
2398 debug(DBG_INFO, "replyh: already received, ignoring reply");
2402 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2403 pthread_mutex_unlock(&server->newrq_mutex);
2404 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2408 len = RADLEN(buf) - 20;
2411 if (!attrvalidate(attrs, len)) {
2412 pthread_mutex_unlock(&server->newrq_mutex);
2413 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2417 /* Message Authenticator */
2418 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2420 if (ATTRVALLEN(messageauth) != 16) {
2421 pthread_mutex_unlock(&server->newrq_mutex);
2422 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2425 memcpy(tmp, buf + 4, 16);
2426 memcpy(buf + 4, rq->buf + 4, 16);
2427 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2428 pthread_mutex_unlock(&server->newrq_mutex);
2429 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2432 memcpy(buf + 4, tmp, 16);
2433 debug(DBG_DBG, "replyh: message auth ok");
2436 gettimeofday(&server->lastrcv, NULL);
2438 if (*rq->buf == RAD_Status_Server) {
2440 pthread_mutex_unlock(&server->newrq_mutex);
2441 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2445 gettimeofday(&server->lastreply, NULL);
2449 pthread_mutex_unlock(&server->newrq_mutex);
2450 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2454 if (server->conf->rewrite) {
2455 dorewrite(buf, server->conf->rewrite);
2456 len = RADLEN(buf) - 20;
2460 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2461 if (ATTRVALLEN(attr) <= 4)
2464 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2467 sublen = ATTRVALLEN(attr) - 4;
2468 subattrs = ATTRVAL(attr) + 4;
2469 if (!attrvalidate(subattrs, sublen) ||
2470 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2471 rq, server->conf->secret, from->conf->secret) ||
2472 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2473 rq, server->conf->secret, from->conf->secret))
2477 pthread_mutex_unlock(&server->newrq_mutex);
2478 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2482 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2483 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2485 radattr2ascii(tmp, sizeof(tmp), attr);
2486 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2488 radattr2ascii(stationid, sizeof(stationid), attr);
2489 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2490 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2492 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2496 buf[1] = (char)rq->origid;
2497 memcpy(buf + 4, rq->origauth, 16);
2499 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2502 if (rq->origusername) {
2503 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2505 pthread_mutex_unlock(&server->newrq_mutex);
2506 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2509 memcpy(username, rq->origusername, strlen(rq->origusername));
2510 len = RADLEN(buf) - 20;
2513 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2517 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2518 pthread_mutex_unlock(&server->newrq_mutex);
2519 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2522 debug(DBG_DBG, "replyh: computed messageauthattr");
2525 fromsa = rq->fromsa; /* only needed for UDP */
2526 /* once we set received = 1, rq may be reused */
2529 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2530 sendreply(from, buf, &fromsa, rq->fromudpsock);
2531 pthread_mutex_unlock(&server->newrq_mutex);
2535 void *udpclientrd(void *arg) {
2536 struct server *server;
2538 int *s = (int *)arg;
2542 buf = radudpget(*s, NULL, &server, NULL);
2543 if (!replyh(server, buf))
2548 void *tlsclientrd(void *arg) {
2549 struct server *server = (struct server *)arg;
2551 struct timeval now, lastconnecttry;
2554 /* yes, lastconnecttry is really necessary */
2555 lastconnecttry = server->lastconnecttry;
2556 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2558 if (server->dynamiclookuparg)
2560 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2564 if (!replyh(server, buf))
2566 if (server->dynamiclookuparg) {
2567 gettimeofday(&now, NULL);
2568 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2569 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2574 ERR_remove_state(0);
2575 server->clientrdgone = 1;
2579 void *tcpclientrd(void *arg) {
2580 struct server *server = (struct server *)arg;
2582 struct timeval lastconnecttry;
2585 /* yes, lastconnecttry is really necessary */
2586 lastconnecttry = server->lastconnecttry;
2587 buf = radtcpget(server->sock, 0);
2589 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2593 if (!replyh(server, buf))
2596 server->clientrdgone = 1;
2600 /* code for removing state not finished */
2601 void *clientwr(void *arg) {
2602 struct server *server = (struct server *)arg;
2604 pthread_t clientrdth;
2605 int i, dynconffail = 0;
2608 struct timespec timeout;
2609 struct request statsrvrq;
2610 unsigned char statsrvbuf[38];
2611 struct clsrvconf *conf;
2613 conf = server->conf;
2615 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2620 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2621 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2625 memset(&timeout, 0, sizeof(struct timespec));
2627 if (conf->statusserver) {
2628 memset(&statsrvrq, 0, sizeof(struct request));
2629 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2630 statsrvbuf[0] = RAD_Status_Server;
2632 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2633 statsrvbuf[21] = 18;
2634 gettimeofday(&server->lastrcv, NULL);
2637 if (conf->pdef->connecter) {
2638 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2640 server->connectionok = 1;
2641 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2642 debug(DBG_ERR, "clientwr: pthread_create failed");
2646 server->connectionok = 1;
2649 pthread_mutex_lock(&server->newrq_mutex);
2650 if (!server->newrq) {
2651 gettimeofday(&now, NULL);
2652 /* random 0-7 seconds */
2653 RAND_bytes(&rnd, 1);
2655 if (conf->statusserver) {
2656 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2657 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2659 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2660 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2663 if (timeout.tv_sec > now.tv_sec)
2664 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2666 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2669 if (server->newrq) {
2670 debug(DBG_DBG, "clientwr: got new request");
2675 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2677 pthread_mutex_unlock(&server->newrq_mutex);
2679 for (i = 0; i < MAX_REQUESTS; i++) {
2680 if (server->clientrdgone) {
2681 pthread_join(clientrdth, NULL);
2684 pthread_mutex_lock(&server->newrq_mutex);
2685 while (i < MAX_REQUESTS && !server->requests[i].buf)
2687 if (i == MAX_REQUESTS) {
2688 pthread_mutex_unlock(&server->newrq_mutex);
2691 rq = server->requests + i;
2694 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2696 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2698 /* setting this to NULL means that it can be reused */
2701 pthread_mutex_unlock(&server->newrq_mutex);
2705 gettimeofday(&now, NULL);
2706 if (now.tv_sec < rq->expiry.tv_sec) {
2707 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2708 timeout.tv_sec = rq->expiry.tv_sec;
2709 pthread_mutex_unlock(&server->newrq_mutex);
2713 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2714 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2715 if (conf->statusserver) {
2716 if (*rq->buf == RAD_Status_Server) {
2717 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2718 if (server->lostrqs < 255)
2722 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2723 if (server->lostrqs < 255)
2727 /* setting this to NULL means that it can be reused */
2729 pthread_mutex_unlock(&server->newrq_mutex);
2732 pthread_mutex_unlock(&server->newrq_mutex);
2734 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2735 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2736 timeout.tv_sec = rq->expiry.tv_sec;
2738 conf->pdef->clientradput(server, server->requests[i].buf);
2740 if (conf->statusserver) {
2741 gettimeofday(&now, NULL);
2742 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2743 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2744 debug(DBG_WARN, "clientwr: failed to generate random auth");
2747 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2748 if (!statsrvrq.buf) {
2749 debug(DBG_ERR, "clientwr: malloc failed");
2752 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2753 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2754 sendrq(server, &statsrvrq);
2759 conf->servers = NULL;
2760 if (server->dynamiclookuparg) {
2761 removeserversubrealms(realms, conf);
2765 freeclsrvconf(conf);
2767 freeserver(server, 1);
2768 ERR_remove_state(0);
2772 void *udpserverwr(void *arg) {
2773 struct replyq *replyq = udp_server_replyq;
2774 struct reply *reply;
2777 pthread_mutex_lock(&replyq->mutex);
2778 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2779 debug(DBG_DBG, "udp server writer, waiting for signal");
2780 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2781 debug(DBG_DBG, "udp server writer, got signal");
2783 pthread_mutex_unlock(&replyq->mutex);
2785 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2786 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2787 debug(DBG_WARN, "sendudp: send failed");
2793 void *udpserverrd(void *arg) {
2795 int *sp = (int *)arg;
2798 memset(&rq, 0, sizeof(struct request));
2799 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2800 rq.fromudpsock = *sp;
2806 void *tlsserverwr(void *arg) {
2808 unsigned long error;
2809 struct client *client = (struct client *)arg;
2810 struct replyq *replyq;
2811 struct reply *reply;
2813 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2814 replyq = client->replyq;
2816 pthread_mutex_lock(&replyq->mutex);
2817 while (!list_first(replyq->replies)) {
2819 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2820 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2821 debug(DBG_DBG, "tlsserverwr: got signal");
2824 /* ssl might have changed while waiting */
2825 pthread_mutex_unlock(&replyq->mutex);
2826 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2827 ERR_remove_state(0);
2831 reply = (struct reply *)list_shift(replyq->replies);
2832 pthread_mutex_unlock(&replyq->mutex);
2833 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2835 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2836 cnt, RADLEN(reply->buf));
2838 while ((error = ERR_get_error()))
2839 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2845 void tlsserverrd(struct client *client) {
2847 pthread_t tlsserverwrth;
2849 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2851 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2852 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2857 memset(&rq, 0, sizeof(struct request));
2858 rq.buf = radtlsget(client->ssl, 0);
2860 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2863 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2866 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2871 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2873 pthread_mutex_lock(&client->replyq->mutex);
2874 pthread_cond_signal(&client->replyq->cond);
2875 pthread_mutex_unlock(&client->replyq->mutex);
2876 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2877 pthread_join(tlsserverwrth, NULL);
2878 removeclientrqs(client);
2879 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2882 void *tlsservernew(void *arg) {
2884 struct sockaddr_storage from;
2885 size_t fromlen = sizeof(from);
2886 struct clsrvconf *conf;
2887 struct list_node *cur = NULL;
2890 unsigned long error;
2891 struct client *client;
2894 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2895 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2898 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2900 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2902 ssl = SSL_new(conf->ssl_ctx);
2905 if (SSL_accept(ssl) <= 0) {
2906 while ((error = ERR_get_error()))
2907 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2908 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2911 cert = verifytlscert(ssl);
2917 if (verifyconfcert(cert, conf)) {
2919 client = addclient(conf);
2922 tlsserverrd(client);
2923 removeclient(client);
2925 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2928 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2930 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2936 ERR_remove_state(0);
2937 shutdown(s, SHUT_RDWR);
2942 void *tlslistener(void *arg) {
2943 pthread_t tlsserverth;
2944 int s, *sp = (int *)arg;
2945 struct sockaddr_storage from;
2946 size_t fromlen = sizeof(from);
2951 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2953 debug(DBG_WARN, "accept failed");
2956 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2957 debug(DBG_ERR, "tlslistener: pthread_create failed");
2958 shutdown(s, SHUT_RDWR);
2962 pthread_detach(tlsserverth);
2968 void *tcpserverwr(void *arg) {
2970 struct client *client = (struct client *)arg;
2971 struct replyq *replyq;
2972 struct reply *reply;
2974 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2975 replyq = client->replyq;
2977 pthread_mutex_lock(&replyq->mutex);
2978 while (!list_first(replyq->replies)) {
2979 if (client->s >= 0) {
2980 debug(DBG_DBG, "tcpserverwr: waiting for signal");
2981 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2982 debug(DBG_DBG, "tcpserverwr: got signal");
2984 if (client->s < 0) {
2985 /* s might have changed while waiting */
2986 pthread_mutex_unlock(&replyq->mutex);
2987 debug(DBG_DBG, "tcpserverwr: exiting as requested");
2991 reply = (struct reply *)list_shift(replyq->replies);
2992 pthread_mutex_unlock(&replyq->mutex);
2993 cnt = write(client->s, reply->buf, RADLEN(reply->buf));
2995 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
2996 cnt, RADLEN(reply->buf));
2998 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3004 void tcpserverrd(struct client *client) {
3006 pthread_t tcpserverwrth;
3008 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3010 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3011 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3016 memset(&rq, 0, sizeof(struct request));
3017 rq.buf = radtcpget(client->s, 0);
3019 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3022 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3025 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3030 /* stop writer by setting s to -1 and give signal in case waiting for data */
3032 pthread_mutex_lock(&client->replyq->mutex);
3033 pthread_cond_signal(&client->replyq->cond);
3034 pthread_mutex_unlock(&client->replyq->mutex);
3035 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3036 pthread_join(tcpserverwrth, NULL);
3037 removeclientrqs(client);
3038 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3041 void *tcpservernew(void *arg) {
3043 struct sockaddr_storage from;
3044 size_t fromlen = sizeof(from);
3045 struct clsrvconf *conf;
3046 struct client *client;
3049 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3050 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3053 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3055 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3057 client = addclient(conf);
3060 tcpserverrd(client);
3061 removeclient(client);
3063 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3065 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3068 shutdown(s, SHUT_RDWR);
3073 void *tcplistener(void *arg) {
3074 pthread_t tcpserverth;
3075 int s, *sp = (int *)arg;
3076 struct sockaddr_storage from;
3077 size_t fromlen = sizeof(from);
3082 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3084 debug(DBG_WARN, "accept failed");
3087 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3088 debug(DBG_ERR, "tcplistener: pthread_create failed");
3089 shutdown(s, SHUT_RDWR);
3093 pthread_detach(tcpserverth);
3099 void createlistener(uint8_t type, char *arg) {
3101 struct clsrvconf *listenres;
3102 struct addrinfo *res;
3103 int s = -1, on = 1, *sp = NULL;
3105 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3107 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3109 for (res = listenres->addrinfo; res; res = res->ai_next) {
3110 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3112 debug(DBG_WARN, "createlistener: socket failed");
3115 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3117 if (res->ai_family == AF_INET6)
3118 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3120 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3121 debug(DBG_WARN, "createlistener: bind failed");
3127 sp = malloc(sizeof(int));
3129 debugx(1, DBG_ERR, "malloc failed");
3131 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3132 debugx(1, DBG_ERR, "pthread_create failed");
3136 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3138 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3139 listenres->host ? listenres->host : "*", listenres->port);
3140 freeclsrvres(listenres);
3143 void createlisteners(uint8_t type, char **args) {
3147 for (i = 0; args[i]; i++)
3148 createlistener(type, args[i]);
3150 createlistener(type, NULL);
3153 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3154 SSL_CTX *ctx = NULL;
3155 STACK_OF(X509_NAME) *calist;
3158 unsigned long error;
3161 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3162 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3163 for (i = 0; i < CRYPTO_num_locks(); i++) {
3164 ssl_lock_count[i] = 0;
3165 pthread_mutex_init(&ssl_locks[i], NULL);
3167 CRYPTO_set_id_callback(ssl_thread_id);
3168 CRYPTO_set_locking_callback(ssl_locking_callback);
3170 SSL_load_error_strings();
3173 while (!RAND_status()) {
3174 time_t t = time(NULL);
3175 pid_t pid = getpid();
3176 RAND_seed((unsigned char *)&t, sizeof(time_t));
3177 RAND_seed((unsigned char *)&pid, sizeof(pid));
3183 ctx = SSL_CTX_new(TLSv1_method());
3186 ctx = SSL_CTX_new(DTLSv1_method());
3187 SSL_CTX_set_read_ahead(ctx, 1);
3191 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3195 if (conf->certkeypwd) {
3196 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3197 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3199 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3200 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3201 !SSL_CTX_check_private_key(ctx) ||
3202 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3203 while ((error = ERR_get_error()))
3204 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3205 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3210 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3211 if (!conf->cacertfile || calist) {
3212 if (conf->cacertpath) {
3214 calist = sk_X509_NAME_new_null();
3215 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3216 sk_X509_NAME_free(calist);
3222 while ((error = ERR_get_error()))
3223 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3224 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3228 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3229 SSL_CTX_set_client_CA_list(ctx, calist);
3231 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3232 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3234 if (conf->crlcheck) {
3235 x509_s = SSL_CTX_get_cert_store(ctx);
3236 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3239 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3243 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3244 struct list_node *entry;
3245 struct tls *t, *t1 = NULL, *t2 = NULL;
3246 SSL_CTX *ctx = NULL;
3248 pthread_mutex_lock(&tlsconfs_lock);
3250 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3251 t = (struct tls *)entry->data;
3252 if (!strcasecmp(t->name, alt1)) {
3256 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3267 t->tlsctx = tlscreatectx(RAD_TLS, t);
3272 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3278 pthread_mutex_unlock(&tlsconfs_lock);
3282 struct list *addsrvconfs(char *value, char **names) {
3283 struct list *conflist;
3285 struct list_node *entry;
3286 struct clsrvconf *conf = NULL;
3288 if (!names || !*names)
3291 conflist = list_create();
3293 debug(DBG_ERR, "malloc failed");
3297 for (n = 0; names[n]; n++) {
3298 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3299 conf = (struct clsrvconf *)entry->data;
3300 if (!strcasecmp(names[n], conf->name))
3304 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3305 list_destroy(conflist);
3308 if (!list_push(conflist, conf)) {
3309 debug(DBG_ERR, "malloc failed");
3310 list_destroy(conflist);
3313 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3318 void freerealm(struct realm *realm) {
3322 free(realm->message);
3323 regfree(&realm->regex);
3324 pthread_mutex_destroy(&realm->subrealms_mutex);
3325 if (realm->subrealms)
3326 list_destroy(realm->subrealms);
3327 if (realm->srvconfs) {
3328 /* emptying list without freeing data */
3329 while (list_shift(realm->srvconfs));
3330 list_destroy(realm->srvconfs);
3332 if (realm->accsrvconfs) {
3333 /* emptying list without freeing data */
3334 while (list_shift(realm->accsrvconfs));
3335 list_destroy(realm->accsrvconfs);
3340 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3342 struct realm *realm;
3343 char *s, *regex = NULL;
3345 if (*value == '/') {
3346 /* regexp, remove optional trailing / if present */
3347 if (value[strlen(value) - 1] == '/')
3348 value[strlen(value) - 1] = '\0';
3350 /* not a regexp, let us make it one */
3351 if (*value == '*' && !value[1])
3352 regex = stringcopy(".*", 0);
3354 for (n = 0, s = value; *s;)
3357 regex = malloc(strlen(value) + n + 3);
3360 for (n = 1, s = value; *s; s++) {
3370 debug(DBG_ERR, "malloc failed");
3374 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3377 realm = malloc(sizeof(struct realm));
3379 debug(DBG_ERR, "malloc failed");
3382 memset(realm, 0, sizeof(struct realm));
3384 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3385 debug(DBG_ERR, "mutex init failed");
3391 realm->name = stringcopy(value, 0);
3393 debug(DBG_ERR, "malloc failed");
3396 if (message && strlen(message) > 253) {
3397 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3400 realm->message = message;
3401 realm->accresp = accresp;
3403 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3404 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3408 if (servers && *servers) {
3409 realm->srvconfs = addsrvconfs(value, servers);
3410 if (!realm->srvconfs)
3414 if (accservers && *accservers) {
3415 realm->accsrvconfs = addsrvconfs(value, accservers);
3416 if (!realm->accsrvconfs)
3420 if (!list_push(realmlist, realm)) {
3421 debug(DBG_ERR, "malloc failed");
3422 pthread_mutex_destroy(&realm->subrealms_mutex);
3426 debug(DBG_DBG, "addrealm: added realm %s", value);
3436 for (n = 0; servers[n]; n++)
3441 for (n = 0; accservers[n]; n++)
3442 free(accservers[n]);
3448 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3449 struct clsrvconf *srvconf;
3450 struct realm *newrealm = NULL;
3451 char *realmname, *s;
3454 if (!conf->dynamiclookupcommand)
3457 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3458 realmname = strrchr(id, '@');
3464 for (s = realmname; *s; s++)
3465 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3468 pthread_mutex_lock(&realm->subrealms_mutex);
3469 /* exit if we now already got a matching subrealm */
3470 if (id2realm(realm->subrealms, id))
3472 srvconf = malloc(sizeof(struct clsrvconf));
3474 debug(DBG_ERR, "malloc failed");
3478 if (!addserver(srvconf))
3481 if (!realm->subrealms)
3482 realm->subrealms = list_create();
3483 if (!realm->subrealms)
3485 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3489 /* add server and accserver to newrealm */
3490 newrealm->srvconfs = list_create();
3491 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3492 debug(DBG_ERR, "malloc failed");
3495 newrealm->accsrvconfs = list_create();
3496 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3497 debug(DBG_ERR, "malloc failed");
3501 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3503 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3504 debug(DBG_ERR, "pthread_create failed");
3507 pthread_detach(clientth);
3512 list_removedata(realm->subrealms, newrealm);
3513 freerealm(newrealm);
3514 if (!list_first(realm->subrealms)) {
3515 list_destroy(realm->subrealms);
3516 realm->subrealms = NULL;
3519 freeserver(srvconf->servers, 1);
3521 debug(DBG_ERR, "failed to create dynamic server");
3524 pthread_mutex_unlock(&realm->subrealms_mutex);
3527 int dynamicconfig(struct server *server) {
3528 int ok, fd[2], status;
3530 struct clsrvconf *conf = server->conf;
3531 struct gconffile *cf = NULL;
3533 /* for now we only learn hostname/address */
3534 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3537 debug(DBG_ERR, "dynamicconfig: pipe error");
3542 debug(DBG_ERR, "dynamicconfig: fork error");
3546 } else if (pid == 0) {
3549 if (fd[1] != STDOUT_FILENO) {
3550 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3551 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3554 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3555 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3559 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3560 ok = getgenericconfig(&cf, NULL,
3561 "Server", CONF_CBK, confserver_cb, (void *)conf,
3566 if (waitpid(pid, &status, 0) < 0) {
3567 debug(DBG_ERR, "dynamicconfig: wait error");
3572 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3580 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3584 int addmatchcertattr(struct clsrvconf *conf) {
3588 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3589 r = &conf->certcnregex;
3590 v = conf->matchcertattr + 4;
3591 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3592 r = &conf->certuriregex;
3593 v = conf->matchcertattr + 20;
3598 /* regexp, remove optional trailing / if present */
3599 if (v[strlen(v) - 1] == '/')
3600 v[strlen(v) - 1] = '\0';
3604 *r = malloc(sizeof(regex_t));
3606 debug(DBG_ERR, "malloc failed");
3609 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3612 debug(DBG_ERR, "failed to compile regular expression %s", v);
3618 int addrewriteattr(struct clsrvconf *conf) {
3621 v = conf->rewriteattr + 11;
3622 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3624 /* regexp, remove optional trailing / if present */
3625 if (v[strlen(v) - 1] == '/')
3626 v[strlen(v) - 1] = '\0';
3634 conf->rewriteattrregex = malloc(sizeof(regex_t));
3635 if (!conf->rewriteattrregex) {
3636 debug(DBG_ERR, "malloc failed");
3640 conf->rewriteattrreplacement = stringcopy(w, 0);
3641 if (!conf->rewriteattrreplacement) {
3642 free(conf->rewriteattrregex);
3643 conf->rewriteattrregex = NULL;
3647 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3648 free(conf->rewriteattrregex);
3649 conf->rewriteattrregex = NULL;
3650 free(conf->rewriteattrreplacement);
3651 conf->rewriteattrreplacement = NULL;
3652 debug(DBG_ERR, "failed to compile regular expression %s", v);
3659 /* should accept both names and numeric values, only numeric right now */
3660 uint8_t attrname2val(char *attrname) {
3663 val = atoi(attrname);
3664 return val > 0 && val < 256 ? val : 0;
3667 /* should accept both names and numeric values, only numeric right now */
3668 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3671 *vendor = atoi(attrname);
3672 s = strchr(attrname, ':');
3677 *type = atoi(s + 1);
3678 return *type >= 0 && *type < 256;
3681 struct rewrite *getrewrite(char *alt1, char *alt2) {
3682 struct list_node *entry;
3683 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3685 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3686 r = (struct rewriteconf *)entry->data;
3687 if (!strcasecmp(r->name, alt1)) {
3691 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3701 void addrewrite(char *value, char **attrs, char **vattrs) {
3702 struct rewriteconf *new;
3703 struct rewrite *rewrite = NULL;
3706 uint32_t *p, *va = NULL;
3710 for (; attrs[n]; n++);
3711 a = malloc((n + 1) * sizeof(uint8_t));
3713 debugx(1, DBG_ERR, "malloc failed");
3715 for (i = 0; i < n; i++) {
3716 if (!(a[i] = attrname2val(attrs[i])))
3717 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3726 for (; vattrs[n]; n++);
3727 va = malloc((2 * n + 1) * sizeof(uint32_t));
3729 debugx(1, DBG_ERR, "malloc failed");
3731 for (p = va, i = 0; i < n; i++, p += 2) {
3732 if (!vattrname2val(vattrs[i], p, p + 1))
3733 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3741 rewrite = malloc(sizeof(struct rewrite));
3743 debugx(1, DBG_ERR, "malloc failed");
3744 rewrite->removeattrs = a;
3745 rewrite->removevendorattrs = va;
3748 new = malloc(sizeof(struct rewriteconf));
3749 if (!new || !list_push(rewriteconfs, new))
3750 debugx(1, DBG_ERR, "malloc failed");
3752 memset(new, 0, sizeof(struct rewriteconf));
3753 new->name = stringcopy(value, 0);
3755 debugx(1, DBG_ERR, "malloc failed");
3757 new->rewrite = rewrite;
3758 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3761 void freeclsrvconf(struct clsrvconf *conf) {
3767 free(conf->matchcertattr);
3768 if (conf->certcnregex)
3769 regfree(conf->certcnregex);
3770 if (conf->certuriregex)
3771 regfree(conf->certuriregex);
3772 free(conf->confrewrite);
3773 free(conf->rewriteattr);
3774 if (conf->rewriteattrregex)
3775 regfree(conf->rewriteattrregex);
3776 free(conf->rewriteattrreplacement);
3777 free(conf->dynamiclookupcommand);
3778 free(conf->rewrite);
3780 freeaddrinfo(conf->addrinfo);
3781 /* not touching ssl_ctx, clients and servers */
3785 int mergeconfstring(char **dst, char **src) {
3794 t = stringcopy(*dst, 0);
3796 debug(DBG_ERR, "malloc failed");
3804 /* assumes dst is a shallow copy */
3805 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3806 if (!mergeconfstring(&dst->name, &src->name) ||
3807 !mergeconfstring(&dst->host, &src->host) ||
3808 !mergeconfstring(&dst->port, &src->port) ||
3809 !mergeconfstring(&dst->secret, &src->secret) ||
3810 !mergeconfstring(&dst->tls, &src->tls) ||
3811 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3812 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3813 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3816 dst->pdef = src->pdef;
3817 dst->statusserver = src->statusserver;
3818 dst->certnamecheck = src->certnamecheck;
3819 if (src->retryinterval != 255)
3820 dst->retryinterval = src->retryinterval;
3821 if (src->retrycount != 255)
3822 dst->retrycount = src->retrycount;
3826 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3827 struct clsrvconf *conf;
3828 char *conftype = NULL;
3830 debug(DBG_DBG, "confclient_cb called for %s", block);
3832 conf = malloc(sizeof(struct clsrvconf));
3833 if (!conf || !list_push(clconfs, conf))
3834 debugx(1, DBG_ERR, "malloc failed");
3835 memset(conf, 0, sizeof(struct clsrvconf));
3836 conf->certnamecheck = 1;
3838 if (!getgenericconfig(cf, block,
3839 "type", CONF_STR, &conftype,
3840 "host", CONF_STR, &conf->host,
3841 "secret", CONF_STR, &conf->secret,
3842 "tls", CONF_STR, &conf->tls,
3843 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3844 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3845 "rewrite", CONF_STR, &conf->confrewrite,
3846 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3849 debugx(1, DBG_ERR, "configuration error");
3851 conf->name = stringcopy(val, 0);
3853 conf->host = stringcopy(val, 0);
3854 if (!conf->name || !conf->host)
3855 debugx(1, DBG_ERR, "malloc failed");
3858 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3859 conf->type = protoname2int(conftype);
3860 conf->pdef = &protodefs[conf->type];
3861 if (!conf->pdef->name)
3862 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3865 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3866 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3868 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3869 if (conf->matchcertattr && !addmatchcertattr(conf))
3870 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3873 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3875 if (conf->rewriteattr) {
3876 if (!addrewriteattr(conf))
3877 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3880 if (!resolvepeer(conf, 0))
3881 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3883 if (!conf->secret) {
3884 if (!conf->pdef->secretdefault)
3885 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3886 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3888 debugx(1, DBG_ERR, "malloc failed");
3893 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3894 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3895 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3896 if (!conf->ssl_ctx) {
3897 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3900 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3901 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3907 conf->port = stringcopy(conf->pdef->portdefault, 0);
3909 debug(DBG_ERR, "malloc failed");
3914 if (conf->retryinterval == 255)
3915 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3916 if (conf->retrycount == 255)
3917 conf->retrycount = protodefs[conf->type].retrycountdefault;
3919 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3921 if (!conf->secret) {
3922 if (!conf->pdef->secretdefault) {
3923 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3926 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3927 if (!conf->secret) {
3928 debug(DBG_ERR, "malloc failed");
3933 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3934 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3940 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3941 struct clsrvconf *conf, *resconf;
3942 char *conftype = NULL;
3943 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3945 debug(DBG_DBG, "confserver_cb called for %s", block);
3947 conf = malloc(sizeof(struct clsrvconf));
3949 debug(DBG_ERR, "malloc failed");
3952 memset(conf, 0, sizeof(struct clsrvconf));
3953 resconf = (struct clsrvconf *)arg;
3955 conf->statusserver = resconf->statusserver;
3956 conf->certnamecheck = resconf->certnamecheck;
3958 conf->certnamecheck = 1;
3960 if (!getgenericconfig(cf, block,
3961 "type", CONF_STR, &conftype,
3962 "host", CONF_STR, &conf->host,
3963 "port", CONF_STR, &conf->port,
3964 "secret", CONF_STR, &conf->secret,
3965 "tls", CONF_STR, &conf->tls,
3966 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3967 "rewrite", CONF_STR, &conf->confrewrite,
3968 "StatusServer", CONF_BLN, &conf->statusserver,
3969 "RetryInterval", CONF_LINT, &retryinterval,
3970 "RetryCount", CONF_LINT, &retrycount,
3971 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3972 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3975 debug(DBG_ERR, "configuration error");
3979 conf->name = stringcopy(val, 0);
3981 debug(DBG_ERR, "malloc failed");
3985 conf->host = stringcopy(val, 0);
3987 debug(DBG_ERR, "malloc failed");
3993 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3994 conf->type = protoname2int(conftype);
3995 conf->pdef = &protodefs[conf->type];
3996 if (!conf->pdef->name) {
3997 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4003 if (retryinterval != LONG_MIN) {
4004 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4005 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4008 conf->retryinterval = (uint8_t)retryinterval;
4010 conf->retryinterval = 255;
4012 if (retrycount != LONG_MIN) {
4013 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4014 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4017 conf->retrycount = (uint8_t)retrycount;
4019 conf->retrycount = 255;
4022 if (!mergesrvconf(resconf, conf))
4026 if (conf->dynamiclookupcommand) {
4027 free(conf->dynamiclookupcommand);
4028 conf->dynamiclookupcommand = NULL;
4032 if (resconf || !conf->dynamiclookupcommand) {
4033 if (!compileserverconfig(conf, block))
4040 if (!list_push(srvconfs, conf)) {
4041 debug(DBG_ERR, "malloc failed");
4047 freeclsrvconf(conf);
4051 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4052 char **servers = NULL, **accservers = NULL, *msg = NULL;
4053 uint8_t accresp = 0;
4055 debug(DBG_DBG, "confrealm_cb called for %s", block);
4057 if (!getgenericconfig(cf, block,
4058 "server", CONF_MSTR, &servers,
4059 "accountingServer", CONF_MSTR, &accservers,
4060 "ReplyMessage", CONF_STR, &msg,
4061 "AccountingResponse", CONF_BLN, &accresp,
4064 debugx(1, DBG_ERR, "configuration error");
4066 addrealm(realms, val, servers, accservers, msg, accresp);
4070 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4073 debug(DBG_DBG, "conftls_cb called for %s", block);
4075 conf = malloc(sizeof(struct tls));
4077 debug(DBG_ERR, "conftls_cb: malloc failed");
4080 memset(conf, 0, sizeof(struct tls));
4082 if (!getgenericconfig(cf, block,
4083 "CACertificateFile", CONF_STR, &conf->cacertfile,
4084 "CACertificatePath", CONF_STR, &conf->cacertpath,
4085 "CertificateFile", CONF_STR, &conf->certfile,
4086 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4087 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4088 "CRLCheck", CONF_BLN, &conf->crlcheck,
4091 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4094 if (!conf->certfile || !conf->certkeyfile) {
4095 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4098 if (!conf->cacertfile && !conf->cacertpath) {
4099 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4103 conf->name = stringcopy(val, 0);
4105 debug(DBG_ERR, "conftls_cb: malloc failed");
4109 pthread_mutex_lock(&tlsconfs_lock);
4110 if (!list_push(tlsconfs, conf)) {
4111 debug(DBG_ERR, "conftls_cb: malloc failed");
4112 pthread_mutex_unlock(&tlsconfs_lock);
4115 pthread_mutex_unlock(&tlsconfs_lock);
4117 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4121 free(conf->cacertfile);
4122 free(conf->cacertpath);
4123 free(conf->certfile);
4124 free(conf->certkeyfile);
4125 free(conf->certkeypwd);
4130 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4131 char **attrs = NULL, **vattrs = NULL;
4133 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4135 if (!getgenericconfig(cf, block,
4136 "removeAttribute", CONF_MSTR, &attrs,
4137 "removeVendorAttribute", CONF_MSTR, &vattrs,
4140 debugx(1, DBG_ERR, "configuration error");
4141 addrewrite(val, attrs, vattrs);
4145 void getmainconfig(const char *configfile) {
4146 long int loglevel = LONG_MIN;
4147 struct gconffile *cfs;
4149 cfs = openconfigfile(configfile);
4150 memset(&options, 0, sizeof(options));
4152 clconfs = list_create();
4154 debugx(1, DBG_ERR, "malloc failed");
4156 srvconfs = list_create();
4158 debugx(1, DBG_ERR, "malloc failed");
4160 realms = list_create();
4162 debugx(1, DBG_ERR, "malloc failed");
4164 tlsconfs = list_create();
4166 debugx(1, DBG_ERR, "malloc failed");
4168 rewriteconfs = list_create();
4170 debugx(1, DBG_ERR, "malloc failed");
4172 if (!getgenericconfig(&cfs, NULL,
4173 "ListenUDP", CONF_MSTR, &options.listenudp,
4174 "ListenTCP", CONF_MSTR, &options.listentcp,
4175 "ListenTLS", CONF_MSTR, &options.listentls,
4176 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4177 "SourceUDP", CONF_STR, &options.sourceudp,
4178 "SourceTCP", CONF_STR, &options.sourcetcp,
4179 "SourceTLS", CONF_STR, &options.sourcetls,
4180 "LogLevel", CONF_LINT, &loglevel,
4181 "LogDestination", CONF_STR, &options.logdestination,
4182 "LoopPrevention", CONF_BLN, &options.loopprevention,
4183 "Client", CONF_CBK, confclient_cb, NULL,
4184 "Server", CONF_CBK, confserver_cb, NULL,
4185 "Realm", CONF_CBK, confrealm_cb, NULL,
4186 "TLS", CONF_CBK, conftls_cb, NULL,
4187 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4190 debugx(1, DBG_ERR, "configuration error");
4192 if (loglevel != LONG_MIN) {
4193 if (loglevel < 1 || loglevel > 4)
4194 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4195 options.loglevel = (uint8_t)loglevel;
4199 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4202 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4205 *configfile = optarg;
4208 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4209 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4210 *loglevel = *optarg - '0';
4219 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4224 if (!(argc - optind))
4228 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4232 int daemon(int a, int b) {
4240 for (i = 0; i < 3; i++) {
4242 open("/dev/null", O_RDWR);
4248 void *sighandler(void *arg) {
4253 sigemptyset(&sigset);
4254 sigaddset(&sigset, SIGPIPE);
4255 sigwait(&sigset, &sig);
4256 /* only get SIGPIPE right now, so could simplify below code */
4259 /* completely ignoring this */
4262 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4265 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4270 int main(int argc, char **argv) {
4271 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
4273 struct list_node *entry;
4274 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4275 char *configfile = NULL;
4276 struct clsrvconf *srvconf;
4278 debug_init("radsecproxy");
4279 debug_set_level(DEBUG_LEVEL);
4280 pthread_mutex_init(&tlsconfs_lock, NULL);
4282 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4284 debug_set_level(loglevel);
4285 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4287 options.loglevel = loglevel;
4288 else if (options.loglevel)
4289 debug_set_level(options.loglevel);
4291 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4292 free(options.logdestination);
4294 if (!list_first(clconfs))
4295 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4296 if (!list_first(srvconfs))
4297 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
4298 if (!list_first(realms))
4299 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4302 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4304 if (!foreground && (daemon(0, 0) < 0))
4305 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4307 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4309 sigemptyset(&sigset);
4310 /* exit on all but SIGPIPE, ignore more? */
4311 sigaddset(&sigset, SIGPIPE);
4312 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4313 pthread_create(&sigth, NULL, sighandler, NULL);
4315 if (find_conf_type(RAD_UDP, clconfs, NULL)) {
4316 udp_server_replyq = newreplyq();
4317 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4318 debugx(1, DBG_ERR, "pthread_create failed");
4319 createlisteners(RAD_UDP, options.listenudp);
4320 if (options.listenaccudp)
4321 createlisteners(RAD_UDP, options.listenaccudp);
4324 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4325 srvconf = (struct clsrvconf *)entry->data;
4326 if (srvconf->dynamiclookupcommand)
4328 if (!addserver(srvconf))
4329 debugx(1, DBG_ERR, "failed to add server");
4330 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4331 (void *)(srvconf->servers)))
4332 debugx(1, DBG_ERR, "pthread_create failed");
4334 /* srcprotores for UDP no longer needed */
4335 if (srcprotores[RAD_UDP]) {
4336 freeaddrinfo(srcprotores[RAD_UDP]);
4337 srcprotores[RAD_UDP] = NULL;
4339 if (udp_client4_sock >= 0)
4340 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4341 debugx(1, DBG_ERR, "pthread_create failed");
4342 if (udp_client6_sock >= 0)
4343 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4344 debugx(1, DBG_ERR, "pthread_create failed");
4346 if (find_conf_type(RAD_TCP, clconfs, NULL))
4347 createlisteners(RAD_TCP, options.listentcp);
4349 if (find_conf_type(RAD_TLS, clconfs, NULL))
4350 createlisteners(RAD_TLS, options.listentls);
4352 /* just hang around doing nothing, anything to do here? */