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 dtlsinit(struct server *server, struct timeval *when, int timeout, char *text);
94 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text);
95 void *udpclientrd(void *arg);
96 void *tlsclientrd(void *arg);
97 void *dtlsclientrd(void *arg);
98 void *tcpclientrd(void *arg);
99 int clientradputudp(struct server *server, unsigned char *rad);
100 int clientradputtls(struct server *server, unsigned char *rad);
101 int clientradputdtls(struct server *server, unsigned char *rad);
102 int clientradputtcp(struct server *server, unsigned char *rad);
104 static const struct protodefs protodefs[] = {
105 { "udp", /* UDP, assuming RAD_UDP defined as 0 */
106 NULL, /* secretdefault */
107 SOCK_DGRAM, /* socktype */
108 "1812", /* portdefault */
109 REQUEST_RETRY_COUNT, /* retrycountdefault */
110 10, /* retrycountmax */
111 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
112 60, /* retryintervalmax */
113 udpserverrd, /* listener */
114 &options.sourceudp, /* srcaddrport */
115 NULL, /* connecter */
116 udpclientrd, /* clientreader */
117 clientradputudp /* clientradput */
119 { "tls", /* TLS, assuming RAD_TLS defined as 1 */
120 "mysecret", /* secretdefault */
121 SOCK_STREAM, /* socktype */
122 "2083", /* portdefault */
123 0, /* retrycountdefault */
124 0, /* retrycountmax */
125 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
126 60, /* retryintervalmax */
127 tlslistener, /* listener */
128 &options.sourcetls, /* srcaddrport */
129 tlsconnect, /* connecter */
130 tlsclientrd, /* clientreader */
131 clientradputtls /* clientradput */
133 { "tcp", /* TCP, assuming RAD_TCP defined as 2 */
134 NULL, /* secretdefault */
135 SOCK_STREAM, /* socktype */
136 "1812", /* portdefault */
137 0, /* retrycountdefault */
138 0, /* retrycountmax */
139 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
140 60, /* retryintervalmax */
141 tcplistener, /* listener */
142 &options.sourcetcp, /* srcaddrport */
143 tcpconnect, /* connecter */
144 tcpclientrd, /* clientreader */
145 clientradputtcp /* clientradput */
147 { "dtls", /* DTLS, assuming RAD_DTLS defined as 3 */
148 NULL, /* secretdefault */
149 SOCK_DGRAM, /* socktype */
150 "1812", /* portdefault */
151 REQUEST_RETRY_COUNT, /* retrycountdefault */
152 10, /* retrycountmax */
153 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
154 60, /* retryintervalmax */
156 &options.sourceudp, /* srcaddrport */
157 dtlsinit, /* connecter */
158 dtlsclientrd, /* clientreader */
159 clientradputdtls /* clientradput */
165 uint8_t protoname2int(const char *name) {
168 for (i = 0; protodefs[i].name && strcasecmp(protodefs[i].name, name); i++);
172 /* callbacks for making OpenSSL thread safe */
173 unsigned long ssl_thread_id() {
174 return (unsigned long)pthread_self();
177 void ssl_locking_callback(int mode, int type, const char *file, int line) {
178 if (mode & CRYPTO_LOCK) {
179 pthread_mutex_lock(&ssl_locks[type]);
180 ssl_lock_count[type]++;
182 pthread_mutex_unlock(&ssl_locks[type]);
185 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
186 int pwdlen = strlen(userdata);
187 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
189 memcpy(buf, userdata, pwdlen);
193 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
198 err_cert = X509_STORE_CTX_get_current_cert(ctx);
199 err = X509_STORE_CTX_get_error(ctx);
200 depth = X509_STORE_CTX_get_error_depth(ctx);
202 if (depth > MAX_CERT_DEPTH) {
204 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
205 X509_STORE_CTX_set_error(ctx, err);
209 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
210 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
213 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
214 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
215 debug(DBG_WARN, "\tIssuer=%s", buf);
217 case X509_V_ERR_CERT_NOT_YET_VALID:
218 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
219 debug(DBG_WARN, "\tCertificate not yet valid");
221 case X509_V_ERR_CERT_HAS_EXPIRED:
222 debug(DBG_WARN, "Certificate has expired");
224 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
225 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
230 printf("certificate verify returns %d\n", ok);
235 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
236 struct addrinfo hints, *addrinfo, *res;
240 slash = conf->host ? strchr(conf->host, '/') : NULL;
244 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
248 if (*s < '0' || *s > '9') {
249 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
252 plen = atoi(slash + 1);
253 if (plen < 0 || plen > 128) {
254 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
259 memset(&hints, 0, sizeof(hints));
260 hints.ai_socktype = conf->pdef->socktype;
261 hints.ai_family = AF_UNSPEC;
262 hints.ai_flags = ai_flags;
263 if (!conf->host && !conf->port) {
264 /* getaddrinfo() doesn't like host and port to be NULL */
265 if (getaddrinfo(conf->host, conf->pdef->portdefault, &hints, &addrinfo)) {
266 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
269 for (res = addrinfo; res; res = res->ai_next) {
270 switch (res->ai_family) {
272 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
275 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
281 hints.ai_flags |= AI_NUMERICHOST;
282 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
283 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
288 switch (addrinfo->ai_family) {
291 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
292 freeaddrinfo(addrinfo);
299 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
300 freeaddrinfo(addrinfo);
303 conf->prefixlen = plen;
305 conf->prefixlen = 255;
308 freeaddrinfo(conf->addrinfo);
309 conf->addrinfo = addrinfo;
313 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
315 struct addrinfo *res;
317 for (res = addrinfo; res; res = res->ai_next) {
318 if (family != AF_UNSPEC && family != res->ai_family)
320 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
322 debug(DBG_WARN, "bindtoaddr: socket failed");
326 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
329 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
332 if (!bind(s, res->ai_addr, res->ai_addrlen))
334 debug(DBG_WARN, "bindtoaddr: bind failed");
340 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
345 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
349 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
351 debugx(1, DBG_ERR, "no ] matching initial [");
355 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
358 debugx(1, DBG_ERR, "missing host/address");
360 conf->host = stringcopy(field, p - field);
363 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
364 debugx(1, DBG_ERR, "unexpected character after ]");
367 /* port number or service name is specified */;
369 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
371 debugx(1, DBG_ERR, "syntax error, : but no following port");
372 conf->port = stringcopy(field, p - field);
374 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
378 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
379 struct clsrvconf *conf;
381 conf = malloc(sizeof(struct clsrvconf));
383 debugx(1, DBG_ERR, "malloc failed");
384 memset(conf, 0, sizeof(struct clsrvconf));
386 conf->pdef = &protodefs[conf->type];
388 parsehostport(lconf, conf, default_port);
389 if (!strcmp(conf->host, "*")) {
394 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
395 if (!resolvepeer(conf, AI_PASSIVE))
396 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
400 void freeclsrvres(struct clsrvconf *res) {
404 freeaddrinfo(res->addrinfo);
408 int connecttcp(struct addrinfo *addrinfo, struct addrinfo *src) {
410 struct addrinfo *res;
413 for (res = addrinfo; res; res = res->ai_next) {
414 s = bindtoaddr(src, res->ai_family, 1, 1);
416 debug(DBG_WARN, "connecttoserver: socket failed");
419 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
421 debug(DBG_WARN, "connecttoserver: connect failed");
428 /* returns 1 if the len first bits are equal, else 0 */
429 int prefixmatch(void *a1, void *a2, uint8_t len) {
430 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
432 if (l && memcmp(a1, a2, l))
437 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
440 /* returns next config with matching address, or NULL */
441 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
442 struct sockaddr_in6 *sa6 = NULL;
443 struct in_addr *a4 = NULL;
444 struct addrinfo *res;
445 struct list_node *entry;
446 struct clsrvconf *conf;
448 if (addr->sa_family == AF_INET6) {
449 sa6 = (struct sockaddr_in6 *)addr;
450 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
451 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
455 a4 = &((struct sockaddr_in *)addr)->sin_addr;
457 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
458 conf = (struct clsrvconf *)entry->data;
459 if (conf->type == type) {
460 if (conf->prefixlen == 255) {
461 for (res = conf->addrinfo; res; res = res->ai_next)
462 if ((a4 && res->ai_family == AF_INET &&
463 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
464 (sa6 && res->ai_family == AF_INET6 &&
465 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
471 res = conf->addrinfo;
473 ((a4 && res->ai_family == AF_INET &&
474 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
475 (sa6 && res->ai_family == AF_INET6 &&
476 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
487 /* returns next config of given type, or NULL */
488 struct clsrvconf *find_conf_type(uint8_t type, struct list *confs, struct list_node **cur) {
489 struct list_node *entry;
490 struct clsrvconf *conf;
492 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
493 conf = (struct clsrvconf *)entry->data;
494 if (conf->type == type) {
503 struct replyq *newreplyq() {
504 struct replyq *replyq;
506 replyq = malloc(sizeof(struct replyq));
508 debugx(1, DBG_ERR, "malloc failed");
509 replyq->replies = list_create();
510 if (!replyq->replies)
511 debugx(1, DBG_ERR, "malloc failed");
512 pthread_mutex_init(&replyq->mutex, NULL);
513 pthread_cond_init(&replyq->cond, NULL);
517 struct client *addclient(struct clsrvconf *conf) {
518 struct client *new = malloc(sizeof(struct client));
521 debug(DBG_ERR, "malloc failed");
524 if (!conf->clients) {
525 conf->clients = list_create();
526 if (!conf->clients) {
527 debug(DBG_ERR, "malloc failed");
532 memset(new, 0, sizeof(struct client));
534 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
536 list_push(conf->clients, new);
540 void removeclient(struct client *client) {
541 struct list_node *entry;
543 if (!client || !client->conf->clients)
546 pthread_mutex_lock(&client->replyq->mutex);
547 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
548 free(((struct reply *)entry)->buf);
549 list_destroy(client->replyq->replies);
550 pthread_cond_destroy(&client->replyq->cond);
551 pthread_mutex_unlock(&client->replyq->mutex);
552 pthread_mutex_destroy(&client->replyq->mutex);
553 list_removedata(client->conf->clients, client);
557 void removeclientrqs(struct client *client) {
558 struct list_node *entry;
559 struct server *server;
563 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
564 server = ((struct clsrvconf *)entry->data)->servers;
567 pthread_mutex_lock(&server->newrq_mutex);
568 for (i = 0; i < MAX_REQUESTS; i++) {
569 rq = server->requests + i;
570 if (rq->from == client)
573 pthread_mutex_unlock(&server->newrq_mutex);
577 void freeserver(struct server *server, uint8_t destroymutex) {
578 struct request *rq, *end;
583 if(server->requests) {
584 rq = server->requests;
585 for (end = rq + MAX_REQUESTS; rq < end; rq++)
587 free(server->requests);
589 free(server->dynamiclookuparg);
591 pthread_mutex_destroy(&server->lock);
592 pthread_cond_destroy(&server->newrq_cond);
593 pthread_mutex_destroy(&server->newrq_mutex);
598 int addserver(struct clsrvconf *conf) {
599 struct clsrvconf *res;
603 debug(DBG_ERR, "addserver: currently works with just one server per conf");
606 conf->servers = malloc(sizeof(struct server));
607 if (!conf->servers) {
608 debug(DBG_ERR, "malloc failed");
611 memset(conf->servers, 0, sizeof(struct server));
612 conf->servers->conf = conf;
615 if (type == RAD_DTLS)
618 if (!srcprotores[type]) {
619 res = resolve_hostport(type, *conf->pdef->srcaddrport, NULL);
620 srcprotores[type] = res->addrinfo;
621 res->addrinfo = NULL;
625 if (type == RAD_UDP) {
626 switch (conf->addrinfo->ai_family) {
628 if (udp_client4_sock < 0) {
629 udp_client4_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET, 0, 1);
630 if (udp_client4_sock < 0)
631 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
633 conf->servers->sock = udp_client4_sock;
636 if (udp_client6_sock < 0) {
637 udp_client6_sock = bindtoaddr(srcprotores[RAD_UDP], AF_INET6, 0, 1);
638 if (udp_client6_sock < 0)
639 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
641 conf->servers->sock = udp_client6_sock;
644 debugx(1, DBG_ERR, "addserver: unsupported address family");
648 conf->servers->sock = -1;
650 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
651 if (!conf->servers->requests) {
652 debug(DBG_ERR, "malloc failed");
655 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
656 debug(DBG_ERR, "mutex init failed");
659 conf->servers->newrq = 0;
660 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
661 debug(DBG_ERR, "mutex init failed");
662 pthread_mutex_destroy(&conf->servers->lock);
665 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
666 debug(DBG_ERR, "mutex init failed");
667 pthread_mutex_destroy(&conf->servers->newrq_mutex);
668 pthread_mutex_destroy(&conf->servers->lock);
675 freeserver(conf->servers, 0);
676 conf->servers = NULL;
680 /* exactly one of client and server must be non-NULL */
681 /* return who we received from in *client or *server */
682 /* return from in sa if not NULL */
683 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
685 unsigned char buf[4], *rad;
686 struct sockaddr_storage from;
687 socklen_t fromlen = sizeof(from);
689 struct list_node *node;
695 if (select(s + 1, &readfds, NULL, NULL, NULL) < 1)
697 cnt = recvfrom(s, buf, 4, MSG_PEEK, (struct sockaddr *)&from, &fromlen);
699 debug(DBG_WARN, "radudpget: recv failed");
703 p = find_conf(RAD_UDP, (struct sockaddr *)&from, client ? clconfs : srvconfs, NULL);
705 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
712 debug(DBG_WARN, "radudpget: length too small");
719 debug(DBG_ERR, "radudpget: malloc failed");
724 cnt = recv(s, rad, len, MSG_TRUNC);
725 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
728 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
734 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
737 node = list_first(p->clients);
738 *client = node ? (struct client *)node->data : addclient(p);
744 *server = p->servers;
752 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
753 int loc, i, l, n, r = 0;
756 STACK_OF(GENERAL_NAME) *alt;
759 debug(DBG_DBG, "subjectaltnameaddr");
761 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
765 ex = X509_get_ext(cert, loc);
766 alt = X509V3_EXT_d2i(ex);
770 n = sk_GENERAL_NAME_num(alt);
771 for (i = 0; i < n; i++) {
772 gn = sk_GENERAL_NAME_value(alt, i);
773 if (gn->type != GEN_IPADD)
776 v = (char *)ASN1_STRING_data(gn->d.ia5);
777 l = ASN1_STRING_length(gn->d.ia5);
778 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
779 && !memcmp(v, &addr, l)) {
784 GENERAL_NAMES_free(alt);
788 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
795 nm = X509_get_subject_name(cert);
798 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
801 e = X509_NAME_get_entry(nm, loc);
802 t = X509_NAME_ENTRY_get_data(e);
803 v = (char *) ASN1_STRING_data(t);
804 l = ASN1_STRING_length(t);
808 if (l == strlen(exact) && !strncasecmp(exact, v, l))
811 s = stringcopy((char *)v, l);
813 debug(DBG_ERR, "malloc failed");
816 if (regexec(regex, s, 0, NULL, 0)) {
827 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
828 int loc, i, l, n, r = 0;
831 STACK_OF(GENERAL_NAME) *alt;
834 debug(DBG_DBG, "subjectaltnameregexp");
836 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
840 ex = X509_get_ext(cert, loc);
841 alt = X509V3_EXT_d2i(ex);
845 n = sk_GENERAL_NAME_num(alt);
846 for (i = 0; i < n; i++) {
847 gn = sk_GENERAL_NAME_value(alt, i);
848 if (gn->type != type)
851 v = (char *)ASN1_STRING_data(gn->d.ia5);
852 l = ASN1_STRING_length(gn->d.ia5);
856 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
859 if (memcmp(v, exact, l))
862 s = stringcopy((char *)v, l);
864 debug(DBG_ERR, "malloc failed");
867 if (regexec(regex, s, 0, NULL, 0)) {
876 GENERAL_NAMES_free(alt);
880 X509 *verifytlscert(SSL *ssl) {
884 if (SSL_get_verify_result(ssl) != X509_V_OK) {
885 debug(DBG_ERR, "verifytlscert: basic validation failed");
886 while ((error = ERR_get_error()))
887 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
891 cert = SSL_get_peer_certificate(ssl);
893 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
897 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
899 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
900 struct in6_addr addr;
902 if (conf->certnamecheck && conf->prefixlen == 255) {
903 if (inet_pton(AF_INET, conf->host, &addr))
905 else if (inet_pton(AF_INET6, conf->host, &addr))
908 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
911 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
914 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
916 if (!cnregexp(cert, conf->host, NULL)) {
917 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
920 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
923 if (conf->certcnregex) {
924 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
925 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
928 debug(DBG_DBG, "verifyconfcert: CN matching regex");
930 if (conf->certuriregex) {
931 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
932 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
935 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
940 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
946 debug(DBG_DBG, "tlsconnect: called from %s", text);
947 pthread_mutex_lock(&server->lock);
948 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
949 /* already reconnected, nothing to do */
950 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
951 pthread_mutex_unlock(&server->lock);
956 gettimeofday(&now, NULL);
957 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
958 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
959 debug(DBG_DBG, "tlsconnect: timeout");
960 if (server->sock >= 0)
962 SSL_free(server->ssl);
964 pthread_mutex_unlock(&server->lock);
967 if (server->connectionok) {
968 server->connectionok = 0;
970 } else if (elapsed < 1)
972 else if (elapsed < 60) {
973 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
975 } else if (elapsed < 100000) {
976 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
979 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
980 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
981 if (server->sock >= 0)
983 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TLS])) < 0) {
984 debug(DBG_ERR, "tlsconnect: connecttcp failed");
988 SSL_free(server->ssl);
989 server->ssl = SSL_new(server->conf->ssl_ctx);
990 SSL_set_fd(server->ssl, server->sock);
991 if (SSL_connect(server->ssl) <= 0) {
992 while ((error = ERR_get_error()))
993 debug(DBG_ERR, "tlsconnect: TLS: %s", ERR_error_string(error, NULL));
996 cert = verifytlscert(server->ssl);
999 if (verifyconfcert(cert, server->conf)) {
1005 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
1006 gettimeofday(&server->lastconnecttry, NULL);
1007 pthread_mutex_unlock(&server->lock);
1011 int dtlsinit(struct server *server, struct timeval *when, int timeout, char *text) {
1012 BIO *dummybio, *wbio;
1014 debug(DBG_DBG, "dtlsinit: called from %s", text);
1015 server->ssl = SSL_new(server->conf->ssl_ctx);
1016 SSL_set_connect_state(server->ssl);
1018 dummybio = BIO_new(BIO_s_mem());
1019 /* trying to read from this BIO always returns retry */
1020 BIO_set_mem_eof_return(dummybio, -1);
1022 wbio = BIO_new_dgram(server->sock, BIO_NOCLOSE);
1023 BIO_dgram_set_peer(wbio, server->conf->addrinfo->ai_addr);
1024 /* the real rbio will be set by radudpget */
1025 SSL_set_bio(server->ssl, dummybio, wbio);
1029 int tcpconnect(struct server *server, struct timeval *when, int timeout, char *text) {
1033 debug(DBG_DBG, "tcpconnect: called from %s", text);
1034 pthread_mutex_lock(&server->lock);
1035 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
1036 /* already reconnected, nothing to do */
1037 debug(DBG_DBG, "tcpconnect(%s): seems already reconnected", text);
1038 pthread_mutex_unlock(&server->lock);
1043 gettimeofday(&now, NULL);
1044 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
1045 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
1046 debug(DBG_DBG, "tcpconnect: timeout");
1047 if (server->sock >= 0)
1048 close(server->sock);
1049 pthread_mutex_unlock(&server->lock);
1052 if (server->connectionok) {
1053 server->connectionok = 0;
1055 } else if (elapsed < 1)
1057 else if (elapsed < 60) {
1058 debug(DBG_INFO, "tcpconnect: sleeping %lds", elapsed);
1060 } else if (elapsed < 100000) {
1061 debug(DBG_INFO, "tcpconnect: sleeping %ds", 60);
1064 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
1065 debug(DBG_WARN, "tcpconnect: trying to open TCP connection to %s port %s", server->conf->host, server->conf->port);
1066 if (server->sock >= 0)
1067 close(server->sock);
1068 if ((server->sock = connecttcp(server->conf->addrinfo, srcprotores[RAD_TCP])) >= 0)
1070 debug(DBG_ERR, "tcpconnect: connecttcp failed");
1072 debug(DBG_WARN, "tcpconnect: TCP connection to %s port %s up", server->conf->host, server->conf->port);
1073 gettimeofday(&server->lastconnecttry, NULL);
1074 pthread_mutex_unlock(&server->lock);
1078 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1079 /* returns 0 on timeout, -1 on error and num if ok */
1080 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
1081 int s, ndesc, cnt, len;
1082 fd_set readfds, writefds;
1083 struct timeval timer;
1085 s = SSL_get_fd(ssl);
1088 /* make socket non-blocking? */
1089 for (len = 0; len < num; len += cnt) {
1091 FD_SET(s, &readfds);
1094 timer.tv_sec = timeout;
1097 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1101 cnt = SSL_read(ssl, buf + len, num - len);
1103 switch (SSL_get_error(ssl, cnt)) {
1104 case SSL_ERROR_WANT_READ:
1105 case SSL_ERROR_WANT_WRITE:
1108 case SSL_ERROR_ZERO_RETURN:
1109 /* remote end sent close_notify, send one back */
1119 /* timeout in seconds, 0 means no timeout (blocking) */
1120 unsigned char *radtlsget(SSL *ssl, int timeout) {
1122 unsigned char buf[4], *rad;
1125 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1127 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1134 debug(DBG_ERR, "radtlsget: malloc failed");
1137 memcpy(rad, buf, 4);
1139 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1141 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1150 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1153 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1157 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
1158 /* returns 0 on timeout, -1 on error and num if ok */
1159 int tcpreadtimeout(int s, unsigned char *buf, int num, int timeout) {
1160 int ndesc, cnt, len;
1161 fd_set readfds, writefds;
1162 struct timeval timer;
1166 /* make socket non-blocking? */
1167 for (len = 0; len < num; len += cnt) {
1169 FD_SET(s, &readfds);
1172 timer.tv_sec = timeout;
1175 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
1179 cnt = read(s, buf + len, num - len);
1186 /* timeout in seconds, 0 means no timeout (blocking) */
1187 unsigned char *radtcpget(int s, int timeout) {
1189 unsigned char buf[4], *rad;
1192 cnt = tcpreadtimeout(s, buf, 4, timeout);
1194 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1201 debug(DBG_ERR, "radtcpget: malloc failed");
1204 memcpy(rad, buf, 4);
1206 cnt = tcpreadtimeout(s, rad + 4, len - 4, timeout);
1208 debug(DBG_DBG, cnt ? "radtcpget: connection lost" : "radtcpget: timeout");
1217 debug(DBG_WARN, "radtcpget: packet smaller than minimum radius size");
1220 debug(DBG_DBG, "radtcpget: got %d bytes", len);
1224 int clientradputudp(struct server *server, unsigned char *rad) {
1226 struct sockaddr_storage sa;
1227 struct sockaddr *sap;
1228 struct clsrvconf *conf = server->conf;
1229 in_port_t *port = NULL;
1233 if (*rad == RAD_Accounting_Request) {
1234 sap = (struct sockaddr *)&sa;
1235 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1237 sap = conf->addrinfo->ai_addr;
1239 switch (sap->sa_family) {
1241 port = &((struct sockaddr_in *)sap)->sin_port;
1244 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1250 if (*rad == RAD_Accounting_Request)
1251 *port = htons(ntohs(*port) + 1);
1253 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1254 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1258 debug(DBG_WARN, "clientradputudp: send failed");
1262 int clientradputtls(struct server *server, unsigned char *rad) {
1265 unsigned long error;
1266 struct timeval lastconnecttry;
1267 struct clsrvconf *conf = server->conf;
1270 lastconnecttry = server->lastconnecttry;
1271 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1272 while ((error = ERR_get_error()))
1273 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1274 if (server->dynamiclookuparg)
1276 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1277 lastconnecttry = server->lastconnecttry;
1280 server->connectionok = 1;
1281 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1285 int clientradputdtls(struct server *server, unsigned char *rad) {
1288 unsigned long error;
1289 struct clsrvconf *conf = server->conf;
1292 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1293 while ((error = ERR_get_error()))
1294 debug(DBG_ERR, "clientradputdtls: DTLS: %s", ERR_error_string(error, NULL));
1296 debug(DBG_DBG, "clientradputdtls: Sent %d bytes, Radius packet of length %d to DTLS peer %s", cnt, len, conf->host);
1300 int clientradputtcp(struct server *server, unsigned char *rad) {
1303 struct timeval lastconnecttry;
1304 struct clsrvconf *conf = server->conf;
1307 lastconnecttry = server->lastconnecttry;
1308 while ((cnt = write(server->sock, rad, len)) <= 0) {
1309 debug(DBG_ERR, "clientradputtcp: write error");
1310 tcpconnect(server, &lastconnecttry, 0, "clientradputtcp");
1311 lastconnecttry = server->lastconnecttry;
1314 server->connectionok = 1;
1315 debug(DBG_DBG, "clientradputtcp: Sent %d bytes, Radius packet of length %d to TCP peer %s", cnt, len, conf->host);
1319 int radsign(unsigned char *rad, unsigned char *sec) {
1320 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1321 static unsigned char first = 1;
1322 static EVP_MD_CTX mdctx;
1323 unsigned int md_len;
1326 pthread_mutex_lock(&lock);
1328 EVP_MD_CTX_init(&mdctx);
1332 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1333 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1334 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1335 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1337 pthread_mutex_unlock(&lock);
1341 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1342 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1343 static unsigned char first = 1;
1344 static EVP_MD_CTX mdctx;
1345 unsigned char hash[EVP_MAX_MD_SIZE];
1349 pthread_mutex_lock(&lock);
1351 EVP_MD_CTX_init(&mdctx);
1357 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1358 EVP_DigestUpdate(&mdctx, rad, 4) &&
1359 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1360 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1361 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1362 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1364 !memcmp(hash, rad + 4, 16));
1365 pthread_mutex_unlock(&lock);
1369 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1370 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1371 static unsigned char first = 1;
1372 static HMAC_CTX hmacctx;
1373 unsigned int md_len;
1374 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1376 pthread_mutex_lock(&lock);
1378 HMAC_CTX_init(&hmacctx);
1382 memcpy(auth, authattr, 16);
1383 memset(authattr, 0, 16);
1385 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1386 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1387 HMAC_Final(&hmacctx, hash, &md_len);
1388 memcpy(authattr, auth, 16);
1390 debug(DBG_WARN, "message auth computation failed");
1391 pthread_mutex_unlock(&lock);
1395 if (memcmp(auth, hash, 16)) {
1396 debug(DBG_WARN, "message authenticator, wrong value");
1397 pthread_mutex_unlock(&lock);
1401 pthread_mutex_unlock(&lock);
1405 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1406 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1407 static unsigned char first = 1;
1408 static HMAC_CTX hmacctx;
1409 unsigned int md_len;
1414 pthread_mutex_lock(&lock);
1416 HMAC_CTX_init(&hmacctx);
1420 memset(authattrval, 0, 16);
1422 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1423 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1424 HMAC_Final(&hmacctx, authattrval, &md_len);
1426 debug(DBG_WARN, "message auth computation failed");
1427 pthread_mutex_unlock(&lock);
1431 pthread_mutex_unlock(&lock);
1435 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1436 while (length > 1) {
1437 if (ATTRTYPE(attrs) == type)
1439 length -= ATTRLEN(attrs);
1440 attrs += ATTRLEN(attrs);
1445 void freerqdata(struct request *rq) {
1446 if (rq->origusername)
1447 free(rq->origusername);
1452 void sendrq(struct server *to, struct request *rq) {
1456 pthread_mutex_lock(&to->newrq_mutex);
1457 /* might simplify if only try nextid, might be ok */
1458 for (i = to->nextid; i < MAX_REQUESTS; i++)
1459 if (!to->requests[i].buf)
1461 if (i == MAX_REQUESTS) {
1462 for (i = 0; i < to->nextid; i++)
1463 if (!to->requests[i].buf)
1465 if (i == to->nextid) {
1466 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1472 rq->buf[1] = (char)i;
1474 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1475 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1480 if (*rq->buf == RAD_Accounting_Request) {
1481 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1482 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1488 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1489 to->requests[i] = *rq;
1494 debug(DBG_DBG, "sendrq: signalling client writer");
1495 pthread_cond_signal(&to->newrq_cond);
1498 pthread_mutex_unlock(&to->newrq_mutex);
1501 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1502 struct reply *reply;
1505 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1507 debug(DBG_WARN, "sendreply: failed to sign message");
1511 reply = malloc(sizeof(struct reply));
1514 debug(DBG_ERR, "sendreply: malloc failed");
1517 memset(reply, 0, sizeof(struct reply));
1520 reply->tosa = *tosa;
1521 reply->toudpsock = toudpsock;
1523 pthread_mutex_lock(&to->replyq->mutex);
1525 first = list_first(to->replyq->replies) == NULL;
1527 if (!list_push(to->replyq->replies, reply)) {
1528 pthread_mutex_unlock(&to->replyq->mutex);
1531 debug(DBG_ERR, "sendreply: malloc failed");
1536 debug(DBG_DBG, "signalling server writer");
1537 pthread_cond_signal(&to->replyq->cond);
1539 pthread_mutex_unlock(&to->replyq->mutex);
1542 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1543 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1544 static unsigned char first = 1;
1545 static EVP_MD_CTX mdctx;
1546 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1547 unsigned int md_len;
1548 uint8_t i, offset = 0, out[128];
1550 pthread_mutex_lock(&lock);
1552 EVP_MD_CTX_init(&mdctx);
1558 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1559 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1560 !EVP_DigestUpdate(&mdctx, input, 16) ||
1561 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1563 pthread_mutex_unlock(&lock);
1566 for (i = 0; i < 16; i++)
1567 out[offset + i] = hash[i] ^ in[offset + i];
1568 input = out + offset - 16;
1573 memcpy(in, out, len);
1574 pthread_mutex_unlock(&lock);
1578 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1579 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1580 static unsigned char first = 1;
1581 static EVP_MD_CTX mdctx;
1582 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1583 unsigned int md_len;
1584 uint8_t i, offset = 0, out[128];
1586 pthread_mutex_lock(&lock);
1588 EVP_MD_CTX_init(&mdctx);
1594 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1595 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1596 !EVP_DigestUpdate(&mdctx, input, 16) ||
1597 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1599 pthread_mutex_unlock(&lock);
1602 for (i = 0; i < 16; i++)
1603 out[offset + i] = hash[i] ^ in[offset + i];
1604 input = in + offset;
1609 memcpy(in, out, len);
1610 pthread_mutex_unlock(&lock);
1614 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1615 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1616 static unsigned char first = 1;
1617 static EVP_MD_CTX mdctx;
1618 unsigned char hash[EVP_MAX_MD_SIZE];
1619 unsigned int md_len;
1622 pthread_mutex_lock(&lock);
1624 EVP_MD_CTX_init(&mdctx);
1629 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1630 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1631 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1634 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1635 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1636 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1637 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1638 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1639 pthread_mutex_unlock(&lock);
1644 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1647 for (i = 0; i < 16; i++)
1650 for (offset = 16; offset < len; offset += 16) {
1652 printf("text + offset - 16 c(%d): ", offset / 16);
1653 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1655 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1656 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1657 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1658 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1660 pthread_mutex_unlock(&lock);
1664 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1667 for (i = 0; i < 16; i++)
1668 text[offset + i] ^= hash[i];
1672 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1675 pthread_mutex_unlock(&lock);
1679 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1680 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1681 static unsigned char first = 1;
1682 static EVP_MD_CTX mdctx;
1683 unsigned char hash[EVP_MAX_MD_SIZE];
1684 unsigned int md_len;
1688 pthread_mutex_lock(&lock);
1690 EVP_MD_CTX_init(&mdctx);
1695 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1696 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1697 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1700 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1701 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1702 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1703 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1704 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1705 pthread_mutex_unlock(&lock);
1710 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1713 for (i = 0; i < 16; i++)
1714 plain[i] = text[i] ^ hash[i];
1716 for (offset = 16; offset < len; offset += 16) {
1718 printf("text + offset - 16 c(%d): ", offset / 16);
1719 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1721 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1722 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1723 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1724 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1726 pthread_mutex_unlock(&lock);
1730 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1733 for (i = 0; i < 16; i++)
1734 plain[offset + i] = text[offset + i] ^ hash[i];
1737 memcpy(text, plain, len);
1739 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1742 pthread_mutex_unlock(&lock);
1746 struct realm *id2realm(struct list *realmlist, char *id) {
1747 struct list_node *entry;
1748 struct realm *realm, *subrealm = NULL;
1750 /* need to do locking for subrealms and check subrealm timers */
1751 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1752 realm = (struct realm *)entry->data;
1753 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1754 pthread_mutex_lock(&realm->subrealms_mutex);
1755 if (realm->subrealms)
1756 subrealm = id2realm(realm->subrealms, id);
1757 pthread_mutex_unlock(&realm->subrealms_mutex);
1758 return subrealm ? subrealm : realm;
1764 /* helper function, only used by removeserversubrealms() */
1765 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1766 struct list_node *entry;
1767 struct realm *realm;
1769 for (entry = list_first(realmlist); entry;) {
1770 realm = (struct realm *)entry->data;
1771 entry = list_next(entry);
1772 if (realm->srvconfs) {
1773 list_removedata(realm->srvconfs, srv);
1774 if (!list_first(realm->srvconfs)) {
1775 list_destroy(realm->srvconfs);
1776 realm->srvconfs = NULL;
1779 if (realm->accsrvconfs) {
1780 list_removedata(realm->accsrvconfs, srv);
1781 if (!list_first(realm->accsrvconfs)) {
1782 list_destroy(realm->accsrvconfs);
1783 realm->accsrvconfs = NULL;
1787 /* remove subrealm if no servers */
1788 if (!realm->srvconfs && !realm->accsrvconfs) {
1789 list_removedata(realmlist, realm);
1795 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1796 struct list_node *entry;
1797 struct realm *realm;
1799 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1800 realm = (struct realm *)entry->data;
1801 pthread_mutex_lock(&realm->subrealms_mutex);
1802 if (realm->subrealms) {
1803 _internal_removeserversubrealms(realm->subrealms, srv);
1804 if (!list_first(realm->subrealms)) {
1805 list_destroy(realm->subrealms);
1806 realm->subrealms = NULL;
1809 pthread_mutex_unlock(&realm->subrealms_mutex);
1813 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1814 struct request *rq = to->requests, *end;
1816 pthread_mutex_lock(&to->newrq_mutex);
1817 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1818 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1820 pthread_mutex_unlock(&to->newrq_mutex);
1825 int attrvalidate(unsigned char *attrs, int length) {
1826 while (length > 1) {
1827 if (ATTRLEN(attrs) < 2) {
1828 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1831 length -= ATTRLEN(attrs);
1833 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1836 attrs += ATTRLEN(attrs);
1839 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1843 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1844 if (len < 16 || len > 128 || len % 16) {
1845 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1849 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1850 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1854 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1856 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1857 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1863 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1866 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1867 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1870 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1871 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1877 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1878 char *oldsecret, char *newsecret) {
1879 unsigned char *attr;
1881 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1882 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1883 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1889 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1893 for (; attrs[0]; attrs += 2)
1894 if (attrs[0] == vendor && attrs[1] == subattr)
1899 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1900 uint8_t alen, sublen, rmlen = 0;
1901 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1904 if (!removevendorattrs)
1907 while (*removevendorattrs && *removevendorattrs != vendor)
1908 removevendorattrs += 2;
1909 if (!*removevendorattrs)
1912 alen = ATTRLEN(attrs);
1914 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1915 /* remove entire vendor attribute */
1916 memmove(attrs, attrs + alen, length - alen);
1921 subattrs = ATTRVAL(attrs) + 4;
1923 if (!attrvalidate(subattrs, sublen)) {
1924 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1929 while (sublen > 1) {
1930 alen = ATTRLEN(subattrs);
1933 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1934 memmove(subattrs, subattrs + alen, length);
1940 ATTRLEN(attrs) -= rmlen;
1944 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1945 uint8_t *attrs, alen;
1946 uint16_t len, rmlen = 0;
1948 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1951 len = RADLEN(buf) - 20;
1954 alen = ATTRLEN(attrs);
1956 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1957 memmove(attrs, attrs + alen, len);
1959 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1960 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1965 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1968 /* returns a pointer to the resized attribute value */
1969 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1970 uint8_t *attrs, *attr, vallen;
1974 len = RADLEN(*buf) - 20;
1977 attr = attrget(attrs, len, type);
1981 vallen = ATTRVALLEN(attr);
1982 if (vallen == newvallen)
1985 len += newvallen - vallen;
1986 if (newvallen > vallen) {
1987 new = realloc(*buf, len + 20);
1989 debug(DBG_ERR, "resizeattr: malloc failed");
1998 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1999 attr[1] = newvallen + 2;
2000 ((uint16_t *)*buf)[1] = htons(len + 20);
2004 int rewriteusername(struct request *rq, char *in) {
2005 size_t nmatch = 10, reslen = 0, start = 0;
2006 regmatch_t pmatch[10], *pfield;
2008 unsigned char *result;
2009 char *out = rq->from->conf->rewriteattrreplacement;
2011 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
2012 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
2016 rq->origusername = stringcopy(in, 0);
2017 if (!rq->origusername)
2020 for (i = start; out[i]; i++) {
2021 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2022 pfield = &pmatch[out[i + 1] - '0'];
2023 if (pfield->rm_so >= 0) {
2024 reslen += i - start + pfield->rm_eo - pfield->rm_so;
2030 reslen += i - start;
2032 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
2038 for (i = start; out[i]; i++) {
2039 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
2040 pfield = &pmatch[out[i + 1] - '0'];
2041 if (pfield->rm_so >= 0) {
2042 memcpy(result + reslen, out + start, i - start);
2043 reslen += i - start;
2044 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
2045 reslen += pfield->rm_eo - pfield->rm_so;
2052 memcpy(result + reslen, out + start, i - start);
2053 reslen += i - start;
2054 memcpy(in, result, reslen);
2059 const char *radmsgtype2string(uint8_t code) {
2060 static const char *rad_msg_names[] = {
2061 "", "Access-Request", "Access-Accept", "Access-Reject",
2062 "Accounting-Request", "Accounting-Response", "", "",
2063 "", "", "", "Access-Challenge",
2064 "Status-Server", "Status-Client"
2066 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
2069 void char2hex(char *h, unsigned char c) {
2070 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
2071 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
2072 h[0] = hexdigits[c / 16];
2073 h[1] = hexdigits[c % 16];
2077 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
2081 if (!attr || len == 1) {
2086 l = ATTRVALLEN(attr);
2087 s = (char *)ATTRVAL(attr);
2090 for (i = 0; i < l; i++) {
2091 if (s[i] > 31 && s[i] < 127) {
2093 if (d - ascii == len - 1)
2096 if (d - ascii > len - 4)
2101 if (d - ascii == len - 1)
2109 void acclog(unsigned char *attrs, int length, char *host) {
2110 unsigned char *attr;
2113 attr = attrget(attrs, length, RAD_Attr_User_Name);
2115 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
2118 radattr2ascii(username, sizeof(username), attr);
2119 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
2122 void respondaccounting(struct request *rq) {
2123 unsigned char *resp;
2127 debug(DBG_ERR, "respondaccounting: malloc failed");
2130 memcpy(resp, rq->buf, 20);
2131 resp[0] = RAD_Accounting_Response;
2134 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
2135 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2138 void respondstatusserver(struct request *rq) {
2139 unsigned char *resp;
2143 debug(DBG_ERR, "respondstatusserver: malloc failed");
2146 memcpy(resp, rq->buf, 20);
2147 resp[0] = RAD_Access_Accept;
2150 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
2151 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2154 void respondreject(struct request *rq, char *message) {
2155 unsigned char *resp;
2158 if (message && *message)
2159 len += 2 + strlen(message);
2163 debug(DBG_ERR, "respondreject: malloc failed");
2166 memcpy(resp, rq->buf, 20);
2167 resp[0] = RAD_Access_Reject;
2168 *(uint16_t *)(resp + 2) = htons(len);
2169 if (message && *message) {
2170 resp[20] = RAD_Attr_Reply_Message;
2171 resp[21] = len - 20;
2172 memcpy(resp + 22, message, len - 22);
2174 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
2177 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
2178 struct list_node *entry;
2179 struct clsrvconf *server, *best = NULL, *first = NULL;
2181 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2182 server = (struct clsrvconf *)entry->data;
2183 if (!server->servers)
2187 if (!server->servers->connectionok)
2189 if (!server->servers->lostrqs)
2195 if (server->servers->lostrqs < best->servers->lostrqs)
2198 return best ? best : first;
2201 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
2202 struct clsrvconf *srvconf;
2204 *realm = id2realm(realms, id);
2207 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2208 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2211 if (!acc && !srvconf->servers)
2212 adddynamicrealmserver(*realm, srvconf, id);
2213 return srvconf->servers;
2216 /* returns 0 if validation/authentication fails, else 1 */
2217 int radsrv(struct request *rq) {
2218 uint8_t code, id, *auth, *attrs, *attr;
2220 struct server *to = NULL;
2221 char username[254], userascii[760];
2222 unsigned char newauth[16];
2223 struct realm *realm = NULL;
2225 code = *(uint8_t *)rq->buf;
2226 id = *(uint8_t *)(rq->buf + 1);
2227 len = RADLEN(rq->buf);
2228 auth = (uint8_t *)(rq->buf + 4);
2230 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2232 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2233 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2238 attrs = rq->buf + 20;
2240 if (!attrvalidate(attrs, len)) {
2241 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2245 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2246 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2247 debug(DBG_WARN, "radsrv: message authentication failed");
2251 if (code == RAD_Status_Server) {
2252 respondstatusserver(rq);
2256 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2258 if (code == RAD_Accounting_Request) {
2259 memset(newauth, 0, 16);
2260 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2261 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2266 if (rq->from->conf->rewrite) {
2267 dorewrite(rq->buf, rq->from->conf->rewrite);
2268 len = RADLEN(rq->buf) - 20;
2271 attr = attrget(attrs, len, RAD_Attr_User_Name);
2273 if (code == RAD_Accounting_Request) {
2274 acclog(attrs, len, rq->from->conf->host);
2275 respondaccounting(rq);
2277 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2280 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2281 username[ATTRVALLEN(attr)] = '\0';
2282 radattr2ascii(userascii, sizeof(userascii), attr);
2284 if (rq->from->conf->rewriteattrregex) {
2285 if (!rewriteusername(rq, username)) {
2286 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2289 len = RADLEN(rq->buf) - 20;
2290 auth = (uint8_t *)(rq->buf + 4);
2291 attrs = rq->buf + 20;
2294 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2296 to = findserver(&realm, username, code == RAD_Accounting_Request);
2298 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2302 if (realm->message && code == RAD_Access_Request) {
2303 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2304 respondreject(rq, realm->message);
2305 } else if (realm->accresp && code == RAD_Accounting_Request) {
2306 acclog(attrs, len, rq->from->conf->host);
2307 respondaccounting(rq);
2312 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2313 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2314 rq->from->conf->name, to->conf->name);
2318 if (rqinqueue(to, rq->from, id, code)) {
2319 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2320 radmsgtype2string(code), rq->from->conf->host, id);
2324 if (code != RAD_Accounting_Request) {
2325 if (!RAND_bytes(newauth, 16)) {
2326 debug(DBG_WARN, "radsrv: failed to generate random auth");
2332 printfchars(NULL, "auth", "%02x ", auth, 16);
2335 attr = attrget(attrs, len, RAD_Attr_User_Password);
2337 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2338 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2342 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2344 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2345 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2350 memcpy(rq->origauth, auth, 16);
2351 memcpy(auth, newauth, 16);
2364 int replyh(struct server *server, unsigned char *buf) {
2365 struct client *from;
2368 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2369 struct sockaddr_storage fromsa;
2370 char tmp[760], stationid[760];
2372 server->connectionok = 1;
2373 server->lostrqs = 0;
2375 i = buf[1]; /* i is the id */
2377 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2378 && *buf != RAD_Accounting_Response) {
2379 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2382 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2384 rq = server->requests + i;
2386 pthread_mutex_lock(&server->newrq_mutex);
2387 if (!rq->buf || !rq->tries) {
2388 pthread_mutex_unlock(&server->newrq_mutex);
2389 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2394 pthread_mutex_unlock(&server->newrq_mutex);
2395 debug(DBG_INFO, "replyh: already received, ignoring reply");
2399 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2400 pthread_mutex_unlock(&server->newrq_mutex);
2401 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2405 len = RADLEN(buf) - 20;
2408 if (!attrvalidate(attrs, len)) {
2409 pthread_mutex_unlock(&server->newrq_mutex);
2410 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2414 /* Message Authenticator */
2415 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2417 if (ATTRVALLEN(messageauth) != 16) {
2418 pthread_mutex_unlock(&server->newrq_mutex);
2419 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2422 memcpy(tmp, buf + 4, 16);
2423 memcpy(buf + 4, rq->buf + 4, 16);
2424 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2425 pthread_mutex_unlock(&server->newrq_mutex);
2426 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2429 memcpy(buf + 4, tmp, 16);
2430 debug(DBG_DBG, "replyh: message auth ok");
2433 gettimeofday(&server->lastrcv, NULL);
2435 if (*rq->buf == RAD_Status_Server) {
2437 pthread_mutex_unlock(&server->newrq_mutex);
2438 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2442 gettimeofday(&server->lastreply, NULL);
2446 pthread_mutex_unlock(&server->newrq_mutex);
2447 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2451 if (server->conf->rewrite) {
2452 dorewrite(buf, server->conf->rewrite);
2453 len = RADLEN(buf) - 20;
2457 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2458 if (ATTRVALLEN(attr) <= 4)
2461 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2464 sublen = ATTRVALLEN(attr) - 4;
2465 subattrs = ATTRVAL(attr) + 4;
2466 if (!attrvalidate(subattrs, sublen) ||
2467 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2468 rq, server->conf->secret, from->conf->secret) ||
2469 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2470 rq, server->conf->secret, from->conf->secret))
2474 pthread_mutex_unlock(&server->newrq_mutex);
2475 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2479 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2480 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2482 radattr2ascii(tmp, sizeof(tmp), attr);
2483 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2485 radattr2ascii(stationid, sizeof(stationid), attr);
2486 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2487 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2489 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2493 buf[1] = (char)rq->origid;
2494 memcpy(buf + 4, rq->origauth, 16);
2496 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2499 if (rq->origusername) {
2500 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2502 pthread_mutex_unlock(&server->newrq_mutex);
2503 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2506 memcpy(username, rq->origusername, strlen(rq->origusername));
2507 len = RADLEN(buf) - 20;
2510 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2514 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2515 pthread_mutex_unlock(&server->newrq_mutex);
2516 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2519 debug(DBG_DBG, "replyh: computed messageauthattr");
2522 fromsa = rq->fromsa; /* only needed for UDP */
2523 /* once we set received = 1, rq may be reused */
2526 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2527 sendreply(from, buf, &fromsa, rq->fromudpsock);
2528 pthread_mutex_unlock(&server->newrq_mutex);
2532 void *udpclientrd(void *arg) {
2533 struct server *server;
2535 int *s = (int *)arg;
2539 buf = radudpget(*s, NULL, &server, NULL);
2540 if (!replyh(server, buf))
2545 void *tlsclientrd(void *arg) {
2546 struct server *server = (struct server *)arg;
2548 struct timeval now, lastconnecttry;
2551 /* yes, lastconnecttry is really necessary */
2552 lastconnecttry = server->lastconnecttry;
2553 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2555 if (server->dynamiclookuparg)
2557 tlsconnect(server, &lastconnecttry, 0, "tlsclientrd");
2561 if (!replyh(server, buf))
2563 if (server->dynamiclookuparg) {
2564 gettimeofday(&now, NULL);
2565 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2566 debug(DBG_INFO, "tlsclientrd: idle timeout for %s", server->conf->name);
2571 ERR_remove_state(0);
2572 server->clientrdgone = 1;
2576 void *dtlsclientrd(void *arg) {
2577 struct server *server = (struct server *)arg;
2582 ERR_remove_state(0);
2583 server->clientrdgone = 1;
2587 void *tcpclientrd(void *arg) {
2588 struct server *server = (struct server *)arg;
2590 struct timeval lastconnecttry;
2593 /* yes, lastconnecttry is really necessary */
2594 lastconnecttry = server->lastconnecttry;
2595 buf = radtcpget(server->sock, 0);
2597 tcpconnect(server, &lastconnecttry, 0, "tcpclientrd");
2601 if (!replyh(server, buf))
2604 server->clientrdgone = 1;
2608 /* code for removing state not finished */
2609 void *clientwr(void *arg) {
2610 struct server *server = (struct server *)arg;
2612 pthread_t clientrdth;
2613 int i, dynconffail = 0;
2616 struct timespec timeout;
2617 struct request statsrvrq;
2618 unsigned char statsrvbuf[38];
2619 struct clsrvconf *conf;
2621 conf = server->conf;
2623 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2628 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2629 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2633 memset(&timeout, 0, sizeof(struct timespec));
2635 if (conf->statusserver) {
2636 memset(&statsrvrq, 0, sizeof(struct request));
2637 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2638 statsrvbuf[0] = RAD_Status_Server;
2640 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2641 statsrvbuf[21] = 18;
2642 gettimeofday(&server->lastrcv, NULL);
2645 if (conf->pdef->connecter) {
2646 if (!conf->pdef->connecter(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2648 server->connectionok = 1;
2649 if (pthread_create(&clientrdth, NULL, conf->pdef->clientreader, (void *)server)) {
2650 debug(DBG_ERR, "clientwr: pthread_create failed");
2654 server->connectionok = 1;
2657 pthread_mutex_lock(&server->newrq_mutex);
2658 if (!server->newrq) {
2659 gettimeofday(&now, NULL);
2660 /* random 0-7 seconds */
2661 RAND_bytes(&rnd, 1);
2663 if (conf->statusserver) {
2664 if (!timeout.tv_sec || timeout.tv_sec > server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd)
2665 timeout.tv_sec = server->lastrcv.tv_sec + STATUS_SERVER_PERIOD + rnd;
2667 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2668 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2671 if (timeout.tv_sec > now.tv_sec)
2672 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2674 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2677 if (server->newrq) {
2678 debug(DBG_DBG, "clientwr: got new request");
2683 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2685 pthread_mutex_unlock(&server->newrq_mutex);
2687 for (i = 0; i < MAX_REQUESTS; i++) {
2688 if (server->clientrdgone) {
2689 pthread_join(clientrdth, NULL);
2692 pthread_mutex_lock(&server->newrq_mutex);
2693 while (i < MAX_REQUESTS && !server->requests[i].buf)
2695 if (i == MAX_REQUESTS) {
2696 pthread_mutex_unlock(&server->newrq_mutex);
2699 rq = server->requests + i;
2702 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2704 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2706 /* setting this to NULL means that it can be reused */
2709 pthread_mutex_unlock(&server->newrq_mutex);
2713 gettimeofday(&now, NULL);
2714 if (now.tv_sec < rq->expiry.tv_sec) {
2715 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2716 timeout.tv_sec = rq->expiry.tv_sec;
2717 pthread_mutex_unlock(&server->newrq_mutex);
2721 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2722 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2723 if (conf->statusserver) {
2724 if (*rq->buf == RAD_Status_Server) {
2725 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2726 if (server->lostrqs < 255)
2730 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2731 if (server->lostrqs < 255)
2735 /* setting this to NULL means that it can be reused */
2737 pthread_mutex_unlock(&server->newrq_mutex);
2740 pthread_mutex_unlock(&server->newrq_mutex);
2742 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2743 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2744 timeout.tv_sec = rq->expiry.tv_sec;
2746 conf->pdef->clientradput(server, server->requests[i].buf);
2748 if (conf->statusserver) {
2749 gettimeofday(&now, NULL);
2750 if (now.tv_sec - server->lastrcv.tv_sec >= STATUS_SERVER_PERIOD) {
2751 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2752 debug(DBG_WARN, "clientwr: failed to generate random auth");
2755 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2756 if (!statsrvrq.buf) {
2757 debug(DBG_ERR, "clientwr: malloc failed");
2760 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2761 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2762 sendrq(server, &statsrvrq);
2767 conf->servers = NULL;
2768 if (server->dynamiclookuparg) {
2769 removeserversubrealms(realms, conf);
2773 freeclsrvconf(conf);
2775 freeserver(server, 1);
2776 ERR_remove_state(0);
2780 void *udpserverwr(void *arg) {
2781 struct replyq *replyq = udp_server_replyq;
2782 struct reply *reply;
2785 pthread_mutex_lock(&replyq->mutex);
2786 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2787 debug(DBG_DBG, "udp server writer, waiting for signal");
2788 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2789 debug(DBG_DBG, "udp server writer, got signal");
2791 pthread_mutex_unlock(&replyq->mutex);
2793 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2794 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2795 debug(DBG_WARN, "sendudp: send failed");
2801 void *udpserverrd(void *arg) {
2803 int *sp = (int *)arg;
2806 memset(&rq, 0, sizeof(struct request));
2807 rq.buf = radudpget(*sp, &rq.from, NULL, &rq.fromsa);
2808 rq.fromudpsock = *sp;
2814 void *tlsserverwr(void *arg) {
2816 unsigned long error;
2817 struct client *client = (struct client *)arg;
2818 struct replyq *replyq;
2819 struct reply *reply;
2821 debug(DBG_DBG, "tlsserverwr: starting for %s", client->conf->host);
2822 replyq = client->replyq;
2824 pthread_mutex_lock(&replyq->mutex);
2825 while (!list_first(replyq->replies)) {
2827 debug(DBG_DBG, "tlsserverwr: waiting for signal");
2828 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2829 debug(DBG_DBG, "tlsserverwr: got signal");
2832 /* ssl might have changed while waiting */
2833 pthread_mutex_unlock(&replyq->mutex);
2834 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2835 ERR_remove_state(0);
2839 reply = (struct reply *)list_shift(replyq->replies);
2840 pthread_mutex_unlock(&replyq->mutex);
2841 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2843 debug(DBG_DBG, "tlsserverwr: sent %d bytes, Radius packet of length %d",
2844 cnt, RADLEN(reply->buf));
2846 while ((error = ERR_get_error()))
2847 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2853 void tlsserverrd(struct client *client) {
2855 pthread_t tlsserverwrth;
2857 debug(DBG_DBG, "tlsserverrd: starting for %s", client->conf->host);
2859 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2860 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2865 memset(&rq, 0, sizeof(struct request));
2866 rq.buf = radtlsget(client->ssl, 0);
2868 debug(DBG_ERR, "tlsserverrd: connection from %s lost", client->conf->host);
2871 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2874 debug(DBG_ERR, "tlsserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
2879 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2881 pthread_mutex_lock(&client->replyq->mutex);
2882 pthread_cond_signal(&client->replyq->cond);
2883 pthread_mutex_unlock(&client->replyq->mutex);
2884 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2885 pthread_join(tlsserverwrth, NULL);
2886 removeclientrqs(client);
2887 debug(DBG_DBG, "tlsserverrd: reader for %s exiting", client->conf->host);
2890 void *tlsservernew(void *arg) {
2892 struct sockaddr_storage from;
2893 size_t fromlen = sizeof(from);
2894 struct clsrvconf *conf;
2895 struct list_node *cur = NULL;
2898 unsigned long error;
2899 struct client *client;
2902 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2903 debug(DBG_DBG, "tlsservernew: getpeername failed, exiting");
2906 debug(DBG_WARN, "tlsservernew: incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2908 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2910 ssl = SSL_new(conf->ssl_ctx);
2913 if (SSL_accept(ssl) <= 0) {
2914 while ((error = ERR_get_error()))
2915 debug(DBG_ERR, "tlsservernew: SSL: %s", ERR_error_string(error, NULL));
2916 debug(DBG_ERR, "tlsservernew: SSL_accept failed");
2919 cert = verifytlscert(ssl);
2925 if (verifyconfcert(cert, conf)) {
2927 client = addclient(conf);
2930 tlsserverrd(client);
2931 removeclient(client);
2933 debug(DBG_WARN, "tlsservernew: failed to create new client instance");
2936 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2938 debug(DBG_WARN, "tlsservernew: ignoring request, no matching TLS client");
2944 ERR_remove_state(0);
2945 shutdown(s, SHUT_RDWR);
2950 void *tlslistener(void *arg) {
2951 pthread_t tlsserverth;
2952 int s, *sp = (int *)arg;
2953 struct sockaddr_storage from;
2954 size_t fromlen = sizeof(from);
2959 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
2961 debug(DBG_WARN, "accept failed");
2964 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2965 debug(DBG_ERR, "tlslistener: pthread_create failed");
2966 shutdown(s, SHUT_RDWR);
2970 pthread_detach(tlsserverth);
2976 void *tcpserverwr(void *arg) {
2978 struct client *client = (struct client *)arg;
2979 struct replyq *replyq;
2980 struct reply *reply;
2982 debug(DBG_DBG, "tcpserverwr: starting for %s", client->conf->host);
2983 replyq = client->replyq;
2985 pthread_mutex_lock(&replyq->mutex);
2986 while (!list_first(replyq->replies)) {
2987 if (client->s >= 0) {
2988 debug(DBG_DBG, "tcpserverwr: waiting for signal");
2989 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2990 debug(DBG_DBG, "tcpserverwr: got signal");
2992 if (client->s < 0) {
2993 /* s might have changed while waiting */
2994 pthread_mutex_unlock(&replyq->mutex);
2995 debug(DBG_DBG, "tcpserverwr: exiting as requested");
2999 reply = (struct reply *)list_shift(replyq->replies);
3000 pthread_mutex_unlock(&replyq->mutex);
3001 cnt = write(client->s, reply->buf, RADLEN(reply->buf));
3003 debug(DBG_DBG, "tcpserverwr: sent %d bytes, Radius packet of length %d",
3004 cnt, RADLEN(reply->buf));
3006 debug(DBG_ERR, "tcpserverwr: write error for %s", client->conf->host);
3012 void tcpserverrd(struct client *client) {
3014 pthread_t tcpserverwrth;
3016 debug(DBG_DBG, "tcpserverrd: starting for %s", client->conf->host);
3018 if (pthread_create(&tcpserverwrth, NULL, tcpserverwr, (void *)client)) {
3019 debug(DBG_ERR, "tcpserverrd: pthread_create failed");
3024 memset(&rq, 0, sizeof(struct request));
3025 rq.buf = radtcpget(client->s, 0);
3027 debug(DBG_ERR, "tcpserverrd: connection from %s lost", client->conf->host);
3030 debug(DBG_DBG, "tcpserverrd: got Radius message from %s", client->conf->host);
3033 debug(DBG_ERR, "tcpserverrd: message authentication/validation failed, closing connection from %s", client->conf->host);
3038 /* stop writer by setting s to -1 and give signal in case waiting for data */
3040 pthread_mutex_lock(&client->replyq->mutex);
3041 pthread_cond_signal(&client->replyq->cond);
3042 pthread_mutex_unlock(&client->replyq->mutex);
3043 debug(DBG_DBG, "tcpserverrd: waiting for writer to end");
3044 pthread_join(tcpserverwrth, NULL);
3045 removeclientrqs(client);
3046 debug(DBG_DBG, "tcpserverrd: reader for %s exiting", client->conf->host);
3049 void *tcpservernew(void *arg) {
3051 struct sockaddr_storage from;
3052 size_t fromlen = sizeof(from);
3053 struct clsrvconf *conf;
3054 struct client *client;
3057 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
3058 debug(DBG_DBG, "tcpservernew: getpeername failed, exiting");
3061 debug(DBG_WARN, "tcpservernew: incoming TCP connection from %s", addr2string((struct sockaddr *)&from, fromlen));
3063 conf = find_conf(RAD_TCP, (struct sockaddr *)&from, clconfs, NULL);
3065 client = addclient(conf);
3068 tcpserverrd(client);
3069 removeclient(client);
3071 debug(DBG_WARN, "tcpservernew: failed to create new client instance");
3073 debug(DBG_WARN, "tcpservernew: ignoring request, no matching TCP client");
3076 shutdown(s, SHUT_RDWR);
3081 void *tcplistener(void *arg) {
3082 pthread_t tcpserverth;
3083 int s, *sp = (int *)arg;
3084 struct sockaddr_storage from;
3085 size_t fromlen = sizeof(from);
3090 s = accept(*sp, (struct sockaddr *)&from, &fromlen);
3092 debug(DBG_WARN, "accept failed");
3095 if (pthread_create(&tcpserverth, NULL, tcpservernew, (void *)&s)) {
3096 debug(DBG_ERR, "tcplistener: pthread_create failed");
3097 shutdown(s, SHUT_RDWR);
3101 pthread_detach(tcpserverth);
3107 void createlistener(uint8_t type, char *arg) {
3109 struct clsrvconf *listenres;
3110 struct addrinfo *res;
3111 int s = -1, on = 1, *sp = NULL;
3113 listenres = resolve_hostport(type, arg, protodefs[type].portdefault);
3115 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
3117 for (res = listenres->addrinfo; res; res = res->ai_next) {
3118 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
3120 debug(DBG_WARN, "createlistener: socket failed");
3123 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
3125 if (res->ai_family == AF_INET6)
3126 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
3128 if (bind(s, res->ai_addr, res->ai_addrlen)) {
3129 debug(DBG_WARN, "createlistener: bind failed");
3135 sp = malloc(sizeof(int));
3137 debugx(1, DBG_ERR, "malloc failed");
3139 if (pthread_create(&th, NULL, protodefs[type].listener, (void *)sp))
3140 debugx(1, DBG_ERR, "pthread_create failed");
3144 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
3146 debug(DBG_WARN, "createlistener: listening for %s on %s:%s", protodefs[type].name,
3147 listenres->host ? listenres->host : "*", listenres->port);
3148 freeclsrvres(listenres);
3151 void createlisteners(uint8_t type, char **args) {
3155 for (i = 0; args[i]; i++)
3156 createlistener(type, args[i]);
3158 createlistener(type, NULL);
3161 SSL_CTX *tlscreatectx(uint8_t type, struct tls *conf) {
3162 SSL_CTX *ctx = NULL;
3163 STACK_OF(X509_NAME) *calist;
3166 unsigned long error;
3169 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
3170 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
3171 for (i = 0; i < CRYPTO_num_locks(); i++) {
3172 ssl_lock_count[i] = 0;
3173 pthread_mutex_init(&ssl_locks[i], NULL);
3175 CRYPTO_set_id_callback(ssl_thread_id);
3176 CRYPTO_set_locking_callback(ssl_locking_callback);
3178 SSL_load_error_strings();
3181 while (!RAND_status()) {
3182 time_t t = time(NULL);
3183 pid_t pid = getpid();
3184 RAND_seed((unsigned char *)&t, sizeof(time_t));
3185 RAND_seed((unsigned char *)&pid, sizeof(pid));
3191 ctx = SSL_CTX_new(TLSv1_method());
3194 ctx = SSL_CTX_new(DTLSv1_method());
3195 SSL_CTX_set_read_ahead(ctx, 1);
3199 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3203 if (conf->certkeypwd) {
3204 SSL_CTX_set_default_passwd_cb_userdata(ctx, conf->certkeypwd);
3205 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
3207 if (!SSL_CTX_use_certificate_chain_file(ctx, conf->certfile) ||
3208 !SSL_CTX_use_PrivateKey_file(ctx, conf->certkeyfile, SSL_FILETYPE_PEM) ||
3209 !SSL_CTX_check_private_key(ctx) ||
3210 !SSL_CTX_load_verify_locations(ctx, conf->cacertfile, conf->cacertpath)) {
3211 while ((error = ERR_get_error()))
3212 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3213 debug(DBG_ERR, "tlscreatectx: Error initialising SSL/TLS in TLS context %s", conf->name);
3218 calist = conf->cacertfile ? SSL_load_client_CA_file(conf->cacertfile) : NULL;
3219 if (!conf->cacertfile || calist) {
3220 if (conf->cacertpath) {
3222 calist = sk_X509_NAME_new_null();
3223 if (!SSL_add_dir_cert_subjects_to_stack(calist, conf->cacertpath)) {
3224 sk_X509_NAME_free(calist);
3230 while ((error = ERR_get_error()))
3231 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
3232 debug(DBG_ERR, "tlscreatectx: Error adding CA subjects in TLS context %s", conf->name);
3236 ERR_clear_error(); /* add_dir_cert_subj returns errors on success */
3237 SSL_CTX_set_client_CA_list(ctx, calist);
3239 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
3240 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
3242 if (conf->crlcheck) {
3243 x509_s = SSL_CTX_get_cert_store(ctx);
3244 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
3247 debug(DBG_DBG, "tlscreatectx: created TLS context %s", conf->name);
3251 SSL_CTX *tlsgetctx(uint8_t type, char *alt1, char *alt2) {
3252 struct list_node *entry;
3253 struct tls *t, *t1 = NULL, *t2 = NULL;
3254 SSL_CTX *ctx = NULL;
3256 pthread_mutex_lock(&tlsconfs_lock);
3258 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
3259 t = (struct tls *)entry->data;
3260 if (!strcasecmp(t->name, alt1)) {
3264 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
3275 t->tlsctx = tlscreatectx(RAD_TLS, t);
3280 t->dtlsctx = tlscreatectx(RAD_DTLS, t);
3286 pthread_mutex_unlock(&tlsconfs_lock);
3290 struct list *addsrvconfs(char *value, char **names) {
3291 struct list *conflist;
3293 struct list_node *entry;
3294 struct clsrvconf *conf = NULL;
3296 if (!names || !*names)
3299 conflist = list_create();
3301 debug(DBG_ERR, "malloc failed");
3305 for (n = 0; names[n]; n++) {
3306 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3307 conf = (struct clsrvconf *)entry->data;
3308 if (!strcasecmp(names[n], conf->name))
3312 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
3313 list_destroy(conflist);
3316 if (!list_push(conflist, conf)) {
3317 debug(DBG_ERR, "malloc failed");
3318 list_destroy(conflist);
3321 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
3326 void freerealm(struct realm *realm) {
3330 free(realm->message);
3331 regfree(&realm->regex);
3332 pthread_mutex_destroy(&realm->subrealms_mutex);
3333 if (realm->subrealms)
3334 list_destroy(realm->subrealms);
3335 if (realm->srvconfs) {
3336 /* emptying list without freeing data */
3337 while (list_shift(realm->srvconfs));
3338 list_destroy(realm->srvconfs);
3340 if (realm->accsrvconfs) {
3341 /* emptying list without freeing data */
3342 while (list_shift(realm->accsrvconfs));
3343 list_destroy(realm->accsrvconfs);
3348 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
3350 struct realm *realm;
3351 char *s, *regex = NULL;
3353 if (*value == '/') {
3354 /* regexp, remove optional trailing / if present */
3355 if (value[strlen(value) - 1] == '/')
3356 value[strlen(value) - 1] = '\0';
3358 /* not a regexp, let us make it one */
3359 if (*value == '*' && !value[1])
3360 regex = stringcopy(".*", 0);
3362 for (n = 0, s = value; *s;)
3365 regex = malloc(strlen(value) + n + 3);
3368 for (n = 1, s = value; *s; s++) {
3378 debug(DBG_ERR, "malloc failed");
3382 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
3385 realm = malloc(sizeof(struct realm));
3387 debug(DBG_ERR, "malloc failed");
3390 memset(realm, 0, sizeof(struct realm));
3392 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
3393 debug(DBG_ERR, "mutex init failed");
3399 realm->name = stringcopy(value, 0);
3401 debug(DBG_ERR, "malloc failed");
3404 if (message && strlen(message) > 253) {
3405 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3408 realm->message = message;
3409 realm->accresp = accresp;
3411 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3412 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3416 if (servers && *servers) {
3417 realm->srvconfs = addsrvconfs(value, servers);
3418 if (!realm->srvconfs)
3422 if (accservers && *accservers) {
3423 realm->accsrvconfs = addsrvconfs(value, accservers);
3424 if (!realm->accsrvconfs)
3428 if (!list_push(realmlist, realm)) {
3429 debug(DBG_ERR, "malloc failed");
3430 pthread_mutex_destroy(&realm->subrealms_mutex);
3434 debug(DBG_DBG, "addrealm: added realm %s", value);
3444 for (n = 0; servers[n]; n++)
3449 for (n = 0; accservers[n]; n++)
3450 free(accservers[n]);
3456 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3457 struct clsrvconf *srvconf;
3458 struct realm *newrealm = NULL;
3459 char *realmname, *s;
3462 if (!conf->dynamiclookupcommand)
3465 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3466 realmname = strrchr(id, '@');
3472 for (s = realmname; *s; s++)
3473 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3476 pthread_mutex_lock(&realm->subrealms_mutex);
3477 /* exit if we now already got a matching subrealm */
3478 if (id2realm(realm->subrealms, id))
3480 srvconf = malloc(sizeof(struct clsrvconf));
3482 debug(DBG_ERR, "malloc failed");
3486 if (!addserver(srvconf))
3489 if (!realm->subrealms)
3490 realm->subrealms = list_create();
3491 if (!realm->subrealms)
3493 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3497 /* add server and accserver to newrealm */
3498 newrealm->srvconfs = list_create();
3499 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3500 debug(DBG_ERR, "malloc failed");
3503 newrealm->accsrvconfs = list_create();
3504 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3505 debug(DBG_ERR, "malloc failed");
3509 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3511 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3512 debug(DBG_ERR, "pthread_create failed");
3515 pthread_detach(clientth);
3520 list_removedata(realm->subrealms, newrealm);
3521 freerealm(newrealm);
3522 if (!list_first(realm->subrealms)) {
3523 list_destroy(realm->subrealms);
3524 realm->subrealms = NULL;
3527 freeserver(srvconf->servers, 1);
3529 debug(DBG_ERR, "failed to create dynamic server");
3532 pthread_mutex_unlock(&realm->subrealms_mutex);
3535 int dynamicconfig(struct server *server) {
3536 int ok, fd[2], status;
3538 struct clsrvconf *conf = server->conf;
3539 struct gconffile *cf = NULL;
3541 /* for now we only learn hostname/address */
3542 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3545 debug(DBG_ERR, "dynamicconfig: pipe error");
3550 debug(DBG_ERR, "dynamicconfig: fork error");
3554 } else if (pid == 0) {
3557 if (fd[1] != STDOUT_FILENO) {
3558 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3559 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3562 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3563 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3567 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3568 ok = getgenericconfig(&cf, NULL,
3569 "Server", CONF_CBK, confserver_cb, (void *)conf,
3574 if (waitpid(pid, &status, 0) < 0) {
3575 debug(DBG_ERR, "dynamicconfig: wait error");
3580 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3588 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3592 int addmatchcertattr(struct clsrvconf *conf) {
3596 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3597 r = &conf->certcnregex;
3598 v = conf->matchcertattr + 4;
3599 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3600 r = &conf->certuriregex;
3601 v = conf->matchcertattr + 20;
3606 /* regexp, remove optional trailing / if present */
3607 if (v[strlen(v) - 1] == '/')
3608 v[strlen(v) - 1] = '\0';
3612 *r = malloc(sizeof(regex_t));
3614 debug(DBG_ERR, "malloc failed");
3617 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3620 debug(DBG_ERR, "failed to compile regular expression %s", v);
3626 int addrewriteattr(struct clsrvconf *conf) {
3629 v = conf->rewriteattr + 11;
3630 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3632 /* regexp, remove optional trailing / if present */
3633 if (v[strlen(v) - 1] == '/')
3634 v[strlen(v) - 1] = '\0';
3642 conf->rewriteattrregex = malloc(sizeof(regex_t));
3643 if (!conf->rewriteattrregex) {
3644 debug(DBG_ERR, "malloc failed");
3648 conf->rewriteattrreplacement = stringcopy(w, 0);
3649 if (!conf->rewriteattrreplacement) {
3650 free(conf->rewriteattrregex);
3651 conf->rewriteattrregex = NULL;
3655 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3656 free(conf->rewriteattrregex);
3657 conf->rewriteattrregex = NULL;
3658 free(conf->rewriteattrreplacement);
3659 conf->rewriteattrreplacement = NULL;
3660 debug(DBG_ERR, "failed to compile regular expression %s", v);
3667 /* should accept both names and numeric values, only numeric right now */
3668 uint8_t attrname2val(char *attrname) {
3671 val = atoi(attrname);
3672 return val > 0 && val < 256 ? val : 0;
3675 /* should accept both names and numeric values, only numeric right now */
3676 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3679 *vendor = atoi(attrname);
3680 s = strchr(attrname, ':');
3685 *type = atoi(s + 1);
3686 return *type >= 0 && *type < 256;
3689 struct rewrite *getrewrite(char *alt1, char *alt2) {
3690 struct list_node *entry;
3691 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3693 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3694 r = (struct rewriteconf *)entry->data;
3695 if (!strcasecmp(r->name, alt1)) {
3699 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3709 void addrewrite(char *value, char **attrs, char **vattrs) {
3710 struct rewriteconf *new;
3711 struct rewrite *rewrite = NULL;
3714 uint32_t *p, *va = NULL;
3718 for (; attrs[n]; n++);
3719 a = malloc((n + 1) * sizeof(uint8_t));
3721 debugx(1, DBG_ERR, "malloc failed");
3723 for (i = 0; i < n; i++) {
3724 if (!(a[i] = attrname2val(attrs[i])))
3725 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3734 for (; vattrs[n]; n++);
3735 va = malloc((2 * n + 1) * sizeof(uint32_t));
3737 debugx(1, DBG_ERR, "malloc failed");
3739 for (p = va, i = 0; i < n; i++, p += 2) {
3740 if (!vattrname2val(vattrs[i], p, p + 1))
3741 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3749 rewrite = malloc(sizeof(struct rewrite));
3751 debugx(1, DBG_ERR, "malloc failed");
3752 rewrite->removeattrs = a;
3753 rewrite->removevendorattrs = va;
3756 new = malloc(sizeof(struct rewriteconf));
3757 if (!new || !list_push(rewriteconfs, new))
3758 debugx(1, DBG_ERR, "malloc failed");
3760 memset(new, 0, sizeof(struct rewriteconf));
3761 new->name = stringcopy(value, 0);
3763 debugx(1, DBG_ERR, "malloc failed");
3765 new->rewrite = rewrite;
3766 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3769 void freeclsrvconf(struct clsrvconf *conf) {
3775 free(conf->matchcertattr);
3776 if (conf->certcnregex)
3777 regfree(conf->certcnregex);
3778 if (conf->certuriregex)
3779 regfree(conf->certuriregex);
3780 free(conf->confrewrite);
3781 free(conf->rewriteattr);
3782 if (conf->rewriteattrregex)
3783 regfree(conf->rewriteattrregex);
3784 free(conf->rewriteattrreplacement);
3785 free(conf->dynamiclookupcommand);
3786 free(conf->rewrite);
3788 freeaddrinfo(conf->addrinfo);
3789 /* not touching ssl_ctx, clients and servers */
3793 int mergeconfstring(char **dst, char **src) {
3802 t = stringcopy(*dst, 0);
3804 debug(DBG_ERR, "malloc failed");
3812 /* assumes dst is a shallow copy */
3813 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3814 if (!mergeconfstring(&dst->name, &src->name) ||
3815 !mergeconfstring(&dst->host, &src->host) ||
3816 !mergeconfstring(&dst->port, &src->port) ||
3817 !mergeconfstring(&dst->secret, &src->secret) ||
3818 !mergeconfstring(&dst->tls, &src->tls) ||
3819 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3820 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3821 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3824 dst->pdef = src->pdef;
3825 dst->statusserver = src->statusserver;
3826 dst->certnamecheck = src->certnamecheck;
3827 if (src->retryinterval != 255)
3828 dst->retryinterval = src->retryinterval;
3829 if (src->retrycount != 255)
3830 dst->retrycount = src->retrycount;
3834 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3835 struct clsrvconf *conf;
3836 char *conftype = NULL;
3838 debug(DBG_DBG, "confclient_cb called for %s", block);
3840 conf = malloc(sizeof(struct clsrvconf));
3841 if (!conf || !list_push(clconfs, conf))
3842 debugx(1, DBG_ERR, "malloc failed");
3843 memset(conf, 0, sizeof(struct clsrvconf));
3844 conf->certnamecheck = 1;
3846 if (!getgenericconfig(cf, block,
3847 "type", CONF_STR, &conftype,
3848 "host", CONF_STR, &conf->host,
3849 "secret", CONF_STR, &conf->secret,
3850 "tls", CONF_STR, &conf->tls,
3851 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3852 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3853 "rewrite", CONF_STR, &conf->confrewrite,
3854 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3857 debugx(1, DBG_ERR, "configuration error");
3859 conf->name = stringcopy(val, 0);
3861 conf->host = stringcopy(val, 0);
3862 if (!conf->name || !conf->host)
3863 debugx(1, DBG_ERR, "malloc failed");
3866 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
3867 conf->type = protoname2int(conftype);
3868 conf->pdef = &protodefs[conf->type];
3869 if (!conf->pdef->name)
3870 debugx(1, DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
3873 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3874 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultclient", "default");
3876 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3877 if (conf->matchcertattr && !addmatchcertattr(conf))
3878 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3881 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3883 if (conf->rewriteattr) {
3884 if (!addrewriteattr(conf))
3885 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3888 if (!resolvepeer(conf, 0))
3889 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3891 if (!conf->secret) {
3892 if (!conf->pdef->secretdefault)
3893 debugx(1, DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3894 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3896 debugx(1, DBG_ERR, "malloc failed");
3901 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3902 if (conf->type == RAD_TLS || conf->type == RAD_DTLS) {
3903 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->type, conf->tls, NULL) : tlsgetctx(conf->type, "defaultserver", "default");
3904 if (!conf->ssl_ctx) {
3905 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3908 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3909 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3915 conf->port = stringcopy(conf->pdef->portdefault, 0);
3917 debug(DBG_ERR, "malloc failed");
3922 if (conf->retryinterval == 255)
3923 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3924 if (conf->retrycount == 255)
3925 conf->retrycount = protodefs[conf->type].retrycountdefault;
3927 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3929 if (!conf->secret) {
3930 if (!conf->pdef->secretdefault) {
3931 debug(DBG_ERR, "error in block %s, secret must be specified for transport type %s", block, conf->pdef->name);
3934 conf->secret = stringcopy(conf->pdef->secretdefault, 0);
3935 if (!conf->secret) {
3936 debug(DBG_ERR, "malloc failed");
3941 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3942 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3948 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3949 struct clsrvconf *conf, *resconf;
3950 char *conftype = NULL;
3951 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3953 debug(DBG_DBG, "confserver_cb called for %s", block);
3955 conf = malloc(sizeof(struct clsrvconf));
3957 debug(DBG_ERR, "malloc failed");
3960 memset(conf, 0, sizeof(struct clsrvconf));
3961 resconf = (struct clsrvconf *)arg;
3963 conf->statusserver = resconf->statusserver;
3964 conf->certnamecheck = resconf->certnamecheck;
3966 conf->certnamecheck = 1;
3968 if (!getgenericconfig(cf, block,
3969 "type", CONF_STR, &conftype,
3970 "host", CONF_STR, &conf->host,
3971 "port", CONF_STR, &conf->port,
3972 "secret", CONF_STR, &conf->secret,
3973 "tls", CONF_STR, &conf->tls,
3974 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3975 "rewrite", CONF_STR, &conf->confrewrite,
3976 "StatusServer", CONF_BLN, &conf->statusserver,
3977 "RetryInterval", CONF_LINT, &retryinterval,
3978 "RetryCount", CONF_LINT, &retrycount,
3979 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3980 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3983 debug(DBG_ERR, "configuration error");
3987 conf->name = stringcopy(val, 0);
3989 debug(DBG_ERR, "malloc failed");
3993 conf->host = stringcopy(val, 0);
3995 debug(DBG_ERR, "malloc failed");
4001 debugx(1, DBG_ERR, "error in block %s, option type missing", block);
4002 conf->type = protoname2int(conftype);
4003 conf->pdef = &protodefs[conf->type];
4004 if (!conf->pdef->name) {
4005 debug(DBG_ERR, "error in block %s, unknown transport %s", block, conftype);
4011 if (retryinterval != LONG_MIN) {
4012 if (retryinterval < 1 || retryinterval > conf->pdef->retryintervalmax) {
4013 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, conf->pdef->retryintervalmax);
4016 conf->retryinterval = (uint8_t)retryinterval;
4018 conf->retryinterval = 255;
4020 if (retrycount != LONG_MIN) {
4021 if (retrycount < 0 || retrycount > conf->pdef->retrycountmax) {
4022 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, retrycount, conf->pdef->retrycountmax);
4025 conf->retrycount = (uint8_t)retrycount;
4027 conf->retrycount = 255;
4030 if (!mergesrvconf(resconf, conf))
4034 if (conf->dynamiclookupcommand) {
4035 free(conf->dynamiclookupcommand);
4036 conf->dynamiclookupcommand = NULL;
4040 if (resconf || !conf->dynamiclookupcommand) {
4041 if (!compileserverconfig(conf, block))
4048 if (!list_push(srvconfs, conf)) {
4049 debug(DBG_ERR, "malloc failed");
4055 freeclsrvconf(conf);
4059 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4060 char **servers = NULL, **accservers = NULL, *msg = NULL;
4061 uint8_t accresp = 0;
4063 debug(DBG_DBG, "confrealm_cb called for %s", block);
4065 if (!getgenericconfig(cf, block,
4066 "server", CONF_MSTR, &servers,
4067 "accountingServer", CONF_MSTR, &accservers,
4068 "ReplyMessage", CONF_STR, &msg,
4069 "AccountingResponse", CONF_BLN, &accresp,
4072 debugx(1, DBG_ERR, "configuration error");
4074 addrealm(realms, val, servers, accservers, msg, accresp);
4078 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4081 debug(DBG_DBG, "conftls_cb called for %s", block);
4083 conf = malloc(sizeof(struct tls));
4085 debug(DBG_ERR, "conftls_cb: malloc failed");
4088 memset(conf, 0, sizeof(struct tls));
4090 if (!getgenericconfig(cf, block,
4091 "CACertificateFile", CONF_STR, &conf->cacertfile,
4092 "CACertificatePath", CONF_STR, &conf->cacertpath,
4093 "CertificateFile", CONF_STR, &conf->certfile,
4094 "CertificateKeyFile", CONF_STR, &conf->certkeyfile,
4095 "CertificateKeyPassword", CONF_STR, &conf->certkeypwd,
4096 "CRLCheck", CONF_BLN, &conf->crlcheck,
4099 debug(DBG_ERR, "conftls_cb: configuration error in block %s", val);
4102 if (!conf->certfile || !conf->certkeyfile) {
4103 debug(DBG_ERR, "conftls_cb: TLSCertificateFile and TLSCertificateKeyFile must be specified in block %s", val);
4106 if (!conf->cacertfile && !conf->cacertpath) {
4107 debug(DBG_ERR, "conftls_cb: CA Certificate file or path need to be specified in block %s", val);
4111 conf->name = stringcopy(val, 0);
4113 debug(DBG_ERR, "conftls_cb: malloc failed");
4117 pthread_mutex_lock(&tlsconfs_lock);
4118 if (!list_push(tlsconfs, conf)) {
4119 debug(DBG_ERR, "conftls_cb: malloc failed");
4120 pthread_mutex_unlock(&tlsconfs_lock);
4123 pthread_mutex_unlock(&tlsconfs_lock);
4125 debug(DBG_DBG, "conftls_cb: added TLS block %s", val);
4129 free(conf->cacertfile);
4130 free(conf->cacertpath);
4131 free(conf->certfile);
4132 free(conf->certkeyfile);
4133 free(conf->certkeypwd);
4138 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
4139 char **attrs = NULL, **vattrs = NULL;
4141 debug(DBG_DBG, "confrewrite_cb called for %s", block);
4143 if (!getgenericconfig(cf, block,
4144 "removeAttribute", CONF_MSTR, &attrs,
4145 "removeVendorAttribute", CONF_MSTR, &vattrs,
4148 debugx(1, DBG_ERR, "configuration error");
4149 addrewrite(val, attrs, vattrs);
4153 void getmainconfig(const char *configfile) {
4154 long int loglevel = LONG_MIN;
4155 struct gconffile *cfs;
4157 cfs = openconfigfile(configfile);
4158 memset(&options, 0, sizeof(options));
4160 clconfs = list_create();
4162 debugx(1, DBG_ERR, "malloc failed");
4164 srvconfs = list_create();
4166 debugx(1, DBG_ERR, "malloc failed");
4168 realms = list_create();
4170 debugx(1, DBG_ERR, "malloc failed");
4172 tlsconfs = list_create();
4174 debugx(1, DBG_ERR, "malloc failed");
4176 rewriteconfs = list_create();
4178 debugx(1, DBG_ERR, "malloc failed");
4180 if (!getgenericconfig(&cfs, NULL,
4181 "ListenUDP", CONF_MSTR, &options.listenudp,
4182 "ListenTCP", CONF_MSTR, &options.listentcp,
4183 "ListenTLS", CONF_MSTR, &options.listentls,
4184 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
4185 "SourceUDP", CONF_STR, &options.sourceudp,
4186 "SourceTCP", CONF_STR, &options.sourcetcp,
4187 "SourceTLS", CONF_STR, &options.sourcetls,
4188 "LogLevel", CONF_LINT, &loglevel,
4189 "LogDestination", CONF_STR, &options.logdestination,
4190 "LoopPrevention", CONF_BLN, &options.loopprevention,
4191 "Client", CONF_CBK, confclient_cb, NULL,
4192 "Server", CONF_CBK, confserver_cb, NULL,
4193 "Realm", CONF_CBK, confrealm_cb, NULL,
4194 "TLS", CONF_CBK, conftls_cb, NULL,
4195 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
4198 debugx(1, DBG_ERR, "configuration error");
4200 if (loglevel != LONG_MIN) {
4201 if (loglevel < 1 || loglevel > 4)
4202 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
4203 options.loglevel = (uint8_t)loglevel;
4207 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
4210 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
4213 *configfile = optarg;
4216 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
4217 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
4218 *loglevel = *optarg - '0';
4227 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
4232 if (!(argc - optind))
4236 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
4240 int daemon(int a, int b) {
4248 for (i = 0; i < 3; i++) {
4250 open("/dev/null", O_RDWR);
4256 void *sighandler(void *arg) {
4261 sigemptyset(&sigset);
4262 sigaddset(&sigset, SIGPIPE);
4263 sigwait(&sigset, &sig);
4264 /* only get SIGPIPE right now, so could simplify below code */
4267 /* completely ignoring this */
4270 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
4273 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
4278 int main(int argc, char **argv) {
4279 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
4281 struct list_node *entry;
4282 uint8_t foreground = 0, pretend = 0, loglevel = 0;
4283 char *configfile = NULL;
4284 struct clsrvconf *srvconf;
4286 debug_init("radsecproxy");
4287 debug_set_level(DEBUG_LEVEL);
4288 pthread_mutex_init(&tlsconfs_lock, NULL);
4290 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
4292 debug_set_level(loglevel);
4293 getmainconfig(configfile ? configfile : CONFIG_MAIN);
4295 options.loglevel = loglevel;
4296 else if (options.loglevel)
4297 debug_set_level(options.loglevel);
4299 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
4300 free(options.logdestination);
4302 if (!list_first(clconfs))
4303 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
4304 if (!list_first(srvconfs))
4305 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
4306 if (!list_first(realms))
4307 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
4310 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
4312 if (!foreground && (daemon(0, 0) < 0))
4313 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
4315 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
4317 sigemptyset(&sigset);
4318 /* exit on all but SIGPIPE, ignore more? */
4319 sigaddset(&sigset, SIGPIPE);
4320 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
4321 pthread_create(&sigth, NULL, sighandler, NULL);
4323 if (find_conf_type(RAD_UDP, clconfs, NULL) || find_conf_type(RAD_DTLS, clconfs, NULL)) {
4324 udp_server_replyq = newreplyq();
4325 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
4326 debugx(1, DBG_ERR, "pthread_create failed");
4327 createlisteners(RAD_UDP, options.listenudp);
4328 if (options.listenaccudp)
4329 createlisteners(RAD_UDP, options.listenaccudp);
4332 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
4333 srvconf = (struct clsrvconf *)entry->data;
4334 if (srvconf->dynamiclookupcommand)
4336 if (!addserver(srvconf))
4337 debugx(1, DBG_ERR, "failed to add server");
4338 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
4339 (void *)(srvconf->servers)))
4340 debugx(1, DBG_ERR, "pthread_create failed");
4342 /* srcprotores for UDP no longer needed */
4343 if (srcprotores[RAD_UDP]) {
4344 freeaddrinfo(srcprotores[RAD_UDP]);
4345 srcprotores[RAD_UDP] = NULL;
4347 if (udp_client4_sock >= 0)
4348 if (pthread_create(&udpclient4rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client4_sock))
4349 debugx(1, DBG_ERR, "pthread_create failed");
4350 if (udp_client6_sock >= 0)
4351 if (pthread_create(&udpclient6rdth, NULL, protodefs[RAD_UDP].clientreader, (void *)&udp_client6_sock))
4352 debugx(1, DBG_ERR, "pthread_create failed");
4354 if (find_conf_type(RAD_TCP, clconfs, NULL))
4355 createlisteners(RAD_TCP, options.listentcp);
4357 if (find_conf_type(RAD_TLS, clconfs, NULL))
4358 createlisteners(RAD_TLS, options.listentls);
4360 /* just hang around doing nothing, anything to do here? */