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 #include <sys/socket.h>
34 #include <netinet/in.h>
43 #include <sys/types.h>
44 #include <sys/select.h>
47 #include <arpa/inet.h>
51 #include <openssl/ssl.h>
52 #include <openssl/rand.h>
53 #include <openssl/err.h>
54 #include <openssl/md5.h>
55 #include <openssl/hmac.h>
56 #include <openssl/x509v3.h>
61 #include "radsecproxy.h"
63 static struct options options;
64 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
66 static int client_udp_count = 0;
67 static int client_tls_count = 0;
68 static int server_udp_count = 0;
69 static int server_tls_count = 0;
71 static struct addrinfo *srcudpres = NULL;
72 static struct addrinfo *srctcpres = NULL;
74 static struct replyq *udp_server_replyq = NULL;
75 static int udp_server_sock = -1;
76 static int udp_accserver_sock = -1;
77 static int udp_client4_sock = -1;
78 static int udp_client6_sock = -1;
79 static pthread_mutex_t *ssl_locks;
80 static long *ssl_lock_count;
84 /* minimum required declarations to avoid reordering code */
85 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
86 int dynamicconfig(struct server *server);
87 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
88 void freerealm(struct realm *realm);
89 void freeclsrvconf(struct clsrvconf *conf);
90 void freerqdata(struct request *rq);
92 /* callbacks for making OpenSSL thread safe */
93 unsigned long ssl_thread_id() {
94 return (unsigned long)pthread_self();
97 void ssl_locking_callback(int mode, int type, const char *file, int line) {
98 if (mode & CRYPTO_LOCK) {
99 pthread_mutex_lock(&ssl_locks[type]);
100 ssl_lock_count[type]++;
102 pthread_mutex_unlock(&ssl_locks[type]);
105 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
106 int pwdlen = strlen(userdata);
107 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
109 memcpy(buf, userdata, pwdlen);
113 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
118 err_cert = X509_STORE_CTX_get_current_cert(ctx);
119 err = X509_STORE_CTX_get_error(ctx);
120 depth = X509_STORE_CTX_get_error_depth(ctx);
122 if (depth > MAX_CERT_DEPTH) {
124 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
125 X509_STORE_CTX_set_error(ctx, err);
129 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
130 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
133 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
134 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
135 debug(DBG_WARN, "\tIssuer=%s", buf);
137 case X509_V_ERR_CERT_NOT_YET_VALID:
138 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
139 debug(DBG_WARN, "\tCertificate not yet valid");
141 case X509_V_ERR_CERT_HAS_EXPIRED:
142 debug(DBG_WARN, "Certificate has expired");
144 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
145 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
150 printf("certificate verify returns %d\n", ok);
155 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
156 struct addrinfo hints, *addrinfo, *res;
160 slash = conf->host ? strchr(conf->host, '/') : NULL;
164 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
168 if (*s < '0' || *s > '9') {
169 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
172 plen = atoi(slash + 1);
173 if (plen < 0 || plen > 128) {
174 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
179 memset(&hints, 0, sizeof(hints));
180 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
181 hints.ai_family = AF_UNSPEC;
182 hints.ai_flags = ai_flags;
183 if (!conf->host && !conf->port) {
184 /* getaddrinfo() doesn't like host and port to be NULL */
185 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
186 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
189 for (res = addrinfo; res; res = res->ai_next) {
190 switch (res->ai_family) {
192 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
195 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
201 hints.ai_flags |= AI_NUMERICHOST;
202 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
203 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
208 switch (addrinfo->ai_family) {
211 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
212 freeaddrinfo(addrinfo);
219 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
220 freeaddrinfo(addrinfo);
223 conf->prefixlen = plen;
225 conf->prefixlen = 255;
228 freeaddrinfo(conf->addrinfo);
229 conf->addrinfo = addrinfo;
233 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
235 struct addrinfo *res;
237 for (res = addrinfo; res; res = res->ai_next) {
238 if (family != AF_UNSPEC && family != res->ai_family)
240 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
242 debug(DBG_WARN, "bindtoaddr: socket failed");
246 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
249 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
252 if (!bind(s, res->ai_addr, res->ai_addrlen))
254 debug(DBG_WARN, "bindtoaddr: bind failed");
260 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
265 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
269 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
271 debugx(1, DBG_ERR, "no ] matching initial [");
275 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
278 debugx(1, DBG_ERR, "missing host/address");
280 conf->host = stringcopy(field, p - field);
283 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
284 debugx(1, DBG_ERR, "unexpected character after ]");
287 /* port number or service name is specified */;
289 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
291 debugx(1, DBG_ERR, "syntax error, : but no following port");
292 conf->port = stringcopy(field, p - field);
294 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
298 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
299 struct clsrvconf *conf;
301 conf = malloc(sizeof(struct clsrvconf));
303 debugx(1, DBG_ERR, "malloc failed");
304 memset(conf, 0, sizeof(struct clsrvconf));
307 parsehostport(lconf, conf, default_port);
308 if (!strcmp(conf->host, "*")) {
313 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
314 if (!resolvepeer(conf, AI_PASSIVE))
315 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
319 void freeclsrvres(struct clsrvconf *res) {
323 freeaddrinfo(res->addrinfo);
327 int connecttcp(struct addrinfo *addrinfo) {
329 struct addrinfo *res;
332 for (res = addrinfo; res; res = res->ai_next) {
333 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
335 debug(DBG_WARN, "connecttoserver: socket failed");
338 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
340 debug(DBG_WARN, "connecttoserver: connect failed");
347 /* returns 1 if the len first bits are equal, else 0 */
348 int prefixmatch(void *a1, void *a2, uint8_t len) {
349 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
351 if (l && memcmp(a1, a2, l))
356 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
359 /* check if conf has matching address */
360 struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
361 struct sockaddr_in6 *sa6 = NULL;
362 struct in_addr *a4 = NULL;
363 struct addrinfo *res;
365 if (addr->sa_family == AF_INET6) {
366 sa6 = (struct sockaddr_in6 *)addr;
367 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
368 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
372 a4 = &((struct sockaddr_in *)addr)->sin_addr;
374 if (conf->type == type) {
375 if (conf->prefixlen == 255) {
376 for (res = conf->addrinfo; res; res = res->ai_next)
377 if ((a4 && res->ai_family == AF_INET &&
378 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
379 (sa6 && res->ai_family == AF_INET6 &&
380 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
383 res = conf->addrinfo;
385 ((a4 && res->ai_family == AF_INET &&
386 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
387 (sa6 && res->ai_family == AF_INET6 &&
388 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
395 /* returns next config with matching address, or NULL */
396 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
397 struct sockaddr_in6 *sa6 = NULL;
398 struct in_addr *a4 = NULL;
399 struct addrinfo *res;
400 struct list_node *entry;
401 struct clsrvconf *conf;
403 if (addr->sa_family == AF_INET6) {
404 sa6 = (struct sockaddr_in6 *)addr;
405 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
406 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
410 a4 = &((struct sockaddr_in *)addr)->sin_addr;
412 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
413 conf = (struct clsrvconf *)entry->data;
414 if (conf->type == type) {
415 if (conf->prefixlen == 255) {
416 for (res = conf->addrinfo; res; res = res->ai_next)
417 if ((a4 && res->ai_family == AF_INET &&
418 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
419 (sa6 && res->ai_family == AF_INET6 &&
420 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
426 res = conf->addrinfo;
428 ((a4 && res->ai_family == AF_INET &&
429 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
430 (sa6 && res->ai_family == AF_INET6 &&
431 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
442 struct replyq *newreplyq() {
443 struct replyq *replyq;
445 replyq = malloc(sizeof(struct replyq));
447 debugx(1, DBG_ERR, "malloc failed");
448 replyq->replies = list_create();
449 if (!replyq->replies)
450 debugx(1, DBG_ERR, "malloc failed");
451 pthread_mutex_init(&replyq->mutex, NULL);
452 pthread_cond_init(&replyq->cond, NULL);
456 struct client *addclient(struct clsrvconf *conf) {
457 struct client *new = malloc(sizeof(struct client));
460 debug(DBG_ERR, "malloc failed");
463 if (!conf->clients) {
464 conf->clients = list_create();
465 if (!conf->clients) {
466 debug(DBG_ERR, "malloc failed");
471 memset(new, 0, sizeof(struct client));
473 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
475 list_push(conf->clients, new);
479 void removeclient(struct client *client) {
480 struct list_node *entry;
482 if (!client || !client->conf->clients)
485 pthread_mutex_lock(&client->replyq->mutex);
486 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
487 free(((struct reply *)entry)->buf);
488 list_destroy(client->replyq->replies);
489 pthread_cond_destroy(&client->replyq->cond);
490 pthread_mutex_unlock(&client->replyq->mutex);
491 pthread_mutex_destroy(&client->replyq->mutex);
492 list_removedata(client->conf->clients, client);
496 void removeclientrqs(struct client *client) {
497 struct list_node *entry;
498 struct server *server;
502 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
503 server = ((struct clsrvconf *)entry->data)->servers;
504 pthread_mutex_lock(&server->newrq_mutex);
505 for (i = 0; i < MAX_REQUESTS; i++) {
506 rq = server->requests + i;
507 if (rq->from == client)
510 pthread_mutex_unlock(&server->newrq_mutex);
514 void freeserver(struct server *server, uint8_t destroymutex) {
515 struct request *rq, *end;
520 if(server->requests) {
521 rq = server->requests;
522 for (end = rq + MAX_REQUESTS; rq < end; rq++)
524 free(server->requests);
526 free(server->dynamiclookuparg);
528 pthread_mutex_destroy(&server->lock);
529 pthread_cond_destroy(&server->newrq_cond);
530 pthread_mutex_destroy(&server->newrq_mutex);
535 int addserver(struct clsrvconf *conf) {
536 struct clsrvconf *res;
539 debug(DBG_ERR, "addserver: currently works with just one server per conf");
542 conf->servers = malloc(sizeof(struct server));
543 if (!conf->servers) {
544 debug(DBG_ERR, "malloc failed");
547 memset(conf->servers, 0, sizeof(struct server));
548 conf->servers->conf = conf;
550 if (conf->type == 'U') {
552 res = resolve_hostport('U', options.sourceudp, NULL);
553 srcudpres = res->addrinfo;
554 res->addrinfo = NULL;
557 switch (conf->addrinfo->ai_family) {
559 if (udp_client4_sock < 0) {
560 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
561 if (udp_client4_sock < 0)
562 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
564 conf->servers->sock = udp_client4_sock;
567 if (udp_client6_sock < 0) {
568 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
569 if (udp_client6_sock < 0)
570 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
572 conf->servers->sock = udp_client6_sock;
575 debugx(1, DBG_ERR, "addserver: unsupported address family");
580 res = resolve_hostport('T', options.sourcetcp, NULL);
581 srctcpres = res->addrinfo;
582 res->addrinfo = NULL;
585 conf->servers->sock = -1;
588 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
589 if (!conf->servers->requests) {
590 debug(DBG_ERR, "malloc failed");
593 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
594 debug(DBG_ERR, "mutex init failed");
597 conf->servers->newrq = 0;
598 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
599 debug(DBG_ERR, "mutex init failed");
600 pthread_mutex_destroy(&conf->servers->lock);
603 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
604 debug(DBG_ERR, "mutex init failed");
605 pthread_mutex_destroy(&conf->servers->newrq_mutex);
606 pthread_mutex_destroy(&conf->servers->lock);
613 freeserver(conf->servers, 0);
614 conf->servers = NULL;
618 /* exactly one of client and server must be non-NULL */
619 /* should probably take peer list (client(s) or server(s)) as argument instead */
620 /* if *peer == NULL we return who we received from, else require it to be from peer */
621 /* return from in sa if not NULL */
622 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
624 unsigned char buf[65536], *rad;
625 struct sockaddr_storage from;
626 socklen_t fromlen = sizeof(from);
628 struct list_node *node;
631 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
633 debug(DBG_WARN, "radudpget: recv failed");
636 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
639 debug(DBG_WARN, "radudpget: packet too small");
645 debug(DBG_WARN, "radudpget: length too small");
650 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
654 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
658 p = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
660 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
663 p = checkconfaddr('U', (struct sockaddr *)&from, (*server)->conf);
665 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
668 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
674 debug(DBG_ERR, "radudpget: malloc failed");
678 if (client && !*client) {
679 node = list_first(p->clients);
680 *client = node ? (struct client *)node->data : addclient(p);
685 } else if (server && !*server)
686 *server = p->servers;
690 memcpy(rad, buf, len);
696 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
697 int loc, i, l, n, r = 0;
700 STACK_OF(GENERAL_NAME) *alt;
703 debug(DBG_DBG, "subjectaltnameaddr");
705 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
709 ex = X509_get_ext(cert, loc);
710 alt = X509V3_EXT_d2i(ex);
714 n = sk_GENERAL_NAME_num(alt);
715 for (i = 0; i < n; i++) {
716 gn = sk_GENERAL_NAME_value(alt, i);
717 if (gn->type != GEN_IPADD)
720 v = (char *)ASN1_STRING_data(gn->d.ia5);
721 l = ASN1_STRING_length(gn->d.ia5);
722 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
723 && !memcmp(v, &addr, l)) {
728 GENERAL_NAMES_free(alt);
732 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
739 nm = X509_get_subject_name(cert);
742 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
745 e = X509_NAME_get_entry(nm, loc);
746 t = X509_NAME_ENTRY_get_data(e);
747 v = (char *) ASN1_STRING_data(t);
748 l = ASN1_STRING_length(t);
752 if (l == strlen(exact) && !strncasecmp(exact, v, l))
755 s = stringcopy((char *)v, l);
757 debug(DBG_ERR, "malloc failed");
760 if (regexec(regex, s, 0, NULL, 0)) {
771 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
772 int loc, i, l, n, r = 0;
775 STACK_OF(GENERAL_NAME) *alt;
778 debug(DBG_DBG, "subjectaltnameregexp");
780 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
784 ex = X509_get_ext(cert, loc);
785 alt = X509V3_EXT_d2i(ex);
789 n = sk_GENERAL_NAME_num(alt);
790 for (i = 0; i < n; i++) {
791 gn = sk_GENERAL_NAME_value(alt, i);
792 if (gn->type != type)
795 v = (char *)ASN1_STRING_data(gn->d.ia5);
796 l = ASN1_STRING_length(gn->d.ia5);
800 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
803 if (memcmp(v, exact, l))
806 s = stringcopy((char *)v, l);
808 debug(DBG_ERR, "malloc failed");
811 if (regexec(regex, s, 0, NULL, 0)) {
820 GENERAL_NAMES_free(alt);
824 X509 *verifytlscert(SSL *ssl) {
828 if (SSL_get_verify_result(ssl) != X509_V_OK) {
829 debug(DBG_ERR, "verifytlscert: basic validation failed");
830 while ((error = ERR_get_error()))
831 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
835 cert = SSL_get_peer_certificate(ssl);
837 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
841 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
843 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
844 struct in6_addr addr;
846 if (conf->certnamecheck && conf->prefixlen == 255) {
847 if (inet_pton(AF_INET, conf->host, &addr))
849 else if (inet_pton(AF_INET6, conf->host, &addr))
852 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
855 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
858 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
860 if (!cnregexp(cert, conf->host, NULL)) {
861 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
864 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
867 if (conf->certcnregex) {
868 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
869 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
872 debug(DBG_DBG, "verifyconfcert: CN matching regex");
874 if (conf->certuriregex) {
875 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
876 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
879 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
884 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
889 debug(DBG_DBG, "tlsconnect called from %s", text);
890 pthread_mutex_lock(&server->lock);
891 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
892 /* already reconnected, nothing to do */
893 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
894 pthread_mutex_unlock(&server->lock);
898 debug(DBG_DBG, "tlsconnect %s", text);
901 gettimeofday(&now, NULL);
902 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
903 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
904 debug(DBG_DBG, "tlsconnect: timeout");
905 if (server->sock >= 0)
907 SSL_free(server->ssl);
909 pthread_mutex_unlock(&server->lock);
912 if (server->connectionok) {
913 server->connectionok = 0;
915 } else if (elapsed < 1)
917 else if (elapsed < 60) {
918 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
920 } else if (elapsed < 100000) {
921 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
924 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
925 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
926 if (server->sock >= 0)
928 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
929 debug(DBG_ERR, "tlsconnect: connecttcp failed");
933 SSL_free(server->ssl);
934 server->ssl = SSL_new(server->conf->ssl_ctx);
935 SSL_set_fd(server->ssl, server->sock);
936 if (SSL_connect(server->ssl) <= 0)
938 cert = verifytlscert(server->ssl);
941 if (verifyconfcert(cert, server->conf)) {
947 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
948 gettimeofday(&server->lastconnecttry, NULL);
949 pthread_mutex_unlock(&server->lock);
953 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
954 /* returns 0 on timeout, -1 on error and num if ok */
955 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
956 int s, ndesc, cnt, len;
957 fd_set readfds, writefds;
958 struct timeval timer;
963 /* make socket non-blocking? */
964 for (len = 0; len < num; len += cnt) {
969 timer.tv_sec = timeout;
972 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
976 cnt = SSL_read(ssl, buf + len, num - len);
978 switch (SSL_get_error(ssl, cnt)) {
979 case SSL_ERROR_WANT_READ:
980 case SSL_ERROR_WANT_WRITE:
983 case SSL_ERROR_ZERO_RETURN:
984 /* remote end sent close_notify, send one back */
994 /* timeout in seconds, 0 means no timeout (blocking) */
995 unsigned char *radtlsget(SSL *ssl, int timeout) {
997 unsigned char buf[4], *rad;
1000 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1002 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1009 debug(DBG_ERR, "radtlsget: malloc failed");
1012 memcpy(rad, buf, 4);
1014 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1016 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1025 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1028 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1032 int clientradputudp(struct server *server, unsigned char *rad) {
1034 struct sockaddr_storage sa;
1035 struct sockaddr *sap;
1036 struct clsrvconf *conf = server->conf;
1037 in_port_t *port = NULL;
1041 if (*rad == RAD_Accounting_Request) {
1042 sap = (struct sockaddr *)&sa;
1043 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1045 sap = conf->addrinfo->ai_addr;
1047 switch (sap->sa_family) {
1049 port = &((struct sockaddr_in *)sap)->sin_port;
1052 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1058 if (*rad == RAD_Accounting_Request)
1059 *port = htons(ntohs(*port) + 1);
1061 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1062 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1066 debug(DBG_WARN, "clientradputudp: send failed");
1070 int clientradputtls(struct server *server, unsigned char *rad) {
1073 unsigned long error;
1074 struct timeval lastconnecttry;
1075 struct clsrvconf *conf = server->conf;
1078 lastconnecttry = server->lastconnecttry;
1079 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1080 while ((error = ERR_get_error()))
1081 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1082 if (server->dynamiclookuparg)
1084 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1085 lastconnecttry = server->lastconnecttry;
1088 server->connectionok = 1;
1089 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1093 int clientradput(struct server *server, unsigned char *rad) {
1094 switch (server->conf->type) {
1096 return clientradputudp(server, rad);
1098 return clientradputtls(server, rad);
1103 int radsign(unsigned char *rad, unsigned char *sec) {
1104 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1105 static unsigned char first = 1;
1106 static EVP_MD_CTX mdctx;
1107 unsigned int md_len;
1110 pthread_mutex_lock(&lock);
1112 EVP_MD_CTX_init(&mdctx);
1116 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1117 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1118 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1119 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1121 pthread_mutex_unlock(&lock);
1125 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1126 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1127 static unsigned char first = 1;
1128 static EVP_MD_CTX mdctx;
1129 unsigned char hash[EVP_MAX_MD_SIZE];
1133 pthread_mutex_lock(&lock);
1135 EVP_MD_CTX_init(&mdctx);
1141 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1142 EVP_DigestUpdate(&mdctx, rad, 4) &&
1143 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1144 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1145 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1146 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1148 !memcmp(hash, rad + 4, 16));
1149 pthread_mutex_unlock(&lock);
1153 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1154 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1155 static unsigned char first = 1;
1156 static HMAC_CTX hmacctx;
1157 unsigned int md_len;
1158 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1160 pthread_mutex_lock(&lock);
1162 HMAC_CTX_init(&hmacctx);
1166 memcpy(auth, authattr, 16);
1167 memset(authattr, 0, 16);
1169 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1170 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1171 HMAC_Final(&hmacctx, hash, &md_len);
1172 memcpy(authattr, auth, 16);
1174 debug(DBG_WARN, "message auth computation failed");
1175 pthread_mutex_unlock(&lock);
1179 if (memcmp(auth, hash, 16)) {
1180 debug(DBG_WARN, "message authenticator, wrong value");
1181 pthread_mutex_unlock(&lock);
1185 pthread_mutex_unlock(&lock);
1189 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1190 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1191 static unsigned char first = 1;
1192 static HMAC_CTX hmacctx;
1193 unsigned int md_len;
1198 pthread_mutex_lock(&lock);
1200 HMAC_CTX_init(&hmacctx);
1204 memset(authattrval, 0, 16);
1206 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1207 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1208 HMAC_Final(&hmacctx, authattrval, &md_len);
1210 debug(DBG_WARN, "message auth computation failed");
1211 pthread_mutex_unlock(&lock);
1215 pthread_mutex_unlock(&lock);
1219 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1220 while (length > 1) {
1221 if (ATTRTYPE(attrs) == type)
1223 length -= ATTRLEN(attrs);
1224 attrs += ATTRLEN(attrs);
1229 void freerqdata(struct request *rq) {
1230 if (rq->origusername)
1231 free(rq->origusername);
1236 void sendrq(struct server *to, struct request *rq) {
1240 pthread_mutex_lock(&to->newrq_mutex);
1241 /* might simplify if only try nextid, might be ok */
1242 for (i = to->nextid; i < MAX_REQUESTS; i++)
1243 if (!to->requests[i].buf)
1245 if (i == MAX_REQUESTS) {
1246 for (i = 0; i < to->nextid; i++)
1247 if (!to->requests[i].buf)
1249 if (i == to->nextid) {
1250 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1256 rq->buf[1] = (char)i;
1258 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1259 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1264 if (*(uint8_t *)rq->buf == RAD_Accounting_Request) {
1265 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1266 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1272 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1273 to->requests[i] = *rq;
1278 debug(DBG_DBG, "sendrq: signalling client writer");
1279 pthread_cond_signal(&to->newrq_cond);
1282 pthread_mutex_unlock(&to->newrq_mutex);
1285 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1286 struct reply *reply;
1289 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1291 debug(DBG_WARN, "sendreply: failed to sign message");
1295 reply = malloc(sizeof(struct reply));
1298 debug(DBG_ERR, "sendreply: malloc failed");
1301 memset(reply, 0, sizeof(struct reply));
1304 reply->tosa = *tosa;
1306 pthread_mutex_lock(&to->replyq->mutex);
1308 first = list_first(to->replyq->replies) == NULL;
1310 if (!list_push(to->replyq->replies, reply)) {
1311 pthread_mutex_unlock(&to->replyq->mutex);
1314 debug(DBG_ERR, "sendreply: malloc failed");
1319 debug(DBG_DBG, "signalling server writer");
1320 pthread_cond_signal(&to->replyq->cond);
1322 pthread_mutex_unlock(&to->replyq->mutex);
1325 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1326 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1327 static unsigned char first = 1;
1328 static EVP_MD_CTX mdctx;
1329 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1330 unsigned int md_len;
1331 uint8_t i, offset = 0, out[128];
1333 pthread_mutex_lock(&lock);
1335 EVP_MD_CTX_init(&mdctx);
1341 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1342 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1343 !EVP_DigestUpdate(&mdctx, input, 16) ||
1344 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1346 pthread_mutex_unlock(&lock);
1349 for (i = 0; i < 16; i++)
1350 out[offset + i] = hash[i] ^ in[offset + i];
1351 input = out + offset - 16;
1356 memcpy(in, out, len);
1357 pthread_mutex_unlock(&lock);
1361 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1362 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1363 static unsigned char first = 1;
1364 static EVP_MD_CTX mdctx;
1365 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1366 unsigned int md_len;
1367 uint8_t i, offset = 0, out[128];
1369 pthread_mutex_lock(&lock);
1371 EVP_MD_CTX_init(&mdctx);
1377 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1378 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1379 !EVP_DigestUpdate(&mdctx, input, 16) ||
1380 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1382 pthread_mutex_unlock(&lock);
1385 for (i = 0; i < 16; i++)
1386 out[offset + i] = hash[i] ^ in[offset + i];
1387 input = in + offset;
1392 memcpy(in, out, len);
1393 pthread_mutex_unlock(&lock);
1397 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1398 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1399 static unsigned char first = 1;
1400 static EVP_MD_CTX mdctx;
1401 unsigned char hash[EVP_MAX_MD_SIZE];
1402 unsigned int md_len;
1405 pthread_mutex_lock(&lock);
1407 EVP_MD_CTX_init(&mdctx);
1412 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1413 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1414 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1417 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1418 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1419 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1420 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1421 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1422 pthread_mutex_unlock(&lock);
1427 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1430 for (i = 0; i < 16; i++)
1433 for (offset = 16; offset < len; offset += 16) {
1435 printf("text + offset - 16 c(%d): ", offset / 16);
1436 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1438 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1439 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1440 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1441 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1443 pthread_mutex_unlock(&lock);
1447 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1450 for (i = 0; i < 16; i++)
1451 text[offset + i] ^= hash[i];
1455 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1458 pthread_mutex_unlock(&lock);
1462 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1463 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1464 static unsigned char first = 1;
1465 static EVP_MD_CTX mdctx;
1466 unsigned char hash[EVP_MAX_MD_SIZE];
1467 unsigned int md_len;
1471 pthread_mutex_lock(&lock);
1473 EVP_MD_CTX_init(&mdctx);
1478 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1479 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1480 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1483 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1484 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1485 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1486 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1487 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1488 pthread_mutex_unlock(&lock);
1493 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1496 for (i = 0; i < 16; i++)
1497 plain[i] = text[i] ^ hash[i];
1499 for (offset = 16; offset < len; offset += 16) {
1501 printf("text + offset - 16 c(%d): ", offset / 16);
1502 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1504 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1505 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1506 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1507 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1509 pthread_mutex_unlock(&lock);
1513 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1516 for (i = 0; i < 16; i++)
1517 plain[offset + i] = text[offset + i] ^ hash[i];
1520 memcpy(text, plain, len);
1522 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1525 pthread_mutex_unlock(&lock);
1529 struct realm *id2realm(struct list *realmlist, char *id) {
1530 struct list_node *entry;
1531 struct realm *realm, *subrealm = NULL;
1533 /* need to do locking for subrealms and check subrealm timers */
1534 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1535 realm = (struct realm *)entry->data;
1536 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1537 pthread_mutex_lock(&realm->subrealms_mutex);
1538 if (realm->subrealms)
1539 subrealm = id2realm(realm->subrealms, id);
1540 pthread_mutex_unlock(&realm->subrealms_mutex);
1541 return subrealm ? subrealm : realm;
1547 /* helper function, only used by removeserversubrealms() */
1548 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1549 struct list_node *entry;
1550 struct realm *realm;
1552 for (entry = list_first(realmlist); entry;) {
1553 realm = (struct realm *)entry->data;
1554 entry = list_next(entry);
1555 if (realm->srvconfs) {
1556 list_removedata(realm->srvconfs, srv);
1557 if (!list_first(realm->srvconfs)) {
1558 list_destroy(realm->srvconfs);
1559 realm->srvconfs = NULL;
1562 if (realm->accsrvconfs) {
1563 list_removedata(realm->accsrvconfs, srv);
1564 if (!list_first(realm->accsrvconfs)) {
1565 list_destroy(realm->accsrvconfs);
1566 realm->accsrvconfs = NULL;
1570 /* remove subrealm if no servers */
1571 if (!realm->srvconfs && !realm->accsrvconfs) {
1572 list_removedata(realmlist, realm);
1578 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1579 struct list_node *entry;
1580 struct realm *realm;
1582 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1583 realm = (struct realm *)entry->data;
1584 pthread_mutex_lock(&realm->subrealms_mutex);
1585 if (realm->subrealms) {
1586 _internal_removeserversubrealms(realm->subrealms, srv);
1587 if (!list_first(realm->subrealms)) {
1588 list_destroy(realm->subrealms);
1589 realm->subrealms = NULL;
1592 pthread_mutex_unlock(&realm->subrealms_mutex);
1596 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1597 struct request *rq = to->requests, *end;
1599 pthread_mutex_lock(&to->newrq_mutex);
1600 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1601 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1603 pthread_mutex_unlock(&to->newrq_mutex);
1608 int attrvalidate(unsigned char *attrs, int length) {
1609 while (length > 1) {
1610 if (ATTRLEN(attrs) < 2) {
1611 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1614 length -= ATTRLEN(attrs);
1616 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1619 attrs += ATTRLEN(attrs);
1622 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1626 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1627 if (len < 16 || len > 128 || len % 16) {
1628 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1632 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1633 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1637 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1639 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1640 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1646 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1649 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1650 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1653 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1654 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1660 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1661 char *oldsecret, char *newsecret) {
1662 unsigned char *attr;
1664 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1665 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1666 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1672 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1676 for (; attrs[0]; attrs += 2)
1677 if (attrs[0] == vendor && attrs[1] == subattr)
1682 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1683 uint8_t alen, sublen, rmlen = 0;
1684 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1687 if (!removevendorattrs)
1690 while (*removevendorattrs && *removevendorattrs != vendor)
1691 removevendorattrs += 2;
1692 if (!*removevendorattrs)
1695 alen = ATTRLEN(attrs);
1697 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1698 /* remove entire vendor attribute */
1699 memmove(attrs, attrs + alen, length - alen);
1704 subattrs = ATTRVAL(attrs) + 4;
1706 if (!attrvalidate(subattrs, sublen)) {
1707 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1712 while (sublen > 1) {
1713 alen = ATTRLEN(subattrs);
1716 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1717 memmove(subattrs, subattrs + alen, length);
1723 ATTRLEN(attrs) -= rmlen;
1727 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1728 uint8_t *attrs, alen;
1729 uint16_t len, rmlen = 0;
1731 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1734 len = RADLEN(buf) - 20;
1737 alen = ATTRLEN(attrs);
1739 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1740 memmove(attrs, attrs + alen, len);
1742 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1743 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1748 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1751 /* returns a pointer to the resized attribute value */
1752 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1753 uint8_t *attrs, *attr, vallen;
1757 len = RADLEN(*buf) - 20;
1760 attr = attrget(attrs, len, type);
1764 vallen = ATTRVALLEN(attr);
1765 if (vallen == newvallen)
1768 len += newvallen - vallen;
1769 if (newvallen > vallen) {
1770 new = realloc(*buf, len + 20);
1772 debug(DBG_ERR, "resizeattr: malloc failed");
1781 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1782 attr[1] = newvallen + 2;
1783 ((uint16_t *)*buf)[1] = htons(len + 20);
1787 int rewriteusername(struct request *rq, char *in) {
1788 size_t nmatch = 10, reslen = 0, start = 0;
1789 regmatch_t pmatch[10], *pfield;
1791 unsigned char *result;
1792 char *out = rq->from->conf->rewriteattrreplacement;
1794 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1795 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1799 rq->origusername = stringcopy(in, 0);
1800 if (!rq->origusername)
1803 for (i = start; out[i]; i++) {
1804 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1805 pfield = &pmatch[out[i + 1] - '0'];
1806 if (pfield->rm_so >= 0) {
1807 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1813 reslen += i - start;
1815 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1821 for (i = start; out[i]; i++) {
1822 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1823 pfield = &pmatch[out[i + 1] - '0'];
1824 if (pfield->rm_so >= 0) {
1825 memcpy(result + reslen, out + start, i - start);
1826 reslen += i - start;
1827 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1828 reslen += pfield->rm_eo - pfield->rm_so;
1835 memcpy(result + reslen, out + start, i - start);
1836 reslen += i - start;
1837 memcpy(in, result, reslen);
1842 const char *radmsgtype2string(uint8_t code) {
1843 static const char *rad_msg_names[] = {
1844 "", "Access-Request", "Access-Accept", "Access-Reject",
1845 "Accounting-Request", "Accounting-Response", "", "",
1846 "", "", "", "Access-Challenge",
1847 "Status-Server", "Status-Client"
1849 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1852 void char2hex(char *h, unsigned char c) {
1853 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1854 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1855 h[0] = hexdigits[c / 16];
1856 h[1] = hexdigits[c % 16];
1860 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1864 if (!attr || len == 1) {
1869 l = ATTRVALLEN(attr);
1870 s = (char *)ATTRVAL(attr);
1873 for (i = 0; i < l; i++) {
1874 if (s[i] > 31 && s[i] < 127) {
1876 if (d - ascii == len - 1)
1879 if (d - ascii > len - 4)
1884 if (d - ascii == len - 1)
1892 void acclog(unsigned char *attrs, int length, char *host) {
1893 unsigned char *attr;
1896 attr = attrget(attrs, length, RAD_Attr_User_Name);
1898 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1901 radattr2ascii(username, sizeof(username), attr);
1902 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1905 void respondaccounting(struct request *rq) {
1906 unsigned char *resp;
1910 debug(DBG_ERR, "respondstatusserver: malloc failed");
1913 memcpy(resp, rq->buf, 20);
1914 resp[0] = RAD_Accounting_Response;
1917 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1918 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1921 void respondstatusserver(struct request *rq) {
1922 unsigned char *resp;
1926 debug(DBG_ERR, "respondstatusserver: malloc failed");
1929 memcpy(resp, rq->buf, 20);
1930 resp[0] = RAD_Access_Accept;
1933 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1934 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1937 void respondreject(struct request *rq, char *message) {
1938 unsigned char *resp;
1941 if (message && *message)
1942 len += 2 + strlen(message);
1946 debug(DBG_ERR, "respondreject: malloc failed");
1949 memcpy(resp, rq->buf, 20);
1950 resp[0] = RAD_Access_Reject;
1951 *(uint16_t *)(resp + 2) = htons(len);
1952 if (message && *message) {
1953 resp[20] = RAD_Attr_Reply_Message;
1954 resp[21] = len - 20;
1955 memcpy(resp + 22, message, len - 22);
1957 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1960 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1961 struct list_node *entry;
1962 struct clsrvconf *server, *best = NULL, *first = NULL;
1964 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1965 server = (struct clsrvconf *)entry->data;
1966 if (!server->servers)
1970 if (!server->servers->connectionok)
1972 if (!server->servers->lostrqs)
1978 if (server->servers->lostrqs < best->servers->lostrqs)
1981 return best ? best : first;
1984 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1985 struct clsrvconf *srvconf;
1987 *realm = id2realm(realms, id);
1990 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1991 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1994 if (!acc && !srvconf->servers)
1995 adddynamicrealmserver(*realm, srvconf, id);
1996 return srvconf->servers;
1999 void radsrv(struct request *rq) {
2000 uint8_t code, id, *auth, *attrs, *attr;
2002 struct server *to = NULL;
2003 char username[254], userascii[760];
2004 unsigned char newauth[16];
2005 struct realm *realm = NULL;
2007 code = *(uint8_t *)rq->buf;
2008 id = *(uint8_t *)(rq->buf + 1);
2009 len = RADLEN(rq->buf);
2010 auth = (uint8_t *)(rq->buf + 4);
2012 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2014 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2015 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2020 attrs = rq->buf + 20;
2022 if (!attrvalidate(attrs, len)) {
2023 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2027 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2028 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2029 debug(DBG_WARN, "radsrv: message authentication failed");
2033 if (code == RAD_Status_Server) {
2034 respondstatusserver(rq);
2038 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2040 if (code == RAD_Accounting_Request) {
2041 memset(newauth, 0, 16);
2042 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2043 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2048 if (rq->from->conf->rewrite) {
2049 dorewrite(rq->buf, rq->from->conf->rewrite);
2050 len = RADLEN(rq->buf) - 20;
2053 attr = attrget(attrs, len, RAD_Attr_User_Name);
2055 if (code == RAD_Accounting_Request) {
2056 acclog(attrs, len, rq->from->conf->host);
2057 respondaccounting(rq);
2059 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2062 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2063 username[ATTRVALLEN(attr)] = '\0';
2064 radattr2ascii(userascii, sizeof(userascii), attr);
2066 if (rq->from->conf->rewriteattrregex) {
2067 if (!rewriteusername(rq, username)) {
2068 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2071 len = RADLEN(rq->buf) - 20;
2072 auth = (uint8_t *)(rq->buf + 4);
2073 attrs = rq->buf + 20;
2076 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2078 to = findserver(&realm, username, code == RAD_Accounting_Request);
2080 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2084 if (realm->message && code == RAD_Access_Request) {
2085 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2086 respondreject(rq, realm->message);
2087 } else if (realm->accresp && code == RAD_Accounting_Request) {
2088 acclog(attrs, len, rq->from->conf->host);
2089 respondaccounting(rq);
2094 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2095 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2096 rq->from->conf->name, to->conf->name);
2100 if (rqinqueue(to, rq->from, id, code)) {
2101 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2102 radmsgtype2string(code), rq->from->conf->host, id);
2106 if (code != RAD_Accounting_Request) {
2107 if (!RAND_bytes(newauth, 16)) {
2108 debug(DBG_WARN, "radsrv: failed to generate random auth");
2114 printfchars(NULL, "auth", "%02x ", auth, 16);
2117 attr = attrget(attrs, len, RAD_Attr_User_Password);
2119 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2120 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2124 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2126 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2127 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2132 memcpy(rq->origauth, auth, 16);
2133 memcpy(auth, newauth, 16);
2141 int replyh(struct server *server, unsigned char *buf) {
2142 struct client *from;
2145 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2146 struct sockaddr_storage fromsa;
2147 char tmp[760], stationid[760];
2149 server->connectionok = 1;
2150 server->lostrqs = 0;
2152 i = buf[1]; /* i is the id */
2154 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2155 && *buf != RAD_Accounting_Response) {
2156 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2159 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2161 rq = server->requests + i;
2163 pthread_mutex_lock(&server->newrq_mutex);
2164 if (!rq->buf || !rq->tries) {
2165 pthread_mutex_unlock(&server->newrq_mutex);
2166 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2171 pthread_mutex_unlock(&server->newrq_mutex);
2172 debug(DBG_INFO, "replyh: already received, ignoring reply");
2176 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2177 pthread_mutex_unlock(&server->newrq_mutex);
2178 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2182 len = RADLEN(buf) - 20;
2185 if (!attrvalidate(attrs, len)) {
2186 pthread_mutex_unlock(&server->newrq_mutex);
2187 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2191 /* Message Authenticator */
2192 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2194 if (ATTRVALLEN(messageauth) != 16) {
2195 pthread_mutex_unlock(&server->newrq_mutex);
2196 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2199 memcpy(tmp, buf + 4, 16);
2200 memcpy(buf + 4, rq->buf + 4, 16);
2201 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2202 pthread_mutex_unlock(&server->newrq_mutex);
2203 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2206 memcpy(buf + 4, tmp, 16);
2207 debug(DBG_DBG, "replyh: message auth ok");
2210 if (*rq->buf == RAD_Status_Server) {
2212 pthread_mutex_unlock(&server->newrq_mutex);
2213 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2217 gettimeofday(&server->lastreply, NULL);
2221 pthread_mutex_unlock(&server->newrq_mutex);
2222 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2226 if (server->conf->rewrite) {
2227 dorewrite(buf, server->conf->rewrite);
2228 len = RADLEN(buf) - 20;
2232 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2233 if (ATTRVALLEN(attr) <= 4)
2236 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2239 sublen = ATTRVALLEN(attr) - 4;
2240 subattrs = ATTRVAL(attr) + 4;
2241 if (!attrvalidate(subattrs, sublen) ||
2242 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2243 rq, server->conf->secret, from->conf->secret) ||
2244 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2245 rq, server->conf->secret, from->conf->secret))
2249 pthread_mutex_unlock(&server->newrq_mutex);
2250 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2254 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2255 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2257 radattr2ascii(tmp, sizeof(tmp), attr);
2258 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2260 radattr2ascii(stationid, sizeof(stationid), attr);
2261 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2262 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2264 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2268 buf[1] = (char)rq->origid;
2269 memcpy(buf + 4, rq->origauth, 16);
2271 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2274 if (rq->origusername) {
2275 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2277 pthread_mutex_unlock(&server->newrq_mutex);
2278 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2281 memcpy(username, rq->origusername, strlen(rq->origusername));
2282 len = RADLEN(buf) - 20;
2285 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2289 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2290 pthread_mutex_unlock(&server->newrq_mutex);
2291 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2294 debug(DBG_DBG, "replyh: computed messageauthattr");
2297 if (from->conf->type == 'U')
2298 fromsa = rq->fromsa;
2299 /* once we set received = 1, rq may be reused */
2302 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2303 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2304 pthread_mutex_unlock(&server->newrq_mutex);
2308 void *udpclientrd(void *arg) {
2309 struct server *server;
2311 int *s = (int *)arg;
2315 buf = radudpget(*s, NULL, &server, NULL);
2316 if (!replyh(server, buf))
2321 void *tlsclientrd(void *arg) {
2322 struct server *server = (struct server *)arg;
2324 struct timeval now, lastconnecttry;
2327 /* yes, lastconnecttry is really necessary */
2328 lastconnecttry = server->lastconnecttry;
2329 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2331 if (server->dynamiclookuparg)
2333 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2337 if (!replyh(server, buf))
2339 if (server->dynamiclookuparg) {
2340 gettimeofday(&now, NULL);
2341 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2342 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2347 server->clientrdgone = 1;
2351 /* code for removing state not finished */
2352 void *clientwr(void *arg) {
2353 struct server *server = (struct server *)arg;
2355 pthread_t tlsclientrdth;
2356 int i, dynconffail = 0;
2358 struct timeval now, lastsend;
2359 struct timespec timeout;
2360 struct request statsrvrq;
2361 unsigned char statsrvbuf[38];
2362 struct clsrvconf *conf;
2364 conf = server->conf;
2366 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2371 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2372 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2376 memset(&timeout, 0, sizeof(struct timespec));
2378 if (conf->statusserver) {
2379 memset(&statsrvrq, 0, sizeof(struct request));
2380 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2381 statsrvbuf[0] = RAD_Status_Server;
2383 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2384 statsrvbuf[21] = 18;
2385 gettimeofday(&lastsend, NULL);
2388 if (conf->type == 'U') {
2389 server->connectionok = 1;
2391 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2393 server->connectionok = 1;
2394 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2395 debug(DBG_ERR, "clientwr: pthread_create failed");
2401 pthread_mutex_lock(&server->newrq_mutex);
2402 if (!server->newrq) {
2403 gettimeofday(&now, NULL);
2404 /* random 0-7 seconds */
2405 RAND_bytes(&rnd, 1);
2407 if (conf->statusserver) {
2408 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2409 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2411 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2412 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2415 if (timeout.tv_sec > now.tv_sec)
2416 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2418 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2421 if (server->newrq) {
2422 debug(DBG_DBG, "clientwr: got new request");
2427 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2429 pthread_mutex_unlock(&server->newrq_mutex);
2431 for (i = 0; i < MAX_REQUESTS; i++) {
2432 if (server->clientrdgone) {
2433 pthread_join(tlsclientrdth, NULL);
2436 pthread_mutex_lock(&server->newrq_mutex);
2437 while (i < MAX_REQUESTS && !server->requests[i].buf)
2439 if (i == MAX_REQUESTS) {
2440 pthread_mutex_unlock(&server->newrq_mutex);
2443 rq = server->requests + i;
2446 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2448 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2450 /* setting this to NULL means that it can be reused */
2453 pthread_mutex_unlock(&server->newrq_mutex);
2457 gettimeofday(&now, NULL);
2458 if (now.tv_sec < rq->expiry.tv_sec) {
2459 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2460 timeout.tv_sec = rq->expiry.tv_sec;
2461 pthread_mutex_unlock(&server->newrq_mutex);
2465 if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
2466 ? 1 : conf->retrycount + 1)) {
2467 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2468 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2469 if (server->lostrqs < 255)
2472 /* setting this to NULL means that it can be reused */
2474 pthread_mutex_unlock(&server->newrq_mutex);
2477 pthread_mutex_unlock(&server->newrq_mutex);
2479 rq->expiry.tv_sec = now.tv_sec +
2480 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2481 ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
2482 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2483 timeout.tv_sec = rq->expiry.tv_sec;
2485 clientradput(server, server->requests[i].buf);
2486 gettimeofday(&lastsend, NULL);
2488 if (conf->statusserver) {
2489 gettimeofday(&now, NULL);
2490 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2491 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2492 debug(DBG_WARN, "clientwr: failed to generate random auth");
2495 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2496 if (!statsrvrq.buf) {
2497 debug(DBG_ERR, "clientwr: malloc failed");
2500 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2501 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2502 lastsend.tv_sec = now.tv_sec;
2503 sendrq(server, &statsrvrq);
2508 conf->servers = NULL;
2509 if (server->dynamiclookuparg) {
2510 removeserversubrealms(realms, conf);
2514 freeclsrvconf(conf);
2516 freeserver(server, 1);
2520 void *udpserverwr(void *arg) {
2521 struct replyq *replyq = udp_server_replyq;
2522 struct reply *reply;
2525 pthread_mutex_lock(&replyq->mutex);
2526 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2527 debug(DBG_DBG, "udp server writer, waiting for signal");
2528 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2529 debug(DBG_DBG, "udp server writer, got signal");
2531 pthread_mutex_unlock(&replyq->mutex);
2533 if (sendto(*(uint8_t *)reply->buf == RAD_Accounting_Response ? udp_accserver_sock : udp_server_sock,
2534 reply->buf, RADLEN(reply->buf), 0,
2535 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2536 debug(DBG_WARN, "sendudp: send failed");
2542 void *udpserverrd(void *arg) {
2544 pthread_t udpserverwrth;
2545 struct clsrvconf *listenres;
2547 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2548 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2549 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2551 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2552 listenres->host ? listenres->host : "*", listenres->port);
2553 freeclsrvres(listenres);
2555 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2556 debugx(1, DBG_ERR, "pthread_create failed");
2559 memset(&rq, 0, sizeof(struct request));
2560 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2565 void *udpaccserverrd(void *arg) {
2567 struct clsrvconf *listenres;
2569 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2570 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2571 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2573 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2574 listenres->host ? listenres->host : "*", listenres->port);
2575 freeclsrvres(listenres);
2578 memset(&rq, 0, sizeof(struct request));
2579 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2580 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2584 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2589 void *tlsserverwr(void *arg) {
2591 unsigned long error;
2592 struct client *client = (struct client *)arg;
2593 struct replyq *replyq;
2594 struct reply *reply;
2596 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2597 replyq = client->replyq;
2599 pthread_mutex_lock(&replyq->mutex);
2600 while (!list_first(replyq->replies)) {
2602 debug(DBG_DBG, "tls server writer, waiting for signal");
2603 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2604 debug(DBG_DBG, "tls server writer, got signal");
2607 /* ssl might have changed while waiting */
2608 pthread_mutex_unlock(&replyq->mutex);
2609 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2613 reply = (struct reply *)list_shift(replyq->replies);
2614 pthread_mutex_unlock(&replyq->mutex);
2615 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2617 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2618 cnt, RADLEN(reply->buf));
2620 while ((error = ERR_get_error()))
2621 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2627 void tlsserverrd(struct client *client) {
2629 pthread_t tlsserverwrth;
2631 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2633 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2634 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2639 memset(&rq, 0, sizeof(struct request));
2640 rq.buf = radtlsget(client->ssl, 0);
2643 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2648 debug(DBG_ERR, "tlsserverrd: connection lost");
2649 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2651 pthread_mutex_lock(&client->replyq->mutex);
2652 pthread_cond_signal(&client->replyq->cond);
2653 pthread_mutex_unlock(&client->replyq->mutex);
2654 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2655 pthread_join(tlsserverwrth, NULL);
2656 removeclientrqs(client);
2657 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2660 void *tlsservernew(void *arg) {
2662 struct sockaddr_storage from;
2663 size_t fromlen = sizeof(from);
2664 struct clsrvconf *conf;
2665 struct list_node *cur = NULL;
2668 unsigned long error;
2669 struct client *client;
2672 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2673 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2676 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2678 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2680 ssl = SSL_new(conf->ssl_ctx);
2683 if (SSL_accept(ssl) <= 0) {
2684 while ((error = ERR_get_error()))
2685 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2686 debug(DBG_ERR, "SSL_accept failed");
2689 cert = verifytlscert(ssl);
2695 if (verifyconfcert(cert, conf)) {
2697 client = addclient(conf);
2700 tlsserverrd(client);
2701 removeclient(client);
2703 debug(DBG_WARN, "Failed to create new client instance");
2706 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2708 debug(DBG_WARN, "ignoring request, no matching TLS client");
2714 shutdown(s, SHUT_RDWR);
2720 pthread_t tlsserverth;
2722 struct sockaddr_storage from;
2723 size_t fromlen = sizeof(from);
2724 struct clsrvconf *listenres;
2726 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2727 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2728 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2730 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2731 freeclsrvres(listenres);
2735 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2737 debug(DBG_WARN, "accept failed");
2740 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2741 debug(DBG_ERR, "tlslistener: pthread_create failed");
2742 shutdown(snew, SHUT_RDWR);
2746 pthread_detach(tlsserverth);
2751 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2754 STACK_OF(X509_NAME) *calist;
2757 unsigned long error;
2759 if (!certfile || !certkeyfile)
2760 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2762 if (!cacertfile && !cacertpath)
2763 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2766 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2767 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2768 for (i = 0; i < CRYPTO_num_locks(); i++) {
2769 ssl_lock_count[i] = 0;
2770 pthread_mutex_init(&ssl_locks[i], NULL);
2772 CRYPTO_set_id_callback(ssl_thread_id);
2773 CRYPTO_set_locking_callback(ssl_locking_callback);
2775 SSL_load_error_strings();
2778 while (!RAND_status()) {
2779 time_t t = time(NULL);
2780 pid_t pid = getpid();
2781 RAND_seed((unsigned char *)&t, sizeof(time_t));
2782 RAND_seed((unsigned char *)&pid, sizeof(pid));
2785 ctx = SSL_CTX_new(TLSv1_method());
2787 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2788 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2790 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2791 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2792 !SSL_CTX_check_private_key(ctx) ||
2793 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2794 while ((error = ERR_get_error()))
2795 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2796 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2799 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2800 if (!cacertfile || calist) {
2803 calist = sk_X509_NAME_new_null();
2804 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2805 sk_X509_NAME_free(calist);
2811 while ((error = ERR_get_error()))
2812 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2813 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2815 SSL_CTX_set_client_CA_list(ctx, calist);
2817 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2818 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2821 x509_s = SSL_CTX_get_cert_store(ctx);
2822 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2825 new = malloc(sizeof(struct tls));
2826 if (!new || !list_push(tlsconfs, new))
2827 debugx(1, DBG_ERR, "malloc failed");
2829 memset(new, 0, sizeof(struct tls));
2830 new->name = stringcopy(value, 0);
2832 debugx(1, DBG_ERR, "malloc failed");
2834 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2837 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2838 struct list_node *entry;
2839 struct tls *t, *t1 = NULL, *t2 = NULL;
2841 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2842 t = (struct tls *)entry->data;
2843 if (!strcasecmp(t->name, alt1)) {
2847 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2857 struct list *addsrvconfs(char *value, char **names) {
2858 struct list *conflist;
2860 struct list_node *entry;
2861 struct clsrvconf *conf = NULL;
2863 if (!names || !*names)
2866 conflist = list_create();
2868 debug(DBG_ERR, "malloc failed");
2872 for (n = 0; names[n]; n++) {
2873 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2874 conf = (struct clsrvconf *)entry->data;
2875 if (!strcasecmp(names[n], conf->name))
2879 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2880 list_destroy(conflist);
2883 if (!list_push(conflist, conf)) {
2884 debug(DBG_ERR, "malloc failed");
2885 list_destroy(conflist);
2888 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2893 void freerealm(struct realm *realm) {
2897 free(realm->message);
2898 regfree(&realm->regex);
2899 pthread_mutex_destroy(&realm->subrealms_mutex);
2900 if (realm->subrealms)
2901 list_destroy(realm->subrealms);
2902 if (realm->srvconfs) {
2903 /* emptying list without freeing data */
2904 while (list_shift(realm->srvconfs));
2905 list_destroy(realm->srvconfs);
2907 if (realm->accsrvconfs) {
2908 /* emptying list without freeing data */
2909 while (list_shift(realm->accsrvconfs));
2910 list_destroy(realm->accsrvconfs);
2915 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2917 struct realm *realm;
2918 char *s, *regex = NULL;
2920 if (*value == '/') {
2921 /* regexp, remove optional trailing / if present */
2922 if (value[strlen(value) - 1] == '/')
2923 value[strlen(value) - 1] = '\0';
2925 /* not a regexp, let us make it one */
2926 if (*value == '*' && !value[1])
2927 regex = stringcopy(".*", 0);
2929 for (n = 0, s = value; *s;)
2932 regex = malloc(strlen(value) + n + 3);
2935 for (n = 1, s = value; *s; s++) {
2945 debug(DBG_ERR, "malloc failed");
2949 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2952 realm = malloc(sizeof(struct realm));
2954 debug(DBG_ERR, "malloc failed");
2957 memset(realm, 0, sizeof(struct realm));
2959 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2960 debug(DBG_ERR, "mutex init failed");
2966 realm->name = stringcopy(value, 0);
2968 debug(DBG_ERR, "malloc failed");
2971 if (message && strlen(message) > 253) {
2972 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2975 realm->message = message;
2976 realm->accresp = accresp;
2978 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2979 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2983 if (servers && *servers) {
2984 realm->srvconfs = addsrvconfs(value, servers);
2985 if (!realm->srvconfs)
2989 if (accservers && *accservers) {
2990 realm->accsrvconfs = addsrvconfs(value, accservers);
2991 if (!realm->accsrvconfs)
2995 if (!list_push(realmlist, realm)) {
2996 debug(DBG_ERR, "malloc failed");
2997 pthread_mutex_destroy(&realm->subrealms_mutex);
3001 debug(DBG_DBG, "addrealm: added realm %s", value);
3011 for (n = 0; servers[n]; n++)
3016 for (n = 0; accservers[n]; n++)
3017 free(accservers[n]);
3023 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3024 struct clsrvconf *srvconf;
3025 struct realm *newrealm = NULL;
3026 char *realmname, *s;
3029 if (!conf->dynamiclookupcommand)
3032 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3033 realmname = strrchr(id, '@');
3039 for (s = realmname; *s; s++)
3040 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3043 pthread_mutex_lock(&realm->subrealms_mutex);
3044 /* exit if we now already got a matching subrealm */
3045 if (id2realm(realm->subrealms, id))
3047 srvconf = malloc(sizeof(struct clsrvconf));
3049 debug(DBG_ERR, "malloc failed");
3053 if (!addserver(srvconf))
3056 if (!realm->subrealms)
3057 realm->subrealms = list_create();
3058 if (!realm->subrealms)
3060 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3064 /* add server and accserver to newrealm */
3065 newrealm->srvconfs = list_create();
3066 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3067 debug(DBG_ERR, "malloc failed");
3070 newrealm->accsrvconfs = list_create();
3071 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3072 debug(DBG_ERR, "malloc failed");
3076 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3078 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3079 debug(DBG_ERR, "pthread_create failed");
3082 pthread_detach(clientth);
3087 list_removedata(realm->subrealms, newrealm);
3088 freerealm(newrealm);
3089 if (!list_first(realm->subrealms)) {
3090 list_destroy(realm->subrealms);
3091 realm->subrealms = NULL;
3094 freeserver(srvconf->servers, 1);
3096 debug(DBG_ERR, "failed to create dynamic server");
3099 pthread_mutex_unlock(&realm->subrealms_mutex);
3102 int dynamicconfig(struct server *server) {
3103 int ok, fd[2], status;
3105 struct clsrvconf *conf = server->conf;
3106 struct gconffile *cf = NULL;
3108 /* for now we only learn hostname/address */
3109 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3112 debug(DBG_ERR, "dynamicconfig: pipe error");
3117 debug(DBG_ERR, "dynamicconfig: fork error");
3121 } else if (pid == 0) {
3124 if (fd[1] != STDOUT_FILENO) {
3125 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3126 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3129 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3130 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3134 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3135 ok = getgenericconfig(&cf, NULL,
3136 "Server", CONF_CBK, confserver_cb, (void *)conf,
3141 if (waitpid(pid, &status, 0) < 0) {
3142 debug(DBG_ERR, "dynamicconfig: wait error");
3147 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3155 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3159 int addmatchcertattr(struct clsrvconf *conf) {
3163 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3164 r = &conf->certcnregex;
3165 v = conf->matchcertattr + 4;
3166 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3167 r = &conf->certuriregex;
3168 v = conf->matchcertattr + 20;
3173 /* regexp, remove optional trailing / if present */
3174 if (v[strlen(v) - 1] == '/')
3175 v[strlen(v) - 1] = '\0';
3179 *r = malloc(sizeof(regex_t));
3181 debug(DBG_ERR, "malloc failed");
3184 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3187 debug(DBG_ERR, "failed to compile regular expression %s", v);
3193 int addrewriteattr(struct clsrvconf *conf) {
3196 v = conf->rewriteattr + 11;
3197 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3199 /* regexp, remove optional trailing / if present */
3200 if (v[strlen(v) - 1] == '/')
3201 v[strlen(v) - 1] = '\0';
3209 conf->rewriteattrregex = malloc(sizeof(regex_t));
3210 if (!conf->rewriteattrregex) {
3211 debug(DBG_ERR, "malloc failed");
3215 conf->rewriteattrreplacement = stringcopy(w, 0);
3216 if (!conf->rewriteattrreplacement) {
3217 free(conf->rewriteattrregex);
3218 conf->rewriteattrregex = NULL;
3222 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3223 free(conf->rewriteattrregex);
3224 conf->rewriteattrregex = NULL;
3225 free(conf->rewriteattrreplacement);
3226 conf->rewriteattrreplacement = NULL;
3227 debug(DBG_ERR, "failed to compile regular expression %s", v);
3234 /* should accept both names and numeric values, only numeric right now */
3235 uint8_t attrname2val(char *attrname) {
3238 val = atoi(attrname);
3239 return val > 0 && val < 256 ? val : 0;
3242 /* should accept both names and numeric values, only numeric right now */
3243 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3246 *vendor = atoi(attrname);
3247 s = strchr(attrname, ':');
3252 *type = atoi(s + 1);
3253 return *type >= 0 && *type < 256;
3256 struct rewrite *getrewrite(char *alt1, char *alt2) {
3257 struct list_node *entry;
3258 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3260 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3261 r = (struct rewriteconf *)entry->data;
3262 if (!strcasecmp(r->name, alt1)) {
3266 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3276 void addrewrite(char *value, char **attrs, char **vattrs) {
3277 struct rewriteconf *new;
3278 struct rewrite *rewrite = NULL;
3281 uint32_t *p, *va = NULL;
3285 for (; attrs[n]; n++);
3286 a = malloc((n + 1) * sizeof(uint8_t));
3288 debugx(1, DBG_ERR, "malloc failed");
3290 for (i = 0; i < n; i++) {
3291 if (!(a[i] = attrname2val(attrs[i])))
3292 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3301 for (; vattrs[n]; n++);
3302 va = malloc((2 * n + 1) * sizeof(uint32_t));
3304 debugx(1, DBG_ERR, "malloc failed");
3306 for (p = va, i = 0; i < n; i++, p += 2) {
3307 if (!vattrname2val(vattrs[i], p, p + 1))
3308 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3316 rewrite = malloc(sizeof(struct rewrite));
3318 debugx(1, DBG_ERR, "malloc failed");
3319 rewrite->removeattrs = a;
3320 rewrite->removevendorattrs = va;
3323 new = malloc(sizeof(struct rewriteconf));
3324 if (!new || !list_push(rewriteconfs, new))
3325 debugx(1, DBG_ERR, "malloc failed");
3327 memset(new, 0, sizeof(struct rewriteconf));
3328 new->name = stringcopy(value, 0);
3330 debugx(1, DBG_ERR, "malloc failed");
3332 new->rewrite = rewrite;
3333 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3336 void freeclsrvconf(struct clsrvconf *conf) {
3338 free(conf->conftype);
3343 free(conf->matchcertattr);
3344 if (conf->certcnregex)
3345 regfree(conf->certcnregex);
3346 if (conf->certuriregex)
3347 regfree(conf->certuriregex);
3348 free(conf->confrewrite);
3349 free(conf->rewriteattr);
3350 if (conf->rewriteattrregex)
3351 regfree(conf->rewriteattrregex);
3352 free(conf->rewriteattrreplacement);
3353 free(conf->dynamiclookupcommand);
3354 free(conf->rewrite);
3356 freeaddrinfo(conf->addrinfo);
3357 /* not touching ssl_ctx, clients and servers */
3361 int mergeconfstring(char **dst, char **src) {
3370 t = stringcopy(*dst, 0);
3372 debug(DBG_ERR, "malloc failed");
3380 /* assumes dst is a shallow copy */
3381 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3382 if (!mergeconfstring(&dst->name, &src->name) ||
3383 !mergeconfstring(&dst->conftype, &src->conftype) ||
3384 !mergeconfstring(&dst->host, &src->host) ||
3385 !mergeconfstring(&dst->port, &src->port) ||
3386 !mergeconfstring(&dst->secret, &src->secret) ||
3387 !mergeconfstring(&dst->tls, &src->tls) ||
3388 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3389 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3390 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3392 dst->statusserver = src->statusserver;
3393 dst->certnamecheck = src->certnamecheck;
3394 if (src->retrydelay != 255)
3395 dst->retrydelay = src->retrydelay;
3396 if (src->retrycount != 255)
3397 dst->retrycount = src->retrycount;
3401 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3402 struct clsrvconf *conf;
3404 debug(DBG_DBG, "confclient_cb called for %s", block);
3406 conf = malloc(sizeof(struct clsrvconf));
3407 if (!conf || !list_push(clconfs, conf))
3408 debugx(1, DBG_ERR, "malloc failed");
3409 memset(conf, 0, sizeof(struct clsrvconf));
3410 conf->certnamecheck = 1;
3412 if (!getgenericconfig(cf, block,
3413 "type", CONF_STR, &conf->conftype,
3414 "host", CONF_STR, &conf->host,
3415 "secret", CONF_STR, &conf->secret,
3416 "tls", CONF_STR, &conf->tls,
3417 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3418 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3419 "rewrite", CONF_STR, &conf->confrewrite,
3420 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3423 debugx(1, DBG_ERR, "configuration error");
3425 conf->name = stringcopy(val, 0);
3427 conf->host = stringcopy(val, 0);
3429 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3432 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3433 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3435 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3436 if (conf->matchcertattr && !addmatchcertattr(conf))
3437 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3441 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3443 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3445 if (conf->rewriteattr) {
3446 if (!addrewriteattr(conf))
3447 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3450 if (!resolvepeer(conf, 0))
3451 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3453 if (!conf->secret) {
3454 if (conf->type == 'U')
3455 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3456 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3461 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3462 switch (conf->type) {
3465 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3468 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3469 if (!conf->ssl_ctx) {
3470 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3473 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3474 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3478 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3482 if (conf->retrydelay == 255)
3483 conf->retrydelay = REQUEST_RETRY_DELAY;
3484 if (conf->retrycount == 255)
3485 conf->retrycount = REQUEST_RETRY_COUNT;
3487 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3489 if (!conf->secret) {
3490 if (conf->type == 'U')
3491 debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3492 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3493 if (!conf->secret) {
3494 debug(DBG_ERR, "malloc failed");
3499 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3500 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3506 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3507 struct clsrvconf *conf, *resconf;
3508 long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
3510 debug(DBG_DBG, "confserver_cb called for %s", block);
3512 conf = malloc(sizeof(struct clsrvconf));
3514 debug(DBG_ERR, "malloc failed");
3517 memset(conf, 0, sizeof(struct clsrvconf));
3518 resconf = (struct clsrvconf *)arg;
3520 conf->statusserver = resconf->statusserver;
3521 conf->certnamecheck = resconf->certnamecheck;
3523 conf->certnamecheck = 1;
3525 if (!getgenericconfig(cf, block,
3526 "type", CONF_STR, &conf->conftype,
3527 "host", CONF_STR, &conf->host,
3528 "port", CONF_STR, &conf->port,
3529 "secret", CONF_STR, &conf->secret,
3530 "tls", CONF_STR, &conf->tls,
3531 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3532 "rewrite", CONF_STR, &conf->confrewrite,
3533 "StatusServer", CONF_BLN, &conf->statusserver,
3534 "RetryDelay", CONF_LINT, &retrydelay,
3535 "RetryCount", CONF_LINT, &retrycount,
3536 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3537 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3540 debug(DBG_ERR, "configuration error");
3544 conf->name = stringcopy(val, 0);
3546 debug(DBG_ERR, "malloc failed");
3550 conf->host = stringcopy(val, 0);
3552 debug(DBG_ERR, "malloc failed");
3557 if (retrydelay != LONG_MIN) {
3558 if (retrydelay < 1 || retrydelay > 60) {
3559 debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
3562 conf->retrydelay = (uint8_t)retrydelay;
3564 conf->retrydelay = 255;
3566 if (retrycount != LONG_MIN) {
3567 if (retrycount < 0 || retrycount > 10) {
3568 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3571 conf->retrycount = (uint8_t)retrycount;
3573 conf->retrycount = 255;
3576 if (!mergesrvconf(resconf, conf))
3580 if (conf->dynamiclookupcommand) {
3581 free(conf->dynamiclookupcommand);
3582 conf->dynamiclookupcommand = NULL;
3586 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3588 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3591 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3595 if (resconf || !conf->dynamiclookupcommand) {
3596 if (!compileserverconfig(conf, block))
3603 switch (conf->type) {
3614 if (!list_push(srvconfs, conf)) {
3615 debug(DBG_ERR, "malloc failed");
3621 freeclsrvconf(conf);
3625 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3626 char **servers = NULL, **accservers = NULL, *msg = NULL;
3627 uint8_t accresp = 0;
3629 debug(DBG_DBG, "confrealm_cb called for %s", block);
3631 if (!getgenericconfig(cf, block,
3632 "server", CONF_MSTR, &servers,
3633 "accountingServer", CONF_MSTR, &accservers,
3634 "ReplyMessage", CONF_STR, &msg,
3635 "AccountingResponse", CONF_BLN, &accresp,
3638 debugx(1, DBG_ERR, "configuration error");
3640 addrealm(realms, val, servers, accservers, msg, accresp);
3644 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3645 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3646 uint8_t crlcheck = 0;
3648 debug(DBG_DBG, "conftls_cb called for %s", block);
3650 if (!getgenericconfig(cf, block,
3651 "CACertificateFile", CONF_STR, &cacertfile,
3652 "CACertificatePath", CONF_STR, &cacertpath,
3653 "CertificateFile", CONF_STR, &certfile,
3654 "CertificateKeyFile", CONF_STR, &certkeyfile,
3655 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3656 "CRLCheck", CONF_BLN, &crlcheck,
3659 debugx(1, DBG_ERR, "configuration error");
3661 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3670 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3671 char **attrs = NULL, **vattrs = NULL;
3673 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3675 if (!getgenericconfig(cf, block,
3676 "removeAttribute", CONF_MSTR, &attrs,
3677 "removeVendorAttribute", CONF_MSTR, &vattrs,
3680 debugx(1, DBG_ERR, "configuration error");
3681 addrewrite(val, attrs, vattrs);
3685 void getmainconfig(const char *configfile) {
3686 long int loglevel = LONG_MIN;
3687 struct gconffile *cfs;
3689 cfs = openconfigfile(configfile);
3690 memset(&options, 0, sizeof(options));
3692 clconfs = list_create();
3694 debugx(1, DBG_ERR, "malloc failed");
3696 srvconfs = list_create();
3698 debugx(1, DBG_ERR, "malloc failed");
3700 realms = list_create();
3702 debugx(1, DBG_ERR, "malloc failed");
3704 tlsconfs = list_create();
3706 debugx(1, DBG_ERR, "malloc failed");
3708 rewriteconfs = list_create();
3710 debugx(1, DBG_ERR, "malloc failed");
3712 if (!getgenericconfig(&cfs, NULL,
3713 "ListenUDP", CONF_STR, &options.listenudp,
3714 "ListenTCP", CONF_STR, &options.listentcp,
3715 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3716 "SourceUDP", CONF_STR, &options.sourceudp,
3717 "SourceTCP", CONF_STR, &options.sourcetcp,
3718 "LogLevel", CONF_LINT, &loglevel,
3719 "LogDestination", CONF_STR, &options.logdestination,
3720 "LoopPrevention", CONF_BLN, &options.loopprevention,
3721 "Client", CONF_CBK, confclient_cb, NULL,
3722 "Server", CONF_CBK, confserver_cb, NULL,
3723 "Realm", CONF_CBK, confrealm_cb, NULL,
3724 "TLS", CONF_CBK, conftls_cb, NULL,
3725 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3728 debugx(1, DBG_ERR, "configuration error");
3730 if (loglevel != LONG_MIN) {
3731 if (loglevel < 1 || loglevel > 4)
3732 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3733 options.loglevel = (uint8_t)loglevel;
3737 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3740 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3743 *configfile = optarg;
3746 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3747 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3748 *loglevel = *optarg - '0';
3757 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3762 if (!(argc - optind))
3766 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3770 int daemon(int a, int b) {
3778 for (i = 0; i < 3; i++) {
3780 open("/dev/null", O_RDWR);
3786 void *sighandler(void *arg) {
3791 sigemptyset(&sigset);
3792 sigaddset(&sigset, SIGPIPE);
3793 sigwait(&sigset, &sig);
3794 /* only get SIGPIPE right now, so could simplify below code */
3797 /* completely ignoring this */
3800 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3803 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3808 int main(int argc, char **argv) {
3809 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3811 struct list_node *entry;
3812 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3813 char *configfile = NULL;
3814 struct clsrvconf *srvconf;
3816 debug_init("radsecproxy");
3817 debug_set_level(DEBUG_LEVEL);
3818 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3820 debug_set_level(loglevel);
3821 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3823 options.loglevel = loglevel;
3824 else if (options.loglevel)
3825 debug_set_level(options.loglevel);
3827 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3828 free(options.logdestination);
3830 if (!list_first(clconfs))
3831 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3832 if (!list_first(srvconfs))
3833 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3834 if (!list_first(realms))
3835 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3838 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3840 if (!foreground && (daemon(0, 0) < 0))
3841 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3843 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3845 sigemptyset(&sigset);
3846 /* exit on all but SIGPIPE, ignore more? */
3847 sigaddset(&sigset, SIGPIPE);
3848 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3849 pthread_create(&sigth, NULL, sighandler, NULL);
3851 if (client_udp_count) {
3852 udp_server_replyq = newreplyq();
3853 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3854 debugx(1, DBG_ERR, "pthread_create failed");
3855 if (options.listenaccudp)
3856 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3857 debugx(1, DBG_ERR, "pthread_create failed");
3860 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3861 srvconf = (struct clsrvconf *)entry->data;
3862 if (srvconf->dynamiclookupcommand)
3864 if (!addserver(srvconf))
3865 debugx(1, DBG_ERR, "failed to add server");
3866 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3867 (void *)(srvconf->servers)))
3868 debugx(1, DBG_ERR, "pthread_create failed");
3870 /* srcudpres no longer needed, while srctcpres is needed later */
3872 freeaddrinfo(srcudpres);
3875 if (udp_client4_sock >= 0)
3876 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3877 debugx(1, DBG_ERR, "pthread_create failed");
3878 if (udp_client6_sock >= 0)
3879 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3880 debugx(1, DBG_ERR, "pthread_create failed");
3882 if (client_tls_count)
3883 return tlslistener();
3885 /* just hang around doing nothing, anything to do here? */