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", total);
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, "No room in queue, dropping request");
1252 pthread_mutex_unlock(&to->newrq_mutex);
1257 rq->buf[1] = (char)i;
1259 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1260 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1262 pthread_mutex_unlock(&to->newrq_mutex);
1266 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1267 to->requests[i] = *rq;
1272 debug(DBG_DBG, "signalling client writer");
1273 pthread_cond_signal(&to->newrq_cond);
1275 pthread_mutex_unlock(&to->newrq_mutex);
1278 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1279 struct reply *reply;
1282 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1284 debug(DBG_WARN, "sendreply: failed to sign message");
1288 reply = malloc(sizeof(struct reply));
1291 debug(DBG_ERR, "sendreply: malloc failed");
1294 memset(reply, 0, sizeof(struct reply));
1297 reply->tosa = *tosa;
1299 pthread_mutex_lock(&to->replyq->mutex);
1301 first = list_first(to->replyq->replies) == NULL;
1303 if (!list_push(to->replyq->replies, reply)) {
1304 pthread_mutex_unlock(&to->replyq->mutex);
1307 debug(DBG_ERR, "sendreply: malloc failed");
1312 debug(DBG_DBG, "signalling server writer");
1313 pthread_cond_signal(&to->replyq->cond);
1315 pthread_mutex_unlock(&to->replyq->mutex);
1318 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1319 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1320 static unsigned char first = 1;
1321 static EVP_MD_CTX mdctx;
1322 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1323 unsigned int md_len;
1324 uint8_t i, offset = 0, out[128];
1326 pthread_mutex_lock(&lock);
1328 EVP_MD_CTX_init(&mdctx);
1334 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1335 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1336 !EVP_DigestUpdate(&mdctx, input, 16) ||
1337 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1339 pthread_mutex_unlock(&lock);
1342 for (i = 0; i < 16; i++)
1343 out[offset + i] = hash[i] ^ in[offset + i];
1344 input = out + offset - 16;
1349 memcpy(in, out, len);
1350 pthread_mutex_unlock(&lock);
1354 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1355 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1356 static unsigned char first = 1;
1357 static EVP_MD_CTX mdctx;
1358 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1359 unsigned int md_len;
1360 uint8_t i, offset = 0, out[128];
1362 pthread_mutex_lock(&lock);
1364 EVP_MD_CTX_init(&mdctx);
1370 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1371 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1372 !EVP_DigestUpdate(&mdctx, input, 16) ||
1373 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1375 pthread_mutex_unlock(&lock);
1378 for (i = 0; i < 16; i++)
1379 out[offset + i] = hash[i] ^ in[offset + i];
1380 input = in + offset;
1385 memcpy(in, out, len);
1386 pthread_mutex_unlock(&lock);
1390 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1391 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1392 static unsigned char first = 1;
1393 static EVP_MD_CTX mdctx;
1394 unsigned char hash[EVP_MAX_MD_SIZE];
1395 unsigned int md_len;
1398 pthread_mutex_lock(&lock);
1400 EVP_MD_CTX_init(&mdctx);
1405 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1406 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1407 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1410 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1411 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1412 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1413 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1414 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1415 pthread_mutex_unlock(&lock);
1420 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1423 for (i = 0; i < 16; i++)
1426 for (offset = 16; offset < len; offset += 16) {
1428 printf("text + offset - 16 c(%d): ", offset / 16);
1429 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1431 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1432 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1433 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1434 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1436 pthread_mutex_unlock(&lock);
1440 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1443 for (i = 0; i < 16; i++)
1444 text[offset + i] ^= hash[i];
1448 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1451 pthread_mutex_unlock(&lock);
1455 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1456 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1457 static unsigned char first = 1;
1458 static EVP_MD_CTX mdctx;
1459 unsigned char hash[EVP_MAX_MD_SIZE];
1460 unsigned int md_len;
1464 pthread_mutex_lock(&lock);
1466 EVP_MD_CTX_init(&mdctx);
1471 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1472 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1473 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1476 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1477 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1478 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1479 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1480 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1481 pthread_mutex_unlock(&lock);
1486 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1489 for (i = 0; i < 16; i++)
1490 plain[i] = text[i] ^ hash[i];
1492 for (offset = 16; offset < len; offset += 16) {
1494 printf("text + offset - 16 c(%d): ", offset / 16);
1495 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1497 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1498 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1499 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1500 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1502 pthread_mutex_unlock(&lock);
1506 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1509 for (i = 0; i < 16; i++)
1510 plain[offset + i] = text[offset + i] ^ hash[i];
1513 memcpy(text, plain, len);
1515 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1518 pthread_mutex_unlock(&lock);
1522 struct realm *id2realm(struct list *realmlist, char *id) {
1523 struct list_node *entry;
1524 struct realm *realm, *subrealm = NULL;
1526 /* need to do locking for subrealms and check subrealm timers */
1527 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1528 realm = (struct realm *)entry->data;
1529 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1530 pthread_mutex_lock(&realm->subrealms_mutex);
1531 if (realm->subrealms)
1532 subrealm = id2realm(realm->subrealms, id);
1533 pthread_mutex_unlock(&realm->subrealms_mutex);
1534 return subrealm ? subrealm : realm;
1540 /* helper function, only used by removeserversubrealms() */
1541 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1542 struct list_node *entry;
1543 struct realm *realm;
1545 for (entry = list_first(realmlist); entry;) {
1546 realm = (struct realm *)entry->data;
1547 entry = list_next(entry);
1548 if (realm->srvconfs) {
1549 list_removedata(realm->srvconfs, srv);
1550 if (!list_first(realm->srvconfs)) {
1551 list_destroy(realm->srvconfs);
1552 realm->srvconfs = NULL;
1555 if (realm->accsrvconfs) {
1556 list_removedata(realm->accsrvconfs, srv);
1557 if (!list_first(realm->accsrvconfs)) {
1558 list_destroy(realm->accsrvconfs);
1559 realm->accsrvconfs = NULL;
1563 /* remove subrealm if no servers */
1564 if (!realm->srvconfs && !realm->accsrvconfs) {
1565 list_removedata(realmlist, realm);
1571 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1572 struct list_node *entry;
1573 struct realm *realm;
1575 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1576 realm = (struct realm *)entry->data;
1577 pthread_mutex_lock(&realm->subrealms_mutex);
1578 if (realm->subrealms) {
1579 _internal_removeserversubrealms(realm->subrealms, srv);
1580 if (!list_first(realm->subrealms)) {
1581 list_destroy(realm->subrealms);
1582 realm->subrealms = NULL;
1585 pthread_mutex_unlock(&realm->subrealms_mutex);
1589 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1590 struct request *rq = to->requests, *end;
1592 pthread_mutex_lock(&to->newrq_mutex);
1593 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1594 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1596 pthread_mutex_unlock(&to->newrq_mutex);
1601 int attrvalidate(unsigned char *attrs, int length) {
1602 while (length > 1) {
1603 if (ATTRLEN(attrs) < 2) {
1604 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1607 length -= ATTRLEN(attrs);
1609 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1612 attrs += ATTRLEN(attrs);
1615 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1619 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1620 if (len < 16 || len > 128 || len % 16) {
1621 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1625 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1626 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1630 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1632 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1633 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1639 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1642 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1643 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1646 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1647 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1653 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1654 char *oldsecret, char *newsecret) {
1655 unsigned char *attr;
1657 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1658 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1659 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1665 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1669 for (; attrs[0]; attrs += 2)
1670 if (attrs[0] == vendor && attrs[1] == subattr)
1675 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1676 uint8_t alen, sublen, rmlen = 0;
1677 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1680 if (!removevendorattrs)
1683 while (*removevendorattrs && *removevendorattrs != vendor)
1684 removevendorattrs += 2;
1685 if (!*removevendorattrs)
1688 alen = ATTRLEN(attrs);
1690 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1691 /* remove entire vendor attribute */
1692 memmove(attrs, attrs + alen, length - alen);
1697 subattrs = ATTRVAL(attrs) + 4;
1699 if (!attrvalidate(subattrs, sublen)) {
1700 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1705 while (sublen > 1) {
1706 alen = ATTRLEN(subattrs);
1709 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1710 memmove(subattrs, subattrs + alen, length);
1716 ATTRLEN(attrs) -= rmlen;
1720 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1721 uint8_t *attrs, alen;
1722 uint16_t len, rmlen = 0;
1724 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1727 len = RADLEN(buf) - 20;
1730 alen = ATTRLEN(attrs);
1732 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1733 memmove(attrs, attrs + alen, len);
1735 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1736 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1741 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1744 /* returns a pointer to the resized attribute value */
1745 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1746 uint8_t *attrs, *attr, vallen;
1750 len = RADLEN(*buf) - 20;
1753 attr = attrget(attrs, len, type);
1757 vallen = ATTRVALLEN(attr);
1758 if (vallen == newvallen)
1761 len += newvallen - vallen;
1762 if (newvallen > vallen) {
1763 new = realloc(*buf, len + 20);
1765 debug(DBG_ERR, "resizeattr: malloc failed");
1774 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1775 attr[1] = newvallen + 2;
1776 ((uint16_t *)*buf)[1] = htons(len + 20);
1780 int rewriteusername(struct request *rq, char *in) {
1781 size_t nmatch = 10, reslen = 0, start = 0;
1782 regmatch_t pmatch[10], *pfield;
1784 unsigned char *result;
1785 char *out = rq->from->conf->rewriteattrreplacement;
1787 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1788 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1792 rq->origusername = stringcopy(in, 0);
1793 if (!rq->origusername)
1796 for (i = start; out[i]; i++) {
1797 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1798 pfield = &pmatch[out[i + 1] - '0'];
1799 if (pfield->rm_so >= 0) {
1800 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1806 reslen += i - start;
1808 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1814 for (i = start; out[i]; i++) {
1815 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1816 pfield = &pmatch[out[i + 1] - '0'];
1817 if (pfield->rm_so >= 0) {
1818 memcpy(result + reslen, out + start, i - start);
1819 reslen += i - start;
1820 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1821 reslen += pfield->rm_eo - pfield->rm_so;
1828 memcpy(result + reslen, out + start, i - start);
1829 reslen += i - start;
1830 memcpy(in, result, reslen);
1835 const char *radmsgtype2string(uint8_t code) {
1836 static const char *rad_msg_names[] = {
1837 "", "Access-Request", "Access-Accept", "Access-Reject",
1838 "Accounting-Request", "Accounting-Response", "", "",
1839 "", "", "", "Access-Challenge",
1840 "Status-Server", "Status-Client"
1842 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1845 void char2hex(char *h, unsigned char c) {
1846 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1847 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1848 h[0] = hexdigits[c / 16];
1849 h[1] = hexdigits[c % 16];
1853 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1857 if (!attr || len == 1) {
1862 l = ATTRVALLEN(attr);
1863 s = (char *)ATTRVAL(attr);
1866 for (i = 0; i < l; i++) {
1867 if (s[i] > 31 && s[i] < 127) {
1869 if (d - ascii == len - 1)
1872 if (d - ascii > len - 4)
1877 if (d - ascii == len - 1)
1885 void acclog(unsigned char *attrs, int length, char *host) {
1886 unsigned char *attr;
1889 attr = attrget(attrs, length, RAD_Attr_User_Name);
1891 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1894 radattr2ascii(username, sizeof(username), attr);
1895 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1898 void respondaccounting(struct request *rq) {
1899 unsigned char *resp;
1903 debug(DBG_ERR, "respondstatusserver: malloc failed");
1906 memcpy(resp, rq->buf, 20);
1907 resp[0] = RAD_Accounting_Response;
1910 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1911 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1914 void respondstatusserver(struct request *rq) {
1915 unsigned char *resp;
1919 debug(DBG_ERR, "respondstatusserver: malloc failed");
1922 memcpy(resp, rq->buf, 20);
1923 resp[0] = RAD_Access_Accept;
1926 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1927 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1930 void respondreject(struct request *rq, char *message) {
1931 unsigned char *resp;
1934 if (message && *message)
1935 len += 2 + strlen(message);
1939 debug(DBG_ERR, "respondreject: malloc failed");
1942 memcpy(resp, rq->buf, 20);
1943 resp[0] = RAD_Access_Reject;
1944 *(uint16_t *)(resp + 2) = htons(len);
1945 if (message && *message) {
1946 resp[20] = RAD_Attr_Reply_Message;
1947 resp[21] = len - 20;
1948 memcpy(resp + 22, message, len - 22);
1950 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1953 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1954 struct list_node *entry;
1955 struct clsrvconf *server, *best = NULL, *first = NULL;
1957 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1958 server = (struct clsrvconf *)entry->data;
1959 if (!server->servers)
1963 if (!server->servers->connectionok)
1965 if (!server->servers->lostrqs)
1971 if (server->servers->lostrqs < best->servers->lostrqs)
1974 return best ? best : first;
1977 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1978 struct clsrvconf *srvconf;
1980 *realm = id2realm(realms, id);
1983 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1984 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1987 if (!acc && !srvconf->servers)
1988 adddynamicrealmserver(*realm, srvconf, id);
1989 return srvconf->servers;
1992 void radsrv(struct request *rq) {
1993 uint8_t code, id, *auth, *attrs, *attr;
1995 struct server *to = NULL;
1996 char username[254], userascii[760];
1997 unsigned char newauth[16];
1998 struct realm *realm = NULL;
2000 code = *(uint8_t *)rq->buf;
2001 id = *(uint8_t *)(rq->buf + 1);
2002 len = RADLEN(rq->buf);
2003 auth = (uint8_t *)(rq->buf + 4);
2005 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2007 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2008 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2013 attrs = rq->buf + 20;
2015 if (!attrvalidate(attrs, len)) {
2016 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2020 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2021 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2022 debug(DBG_WARN, "radsrv: message authentication failed");
2026 if (code == RAD_Status_Server) {
2027 respondstatusserver(rq);
2031 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2033 if (code == RAD_Accounting_Request) {
2034 memset(newauth, 0, 16);
2035 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2036 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2041 if (rq->from->conf->rewrite) {
2042 dorewrite(rq->buf, rq->from->conf->rewrite);
2043 len = RADLEN(rq->buf) - 20;
2046 attr = attrget(attrs, len, RAD_Attr_User_Name);
2048 if (code == RAD_Accounting_Request) {
2049 acclog(attrs, len, rq->from->conf->host);
2050 respondaccounting(rq);
2052 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2055 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2056 username[ATTRVALLEN(attr)] = '\0';
2057 radattr2ascii(userascii, sizeof(userascii), attr);
2059 if (rq->from->conf->rewriteattrregex) {
2060 if (!rewriteusername(rq, username)) {
2061 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2064 len = RADLEN(rq->buf) - 20;
2065 auth = (uint8_t *)(rq->buf + 4);
2066 attrs = rq->buf + 20;
2069 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2071 to = findserver(&realm, username, code == RAD_Accounting_Request);
2073 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2077 if (realm->message && code == RAD_Access_Request) {
2078 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2079 respondreject(rq, realm->message);
2080 } else if (realm->accresp && code == RAD_Accounting_Request) {
2081 acclog(attrs, len, rq->from->conf->host);
2082 respondaccounting(rq);
2087 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2088 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2089 rq->from->conf->name, to->conf->name);
2093 if (rqinqueue(to, rq->from, id, code)) {
2094 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2095 radmsgtype2string(code), rq->from->conf->host, id);
2099 if (code != RAD_Accounting_Request) {
2100 if (!RAND_bytes(newauth, 16)) {
2101 debug(DBG_WARN, "radsrv: failed to generate random auth");
2107 printfchars(NULL, "auth", "%02x ", auth, 16);
2110 attr = attrget(attrs, len, RAD_Attr_User_Password);
2112 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2113 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2117 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2119 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2120 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2125 memcpy(rq->origauth, auth, 16);
2126 if (code == RAD_Accounting_Request) {
2127 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
2128 debug(DBG_WARN, "radsrv: failed to sign Accounting-Request message");
2132 memcpy(auth, newauth, 16);
2140 int replyh(struct server *server, unsigned char *buf) {
2141 struct client *from;
2144 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2145 struct sockaddr_storage fromsa;
2146 char tmp[760], stationid[760];
2148 server->connectionok = 1;
2149 server->lostrqs = 0;
2151 i = buf[1]; /* i is the id */
2153 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2154 && *buf != RAD_Accounting_Response) {
2155 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2158 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2160 rq = server->requests + i;
2162 pthread_mutex_lock(&server->newrq_mutex);
2163 if (!rq->buf || !rq->tries) {
2164 pthread_mutex_unlock(&server->newrq_mutex);
2165 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2170 pthread_mutex_unlock(&server->newrq_mutex);
2171 debug(DBG_INFO, "replyh: already received, ignoring reply");
2175 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2176 pthread_mutex_unlock(&server->newrq_mutex);
2177 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2181 len = RADLEN(buf) - 20;
2184 if (!attrvalidate(attrs, len)) {
2185 pthread_mutex_unlock(&server->newrq_mutex);
2186 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2190 /* Message Authenticator */
2191 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2193 if (ATTRVALLEN(messageauth) != 16) {
2194 pthread_mutex_unlock(&server->newrq_mutex);
2195 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2198 memcpy(tmp, buf + 4, 16);
2199 memcpy(buf + 4, rq->buf + 4, 16);
2200 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2201 pthread_mutex_unlock(&server->newrq_mutex);
2202 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2205 memcpy(buf + 4, tmp, 16);
2206 debug(DBG_DBG, "replyh: message auth ok");
2209 if (*rq->buf == RAD_Status_Server) {
2211 pthread_mutex_unlock(&server->newrq_mutex);
2212 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2216 gettimeofday(&server->lastreply, NULL);
2220 pthread_mutex_unlock(&server->newrq_mutex);
2221 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2225 if (server->conf->rewrite) {
2226 dorewrite(buf, server->conf->rewrite);
2227 len = RADLEN(buf) - 20;
2231 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2232 if (ATTRVALLEN(attr) <= 4)
2235 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2238 sublen = ATTRVALLEN(attr) - 4;
2239 subattrs = ATTRVAL(attr) + 4;
2240 if (!attrvalidate(subattrs, sublen) ||
2241 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2242 rq, server->conf->secret, from->conf->secret) ||
2243 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2244 rq, server->conf->secret, from->conf->secret))
2248 pthread_mutex_unlock(&server->newrq_mutex);
2249 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2253 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2254 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2256 radattr2ascii(tmp, sizeof(tmp), attr);
2257 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2259 radattr2ascii(stationid, sizeof(stationid), attr);
2260 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2261 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2263 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2267 buf[1] = (char)rq->origid;
2268 memcpy(buf + 4, rq->origauth, 16);
2270 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2273 if (rq->origusername) {
2274 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2276 pthread_mutex_unlock(&server->newrq_mutex);
2277 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2280 memcpy(username, rq->origusername, strlen(rq->origusername));
2281 len = RADLEN(buf) - 20;
2284 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2288 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2289 pthread_mutex_unlock(&server->newrq_mutex);
2290 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2293 debug(DBG_DBG, "replyh: computed messageauthattr");
2296 if (from->conf->type == 'U')
2297 fromsa = rq->fromsa;
2298 /* once we set received = 1, rq may be reused */
2301 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2302 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2303 pthread_mutex_unlock(&server->newrq_mutex);
2307 void *udpclientrd(void *arg) {
2308 struct server *server;
2310 int *s = (int *)arg;
2314 buf = radudpget(*s, NULL, &server, NULL);
2315 if (!replyh(server, buf))
2320 void *tlsclientrd(void *arg) {
2321 struct server *server = (struct server *)arg;
2323 struct timeval now, lastconnecttry;
2326 /* yes, lastconnecttry is really necessary */
2327 lastconnecttry = server->lastconnecttry;
2328 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2330 if (server->dynamiclookuparg)
2332 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2336 if (!replyh(server, buf))
2338 if (server->dynamiclookuparg) {
2339 gettimeofday(&now, NULL);
2340 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2341 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2346 server->clientrdgone = 1;
2350 /* code for removing state not finished */
2351 void *clientwr(void *arg) {
2352 struct server *server = (struct server *)arg;
2354 pthread_t tlsclientrdth;
2355 int i, dynconffail = 0;
2357 struct timeval now, lastsend;
2358 struct timespec timeout;
2359 struct request statsrvrq;
2360 unsigned char statsrvbuf[38];
2361 struct clsrvconf *conf;
2363 conf = server->conf;
2365 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2370 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2371 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2375 memset(&timeout, 0, sizeof(struct timespec));
2377 if (conf->statusserver) {
2378 memset(&statsrvrq, 0, sizeof(struct request));
2379 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2380 statsrvbuf[0] = RAD_Status_Server;
2382 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2383 statsrvbuf[21] = 18;
2384 gettimeofday(&lastsend, NULL);
2387 if (conf->type == 'U') {
2388 server->connectionok = 1;
2390 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2392 server->connectionok = 1;
2393 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2394 debug(DBG_ERR, "clientwr: pthread_create failed");
2400 pthread_mutex_lock(&server->newrq_mutex);
2401 if (!server->newrq) {
2402 gettimeofday(&now, NULL);
2403 /* random 0-7 seconds */
2404 RAND_bytes(&rnd, 1);
2406 if (conf->statusserver) {
2407 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2408 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2410 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2411 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2414 if (timeout.tv_sec > now.tv_sec)
2415 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2417 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2420 if (server->newrq) {
2421 debug(DBG_DBG, "clientwr: got new request");
2426 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2428 pthread_mutex_unlock(&server->newrq_mutex);
2430 for (i = 0; i < MAX_REQUESTS; i++) {
2431 if (server->clientrdgone) {
2432 pthread_join(tlsclientrdth, NULL);
2435 pthread_mutex_lock(&server->newrq_mutex);
2436 while (i < MAX_REQUESTS && !server->requests[i].buf)
2438 if (i == MAX_REQUESTS) {
2439 pthread_mutex_unlock(&server->newrq_mutex);
2442 rq = server->requests + i;
2445 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2447 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2449 /* setting this to NULL means that it can be reused */
2452 pthread_mutex_unlock(&server->newrq_mutex);
2456 gettimeofday(&now, NULL);
2457 if (now.tv_sec < rq->expiry.tv_sec) {
2458 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2459 timeout.tv_sec = rq->expiry.tv_sec;
2460 pthread_mutex_unlock(&server->newrq_mutex);
2464 if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
2465 ? 1 : conf->retrycount + 1)) {
2466 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2467 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2468 if (server->lostrqs < 255)
2471 /* setting this to NULL means that it can be reused */
2473 pthread_mutex_unlock(&server->newrq_mutex);
2476 pthread_mutex_unlock(&server->newrq_mutex);
2478 rq->expiry.tv_sec = now.tv_sec +
2479 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2480 ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
2481 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2482 timeout.tv_sec = rq->expiry.tv_sec;
2484 clientradput(server, server->requests[i].buf);
2485 gettimeofday(&lastsend, NULL);
2487 if (conf->statusserver) {
2488 gettimeofday(&now, NULL);
2489 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2490 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2491 debug(DBG_WARN, "clientwr: failed to generate random auth");
2494 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2495 if (!statsrvrq.buf) {
2496 debug(DBG_ERR, "clientwr: malloc failed");
2499 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2500 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2501 lastsend.tv_sec = now.tv_sec;
2502 sendrq(server, &statsrvrq);
2507 conf->servers = NULL;
2508 if (server->dynamiclookuparg) {
2509 removeserversubrealms(realms, conf);
2513 freeclsrvconf(conf);
2515 freeserver(server, 1);
2519 void *udpserverwr(void *arg) {
2520 struct replyq *replyq = udp_server_replyq;
2521 struct reply *reply;
2524 pthread_mutex_lock(&replyq->mutex);
2525 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2526 debug(DBG_DBG, "udp server writer, waiting for signal");
2527 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2528 debug(DBG_DBG, "udp server writer, got signal");
2530 pthread_mutex_unlock(&replyq->mutex);
2532 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2533 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2534 debug(DBG_WARN, "sendudp: send failed");
2540 void *udpserverrd(void *arg) {
2542 pthread_t udpserverwrth;
2543 struct clsrvconf *listenres;
2545 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2546 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2547 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2549 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2550 listenres->host ? listenres->host : "*", listenres->port);
2551 freeclsrvres(listenres);
2553 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2554 debugx(1, DBG_ERR, "pthread_create failed");
2557 memset(&rq, 0, sizeof(struct request));
2558 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2563 void *udpaccserverrd(void *arg) {
2565 struct clsrvconf *listenres;
2567 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2568 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2569 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2571 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2572 listenres->host ? listenres->host : "*", listenres->port);
2573 freeclsrvres(listenres);
2576 memset(&rq, 0, sizeof(struct request));
2577 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2578 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2582 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2587 void *tlsserverwr(void *arg) {
2589 unsigned long error;
2590 struct client *client = (struct client *)arg;
2591 struct replyq *replyq;
2592 struct reply *reply;
2594 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2595 replyq = client->replyq;
2597 pthread_mutex_lock(&replyq->mutex);
2598 while (!list_first(replyq->replies)) {
2600 debug(DBG_DBG, "tls server writer, waiting for signal");
2601 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2602 debug(DBG_DBG, "tls server writer, got signal");
2605 /* ssl might have changed while waiting */
2606 pthread_mutex_unlock(&replyq->mutex);
2607 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2611 reply = (struct reply *)list_shift(replyq->replies);
2612 pthread_mutex_unlock(&replyq->mutex);
2613 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2615 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2616 cnt, RADLEN(reply->buf));
2618 while ((error = ERR_get_error()))
2619 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2625 void tlsserverrd(struct client *client) {
2627 pthread_t tlsserverwrth;
2629 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2631 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2632 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2637 memset(&rq, 0, sizeof(struct request));
2638 rq.buf = radtlsget(client->ssl, 0);
2641 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2646 debug(DBG_ERR, "tlsserverrd: connection lost");
2647 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2649 pthread_mutex_lock(&client->replyq->mutex);
2650 pthread_cond_signal(&client->replyq->cond);
2651 pthread_mutex_unlock(&client->replyq->mutex);
2652 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2653 pthread_join(tlsserverwrth, NULL);
2654 removeclientrqs(client);
2655 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2658 void *tlsservernew(void *arg) {
2660 struct sockaddr_storage from;
2661 size_t fromlen = sizeof(from);
2662 struct clsrvconf *conf;
2663 struct list_node *cur = NULL;
2666 unsigned long error;
2667 struct client *client;
2670 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2671 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2674 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2676 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2678 ssl = SSL_new(conf->ssl_ctx);
2681 if (SSL_accept(ssl) <= 0) {
2682 while ((error = ERR_get_error()))
2683 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2684 debug(DBG_ERR, "SSL_accept failed");
2687 cert = verifytlscert(ssl);
2693 if (verifyconfcert(cert, conf)) {
2695 client = addclient(conf);
2698 tlsserverrd(client);
2699 removeclient(client);
2701 debug(DBG_WARN, "Failed to create new client instance");
2704 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2706 debug(DBG_WARN, "ignoring request, no matching TLS client");
2712 shutdown(s, SHUT_RDWR);
2718 pthread_t tlsserverth;
2720 struct sockaddr_storage from;
2721 size_t fromlen = sizeof(from);
2722 struct clsrvconf *listenres;
2724 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2725 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2726 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2728 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2729 freeclsrvres(listenres);
2733 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2735 debug(DBG_WARN, "accept failed");
2738 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2739 debug(DBG_ERR, "tlslistener: pthread_create failed");
2740 shutdown(snew, SHUT_RDWR);
2744 pthread_detach(tlsserverth);
2749 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2752 STACK_OF(X509_NAME) *calist;
2754 unsigned long error;
2756 if (!certfile || !certkeyfile)
2757 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2759 if (!cacertfile && !cacertpath)
2760 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2763 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2764 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2765 for (i = 0; i < CRYPTO_num_locks(); i++) {
2766 ssl_lock_count[i] = 0;
2767 pthread_mutex_init(&ssl_locks[i], NULL);
2769 CRYPTO_set_id_callback(ssl_thread_id);
2770 CRYPTO_set_locking_callback(ssl_locking_callback);
2772 SSL_load_error_strings();
2775 while (!RAND_status()) {
2776 time_t t = time(NULL);
2777 pid_t pid = getpid();
2778 RAND_seed((unsigned char *)&t, sizeof(time_t));
2779 RAND_seed((unsigned char *)&pid, sizeof(pid));
2782 ctx = SSL_CTX_new(TLSv1_method());
2784 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2785 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2787 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2788 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2789 !SSL_CTX_check_private_key(ctx) ||
2790 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2791 while ((error = ERR_get_error()))
2792 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2793 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2796 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2797 if (!cacertfile || calist) {
2800 calist = sk_X509_NAME_new_null();
2801 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2802 sk_X509_NAME_free(calist);
2808 while ((error = ERR_get_error()))
2809 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2810 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2812 SSL_CTX_set_client_CA_list(ctx, calist);
2814 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2815 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2817 new = malloc(sizeof(struct tls));
2818 if (!new || !list_push(tlsconfs, new))
2819 debugx(1, DBG_ERR, "malloc failed");
2821 memset(new, 0, sizeof(struct tls));
2822 new->name = stringcopy(value, 0);
2824 debugx(1, DBG_ERR, "malloc failed");
2826 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2829 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2830 struct list_node *entry;
2831 struct tls *t, *t1 = NULL, *t2 = NULL;
2833 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2834 t = (struct tls *)entry->data;
2835 if (!strcasecmp(t->name, alt1)) {
2839 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2849 struct list *addsrvconfs(char *value, char **names) {
2850 struct list *conflist;
2852 struct list_node *entry;
2853 struct clsrvconf *conf = NULL;
2855 if (!names || !*names)
2858 conflist = list_create();
2860 debug(DBG_ERR, "malloc failed");
2864 for (n = 0; names[n]; n++) {
2865 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2866 conf = (struct clsrvconf *)entry->data;
2867 if (!strcasecmp(names[n], conf->name))
2871 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2872 list_destroy(conflist);
2875 if (!list_push(conflist, conf)) {
2876 debug(DBG_ERR, "malloc failed");
2877 list_destroy(conflist);
2880 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2885 void freerealm(struct realm *realm) {
2889 free(realm->message);
2890 regfree(&realm->regex);
2891 pthread_mutex_destroy(&realm->subrealms_mutex);
2892 if (realm->subrealms)
2893 list_destroy(realm->subrealms);
2894 if (realm->srvconfs) {
2895 /* emptying list without freeing data */
2896 while (list_shift(realm->srvconfs));
2897 list_destroy(realm->srvconfs);
2899 if (realm->accsrvconfs) {
2900 /* emptying list without freeing data */
2901 while (list_shift(realm->accsrvconfs));
2902 list_destroy(realm->accsrvconfs);
2907 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2909 struct realm *realm;
2910 char *s, *regex = NULL;
2912 if (*value == '/') {
2913 /* regexp, remove optional trailing / if present */
2914 if (value[strlen(value) - 1] == '/')
2915 value[strlen(value) - 1] = '\0';
2917 /* not a regexp, let us make it one */
2918 if (*value == '*' && !value[1])
2919 regex = stringcopy(".*", 0);
2921 for (n = 0, s = value; *s;)
2924 regex = malloc(strlen(value) + n + 3);
2927 for (n = 1, s = value; *s; s++) {
2937 debug(DBG_ERR, "malloc failed");
2941 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2944 realm = malloc(sizeof(struct realm));
2946 debug(DBG_ERR, "malloc failed");
2949 memset(realm, 0, sizeof(struct realm));
2951 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2952 debug(DBG_ERR, "mutex init failed");
2958 realm->name = stringcopy(value, 0);
2960 debug(DBG_ERR, "malloc failed");
2963 if (message && strlen(message) > 253) {
2964 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2967 realm->message = message;
2968 realm->accresp = accresp;
2970 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2971 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2975 if (servers && *servers) {
2976 realm->srvconfs = addsrvconfs(value, servers);
2977 if (!realm->srvconfs)
2981 if (accservers && *accservers) {
2982 realm->accsrvconfs = addsrvconfs(value, accservers);
2983 if (!realm->accsrvconfs)
2987 if (!list_push(realmlist, realm)) {
2988 debug(DBG_ERR, "malloc failed");
2989 pthread_mutex_destroy(&realm->subrealms_mutex);
2993 debug(DBG_DBG, "addrealm: added realm %s", value);
3003 for (n = 0; servers[n]; n++)
3008 for (n = 0; accservers[n]; n++)
3009 free(accservers[n]);
3015 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3016 struct clsrvconf *srvconf;
3017 struct realm *newrealm = NULL;
3018 char *realmname, *s;
3021 if (!conf->dynamiclookupcommand)
3024 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3025 realmname = strrchr(id, '@');
3031 for (s = realmname; *s; s++)
3032 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3035 pthread_mutex_lock(&realm->subrealms_mutex);
3036 /* exit if we now already got a matching subrealm */
3037 if (id2realm(realm->subrealms, id))
3039 srvconf = malloc(sizeof(struct clsrvconf));
3041 debug(DBG_ERR, "malloc failed");
3045 if (!addserver(srvconf))
3048 if (!realm->subrealms)
3049 realm->subrealms = list_create();
3050 if (!realm->subrealms)
3052 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3056 /* add server and accserver to newrealm */
3057 newrealm->srvconfs = list_create();
3058 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3059 debug(DBG_ERR, "malloc failed");
3062 newrealm->accsrvconfs = list_create();
3063 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3064 debug(DBG_ERR, "malloc failed");
3068 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3070 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3071 debug(DBG_ERR, "pthread_create failed");
3074 pthread_detach(clientth);
3079 list_removedata(realm->subrealms, newrealm);
3080 freerealm(newrealm);
3081 if (!list_first(realm->subrealms)) {
3082 list_destroy(realm->subrealms);
3083 realm->subrealms = NULL;
3086 freeserver(srvconf->servers, 1);
3088 debug(DBG_ERR, "failed to create dynamic server");
3091 pthread_mutex_unlock(&realm->subrealms_mutex);
3094 int dynamicconfig(struct server *server) {
3095 int ok, fd[2], status;
3097 struct clsrvconf *conf = server->conf;
3098 struct gconffile *cf = NULL;
3100 /* for now we only learn hostname/address */
3101 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3104 debug(DBG_ERR, "dynamicconfig: pipe error");
3109 debug(DBG_ERR, "dynamicconfig: fork error");
3113 } else if (pid == 0) {
3116 if (fd[1] != STDOUT_FILENO) {
3117 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3118 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3121 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3122 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3126 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3127 ok = getgenericconfig(&cf, NULL,
3128 "Server", CONF_CBK, confserver_cb, (void *)conf,
3133 if (waitpid(pid, &status, 0) < 0) {
3134 debug(DBG_ERR, "dynamicconfig: wait error");
3139 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3147 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3151 int addmatchcertattr(struct clsrvconf *conf) {
3155 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3156 r = &conf->certcnregex;
3157 v = conf->matchcertattr + 4;
3158 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3159 r = &conf->certuriregex;
3160 v = conf->matchcertattr + 20;
3165 /* regexp, remove optional trailing / if present */
3166 if (v[strlen(v) - 1] == '/')
3167 v[strlen(v) - 1] = '\0';
3171 *r = malloc(sizeof(regex_t));
3173 debug(DBG_ERR, "malloc failed");
3176 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3179 debug(DBG_ERR, "failed to compile regular expression %s", v);
3185 int addrewriteattr(struct clsrvconf *conf) {
3188 v = conf->rewriteattr + 11;
3189 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3191 /* regexp, remove optional trailing / if present */
3192 if (v[strlen(v) - 1] == '/')
3193 v[strlen(v) - 1] = '\0';
3201 conf->rewriteattrregex = malloc(sizeof(regex_t));
3202 if (!conf->rewriteattrregex) {
3203 debug(DBG_ERR, "malloc failed");
3207 conf->rewriteattrreplacement = stringcopy(w, 0);
3208 if (!conf->rewriteattrreplacement) {
3209 free(conf->rewriteattrregex);
3210 conf->rewriteattrregex = NULL;
3214 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3215 free(conf->rewriteattrregex);
3216 conf->rewriteattrregex = NULL;
3217 free(conf->rewriteattrreplacement);
3218 conf->rewriteattrreplacement = NULL;
3219 debug(DBG_ERR, "failed to compile regular expression %s", v);
3226 /* should accept both names and numeric values, only numeric right now */
3227 uint8_t attrname2val(char *attrname) {
3230 val = atoi(attrname);
3231 return val > 0 && val < 256 ? val : 0;
3234 /* should accept both names and numeric values, only numeric right now */
3235 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3238 *vendor = atoi(attrname);
3239 s = strchr(attrname, ':');
3244 *type = atoi(s + 1);
3245 return *type >= 0 && *type < 256;
3248 struct rewrite *getrewrite(char *alt1, char *alt2) {
3249 struct list_node *entry;
3250 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3252 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3253 r = (struct rewriteconf *)entry->data;
3254 if (!strcasecmp(r->name, alt1)) {
3258 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3268 void addrewrite(char *value, char **attrs, char **vattrs) {
3269 struct rewriteconf *new;
3270 struct rewrite *rewrite = NULL;
3273 uint32_t *p, *va = NULL;
3277 for (; attrs[n]; n++);
3278 a = malloc((n + 1) * sizeof(uint8_t));
3280 debugx(1, DBG_ERR, "malloc failed");
3282 for (i = 0; i < n; i++) {
3283 if (!(a[i] = attrname2val(attrs[i])))
3284 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3293 for (; vattrs[n]; n++);
3294 va = malloc((2 * n + 1) * sizeof(uint32_t));
3296 debugx(1, DBG_ERR, "malloc failed");
3298 for (p = va, i = 0; i < n; i++, p += 2) {
3299 if (!vattrname2val(vattrs[i], p, p + 1))
3300 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3308 rewrite = malloc(sizeof(struct rewrite));
3310 debugx(1, DBG_ERR, "malloc failed");
3311 rewrite->removeattrs = a;
3312 rewrite->removevendorattrs = va;
3315 new = malloc(sizeof(struct rewriteconf));
3316 if (!new || !list_push(rewriteconfs, new))
3317 debugx(1, DBG_ERR, "malloc failed");
3319 memset(new, 0, sizeof(struct rewriteconf));
3320 new->name = stringcopy(value, 0);
3322 debugx(1, DBG_ERR, "malloc failed");
3324 new->rewrite = rewrite;
3325 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3328 void freeclsrvconf(struct clsrvconf *conf) {
3330 free(conf->conftype);
3335 free(conf->matchcertattr);
3336 if (conf->certcnregex)
3337 regfree(conf->certcnregex);
3338 if (conf->certuriregex)
3339 regfree(conf->certuriregex);
3340 free(conf->confrewrite);
3341 free(conf->rewriteattr);
3342 if (conf->rewriteattrregex)
3343 regfree(conf->rewriteattrregex);
3344 free(conf->rewriteattrreplacement);
3345 free(conf->dynamiclookupcommand);
3346 free(conf->rewrite);
3348 freeaddrinfo(conf->addrinfo);
3349 /* not touching ssl_ctx, clients and servers */
3353 int mergeconfstring(char **dst, char **src) {
3362 t = stringcopy(*dst, 0);
3364 debug(DBG_ERR, "malloc failed");
3372 /* assumes dst is a shallow copy */
3373 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3374 if (!mergeconfstring(&dst->name, &src->name) ||
3375 !mergeconfstring(&dst->conftype, &src->conftype) ||
3376 !mergeconfstring(&dst->host, &src->host) ||
3377 !mergeconfstring(&dst->port, &src->port) ||
3378 !mergeconfstring(&dst->secret, &src->secret) ||
3379 !mergeconfstring(&dst->tls, &src->tls) ||
3380 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3381 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3382 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3384 dst->statusserver = src->statusserver;
3385 dst->certnamecheck = src->certnamecheck;
3386 if (src->retrydelay != 255)
3387 dst->retrydelay = src->retrydelay;
3388 if (src->retrycount != 255)
3389 dst->retrycount = src->retrycount;
3393 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3394 struct clsrvconf *conf;
3396 debug(DBG_DBG, "confclient_cb called for %s", block);
3398 conf = malloc(sizeof(struct clsrvconf));
3399 if (!conf || !list_push(clconfs, conf))
3400 debugx(1, DBG_ERR, "malloc failed");
3401 memset(conf, 0, sizeof(struct clsrvconf));
3402 conf->certnamecheck = 1;
3404 if (!getgenericconfig(cf, block,
3405 "type", CONF_STR, &conf->conftype,
3406 "host", CONF_STR, &conf->host,
3407 "secret", CONF_STR, &conf->secret,
3408 "tls", CONF_STR, &conf->tls,
3409 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3410 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3411 "rewrite", CONF_STR, &conf->confrewrite,
3412 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3415 debugx(1, DBG_ERR, "configuration error");
3417 conf->name = stringcopy(val, 0);
3419 conf->host = stringcopy(val, 0);
3421 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3424 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3425 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3427 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3428 if (conf->matchcertattr && !addmatchcertattr(conf))
3429 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3433 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3435 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3437 if (conf->rewriteattr) {
3438 if (!addrewriteattr(conf))
3439 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3442 if (!resolvepeer(conf, 0))
3443 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3445 if (!conf->secret) {
3446 if (conf->type == 'U')
3447 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3448 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3453 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3454 switch (conf->type) {
3457 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3460 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3461 if (!conf->ssl_ctx) {
3462 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3465 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3466 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3470 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3474 if (conf->retrydelay == 255)
3475 conf->retrydelay = REQUEST_RETRY_DELAY;
3476 if (conf->retrycount == 255)
3477 conf->retrycount = REQUEST_RETRY_COUNT;
3479 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3481 if (!conf->secret) {
3482 if (conf->type == 'U')
3483 debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3484 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3485 if (!conf->secret) {
3486 debug(DBG_ERR, "malloc failed");
3491 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3492 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3498 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3499 struct clsrvconf *conf, *resconf;
3500 long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
3502 debug(DBG_DBG, "confserver_cb called for %s", block);
3504 conf = malloc(sizeof(struct clsrvconf));
3506 debug(DBG_ERR, "malloc failed");
3509 memset(conf, 0, sizeof(struct clsrvconf));
3510 resconf = (struct clsrvconf *)arg;
3512 conf->statusserver = resconf->statusserver;
3513 conf->certnamecheck = resconf->certnamecheck;
3515 conf->certnamecheck = 1;
3517 if (!getgenericconfig(cf, block,
3518 "type", CONF_STR, &conf->conftype,
3519 "host", CONF_STR, &conf->host,
3520 "port", CONF_STR, &conf->port,
3521 "secret", CONF_STR, &conf->secret,
3522 "tls", CONF_STR, &conf->tls,
3523 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3524 "rewrite", CONF_STR, &conf->confrewrite,
3525 "StatusServer", CONF_BLN, &conf->statusserver,
3526 "RetryDelay", CONF_LINT, &retrydelay,
3527 "RetryCount", CONF_LINT, &retrycount,
3528 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3529 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3532 debug(DBG_ERR, "configuration error");
3536 conf->name = stringcopy(val, 0);
3538 debug(DBG_ERR, "malloc failed");
3542 conf->host = stringcopy(val, 0);
3544 debug(DBG_ERR, "malloc failed");
3549 if (retrydelay != LONG_MIN) {
3550 if (retrydelay < 1 || retrydelay > 60) {
3551 debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
3554 conf->retrydelay = (uint8_t)retrydelay;
3556 conf->retrydelay = 255;
3558 if (retrycount != LONG_MIN) {
3559 if (retrycount < 0 || retrycount > 10) {
3560 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3563 conf->retrycount = (uint8_t)retrycount;
3565 conf->retrycount = 255;
3568 if (!mergesrvconf(resconf, conf))
3572 if (conf->dynamiclookupcommand) {
3573 free(conf->dynamiclookupcommand);
3574 conf->dynamiclookupcommand = NULL;
3578 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3580 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3583 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3587 if (resconf || !conf->dynamiclookupcommand) {
3588 if (!compileserverconfig(conf, block))
3595 switch (conf->type) {
3606 if (!list_push(srvconfs, conf)) {
3607 debug(DBG_ERR, "malloc failed");
3613 freeclsrvconf(conf);
3617 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3618 char **servers = NULL, **accservers = NULL, *msg = NULL;
3619 uint8_t accresp = 0;
3621 debug(DBG_DBG, "confrealm_cb called for %s", block);
3623 if (!getgenericconfig(cf, block,
3624 "server", CONF_MSTR, &servers,
3625 "accountingServer", CONF_MSTR, &accservers,
3626 "ReplyMessage", CONF_STR, &msg,
3627 "AccountingResponse", CONF_BLN, &accresp,
3630 debugx(1, DBG_ERR, "configuration error");
3632 addrealm(realms, val, servers, accservers, msg, accresp);
3636 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3637 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3639 debug(DBG_DBG, "conftls_cb called for %s", block);
3641 if (!getgenericconfig(cf, block,
3642 "CACertificateFile", CONF_STR, &cacertfile,
3643 "CACertificatePath", CONF_STR, &cacertpath,
3644 "CertificateFile", CONF_STR, &certfile,
3645 "CertificateKeyFile", CONF_STR, &certkeyfile,
3646 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3649 debugx(1, DBG_ERR, "configuration error");
3651 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
3660 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3661 char **attrs = NULL, **vattrs = NULL;
3663 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3665 if (!getgenericconfig(cf, block,
3666 "removeAttribute", CONF_MSTR, &attrs,
3667 "removeVendorAttribute", CONF_MSTR, &vattrs,
3670 debugx(1, DBG_ERR, "configuration error");
3671 addrewrite(val, attrs, vattrs);
3675 void getmainconfig(const char *configfile) {
3676 long int loglevel = LONG_MIN;
3677 struct gconffile *cfs;
3679 cfs = openconfigfile(configfile);
3680 memset(&options, 0, sizeof(options));
3682 clconfs = list_create();
3684 debugx(1, DBG_ERR, "malloc failed");
3686 srvconfs = list_create();
3688 debugx(1, DBG_ERR, "malloc failed");
3690 realms = list_create();
3692 debugx(1, DBG_ERR, "malloc failed");
3694 tlsconfs = list_create();
3696 debugx(1, DBG_ERR, "malloc failed");
3698 rewriteconfs = list_create();
3700 debugx(1, DBG_ERR, "malloc failed");
3702 if (!getgenericconfig(&cfs, NULL,
3703 "ListenUDP", CONF_STR, &options.listenudp,
3704 "ListenTCP", CONF_STR, &options.listentcp,
3705 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3706 "SourceUDP", CONF_STR, &options.sourceudp,
3707 "SourceTCP", CONF_STR, &options.sourcetcp,
3708 "LogLevel", CONF_LINT, &loglevel,
3709 "LogDestination", CONF_STR, &options.logdestination,
3710 "LoopPrevention", CONF_BLN, &options.loopprevention,
3711 "Client", CONF_CBK, confclient_cb, NULL,
3712 "Server", CONF_CBK, confserver_cb, NULL,
3713 "Realm", CONF_CBK, confrealm_cb, NULL,
3714 "TLS", CONF_CBK, conftls_cb, NULL,
3715 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3718 debugx(1, DBG_ERR, "configuration error");
3720 if (loglevel != LONG_MIN) {
3721 if (loglevel < 1 || loglevel > 4)
3722 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3723 options.loglevel = (uint8_t)loglevel;
3727 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3730 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3733 *configfile = optarg;
3736 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3737 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3738 *loglevel = *optarg - '0';
3747 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3752 if (!(argc - optind))
3756 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3760 int daemon(int a, int b) {
3768 for (i = 0; i < 3; i++) {
3770 open("/dev/null", O_RDWR);
3776 void *sighandler(void *arg) {
3781 sigemptyset(&sigset);
3782 sigaddset(&sigset, SIGPIPE);
3783 sigwait(&sigset, &sig);
3784 /* only get SIGPIPE right now, so could simplify below code */
3787 /* completely ignoring this */
3790 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3793 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3798 int main(int argc, char **argv) {
3799 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3801 struct list_node *entry;
3802 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3803 char *configfile = NULL;
3804 struct clsrvconf *srvconf;
3806 debug_init("radsecproxy");
3807 debug_set_level(DEBUG_LEVEL);
3808 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3810 debug_set_level(loglevel);
3811 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3813 options.loglevel = loglevel;
3814 else if (options.loglevel)
3815 debug_set_level(options.loglevel);
3817 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3818 free(options.logdestination);
3820 if (!list_first(clconfs))
3821 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3822 if (!list_first(srvconfs))
3823 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3824 if (!list_first(realms))
3825 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3828 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3830 if (!foreground && (daemon(0, 0) < 0))
3831 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3833 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3835 sigemptyset(&sigset);
3836 /* exit on all but SIGPIPE, ignore more? */
3837 sigaddset(&sigset, SIGPIPE);
3838 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3839 pthread_create(&sigth, NULL, sighandler, NULL);
3841 if (client_udp_count) {
3842 udp_server_replyq = newreplyq();
3843 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3844 debugx(1, DBG_ERR, "pthread_create failed");
3845 if (options.listenaccudp)
3846 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3847 debugx(1, DBG_ERR, "pthread_create failed");
3850 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3851 srvconf = (struct clsrvconf *)entry->data;
3852 if (srvconf->dynamiclookupcommand)
3854 if (!addserver(srvconf))
3855 debugx(1, DBG_ERR, "failed to add server");
3856 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3857 (void *)(srvconf->servers)))
3858 debugx(1, DBG_ERR, "pthread_create failed");
3860 /* srcudpres no longer needed, while srctcpres is needed later */
3862 freeaddrinfo(srcudpres);
3865 if (udp_client4_sock >= 0)
3866 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3867 debugx(1, DBG_ERR, "pthread_create failed");
3868 if (udp_client6_sock >= 0)
3869 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3870 debugx(1, DBG_ERR, "pthread_create failed");
3872 if (client_tls_count)
3873 return tlslistener();
3875 /* just hang around doing nothing, anything to do here? */