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_client4_sock = -1;
76 static int udp_client6_sock = -1;
77 static pthread_mutex_t *ssl_locks;
78 static long *ssl_lock_count;
82 /* minimum required declarations to avoid reordering code */
83 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id);
84 int dynamicconfig(struct server *server);
85 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val);
86 void freerealm(struct realm *realm);
87 void freeclsrvconf(struct clsrvconf *conf);
88 void freerqdata(struct request *rq);
90 static const struct protodefs protodefs[] = {
91 { /* UDP, assuming RAD_UDP defined as 0 */
92 REQUEST_RETRY_COUNT, /* retrycountdefault */
93 10, /* retrycountmax */
94 REQUEST_RETRY_INTERVAL, /* retryintervaldefault */
95 60 /* retryintervalmax */
97 { /* TLS, assuming RAD_TLS defined as 1 */
98 0, /* retrycountdefault */
99 0, /* retrycountmax */
100 REQUEST_RETRY_INTERVAL * REQUEST_RETRY_COUNT, /* retryintervaldefault */
101 60 /* retryintervalmax */
105 /* callbacks for making OpenSSL thread safe */
106 unsigned long ssl_thread_id() {
107 return (unsigned long)pthread_self();
110 void ssl_locking_callback(int mode, int type, const char *file, int line) {
111 if (mode & CRYPTO_LOCK) {
112 pthread_mutex_lock(&ssl_locks[type]);
113 ssl_lock_count[type]++;
115 pthread_mutex_unlock(&ssl_locks[type]);
118 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
119 int pwdlen = strlen(userdata);
120 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
122 memcpy(buf, userdata, pwdlen);
126 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
131 err_cert = X509_STORE_CTX_get_current_cert(ctx);
132 err = X509_STORE_CTX_get_error(ctx);
133 depth = X509_STORE_CTX_get_error_depth(ctx);
135 if (depth > MAX_CERT_DEPTH) {
137 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
138 X509_STORE_CTX_set_error(ctx, err);
142 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
143 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
146 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
147 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
148 debug(DBG_WARN, "\tIssuer=%s", buf);
150 case X509_V_ERR_CERT_NOT_YET_VALID:
151 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
152 debug(DBG_WARN, "\tCertificate not yet valid");
154 case X509_V_ERR_CERT_HAS_EXPIRED:
155 debug(DBG_WARN, "Certificate has expired");
157 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
158 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
163 printf("certificate verify returns %d\n", ok);
168 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
169 struct addrinfo hints, *addrinfo, *res;
173 slash = conf->host ? strchr(conf->host, '/') : NULL;
177 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
181 if (*s < '0' || *s > '9') {
182 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
185 plen = atoi(slash + 1);
186 if (plen < 0 || plen > 128) {
187 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
192 memset(&hints, 0, sizeof(hints));
193 hints.ai_socktype = (conf->type == RAD_UDP ? SOCK_DGRAM : SOCK_STREAM);
194 hints.ai_family = AF_UNSPEC;
195 hints.ai_flags = ai_flags;
196 if (!conf->host && !conf->port) {
197 /* getaddrinfo() doesn't like host and port to be NULL */
198 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
199 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
202 for (res = addrinfo; res; res = res->ai_next) {
203 switch (res->ai_family) {
205 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
208 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
214 hints.ai_flags |= AI_NUMERICHOST;
215 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
216 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
221 switch (addrinfo->ai_family) {
224 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
225 freeaddrinfo(addrinfo);
232 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
233 freeaddrinfo(addrinfo);
236 conf->prefixlen = plen;
238 conf->prefixlen = 255;
241 freeaddrinfo(conf->addrinfo);
242 conf->addrinfo = addrinfo;
246 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
248 struct addrinfo *res;
250 for (res = addrinfo; res; res = res->ai_next) {
251 if (family != AF_UNSPEC && family != res->ai_family)
253 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
255 debug(DBG_WARN, "bindtoaddr: socket failed");
259 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
262 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
265 if (!bind(s, res->ai_addr, res->ai_addrlen))
267 debug(DBG_WARN, "bindtoaddr: bind failed");
273 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
278 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
282 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
284 debugx(1, DBG_ERR, "no ] matching initial [");
288 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
291 debugx(1, DBG_ERR, "missing host/address");
293 conf->host = stringcopy(field, p - field);
296 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
297 debugx(1, DBG_ERR, "unexpected character after ]");
300 /* port number or service name is specified */;
302 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
304 debugx(1, DBG_ERR, "syntax error, : but no following port");
305 conf->port = stringcopy(field, p - field);
307 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
311 struct clsrvconf *resolve_hostport(uint8_t type, char *lconf, char *default_port) {
312 struct clsrvconf *conf;
314 conf = malloc(sizeof(struct clsrvconf));
316 debugx(1, DBG_ERR, "malloc failed");
317 memset(conf, 0, sizeof(struct clsrvconf));
320 parsehostport(lconf, conf, default_port);
321 if (!strcmp(conf->host, "*")) {
326 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
327 if (!resolvepeer(conf, AI_PASSIVE))
328 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
332 void freeclsrvres(struct clsrvconf *res) {
336 freeaddrinfo(res->addrinfo);
340 int connecttcp(struct addrinfo *addrinfo) {
342 struct addrinfo *res;
345 for (res = addrinfo; res; res = res->ai_next) {
346 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
348 debug(DBG_WARN, "connecttoserver: socket failed");
351 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
353 debug(DBG_WARN, "connecttoserver: connect failed");
360 /* returns 1 if the len first bits are equal, else 0 */
361 int prefixmatch(void *a1, void *a2, uint8_t len) {
362 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
364 if (l && memcmp(a1, a2, l))
369 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
372 /* check if conf has matching address */
373 struct clsrvconf *checkconfaddr(uint8_t type, struct sockaddr *addr, struct clsrvconf *conf) {
374 struct sockaddr_in6 *sa6 = NULL;
375 struct in_addr *a4 = NULL;
376 struct addrinfo *res;
378 if (addr->sa_family == AF_INET6) {
379 sa6 = (struct sockaddr_in6 *)addr;
380 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
381 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
385 a4 = &((struct sockaddr_in *)addr)->sin_addr;
387 if (conf->type == type) {
388 if (conf->prefixlen == 255) {
389 for (res = conf->addrinfo; res; res = res->ai_next)
390 if ((a4 && res->ai_family == AF_INET &&
391 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
392 (sa6 && res->ai_family == AF_INET6 &&
393 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
396 res = conf->addrinfo;
398 ((a4 && res->ai_family == AF_INET &&
399 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
400 (sa6 && res->ai_family == AF_INET6 &&
401 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
408 /* returns next config with matching address, or NULL */
409 struct clsrvconf *find_conf(uint8_t type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
410 struct sockaddr_in6 *sa6 = NULL;
411 struct in_addr *a4 = NULL;
412 struct addrinfo *res;
413 struct list_node *entry;
414 struct clsrvconf *conf;
416 if (addr->sa_family == AF_INET6) {
417 sa6 = (struct sockaddr_in6 *)addr;
418 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
419 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
423 a4 = &((struct sockaddr_in *)addr)->sin_addr;
425 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
426 conf = (struct clsrvconf *)entry->data;
427 if (conf->type == type) {
428 if (conf->prefixlen == 255) {
429 for (res = conf->addrinfo; res; res = res->ai_next)
430 if ((a4 && res->ai_family == AF_INET &&
431 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
432 (sa6 && res->ai_family == AF_INET6 &&
433 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
439 res = conf->addrinfo;
441 ((a4 && res->ai_family == AF_INET &&
442 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
443 (sa6 && res->ai_family == AF_INET6 &&
444 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
455 struct replyq *newreplyq() {
456 struct replyq *replyq;
458 replyq = malloc(sizeof(struct replyq));
460 debugx(1, DBG_ERR, "malloc failed");
461 replyq->replies = list_create();
462 if (!replyq->replies)
463 debugx(1, DBG_ERR, "malloc failed");
464 pthread_mutex_init(&replyq->mutex, NULL);
465 pthread_cond_init(&replyq->cond, NULL);
469 struct client *addclient(struct clsrvconf *conf) {
470 struct client *new = malloc(sizeof(struct client));
473 debug(DBG_ERR, "malloc failed");
476 if (!conf->clients) {
477 conf->clients = list_create();
478 if (!conf->clients) {
479 debug(DBG_ERR, "malloc failed");
484 memset(new, 0, sizeof(struct client));
486 new->replyq = conf->type == RAD_UDP ? udp_server_replyq : newreplyq();
488 list_push(conf->clients, new);
492 void removeclient(struct client *client) {
493 struct list_node *entry;
495 if (!client || !client->conf->clients)
498 pthread_mutex_lock(&client->replyq->mutex);
499 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
500 free(((struct reply *)entry)->buf);
501 list_destroy(client->replyq->replies);
502 pthread_cond_destroy(&client->replyq->cond);
503 pthread_mutex_unlock(&client->replyq->mutex);
504 pthread_mutex_destroy(&client->replyq->mutex);
505 list_removedata(client->conf->clients, client);
509 void removeclientrqs(struct client *client) {
510 struct list_node *entry;
511 struct server *server;
515 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
516 server = ((struct clsrvconf *)entry->data)->servers;
517 pthread_mutex_lock(&server->newrq_mutex);
518 for (i = 0; i < MAX_REQUESTS; i++) {
519 rq = server->requests + i;
520 if (rq->from == client)
523 pthread_mutex_unlock(&server->newrq_mutex);
527 void freeserver(struct server *server, uint8_t destroymutex) {
528 struct request *rq, *end;
533 if(server->requests) {
534 rq = server->requests;
535 for (end = rq + MAX_REQUESTS; rq < end; rq++)
537 free(server->requests);
539 free(server->dynamiclookuparg);
541 pthread_mutex_destroy(&server->lock);
542 pthread_cond_destroy(&server->newrq_cond);
543 pthread_mutex_destroy(&server->newrq_mutex);
548 int addserver(struct clsrvconf *conf) {
549 struct clsrvconf *res;
552 debug(DBG_ERR, "addserver: currently works with just one server per conf");
555 conf->servers = malloc(sizeof(struct server));
556 if (!conf->servers) {
557 debug(DBG_ERR, "malloc failed");
560 memset(conf->servers, 0, sizeof(struct server));
561 conf->servers->conf = conf;
563 if (conf->type == RAD_UDP) {
565 res = resolve_hostport(RAD_UDP, options.sourceudp, NULL);
566 srcudpres = res->addrinfo;
567 res->addrinfo = NULL;
570 switch (conf->addrinfo->ai_family) {
572 if (udp_client4_sock < 0) {
573 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
574 if (udp_client4_sock < 0)
575 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
577 conf->servers->sock = udp_client4_sock;
580 if (udp_client6_sock < 0) {
581 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
582 if (udp_client6_sock < 0)
583 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
585 conf->servers->sock = udp_client6_sock;
588 debugx(1, DBG_ERR, "addserver: unsupported address family");
593 res = resolve_hostport(RAD_TLS, options.sourcetcp, NULL);
594 srctcpres = res->addrinfo;
595 res->addrinfo = NULL;
598 conf->servers->sock = -1;
601 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
602 if (!conf->servers->requests) {
603 debug(DBG_ERR, "malloc failed");
606 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
607 debug(DBG_ERR, "mutex init failed");
610 conf->servers->newrq = 0;
611 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
612 debug(DBG_ERR, "mutex init failed");
613 pthread_mutex_destroy(&conf->servers->lock);
616 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
617 debug(DBG_ERR, "mutex init failed");
618 pthread_mutex_destroy(&conf->servers->newrq_mutex);
619 pthread_mutex_destroy(&conf->servers->lock);
626 freeserver(conf->servers, 0);
627 conf->servers = NULL;
631 /* exactly one of client and server must be non-NULL */
632 /* should probably take peer list (client(s) or server(s)) as argument instead */
633 /* if *peer == NULL we return who we received from, else require it to be from peer */
634 /* return from in sa if not NULL */
635 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
637 unsigned char buf[65536], *rad;
638 struct sockaddr_storage from;
639 socklen_t fromlen = sizeof(from);
641 struct list_node *node;
644 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
646 debug(DBG_WARN, "radudpget: recv failed");
649 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
652 debug(DBG_WARN, "radudpget: packet too small");
658 debug(DBG_WARN, "radudpget: length too small");
663 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
667 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
671 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*client)->conf);
673 p = find_conf(RAD_UDP, (struct sockaddr *)&from, clconfs, NULL);
676 p = checkconfaddr(RAD_UDP, (struct sockaddr *)&from, (*server)->conf);
678 p = find_conf(RAD_UDP, (struct sockaddr *)&from, srvconfs, NULL);
681 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
687 debug(DBG_ERR, "radudpget: malloc failed");
691 if (client && !*client) {
692 node = list_first(p->clients);
693 *client = node ? (struct client *)node->data : addclient(p);
698 } else if (server && !*server)
699 *server = p->servers;
703 memcpy(rad, buf, len);
709 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
710 int loc, i, l, n, r = 0;
713 STACK_OF(GENERAL_NAME) *alt;
716 debug(DBG_DBG, "subjectaltnameaddr");
718 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
722 ex = X509_get_ext(cert, loc);
723 alt = X509V3_EXT_d2i(ex);
727 n = sk_GENERAL_NAME_num(alt);
728 for (i = 0; i < n; i++) {
729 gn = sk_GENERAL_NAME_value(alt, i);
730 if (gn->type != GEN_IPADD)
733 v = (char *)ASN1_STRING_data(gn->d.ia5);
734 l = ASN1_STRING_length(gn->d.ia5);
735 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
736 && !memcmp(v, &addr, l)) {
741 GENERAL_NAMES_free(alt);
745 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
752 nm = X509_get_subject_name(cert);
755 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
758 e = X509_NAME_get_entry(nm, loc);
759 t = X509_NAME_ENTRY_get_data(e);
760 v = (char *) ASN1_STRING_data(t);
761 l = ASN1_STRING_length(t);
765 if (l == strlen(exact) && !strncasecmp(exact, v, l))
768 s = stringcopy((char *)v, l);
770 debug(DBG_ERR, "malloc failed");
773 if (regexec(regex, s, 0, NULL, 0)) {
784 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
785 int loc, i, l, n, r = 0;
788 STACK_OF(GENERAL_NAME) *alt;
791 debug(DBG_DBG, "subjectaltnameregexp");
793 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
797 ex = X509_get_ext(cert, loc);
798 alt = X509V3_EXT_d2i(ex);
802 n = sk_GENERAL_NAME_num(alt);
803 for (i = 0; i < n; i++) {
804 gn = sk_GENERAL_NAME_value(alt, i);
805 if (gn->type != type)
808 v = (char *)ASN1_STRING_data(gn->d.ia5);
809 l = ASN1_STRING_length(gn->d.ia5);
813 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
816 if (memcmp(v, exact, l))
819 s = stringcopy((char *)v, l);
821 debug(DBG_ERR, "malloc failed");
824 if (regexec(regex, s, 0, NULL, 0)) {
833 GENERAL_NAMES_free(alt);
837 X509 *verifytlscert(SSL *ssl) {
841 if (SSL_get_verify_result(ssl) != X509_V_OK) {
842 debug(DBG_ERR, "verifytlscert: basic validation failed");
843 while ((error = ERR_get_error()))
844 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
848 cert = SSL_get_peer_certificate(ssl);
850 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
854 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
856 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
857 struct in6_addr addr;
859 if (conf->certnamecheck && conf->prefixlen == 255) {
860 if (inet_pton(AF_INET, conf->host, &addr))
862 else if (inet_pton(AF_INET6, conf->host, &addr))
865 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
868 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
871 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
873 if (!cnregexp(cert, conf->host, NULL)) {
874 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
877 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
880 if (conf->certcnregex) {
881 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
882 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
885 debug(DBG_DBG, "verifyconfcert: CN matching regex");
887 if (conf->certuriregex) {
888 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
889 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
892 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
897 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
902 debug(DBG_DBG, "tlsconnect called from %s", text);
903 pthread_mutex_lock(&server->lock);
904 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
905 /* already reconnected, nothing to do */
906 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
907 pthread_mutex_unlock(&server->lock);
911 debug(DBG_DBG, "tlsconnect %s", text);
914 gettimeofday(&now, NULL);
915 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
916 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
917 debug(DBG_DBG, "tlsconnect: timeout");
918 if (server->sock >= 0)
920 SSL_free(server->ssl);
922 pthread_mutex_unlock(&server->lock);
925 if (server->connectionok) {
926 server->connectionok = 0;
928 } else if (elapsed < 1)
930 else if (elapsed < 60) {
931 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
933 } else if (elapsed < 100000) {
934 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
937 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
938 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
939 if (server->sock >= 0)
941 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
942 debug(DBG_ERR, "tlsconnect: connecttcp failed");
946 SSL_free(server->ssl);
947 server->ssl = SSL_new(server->conf->ssl_ctx);
948 SSL_set_fd(server->ssl, server->sock);
949 if (SSL_connect(server->ssl) <= 0)
951 cert = verifytlscert(server->ssl);
954 if (verifyconfcert(cert, server->conf)) {
960 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
961 gettimeofday(&server->lastconnecttry, NULL);
962 pthread_mutex_unlock(&server->lock);
966 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
967 /* returns 0 on timeout, -1 on error and num if ok */
968 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
969 int s, ndesc, cnt, len;
970 fd_set readfds, writefds;
971 struct timeval timer;
976 /* make socket non-blocking? */
977 for (len = 0; len < num; len += cnt) {
982 timer.tv_sec = timeout;
985 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
989 cnt = SSL_read(ssl, buf + len, num - len);
991 switch (SSL_get_error(ssl, cnt)) {
992 case SSL_ERROR_WANT_READ:
993 case SSL_ERROR_WANT_WRITE:
996 case SSL_ERROR_ZERO_RETURN:
997 /* remote end sent close_notify, send one back */
1007 /* timeout in seconds, 0 means no timeout (blocking) */
1008 unsigned char *radtlsget(SSL *ssl, int timeout) {
1010 unsigned char buf[4], *rad;
1013 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1015 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1022 debug(DBG_ERR, "radtlsget: malloc failed");
1025 memcpy(rad, buf, 4);
1027 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1029 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1038 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1041 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1045 int clientradputudp(struct server *server, unsigned char *rad) {
1047 struct sockaddr_storage sa;
1048 struct sockaddr *sap;
1049 struct clsrvconf *conf = server->conf;
1050 in_port_t *port = NULL;
1054 if (*rad == RAD_Accounting_Request) {
1055 sap = (struct sockaddr *)&sa;
1056 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1058 sap = conf->addrinfo->ai_addr;
1060 switch (sap->sa_family) {
1062 port = &((struct sockaddr_in *)sap)->sin_port;
1065 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1071 if (*rad == RAD_Accounting_Request)
1072 *port = htons(ntohs(*port) + 1);
1074 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1075 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1079 debug(DBG_WARN, "clientradputudp: send failed");
1083 int clientradputtls(struct server *server, unsigned char *rad) {
1086 unsigned long error;
1087 struct timeval lastconnecttry;
1088 struct clsrvconf *conf = server->conf;
1091 lastconnecttry = server->lastconnecttry;
1092 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1093 while ((error = ERR_get_error()))
1094 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1095 if (server->dynamiclookuparg)
1097 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1098 lastconnecttry = server->lastconnecttry;
1101 server->connectionok = 1;
1102 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1106 int clientradput(struct server *server, unsigned char *rad) {
1107 switch (server->conf->type) {
1109 return clientradputudp(server, rad);
1111 return clientradputtls(server, rad);
1116 int radsign(unsigned char *rad, unsigned char *sec) {
1117 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1118 static unsigned char first = 1;
1119 static EVP_MD_CTX mdctx;
1120 unsigned int md_len;
1123 pthread_mutex_lock(&lock);
1125 EVP_MD_CTX_init(&mdctx);
1129 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1130 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1131 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1132 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1134 pthread_mutex_unlock(&lock);
1138 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1139 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1140 static unsigned char first = 1;
1141 static EVP_MD_CTX mdctx;
1142 unsigned char hash[EVP_MAX_MD_SIZE];
1146 pthread_mutex_lock(&lock);
1148 EVP_MD_CTX_init(&mdctx);
1154 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1155 EVP_DigestUpdate(&mdctx, rad, 4) &&
1156 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1157 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1158 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1159 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1161 !memcmp(hash, rad + 4, 16));
1162 pthread_mutex_unlock(&lock);
1166 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1167 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1168 static unsigned char first = 1;
1169 static HMAC_CTX hmacctx;
1170 unsigned int md_len;
1171 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1173 pthread_mutex_lock(&lock);
1175 HMAC_CTX_init(&hmacctx);
1179 memcpy(auth, authattr, 16);
1180 memset(authattr, 0, 16);
1182 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1183 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1184 HMAC_Final(&hmacctx, hash, &md_len);
1185 memcpy(authattr, auth, 16);
1187 debug(DBG_WARN, "message auth computation failed");
1188 pthread_mutex_unlock(&lock);
1192 if (memcmp(auth, hash, 16)) {
1193 debug(DBG_WARN, "message authenticator, wrong value");
1194 pthread_mutex_unlock(&lock);
1198 pthread_mutex_unlock(&lock);
1202 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1203 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1204 static unsigned char first = 1;
1205 static HMAC_CTX hmacctx;
1206 unsigned int md_len;
1211 pthread_mutex_lock(&lock);
1213 HMAC_CTX_init(&hmacctx);
1217 memset(authattrval, 0, 16);
1219 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1220 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1221 HMAC_Final(&hmacctx, authattrval, &md_len);
1223 debug(DBG_WARN, "message auth computation failed");
1224 pthread_mutex_unlock(&lock);
1228 pthread_mutex_unlock(&lock);
1232 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1233 while (length > 1) {
1234 if (ATTRTYPE(attrs) == type)
1236 length -= ATTRLEN(attrs);
1237 attrs += ATTRLEN(attrs);
1242 void freerqdata(struct request *rq) {
1243 if (rq->origusername)
1244 free(rq->origusername);
1249 void sendrq(struct server *to, struct request *rq) {
1253 pthread_mutex_lock(&to->newrq_mutex);
1254 /* might simplify if only try nextid, might be ok */
1255 for (i = to->nextid; i < MAX_REQUESTS; i++)
1256 if (!to->requests[i].buf)
1258 if (i == MAX_REQUESTS) {
1259 for (i = 0; i < to->nextid; i++)
1260 if (!to->requests[i].buf)
1262 if (i == to->nextid) {
1263 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1269 rq->buf[1] = (char)i;
1271 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1272 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1277 if (*rq->buf == RAD_Accounting_Request) {
1278 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1279 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1285 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1286 to->requests[i] = *rq;
1291 debug(DBG_DBG, "sendrq: signalling client writer");
1292 pthread_cond_signal(&to->newrq_cond);
1295 pthread_mutex_unlock(&to->newrq_mutex);
1298 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1299 struct reply *reply;
1302 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1304 debug(DBG_WARN, "sendreply: failed to sign message");
1308 reply = malloc(sizeof(struct reply));
1311 debug(DBG_ERR, "sendreply: malloc failed");
1314 memset(reply, 0, sizeof(struct reply));
1317 reply->tosa = *tosa;
1318 reply->toudpsock = toudpsock;
1320 pthread_mutex_lock(&to->replyq->mutex);
1322 first = list_first(to->replyq->replies) == NULL;
1324 if (!list_push(to->replyq->replies, reply)) {
1325 pthread_mutex_unlock(&to->replyq->mutex);
1328 debug(DBG_ERR, "sendreply: malloc failed");
1333 debug(DBG_DBG, "signalling server writer");
1334 pthread_cond_signal(&to->replyq->cond);
1336 pthread_mutex_unlock(&to->replyq->mutex);
1339 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1340 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1341 static unsigned char first = 1;
1342 static EVP_MD_CTX mdctx;
1343 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1344 unsigned int md_len;
1345 uint8_t i, offset = 0, out[128];
1347 pthread_mutex_lock(&lock);
1349 EVP_MD_CTX_init(&mdctx);
1355 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1356 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1357 !EVP_DigestUpdate(&mdctx, input, 16) ||
1358 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1360 pthread_mutex_unlock(&lock);
1363 for (i = 0; i < 16; i++)
1364 out[offset + i] = hash[i] ^ in[offset + i];
1365 input = out + offset - 16;
1370 memcpy(in, out, len);
1371 pthread_mutex_unlock(&lock);
1375 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1376 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1377 static unsigned char first = 1;
1378 static EVP_MD_CTX mdctx;
1379 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1380 unsigned int md_len;
1381 uint8_t i, offset = 0, out[128];
1383 pthread_mutex_lock(&lock);
1385 EVP_MD_CTX_init(&mdctx);
1391 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1392 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1393 !EVP_DigestUpdate(&mdctx, input, 16) ||
1394 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1396 pthread_mutex_unlock(&lock);
1399 for (i = 0; i < 16; i++)
1400 out[offset + i] = hash[i] ^ in[offset + i];
1401 input = in + offset;
1406 memcpy(in, out, len);
1407 pthread_mutex_unlock(&lock);
1411 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1412 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1413 static unsigned char first = 1;
1414 static EVP_MD_CTX mdctx;
1415 unsigned char hash[EVP_MAX_MD_SIZE];
1416 unsigned int md_len;
1419 pthread_mutex_lock(&lock);
1421 EVP_MD_CTX_init(&mdctx);
1426 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1427 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1428 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1431 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1432 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1433 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1434 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1435 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1436 pthread_mutex_unlock(&lock);
1441 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1444 for (i = 0; i < 16; i++)
1447 for (offset = 16; offset < len; offset += 16) {
1449 printf("text + offset - 16 c(%d): ", offset / 16);
1450 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1452 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1453 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1454 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1455 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1457 pthread_mutex_unlock(&lock);
1461 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1464 for (i = 0; i < 16; i++)
1465 text[offset + i] ^= hash[i];
1469 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1472 pthread_mutex_unlock(&lock);
1476 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1477 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1478 static unsigned char first = 1;
1479 static EVP_MD_CTX mdctx;
1480 unsigned char hash[EVP_MAX_MD_SIZE];
1481 unsigned int md_len;
1485 pthread_mutex_lock(&lock);
1487 EVP_MD_CTX_init(&mdctx);
1492 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1493 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1494 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1497 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1498 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1499 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1500 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1501 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1502 pthread_mutex_unlock(&lock);
1507 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1510 for (i = 0; i < 16; i++)
1511 plain[i] = text[i] ^ hash[i];
1513 for (offset = 16; offset < len; offset += 16) {
1515 printf("text + offset - 16 c(%d): ", offset / 16);
1516 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1518 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1519 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1520 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1521 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1523 pthread_mutex_unlock(&lock);
1527 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1530 for (i = 0; i < 16; i++)
1531 plain[offset + i] = text[offset + i] ^ hash[i];
1534 memcpy(text, plain, len);
1536 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1539 pthread_mutex_unlock(&lock);
1543 struct realm *id2realm(struct list *realmlist, char *id) {
1544 struct list_node *entry;
1545 struct realm *realm, *subrealm = NULL;
1547 /* need to do locking for subrealms and check subrealm timers */
1548 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1549 realm = (struct realm *)entry->data;
1550 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1551 pthread_mutex_lock(&realm->subrealms_mutex);
1552 if (realm->subrealms)
1553 subrealm = id2realm(realm->subrealms, id);
1554 pthread_mutex_unlock(&realm->subrealms_mutex);
1555 return subrealm ? subrealm : realm;
1561 /* helper function, only used by removeserversubrealms() */
1562 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1563 struct list_node *entry;
1564 struct realm *realm;
1566 for (entry = list_first(realmlist); entry;) {
1567 realm = (struct realm *)entry->data;
1568 entry = list_next(entry);
1569 if (realm->srvconfs) {
1570 list_removedata(realm->srvconfs, srv);
1571 if (!list_first(realm->srvconfs)) {
1572 list_destroy(realm->srvconfs);
1573 realm->srvconfs = NULL;
1576 if (realm->accsrvconfs) {
1577 list_removedata(realm->accsrvconfs, srv);
1578 if (!list_first(realm->accsrvconfs)) {
1579 list_destroy(realm->accsrvconfs);
1580 realm->accsrvconfs = NULL;
1584 /* remove subrealm if no servers */
1585 if (!realm->srvconfs && !realm->accsrvconfs) {
1586 list_removedata(realmlist, realm);
1592 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1593 struct list_node *entry;
1594 struct realm *realm;
1596 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1597 realm = (struct realm *)entry->data;
1598 pthread_mutex_lock(&realm->subrealms_mutex);
1599 if (realm->subrealms) {
1600 _internal_removeserversubrealms(realm->subrealms, srv);
1601 if (!list_first(realm->subrealms)) {
1602 list_destroy(realm->subrealms);
1603 realm->subrealms = NULL;
1606 pthread_mutex_unlock(&realm->subrealms_mutex);
1610 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1611 struct request *rq = to->requests, *end;
1613 pthread_mutex_lock(&to->newrq_mutex);
1614 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1615 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1617 pthread_mutex_unlock(&to->newrq_mutex);
1622 int attrvalidate(unsigned char *attrs, int length) {
1623 while (length > 1) {
1624 if (ATTRLEN(attrs) < 2) {
1625 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1628 length -= ATTRLEN(attrs);
1630 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1633 attrs += ATTRLEN(attrs);
1636 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1640 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1641 if (len < 16 || len > 128 || len % 16) {
1642 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1646 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1647 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1651 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1653 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1654 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1660 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1663 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1664 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1667 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1668 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1674 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1675 char *oldsecret, char *newsecret) {
1676 unsigned char *attr;
1678 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1679 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1680 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1686 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1690 for (; attrs[0]; attrs += 2)
1691 if (attrs[0] == vendor && attrs[1] == subattr)
1696 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1697 uint8_t alen, sublen, rmlen = 0;
1698 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1701 if (!removevendorattrs)
1704 while (*removevendorattrs && *removevendorattrs != vendor)
1705 removevendorattrs += 2;
1706 if (!*removevendorattrs)
1709 alen = ATTRLEN(attrs);
1711 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1712 /* remove entire vendor attribute */
1713 memmove(attrs, attrs + alen, length - alen);
1718 subattrs = ATTRVAL(attrs) + 4;
1720 if (!attrvalidate(subattrs, sublen)) {
1721 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1726 while (sublen > 1) {
1727 alen = ATTRLEN(subattrs);
1730 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1731 memmove(subattrs, subattrs + alen, length);
1737 ATTRLEN(attrs) -= rmlen;
1741 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1742 uint8_t *attrs, alen;
1743 uint16_t len, rmlen = 0;
1745 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1748 len = RADLEN(buf) - 20;
1751 alen = ATTRLEN(attrs);
1753 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1754 memmove(attrs, attrs + alen, len);
1756 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1757 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1762 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1765 /* returns a pointer to the resized attribute value */
1766 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1767 uint8_t *attrs, *attr, vallen;
1771 len = RADLEN(*buf) - 20;
1774 attr = attrget(attrs, len, type);
1778 vallen = ATTRVALLEN(attr);
1779 if (vallen == newvallen)
1782 len += newvallen - vallen;
1783 if (newvallen > vallen) {
1784 new = realloc(*buf, len + 20);
1786 debug(DBG_ERR, "resizeattr: malloc failed");
1795 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1796 attr[1] = newvallen + 2;
1797 ((uint16_t *)*buf)[1] = htons(len + 20);
1801 int rewriteusername(struct request *rq, char *in) {
1802 size_t nmatch = 10, reslen = 0, start = 0;
1803 regmatch_t pmatch[10], *pfield;
1805 unsigned char *result;
1806 char *out = rq->from->conf->rewriteattrreplacement;
1808 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1809 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1813 rq->origusername = stringcopy(in, 0);
1814 if (!rq->origusername)
1817 for (i = start; out[i]; i++) {
1818 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1819 pfield = &pmatch[out[i + 1] - '0'];
1820 if (pfield->rm_so >= 0) {
1821 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1827 reslen += i - start;
1829 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1835 for (i = start; out[i]; i++) {
1836 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1837 pfield = &pmatch[out[i + 1] - '0'];
1838 if (pfield->rm_so >= 0) {
1839 memcpy(result + reslen, out + start, i - start);
1840 reslen += i - start;
1841 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1842 reslen += pfield->rm_eo - pfield->rm_so;
1849 memcpy(result + reslen, out + start, i - start);
1850 reslen += i - start;
1851 memcpy(in, result, reslen);
1856 const char *radmsgtype2string(uint8_t code) {
1857 static const char *rad_msg_names[] = {
1858 "", "Access-Request", "Access-Accept", "Access-Reject",
1859 "Accounting-Request", "Accounting-Response", "", "",
1860 "", "", "", "Access-Challenge",
1861 "Status-Server", "Status-Client"
1863 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1866 void char2hex(char *h, unsigned char c) {
1867 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1868 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1869 h[0] = hexdigits[c / 16];
1870 h[1] = hexdigits[c % 16];
1874 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1878 if (!attr || len == 1) {
1883 l = ATTRVALLEN(attr);
1884 s = (char *)ATTRVAL(attr);
1887 for (i = 0; i < l; i++) {
1888 if (s[i] > 31 && s[i] < 127) {
1890 if (d - ascii == len - 1)
1893 if (d - ascii > len - 4)
1898 if (d - ascii == len - 1)
1906 void acclog(unsigned char *attrs, int length, char *host) {
1907 unsigned char *attr;
1910 attr = attrget(attrs, length, RAD_Attr_User_Name);
1912 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1915 radattr2ascii(username, sizeof(username), attr);
1916 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1919 void respondaccounting(struct request *rq) {
1920 unsigned char *resp;
1924 debug(DBG_ERR, "respondaccounting: malloc failed");
1927 memcpy(resp, rq->buf, 20);
1928 resp[0] = RAD_Accounting_Response;
1931 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1932 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1935 void respondstatusserver(struct request *rq) {
1936 unsigned char *resp;
1940 debug(DBG_ERR, "respondstatusserver: malloc failed");
1943 memcpy(resp, rq->buf, 20);
1944 resp[0] = RAD_Access_Accept;
1947 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1948 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1951 void respondreject(struct request *rq, char *message) {
1952 unsigned char *resp;
1955 if (message && *message)
1956 len += 2 + strlen(message);
1960 debug(DBG_ERR, "respondreject: malloc failed");
1963 memcpy(resp, rq->buf, 20);
1964 resp[0] = RAD_Access_Reject;
1965 *(uint16_t *)(resp + 2) = htons(len);
1966 if (message && *message) {
1967 resp[20] = RAD_Attr_Reply_Message;
1968 resp[21] = len - 20;
1969 memcpy(resp + 22, message, len - 22);
1971 sendreply(rq->from, resp, &rq->fromsa, rq->fromudpsock);
1974 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1975 struct list_node *entry;
1976 struct clsrvconf *server, *best = NULL, *first = NULL;
1978 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1979 server = (struct clsrvconf *)entry->data;
1980 if (!server->servers)
1984 if (!server->servers->connectionok)
1986 if (!server->servers->lostrqs)
1992 if (server->servers->lostrqs < best->servers->lostrqs)
1995 return best ? best : first;
1998 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1999 struct clsrvconf *srvconf;
2001 *realm = id2realm(realms, id);
2004 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
2005 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
2008 if (!acc && !srvconf->servers)
2009 adddynamicrealmserver(*realm, srvconf, id);
2010 return srvconf->servers;
2013 void radsrv(struct request *rq) {
2014 uint8_t code, id, *auth, *attrs, *attr;
2016 struct server *to = NULL;
2017 char username[254], userascii[760];
2018 unsigned char newauth[16];
2019 struct realm *realm = NULL;
2021 code = *(uint8_t *)rq->buf;
2022 id = *(uint8_t *)(rq->buf + 1);
2023 len = RADLEN(rq->buf);
2024 auth = (uint8_t *)(rq->buf + 4);
2026 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2028 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2029 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2034 attrs = rq->buf + 20;
2036 if (!attrvalidate(attrs, len)) {
2037 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2041 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2042 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2043 debug(DBG_WARN, "radsrv: message authentication failed");
2047 if (code == RAD_Status_Server) {
2048 respondstatusserver(rq);
2052 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2054 if (code == RAD_Accounting_Request) {
2055 memset(newauth, 0, 16);
2056 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2057 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2062 if (rq->from->conf->rewrite) {
2063 dorewrite(rq->buf, rq->from->conf->rewrite);
2064 len = RADLEN(rq->buf) - 20;
2067 attr = attrget(attrs, len, RAD_Attr_User_Name);
2069 if (code == RAD_Accounting_Request) {
2070 acclog(attrs, len, rq->from->conf->host);
2071 respondaccounting(rq);
2073 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2076 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2077 username[ATTRVALLEN(attr)] = '\0';
2078 radattr2ascii(userascii, sizeof(userascii), attr);
2080 if (rq->from->conf->rewriteattrregex) {
2081 if (!rewriteusername(rq, username)) {
2082 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2085 len = RADLEN(rq->buf) - 20;
2086 auth = (uint8_t *)(rq->buf + 4);
2087 attrs = rq->buf + 20;
2090 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2092 to = findserver(&realm, username, code == RAD_Accounting_Request);
2094 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2098 if (realm->message && code == RAD_Access_Request) {
2099 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2100 respondreject(rq, realm->message);
2101 } else if (realm->accresp && code == RAD_Accounting_Request) {
2102 acclog(attrs, len, rq->from->conf->host);
2103 respondaccounting(rq);
2108 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2109 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2110 rq->from->conf->name, to->conf->name);
2114 if (rqinqueue(to, rq->from, id, code)) {
2115 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2116 radmsgtype2string(code), rq->from->conf->host, id);
2120 if (code != RAD_Accounting_Request) {
2121 if (!RAND_bytes(newauth, 16)) {
2122 debug(DBG_WARN, "radsrv: failed to generate random auth");
2128 printfchars(NULL, "auth", "%02x ", auth, 16);
2131 attr = attrget(attrs, len, RAD_Attr_User_Password);
2133 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2134 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2138 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2140 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2141 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2146 memcpy(rq->origauth, auth, 16);
2147 memcpy(auth, newauth, 16);
2155 int replyh(struct server *server, unsigned char *buf) {
2156 struct client *from;
2159 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2160 struct sockaddr_storage fromsa;
2161 char tmp[760], stationid[760];
2163 server->connectionok = 1;
2164 server->lostrqs = 0;
2166 i = buf[1]; /* i is the id */
2168 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2169 && *buf != RAD_Accounting_Response) {
2170 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2173 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2175 rq = server->requests + i;
2177 pthread_mutex_lock(&server->newrq_mutex);
2178 if (!rq->buf || !rq->tries) {
2179 pthread_mutex_unlock(&server->newrq_mutex);
2180 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2185 pthread_mutex_unlock(&server->newrq_mutex);
2186 debug(DBG_INFO, "replyh: already received, ignoring reply");
2190 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2191 pthread_mutex_unlock(&server->newrq_mutex);
2192 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2196 len = RADLEN(buf) - 20;
2199 if (!attrvalidate(attrs, len)) {
2200 pthread_mutex_unlock(&server->newrq_mutex);
2201 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2205 /* Message Authenticator */
2206 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2208 if (ATTRVALLEN(messageauth) != 16) {
2209 pthread_mutex_unlock(&server->newrq_mutex);
2210 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2213 memcpy(tmp, buf + 4, 16);
2214 memcpy(buf + 4, rq->buf + 4, 16);
2215 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2216 pthread_mutex_unlock(&server->newrq_mutex);
2217 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2220 memcpy(buf + 4, tmp, 16);
2221 debug(DBG_DBG, "replyh: message auth ok");
2224 if (*rq->buf == RAD_Status_Server) {
2226 pthread_mutex_unlock(&server->newrq_mutex);
2227 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2231 gettimeofday(&server->lastreply, NULL);
2235 pthread_mutex_unlock(&server->newrq_mutex);
2236 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2240 if (server->conf->rewrite) {
2241 dorewrite(buf, server->conf->rewrite);
2242 len = RADLEN(buf) - 20;
2246 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2247 if (ATTRVALLEN(attr) <= 4)
2250 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2253 sublen = ATTRVALLEN(attr) - 4;
2254 subattrs = ATTRVAL(attr) + 4;
2255 if (!attrvalidate(subattrs, sublen) ||
2256 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2257 rq, server->conf->secret, from->conf->secret) ||
2258 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2259 rq, server->conf->secret, from->conf->secret))
2263 pthread_mutex_unlock(&server->newrq_mutex);
2264 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2268 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2269 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2271 radattr2ascii(tmp, sizeof(tmp), attr);
2272 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2274 radattr2ascii(stationid, sizeof(stationid), attr);
2275 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2276 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2278 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2282 buf[1] = (char)rq->origid;
2283 memcpy(buf + 4, rq->origauth, 16);
2285 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2288 if (rq->origusername) {
2289 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2291 pthread_mutex_unlock(&server->newrq_mutex);
2292 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2295 memcpy(username, rq->origusername, strlen(rq->origusername));
2296 len = RADLEN(buf) - 20;
2299 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2303 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2304 pthread_mutex_unlock(&server->newrq_mutex);
2305 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2308 debug(DBG_DBG, "replyh: computed messageauthattr");
2311 fromsa = rq->fromsa; /* only needed for UDP */
2312 /* once we set received = 1, rq may be reused */
2315 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2316 sendreply(from, buf, &fromsa, rq->fromudpsock);
2317 pthread_mutex_unlock(&server->newrq_mutex);
2321 void *udpclientrd(void *arg) {
2322 struct server *server;
2324 int *s = (int *)arg;
2328 buf = radudpget(*s, NULL, &server, NULL);
2329 if (!replyh(server, buf))
2334 void *tlsclientrd(void *arg) {
2335 struct server *server = (struct server *)arg;
2337 struct timeval now, lastconnecttry;
2340 /* yes, lastconnecttry is really necessary */
2341 lastconnecttry = server->lastconnecttry;
2342 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2344 if (server->dynamiclookuparg)
2346 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2350 if (!replyh(server, buf))
2352 if (server->dynamiclookuparg) {
2353 gettimeofday(&now, NULL);
2354 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2355 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2360 server->clientrdgone = 1;
2364 /* code for removing state not finished */
2365 void *clientwr(void *arg) {
2366 struct server *server = (struct server *)arg;
2368 pthread_t tlsclientrdth;
2369 int i, dynconffail = 0;
2371 struct timeval now, lastsend;
2372 struct timespec timeout;
2373 struct request statsrvrq;
2374 unsigned char statsrvbuf[38];
2375 struct clsrvconf *conf;
2377 conf = server->conf;
2379 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2384 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2385 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2389 memset(&timeout, 0, sizeof(struct timespec));
2391 if (conf->statusserver) {
2392 memset(&statsrvrq, 0, sizeof(struct request));
2393 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2394 statsrvbuf[0] = RAD_Status_Server;
2396 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2397 statsrvbuf[21] = 18;
2398 gettimeofday(&lastsend, NULL);
2401 if (conf->type == RAD_UDP) {
2402 server->connectionok = 1;
2404 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2406 server->connectionok = 1;
2407 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2408 debug(DBG_ERR, "clientwr: pthread_create failed");
2414 pthread_mutex_lock(&server->newrq_mutex);
2415 if (!server->newrq) {
2416 gettimeofday(&now, NULL);
2417 /* random 0-7 seconds */
2418 RAND_bytes(&rnd, 1);
2420 if (conf->statusserver) {
2421 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2422 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2424 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2425 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2428 if (timeout.tv_sec > now.tv_sec)
2429 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2431 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2434 if (server->newrq) {
2435 debug(DBG_DBG, "clientwr: got new request");
2440 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2442 pthread_mutex_unlock(&server->newrq_mutex);
2444 for (i = 0; i < MAX_REQUESTS; i++) {
2445 if (server->clientrdgone) {
2446 pthread_join(tlsclientrdth, NULL);
2449 pthread_mutex_lock(&server->newrq_mutex);
2450 while (i < MAX_REQUESTS && !server->requests[i].buf)
2452 if (i == MAX_REQUESTS) {
2453 pthread_mutex_unlock(&server->newrq_mutex);
2456 rq = server->requests + i;
2459 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2461 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2463 /* setting this to NULL means that it can be reused */
2466 pthread_mutex_unlock(&server->newrq_mutex);
2470 gettimeofday(&now, NULL);
2471 if (now.tv_sec < rq->expiry.tv_sec) {
2472 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2473 timeout.tv_sec = rq->expiry.tv_sec;
2474 pthread_mutex_unlock(&server->newrq_mutex);
2478 if (rq->tries == (*rq->buf == RAD_Status_Server ? 1 : conf->retrycount + 1)) {
2479 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2480 if (conf->statusserver) {
2481 if (*rq->buf == RAD_Status_Server) {
2482 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2483 if (server->lostrqs < 255)
2487 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2488 if (server->lostrqs < 255)
2492 /* setting this to NULL means that it can be reused */
2494 pthread_mutex_unlock(&server->newrq_mutex);
2497 pthread_mutex_unlock(&server->newrq_mutex);
2499 rq->expiry.tv_sec = now.tv_sec + conf->retryinterval;
2500 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2501 timeout.tv_sec = rq->expiry.tv_sec;
2503 clientradput(server, server->requests[i].buf);
2504 gettimeofday(&lastsend, NULL);
2506 if (conf->statusserver) {
2507 gettimeofday(&now, NULL);
2508 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2509 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2510 debug(DBG_WARN, "clientwr: failed to generate random auth");
2513 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2514 if (!statsrvrq.buf) {
2515 debug(DBG_ERR, "clientwr: malloc failed");
2518 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2519 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2520 lastsend.tv_sec = now.tv_sec;
2521 sendrq(server, &statsrvrq);
2526 conf->servers = NULL;
2527 if (server->dynamiclookuparg) {
2528 removeserversubrealms(realms, conf);
2532 freeclsrvconf(conf);
2534 freeserver(server, 1);
2538 void *udpserverwr(void *arg) {
2539 struct replyq *replyq = udp_server_replyq;
2540 struct reply *reply;
2543 pthread_mutex_lock(&replyq->mutex);
2544 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2545 debug(DBG_DBG, "udp server writer, waiting for signal");
2546 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2547 debug(DBG_DBG, "udp server writer, got signal");
2549 pthread_mutex_unlock(&replyq->mutex);
2551 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2552 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2553 debug(DBG_WARN, "sendudp: send failed");
2559 void *udpserverrd(void *arg) {
2561 struct listenerarg *larg = (struct listenerarg *)arg;
2564 memset(&rq, 0, sizeof(struct request));
2565 rq.buf = radudpget(larg->s, &rq.from, NULL, &rq.fromsa);
2566 if (larg->acconly && *rq.buf != RAD_Accounting_Request) {
2567 debug(DBG_INFO, "udpserverrd: got something other than accounting-request, ignoring");
2571 rq.fromudpsock = larg->s;
2576 void *tlsserverwr(void *arg) {
2578 unsigned long error;
2579 struct client *client = (struct client *)arg;
2580 struct replyq *replyq;
2581 struct reply *reply;
2583 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2584 replyq = client->replyq;
2586 pthread_mutex_lock(&replyq->mutex);
2587 while (!list_first(replyq->replies)) {
2589 debug(DBG_DBG, "tls server writer, waiting for signal");
2590 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2591 debug(DBG_DBG, "tls server writer, got signal");
2594 /* ssl might have changed while waiting */
2595 pthread_mutex_unlock(&replyq->mutex);
2596 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2600 reply = (struct reply *)list_shift(replyq->replies);
2601 pthread_mutex_unlock(&replyq->mutex);
2602 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2604 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2605 cnt, RADLEN(reply->buf));
2607 while ((error = ERR_get_error()))
2608 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2614 void tlsserverrd(struct client *client) {
2616 pthread_t tlsserverwrth;
2618 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2620 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2621 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2626 memset(&rq, 0, sizeof(struct request));
2627 rq.buf = radtlsget(client->ssl, 0);
2630 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2635 debug(DBG_ERR, "tlsserverrd: connection lost");
2636 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2638 pthread_mutex_lock(&client->replyq->mutex);
2639 pthread_cond_signal(&client->replyq->cond);
2640 pthread_mutex_unlock(&client->replyq->mutex);
2641 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2642 pthread_join(tlsserverwrth, NULL);
2643 removeclientrqs(client);
2644 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2647 void *tlsservernew(void *arg) {
2649 struct sockaddr_storage from;
2650 size_t fromlen = sizeof(from);
2651 struct clsrvconf *conf;
2652 struct list_node *cur = NULL;
2655 unsigned long error;
2656 struct client *client;
2659 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2660 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2663 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2665 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2667 ssl = SSL_new(conf->ssl_ctx);
2670 if (SSL_accept(ssl) <= 0) {
2671 while ((error = ERR_get_error()))
2672 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2673 debug(DBG_ERR, "SSL_accept failed");
2676 cert = verifytlscert(ssl);
2682 if (verifyconfcert(cert, conf)) {
2684 client = addclient(conf);
2687 tlsserverrd(client);
2688 removeclient(client);
2690 debug(DBG_WARN, "Failed to create new client instance");
2693 conf = find_conf(RAD_TLS, (struct sockaddr *)&from, clconfs, &cur);
2695 debug(DBG_WARN, "ignoring request, no matching TLS client");
2701 shutdown(s, SHUT_RDWR);
2706 void *tlslistener(void *arg) {
2707 pthread_t tlsserverth;
2709 struct sockaddr_storage from;
2710 size_t fromlen = sizeof(from);
2711 struct listenerarg *larg = (struct listenerarg *)arg;
2716 s = accept(larg->s, (struct sockaddr *)&from, &fromlen);
2718 debug(DBG_WARN, "accept failed");
2721 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&s)) {
2722 debug(DBG_ERR, "tlslistener: pthread_create failed");
2723 shutdown(s, SHUT_RDWR);
2727 pthread_detach(tlsserverth);
2732 void createlistener(uint8_t type, char *arg, uint8_t acconly) {
2734 struct clsrvconf *listenres;
2735 struct addrinfo *res;
2736 struct listenerarg *larg = NULL;
2739 listenres = resolve_hostport(type, arg, type == RAD_TLS ? DEFAULT_TLS_PORT : DEFAULT_UDP_PORT);
2741 debugx(1, DBG_ERR, "createlistener: failed to resolve %s", arg);
2743 for (res = listenres->addrinfo; res; res = res->ai_next) {
2744 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
2746 debug(DBG_WARN, "createlistener: socket failed");
2749 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
2751 if (res->ai_family == AF_INET6)
2752 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
2754 if (bind(s, res->ai_addr, res->ai_addrlen)) {
2755 debug(DBG_WARN, "createlistener: bind failed");
2761 larg = malloc(sizeof(struct listenerarg));
2763 debugx(1, DBG_ERR, "malloc failed");
2765 larg->acconly = acconly;
2766 if (pthread_create(&th, NULL, type == RAD_UDP ? udpserverrd : tlslistener, (void *)larg))
2767 debugx(1, DBG_ERR, "pthread_create failed");
2771 debugx(1, DBG_ERR, "createlistener: socket/bind failed");
2773 debug(DBG_WARN, "createlistener: listening for %s%s on %s:%s",
2774 type == RAD_UDP ? "UDP" : "TCP", acconly ? " accounting" : "",
2775 listenres->host ? listenres->host : "*", listenres->port);
2776 freeclsrvres(listenres);
2779 void createlisteners(uint8_t type, char **args, uint8_t acconly) {
2783 for (i = 0; args[i]; i++)
2784 createlistener(type, args[i], acconly);
2786 createlistener(type, NULL, acconly);
2789 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2792 STACK_OF(X509_NAME) *calist;
2795 unsigned long error;
2797 if (!certfile || !certkeyfile)
2798 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2800 if (!cacertfile && !cacertpath)
2801 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2804 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2805 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2806 for (i = 0; i < CRYPTO_num_locks(); i++) {
2807 ssl_lock_count[i] = 0;
2808 pthread_mutex_init(&ssl_locks[i], NULL);
2810 CRYPTO_set_id_callback(ssl_thread_id);
2811 CRYPTO_set_locking_callback(ssl_locking_callback);
2813 SSL_load_error_strings();
2816 while (!RAND_status()) {
2817 time_t t = time(NULL);
2818 pid_t pid = getpid();
2819 RAND_seed((unsigned char *)&t, sizeof(time_t));
2820 RAND_seed((unsigned char *)&pid, sizeof(pid));
2823 ctx = SSL_CTX_new(TLSv1_method());
2825 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2826 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2828 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2829 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2830 !SSL_CTX_check_private_key(ctx) ||
2831 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2832 while ((error = ERR_get_error()))
2833 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2834 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2837 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2838 if (!cacertfile || calist) {
2841 calist = sk_X509_NAME_new_null();
2842 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2843 sk_X509_NAME_free(calist);
2849 while ((error = ERR_get_error()))
2850 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2851 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2853 SSL_CTX_set_client_CA_list(ctx, calist);
2855 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2856 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2859 x509_s = SSL_CTX_get_cert_store(ctx);
2860 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2863 new = malloc(sizeof(struct tls));
2864 if (!new || !list_push(tlsconfs, new))
2865 debugx(1, DBG_ERR, "malloc failed");
2867 memset(new, 0, sizeof(struct tls));
2868 new->name = stringcopy(value, 0);
2870 debugx(1, DBG_ERR, "malloc failed");
2872 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2875 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2876 struct list_node *entry;
2877 struct tls *t, *t1 = NULL, *t2 = NULL;
2879 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2880 t = (struct tls *)entry->data;
2881 if (!strcasecmp(t->name, alt1)) {
2885 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2895 struct list *addsrvconfs(char *value, char **names) {
2896 struct list *conflist;
2898 struct list_node *entry;
2899 struct clsrvconf *conf = NULL;
2901 if (!names || !*names)
2904 conflist = list_create();
2906 debug(DBG_ERR, "malloc failed");
2910 for (n = 0; names[n]; n++) {
2911 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2912 conf = (struct clsrvconf *)entry->data;
2913 if (!strcasecmp(names[n], conf->name))
2917 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2918 list_destroy(conflist);
2921 if (!list_push(conflist, conf)) {
2922 debug(DBG_ERR, "malloc failed");
2923 list_destroy(conflist);
2926 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2931 void freerealm(struct realm *realm) {
2935 free(realm->message);
2936 regfree(&realm->regex);
2937 pthread_mutex_destroy(&realm->subrealms_mutex);
2938 if (realm->subrealms)
2939 list_destroy(realm->subrealms);
2940 if (realm->srvconfs) {
2941 /* emptying list without freeing data */
2942 while (list_shift(realm->srvconfs));
2943 list_destroy(realm->srvconfs);
2945 if (realm->accsrvconfs) {
2946 /* emptying list without freeing data */
2947 while (list_shift(realm->accsrvconfs));
2948 list_destroy(realm->accsrvconfs);
2953 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2955 struct realm *realm;
2956 char *s, *regex = NULL;
2958 if (*value == '/') {
2959 /* regexp, remove optional trailing / if present */
2960 if (value[strlen(value) - 1] == '/')
2961 value[strlen(value) - 1] = '\0';
2963 /* not a regexp, let us make it one */
2964 if (*value == '*' && !value[1])
2965 regex = stringcopy(".*", 0);
2967 for (n = 0, s = value; *s;)
2970 regex = malloc(strlen(value) + n + 3);
2973 for (n = 1, s = value; *s; s++) {
2983 debug(DBG_ERR, "malloc failed");
2987 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2990 realm = malloc(sizeof(struct realm));
2992 debug(DBG_ERR, "malloc failed");
2995 memset(realm, 0, sizeof(struct realm));
2997 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2998 debug(DBG_ERR, "mutex init failed");
3004 realm->name = stringcopy(value, 0);
3006 debug(DBG_ERR, "malloc failed");
3009 if (message && strlen(message) > 253) {
3010 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
3013 realm->message = message;
3014 realm->accresp = accresp;
3016 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
3017 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
3021 if (servers && *servers) {
3022 realm->srvconfs = addsrvconfs(value, servers);
3023 if (!realm->srvconfs)
3027 if (accservers && *accservers) {
3028 realm->accsrvconfs = addsrvconfs(value, accservers);
3029 if (!realm->accsrvconfs)
3033 if (!list_push(realmlist, realm)) {
3034 debug(DBG_ERR, "malloc failed");
3035 pthread_mutex_destroy(&realm->subrealms_mutex);
3039 debug(DBG_DBG, "addrealm: added realm %s", value);
3049 for (n = 0; servers[n]; n++)
3054 for (n = 0; accservers[n]; n++)
3055 free(accservers[n]);
3061 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3062 struct clsrvconf *srvconf;
3063 struct realm *newrealm = NULL;
3064 char *realmname, *s;
3067 if (!conf->dynamiclookupcommand)
3070 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3071 realmname = strrchr(id, '@');
3077 for (s = realmname; *s; s++)
3078 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3081 pthread_mutex_lock(&realm->subrealms_mutex);
3082 /* exit if we now already got a matching subrealm */
3083 if (id2realm(realm->subrealms, id))
3085 srvconf = malloc(sizeof(struct clsrvconf));
3087 debug(DBG_ERR, "malloc failed");
3091 if (!addserver(srvconf))
3094 if (!realm->subrealms)
3095 realm->subrealms = list_create();
3096 if (!realm->subrealms)
3098 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3102 /* add server and accserver to newrealm */
3103 newrealm->srvconfs = list_create();
3104 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3105 debug(DBG_ERR, "malloc failed");
3108 newrealm->accsrvconfs = list_create();
3109 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3110 debug(DBG_ERR, "malloc failed");
3114 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3116 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3117 debug(DBG_ERR, "pthread_create failed");
3120 pthread_detach(clientth);
3125 list_removedata(realm->subrealms, newrealm);
3126 freerealm(newrealm);
3127 if (!list_first(realm->subrealms)) {
3128 list_destroy(realm->subrealms);
3129 realm->subrealms = NULL;
3132 freeserver(srvconf->servers, 1);
3134 debug(DBG_ERR, "failed to create dynamic server");
3137 pthread_mutex_unlock(&realm->subrealms_mutex);
3140 int dynamicconfig(struct server *server) {
3141 int ok, fd[2], status;
3143 struct clsrvconf *conf = server->conf;
3144 struct gconffile *cf = NULL;
3146 /* for now we only learn hostname/address */
3147 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3150 debug(DBG_ERR, "dynamicconfig: pipe error");
3155 debug(DBG_ERR, "dynamicconfig: fork error");
3159 } else if (pid == 0) {
3162 if (fd[1] != STDOUT_FILENO) {
3163 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3164 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3167 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3168 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3172 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3173 ok = getgenericconfig(&cf, NULL,
3174 "Server", CONF_CBK, confserver_cb, (void *)conf,
3179 if (waitpid(pid, &status, 0) < 0) {
3180 debug(DBG_ERR, "dynamicconfig: wait error");
3185 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3193 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3197 int addmatchcertattr(struct clsrvconf *conf) {
3201 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3202 r = &conf->certcnregex;
3203 v = conf->matchcertattr + 4;
3204 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3205 r = &conf->certuriregex;
3206 v = conf->matchcertattr + 20;
3211 /* regexp, remove optional trailing / if present */
3212 if (v[strlen(v) - 1] == '/')
3213 v[strlen(v) - 1] = '\0';
3217 *r = malloc(sizeof(regex_t));
3219 debug(DBG_ERR, "malloc failed");
3222 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3225 debug(DBG_ERR, "failed to compile regular expression %s", v);
3231 int addrewriteattr(struct clsrvconf *conf) {
3234 v = conf->rewriteattr + 11;
3235 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3237 /* regexp, remove optional trailing / if present */
3238 if (v[strlen(v) - 1] == '/')
3239 v[strlen(v) - 1] = '\0';
3247 conf->rewriteattrregex = malloc(sizeof(regex_t));
3248 if (!conf->rewriteattrregex) {
3249 debug(DBG_ERR, "malloc failed");
3253 conf->rewriteattrreplacement = stringcopy(w, 0);
3254 if (!conf->rewriteattrreplacement) {
3255 free(conf->rewriteattrregex);
3256 conf->rewriteattrregex = NULL;
3260 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3261 free(conf->rewriteattrregex);
3262 conf->rewriteattrregex = NULL;
3263 free(conf->rewriteattrreplacement);
3264 conf->rewriteattrreplacement = NULL;
3265 debug(DBG_ERR, "failed to compile regular expression %s", v);
3272 /* should accept both names and numeric values, only numeric right now */
3273 uint8_t attrname2val(char *attrname) {
3276 val = atoi(attrname);
3277 return val > 0 && val < 256 ? val : 0;
3280 /* should accept both names and numeric values, only numeric right now */
3281 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3284 *vendor = atoi(attrname);
3285 s = strchr(attrname, ':');
3290 *type = atoi(s + 1);
3291 return *type >= 0 && *type < 256;
3294 struct rewrite *getrewrite(char *alt1, char *alt2) {
3295 struct list_node *entry;
3296 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3298 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3299 r = (struct rewriteconf *)entry->data;
3300 if (!strcasecmp(r->name, alt1)) {
3304 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3314 void addrewrite(char *value, char **attrs, char **vattrs) {
3315 struct rewriteconf *new;
3316 struct rewrite *rewrite = NULL;
3319 uint32_t *p, *va = NULL;
3323 for (; attrs[n]; n++);
3324 a = malloc((n + 1) * sizeof(uint8_t));
3326 debugx(1, DBG_ERR, "malloc failed");
3328 for (i = 0; i < n; i++) {
3329 if (!(a[i] = attrname2val(attrs[i])))
3330 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3339 for (; vattrs[n]; n++);
3340 va = malloc((2 * n + 1) * sizeof(uint32_t));
3342 debugx(1, DBG_ERR, "malloc failed");
3344 for (p = va, i = 0; i < n; i++, p += 2) {
3345 if (!vattrname2val(vattrs[i], p, p + 1))
3346 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3354 rewrite = malloc(sizeof(struct rewrite));
3356 debugx(1, DBG_ERR, "malloc failed");
3357 rewrite->removeattrs = a;
3358 rewrite->removevendorattrs = va;
3361 new = malloc(sizeof(struct rewriteconf));
3362 if (!new || !list_push(rewriteconfs, new))
3363 debugx(1, DBG_ERR, "malloc failed");
3365 memset(new, 0, sizeof(struct rewriteconf));
3366 new->name = stringcopy(value, 0);
3368 debugx(1, DBG_ERR, "malloc failed");
3370 new->rewrite = rewrite;
3371 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3374 void freeclsrvconf(struct clsrvconf *conf) {
3376 free(conf->conftype);
3381 free(conf->matchcertattr);
3382 if (conf->certcnregex)
3383 regfree(conf->certcnregex);
3384 if (conf->certuriregex)
3385 regfree(conf->certuriregex);
3386 free(conf->confrewrite);
3387 free(conf->rewriteattr);
3388 if (conf->rewriteattrregex)
3389 regfree(conf->rewriteattrregex);
3390 free(conf->rewriteattrreplacement);
3391 free(conf->dynamiclookupcommand);
3392 free(conf->rewrite);
3394 freeaddrinfo(conf->addrinfo);
3395 /* not touching ssl_ctx, clients and servers */
3399 int mergeconfstring(char **dst, char **src) {
3408 t = stringcopy(*dst, 0);
3410 debug(DBG_ERR, "malloc failed");
3418 /* assumes dst is a shallow copy */
3419 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3420 if (!mergeconfstring(&dst->name, &src->name) ||
3421 !mergeconfstring(&dst->conftype, &src->conftype) ||
3422 !mergeconfstring(&dst->host, &src->host) ||
3423 !mergeconfstring(&dst->port, &src->port) ||
3424 !mergeconfstring(&dst->secret, &src->secret) ||
3425 !mergeconfstring(&dst->tls, &src->tls) ||
3426 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3427 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3428 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3430 dst->statusserver = src->statusserver;
3431 dst->certnamecheck = src->certnamecheck;
3432 if (src->retryinterval != 255)
3433 dst->retryinterval = src->retryinterval;
3434 if (src->retrycount != 255)
3435 dst->retrycount = src->retrycount;
3439 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3440 struct clsrvconf *conf;
3442 debug(DBG_DBG, "confclient_cb called for %s", block);
3444 conf = malloc(sizeof(struct clsrvconf));
3445 if (!conf || !list_push(clconfs, conf))
3446 debugx(1, DBG_ERR, "malloc failed");
3447 memset(conf, 0, sizeof(struct clsrvconf));
3448 conf->certnamecheck = 1;
3450 if (!getgenericconfig(cf, block,
3451 "type", CONF_STR, &conf->conftype,
3452 "host", CONF_STR, &conf->host,
3453 "secret", CONF_STR, &conf->secret,
3454 "tls", CONF_STR, &conf->tls,
3455 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3456 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3457 "rewrite", CONF_STR, &conf->confrewrite,
3458 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3461 debugx(1, DBG_ERR, "configuration error");
3463 conf->name = stringcopy(val, 0);
3465 conf->host = stringcopy(val, 0);
3467 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3468 conf->type = RAD_UDP;
3470 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3471 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3473 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3474 if (conf->matchcertattr && !addmatchcertattr(conf))
3475 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3476 conf->type = RAD_TLS;
3479 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3481 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3483 if (conf->rewriteattr) {
3484 if (!addrewriteattr(conf))
3485 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3488 if (!resolvepeer(conf, 0))
3489 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3491 if (!conf->secret) {
3492 if (conf->type != RAD_TLS)
3493 debugx(1, DBG_ERR, "error in block %s, secret must be specified when not TLS", block);
3494 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3499 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3500 switch (conf->type) {
3503 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3506 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3507 if (!conf->ssl_ctx) {
3508 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3511 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3512 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3516 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3520 if (conf->retryinterval == 255)
3521 conf->retryinterval = protodefs[conf->type].retryintervaldefault;
3522 if (conf->retrycount == 255)
3523 conf->retrycount = protodefs[conf->type].retrycountdefault;
3525 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3526 if (!conf->secret) {
3527 if (conf->type != RAD_TLS)
3528 debug(DBG_ERR, "error in block %s, secret must be specified when not TLS", block);
3529 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3530 if (!conf->secret) {
3531 debug(DBG_ERR, "malloc failed");
3536 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3537 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3543 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3544 struct clsrvconf *conf, *resconf;
3545 const struct protodefs *pdef;
3546 long int retryinterval = LONG_MIN, retrycount = LONG_MIN;
3548 debug(DBG_DBG, "confserver_cb called for %s", block);
3550 conf = malloc(sizeof(struct clsrvconf));
3552 debug(DBG_ERR, "malloc failed");
3555 memset(conf, 0, sizeof(struct clsrvconf));
3556 resconf = (struct clsrvconf *)arg;
3558 conf->statusserver = resconf->statusserver;
3559 conf->certnamecheck = resconf->certnamecheck;
3561 conf->certnamecheck = 1;
3563 if (!getgenericconfig(cf, block,
3564 "type", CONF_STR, &conf->conftype,
3565 "host", CONF_STR, &conf->host,
3566 "port", CONF_STR, &conf->port,
3567 "secret", CONF_STR, &conf->secret,
3568 "tls", CONF_STR, &conf->tls,
3569 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3570 "rewrite", CONF_STR, &conf->confrewrite,
3571 "StatusServer", CONF_BLN, &conf->statusserver,
3572 "RetryInterval", CONF_LINT, &retryinterval,
3573 "RetryCount", CONF_LINT, &retrycount,
3574 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3575 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3578 debug(DBG_ERR, "configuration error");
3582 conf->name = stringcopy(val, 0);
3584 debug(DBG_ERR, "malloc failed");
3588 conf->host = stringcopy(val, 0);
3590 debug(DBG_ERR, "malloc failed");
3595 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3596 conf->type = RAD_UDP;
3597 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3598 conf->type = RAD_TLS;
3600 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3603 pdef = &protodefs[conf->type];
3605 if (retryinterval != LONG_MIN) {
3606 if (retryinterval < 1 || retryinterval > pdef->retryintervalmax) {
3607 debug(DBG_ERR, "error in block %s, value of option RetryInterval is %d, must be 1-%d", block, retryinterval, pdef->retryintervalmax);
3610 conf->retryinterval = (uint8_t)retryinterval;
3612 conf->retryinterval = 255;
3614 if (retrycount != LONG_MIN) {
3615 if (retrycount < 0 || retrycount > pdef->retrycountmax) {
3616 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-%d", block, pdef->retrycountmax);
3619 conf->retrycount = (uint8_t)retrycount;
3621 conf->retrycount = 255;
3624 if (!mergesrvconf(resconf, conf))
3628 if (conf->dynamiclookupcommand) {
3629 free(conf->dynamiclookupcommand);
3630 conf->dynamiclookupcommand = NULL;
3634 if (resconf || !conf->dynamiclookupcommand) {
3635 if (!compileserverconfig(conf, block))
3642 switch (conf->type) {
3653 if (!list_push(srvconfs, conf)) {
3654 debug(DBG_ERR, "malloc failed");
3660 freeclsrvconf(conf);
3664 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3665 char **servers = NULL, **accservers = NULL, *msg = NULL;
3666 uint8_t accresp = 0;
3668 debug(DBG_DBG, "confrealm_cb called for %s", block);
3670 if (!getgenericconfig(cf, block,
3671 "server", CONF_MSTR, &servers,
3672 "accountingServer", CONF_MSTR, &accservers,
3673 "ReplyMessage", CONF_STR, &msg,
3674 "AccountingResponse", CONF_BLN, &accresp,
3677 debugx(1, DBG_ERR, "configuration error");
3679 addrealm(realms, val, servers, accservers, msg, accresp);
3683 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3684 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3685 uint8_t crlcheck = 0;
3687 debug(DBG_DBG, "conftls_cb called for %s", block);
3689 if (!getgenericconfig(cf, block,
3690 "CACertificateFile", CONF_STR, &cacertfile,
3691 "CACertificatePath", CONF_STR, &cacertpath,
3692 "CertificateFile", CONF_STR, &certfile,
3693 "CertificateKeyFile", CONF_STR, &certkeyfile,
3694 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3695 "CRLCheck", CONF_BLN, &crlcheck,
3698 debugx(1, DBG_ERR, "configuration error");
3700 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3709 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3710 char **attrs = NULL, **vattrs = NULL;
3712 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3714 if (!getgenericconfig(cf, block,
3715 "removeAttribute", CONF_MSTR, &attrs,
3716 "removeVendorAttribute", CONF_MSTR, &vattrs,
3719 debugx(1, DBG_ERR, "configuration error");
3720 addrewrite(val, attrs, vattrs);
3724 void getmainconfig(const char *configfile) {
3725 long int loglevel = LONG_MIN;
3726 struct gconffile *cfs;
3728 cfs = openconfigfile(configfile);
3729 memset(&options, 0, sizeof(options));
3731 clconfs = list_create();
3733 debugx(1, DBG_ERR, "malloc failed");
3735 srvconfs = list_create();
3737 debugx(1, DBG_ERR, "malloc failed");
3739 realms = list_create();
3741 debugx(1, DBG_ERR, "malloc failed");
3743 tlsconfs = list_create();
3745 debugx(1, DBG_ERR, "malloc failed");
3747 rewriteconfs = list_create();
3749 debugx(1, DBG_ERR, "malloc failed");
3751 if (!getgenericconfig(&cfs, NULL,
3752 "ListenUDP", CONF_MSTR, &options.listenudp,
3753 "ListenTCP", CONF_MSTR, &options.listentcp,
3754 "ListenAccountingUDP", CONF_MSTR, &options.listenaccudp,
3755 "SourceUDP", CONF_STR, &options.sourceudp,
3756 "SourceTCP", CONF_STR, &options.sourcetcp,
3757 "LogLevel", CONF_LINT, &loglevel,
3758 "LogDestination", CONF_STR, &options.logdestination,
3759 "LoopPrevention", CONF_BLN, &options.loopprevention,
3760 "Client", CONF_CBK, confclient_cb, NULL,
3761 "Server", CONF_CBK, confserver_cb, NULL,
3762 "Realm", CONF_CBK, confrealm_cb, NULL,
3763 "TLS", CONF_CBK, conftls_cb, NULL,
3764 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3767 debugx(1, DBG_ERR, "configuration error");
3769 if (loglevel != LONG_MIN) {
3770 if (loglevel < 1 || loglevel > 4)
3771 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3772 options.loglevel = (uint8_t)loglevel;
3776 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3779 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3782 *configfile = optarg;
3785 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3786 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3787 *loglevel = *optarg - '0';
3796 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3801 if (!(argc - optind))
3805 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3809 int daemon(int a, int b) {
3817 for (i = 0; i < 3; i++) {
3819 open("/dev/null", O_RDWR);
3825 void *sighandler(void *arg) {
3830 sigemptyset(&sigset);
3831 sigaddset(&sigset, SIGPIPE);
3832 sigwait(&sigset, &sig);
3833 /* only get SIGPIPE right now, so could simplify below code */
3836 /* completely ignoring this */
3839 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3842 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3847 int main(int argc, char **argv) {
3848 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
3850 struct list_node *entry;
3851 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3852 char *configfile = NULL;
3853 struct clsrvconf *srvconf;
3855 debug_init("radsecproxy");
3856 debug_set_level(DEBUG_LEVEL);
3857 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3859 debug_set_level(loglevel);
3860 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3862 options.loglevel = loglevel;
3863 else if (options.loglevel)
3864 debug_set_level(options.loglevel);
3866 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3867 free(options.logdestination);
3869 if (!list_first(clconfs))
3870 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3871 if (!list_first(srvconfs))
3872 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3873 if (!list_first(realms))
3874 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3877 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3879 if (!foreground && (daemon(0, 0) < 0))
3880 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3882 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3884 sigemptyset(&sigset);
3885 /* exit on all but SIGPIPE, ignore more? */
3886 sigaddset(&sigset, SIGPIPE);
3887 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3888 pthread_create(&sigth, NULL, sighandler, NULL);
3890 if (client_udp_count) {
3891 udp_server_replyq = newreplyq();
3892 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
3893 debugx(1, DBG_ERR, "pthread_create failed");
3894 createlisteners(RAD_UDP, options.listenudp, 0);
3895 if (options.listenaccudp)
3896 createlisteners(RAD_UDP, options.listenaccudp, 1);
3899 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3900 srvconf = (struct clsrvconf *)entry->data;
3901 if (srvconf->dynamiclookupcommand)
3903 if (!addserver(srvconf))
3904 debugx(1, DBG_ERR, "failed to add server");
3905 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3906 (void *)(srvconf->servers)))
3907 debugx(1, DBG_ERR, "pthread_create failed");
3909 /* srcudpres no longer needed, while srctcpres is needed later */
3911 freeaddrinfo(srcudpres);
3914 if (udp_client4_sock >= 0)
3915 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3916 debugx(1, DBG_ERR, "pthread_create failed");
3917 if (udp_client6_sock >= 0)
3918 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3919 debugx(1, DBG_ERR, "pthread_create failed");
3921 if (client_tls_count)
3922 createlisteners(RAD_TLS, options.listentcp, 0);
3924 /* just hang around doing nothing, anything to do here? */