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 /* callbacks for making OpenSSL thread safe */
91 unsigned long ssl_thread_id() {
92 return (unsigned long)pthread_self();
95 void ssl_locking_callback(int mode, int type, const char *file, int line) {
96 if (mode & CRYPTO_LOCK) {
97 pthread_mutex_lock(&ssl_locks[type]);
98 ssl_lock_count[type]++;
100 pthread_mutex_unlock(&ssl_locks[type]);
103 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
104 int pwdlen = strlen(userdata);
105 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
107 memcpy(buf, userdata, pwdlen);
111 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
116 err_cert = X509_STORE_CTX_get_current_cert(ctx);
117 err = X509_STORE_CTX_get_error(ctx);
118 depth = X509_STORE_CTX_get_error_depth(ctx);
120 if (depth > MAX_CERT_DEPTH) {
122 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
123 X509_STORE_CTX_set_error(ctx, err);
127 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
128 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
131 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
132 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
133 debug(DBG_WARN, "\tIssuer=%s", buf);
135 case X509_V_ERR_CERT_NOT_YET_VALID:
136 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
137 debug(DBG_WARN, "\tCertificate not yet valid");
139 case X509_V_ERR_CERT_HAS_EXPIRED:
140 debug(DBG_WARN, "Certificate has expired");
142 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
143 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
148 printf("certificate verify returns %d\n", ok);
153 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
154 struct addrinfo hints, *addrinfo, *res;
158 slash = conf->host ? strchr(conf->host, '/') : NULL;
162 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
166 if (*s < '0' || *s > '9') {
167 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
170 plen = atoi(slash + 1);
171 if (plen < 0 || plen > 128) {
172 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
177 memset(&hints, 0, sizeof(hints));
178 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
179 hints.ai_family = AF_UNSPEC;
180 hints.ai_flags = ai_flags;
181 if (!conf->host && !conf->port) {
182 /* getaddrinfo() doesn't like host and port to be NULL */
183 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
184 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
187 for (res = addrinfo; res; res = res->ai_next) {
188 switch (res->ai_family) {
190 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
193 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
199 hints.ai_flags |= AI_NUMERICHOST;
200 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
201 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
206 switch (addrinfo->ai_family) {
209 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
210 freeaddrinfo(addrinfo);
217 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
218 freeaddrinfo(addrinfo);
221 conf->prefixlen = plen;
223 conf->prefixlen = 255;
226 freeaddrinfo(conf->addrinfo);
227 conf->addrinfo = addrinfo;
231 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
233 struct addrinfo *res;
235 for (res = addrinfo; res; res = res->ai_next) {
236 if (family != AF_UNSPEC && family != res->ai_family)
238 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
240 debug(DBG_WARN, "bindtoaddr: socket failed");
244 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
247 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
250 if (!bind(s, res->ai_addr, res->ai_addrlen))
252 debug(DBG_WARN, "bindtoaddr: bind failed");
258 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
263 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
267 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
269 debugx(1, DBG_ERR, "no ] matching initial [");
273 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
276 debugx(1, DBG_ERR, "missing host/address");
278 conf->host = stringcopy(field, p - field);
281 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
282 debugx(1, DBG_ERR, "unexpected character after ]");
285 /* port number or service name is specified */;
287 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
289 debugx(1, DBG_ERR, "syntax error, : but no following port");
290 conf->port = stringcopy(field, p - field);
292 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
296 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
297 struct clsrvconf *conf;
299 conf = malloc(sizeof(struct clsrvconf));
301 debugx(1, DBG_ERR, "malloc failed");
302 memset(conf, 0, sizeof(struct clsrvconf));
305 parsehostport(lconf, conf, default_port);
306 if (!strcmp(conf->host, "*")) {
311 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
312 if (!resolvepeer(conf, AI_PASSIVE))
313 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
317 void freeclsrvres(struct clsrvconf *res) {
321 freeaddrinfo(res->addrinfo);
325 int connecttcp(struct addrinfo *addrinfo) {
327 struct addrinfo *res;
330 for (res = addrinfo; res; res = res->ai_next) {
331 s = bindtoaddr(srctcpres, res->ai_family, 1, 1);
333 debug(DBG_WARN, "connecttoserver: socket failed");
336 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
338 debug(DBG_WARN, "connecttoserver: connect failed");
345 /* returns 1 if the len first bits are equal, else 0 */
346 int prefixmatch(void *a1, void *a2, uint8_t len) {
347 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
349 if (l && memcmp(a1, a2, l))
354 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
357 /* check if conf has matching address */
358 struct clsrvconf *checkconfaddr(char type, struct sockaddr *addr, struct clsrvconf *conf) {
359 struct sockaddr_in6 *sa6 = NULL;
360 struct in_addr *a4 = NULL;
361 struct addrinfo *res;
363 if (addr->sa_family == AF_INET6) {
364 sa6 = (struct sockaddr_in6 *)addr;
365 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
366 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
370 a4 = &((struct sockaddr_in *)addr)->sin_addr;
372 if (conf->type == type) {
373 if (conf->prefixlen == 255) {
374 for (res = conf->addrinfo; res; res = res->ai_next)
375 if ((a4 && res->ai_family == AF_INET &&
376 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
377 (sa6 && res->ai_family == AF_INET6 &&
378 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
381 res = conf->addrinfo;
383 ((a4 && res->ai_family == AF_INET &&
384 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
385 (sa6 && res->ai_family == AF_INET6 &&
386 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
393 /* returns next config with matching address, or NULL */
394 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct list_node **cur) {
395 struct sockaddr_in6 *sa6 = NULL;
396 struct in_addr *a4 = NULL;
397 struct addrinfo *res;
398 struct list_node *entry;
399 struct clsrvconf *conf;
401 if (addr->sa_family == AF_INET6) {
402 sa6 = (struct sockaddr_in6 *)addr;
403 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
404 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
408 a4 = &((struct sockaddr_in *)addr)->sin_addr;
410 for (entry = (cur && *cur ? list_next(*cur) : list_first(confs)); entry; entry = list_next(entry)) {
411 conf = (struct clsrvconf *)entry->data;
412 if (conf->type == type) {
413 if (conf->prefixlen == 255) {
414 for (res = conf->addrinfo; res; res = res->ai_next)
415 if ((a4 && res->ai_family == AF_INET &&
416 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
417 (sa6 && res->ai_family == AF_INET6 &&
418 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16))) {
424 res = conf->addrinfo;
426 ((a4 && res->ai_family == AF_INET &&
427 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
428 (sa6 && res->ai_family == AF_INET6 &&
429 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen)))) {
440 struct replyq *newreplyq() {
441 struct replyq *replyq;
443 replyq = malloc(sizeof(struct replyq));
445 debugx(1, DBG_ERR, "malloc failed");
446 replyq->replies = list_create();
447 if (!replyq->replies)
448 debugx(1, DBG_ERR, "malloc failed");
449 pthread_mutex_init(&replyq->mutex, NULL);
450 pthread_cond_init(&replyq->cond, NULL);
454 struct client *addclient(struct clsrvconf *conf) {
455 struct client *new = malloc(sizeof(struct client));
458 debug(DBG_ERR, "malloc failed");
461 if (!conf->clients) {
462 conf->clients = list_create();
463 if (!conf->clients) {
464 debug(DBG_ERR, "malloc failed");
469 memset(new, 0, sizeof(struct client));
471 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
473 list_push(conf->clients, new);
477 void removeclient(struct client *client) {
478 struct list_node *entry;
480 if (!client || !client->conf->clients)
483 pthread_mutex_lock(&client->replyq->mutex);
484 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
485 free(((struct reply *)entry)->buf);
486 list_destroy(client->replyq->replies);
487 pthread_cond_destroy(&client->replyq->cond);
488 pthread_mutex_unlock(&client->replyq->mutex);
489 pthread_mutex_destroy(&client->replyq->mutex);
490 list_removedata(client->conf->clients, client);
494 void removeclientrqs(struct client *client) {
495 struct list_node *entry;
496 struct server *server;
500 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
501 server = ((struct clsrvconf *)entry->data)->servers;
502 pthread_mutex_lock(&server->newrq_mutex);
503 for (i = 0; i < MAX_REQUESTS; i++) {
504 rq = server->requests + i;
505 if (rq->from == client)
508 pthread_mutex_unlock(&server->newrq_mutex);
512 void freeserver(struct server *server, uint8_t destroymutex) {
513 struct request *rq, *end;
518 if(server->requests) {
519 rq = server->requests;
520 for (end = rq + MAX_REQUESTS; rq < end; rq++)
522 free(server->requests);
524 free(server->dynamiclookuparg);
526 pthread_mutex_destroy(&server->lock);
527 pthread_cond_destroy(&server->newrq_cond);
528 pthread_mutex_destroy(&server->newrq_mutex);
533 int addserver(struct clsrvconf *conf) {
534 struct clsrvconf *res;
537 debug(DBG_ERR, "addserver: currently works with just one server per conf");
540 conf->servers = malloc(sizeof(struct server));
541 if (!conf->servers) {
542 debug(DBG_ERR, "malloc failed");
545 memset(conf->servers, 0, sizeof(struct server));
546 conf->servers->conf = conf;
548 if (conf->type == 'U') {
550 res = resolve_hostport('U', options.sourceudp, NULL);
551 srcudpres = res->addrinfo;
552 res->addrinfo = NULL;
555 switch (conf->addrinfo->ai_family) {
557 if (udp_client4_sock < 0) {
558 udp_client4_sock = bindtoaddr(srcudpres, AF_INET, 0, 1);
559 if (udp_client4_sock < 0)
560 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
562 conf->servers->sock = udp_client4_sock;
565 if (udp_client6_sock < 0) {
566 udp_client6_sock = bindtoaddr(srcudpres, AF_INET6, 0, 1);
567 if (udp_client6_sock < 0)
568 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
570 conf->servers->sock = udp_client6_sock;
573 debugx(1, DBG_ERR, "addserver: unsupported address family");
578 res = resolve_hostport('T', options.sourcetcp, NULL);
579 srctcpres = res->addrinfo;
580 res->addrinfo = NULL;
583 conf->servers->sock = -1;
586 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
587 if (!conf->servers->requests) {
588 debug(DBG_ERR, "malloc failed");
591 if (pthread_mutex_init(&conf->servers->lock, NULL)) {
592 debug(DBG_ERR, "mutex init failed");
595 conf->servers->newrq = 0;
596 if (pthread_mutex_init(&conf->servers->newrq_mutex, NULL)) {
597 debug(DBG_ERR, "mutex init failed");
598 pthread_mutex_destroy(&conf->servers->lock);
601 if (pthread_cond_init(&conf->servers->newrq_cond, NULL)) {
602 debug(DBG_ERR, "mutex init failed");
603 pthread_mutex_destroy(&conf->servers->newrq_mutex);
604 pthread_mutex_destroy(&conf->servers->lock);
611 freeserver(conf->servers, 0);
612 conf->servers = NULL;
616 /* exactly one of client and server must be non-NULL */
617 /* should probably take peer list (client(s) or server(s)) as argument instead */
618 /* if *peer == NULL we return who we received from, else require it to be from peer */
619 /* return from in sa if not NULL */
620 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
622 unsigned char buf[65536], *rad;
623 struct sockaddr_storage from;
624 socklen_t fromlen = sizeof(from);
626 struct list_node *node;
629 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
631 debug(DBG_WARN, "radudpget: recv failed");
634 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
637 debug(DBG_WARN, "radudpget: packet too small");
643 debug(DBG_WARN, "radudpget: length too small");
648 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
652 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
656 p = checkconfaddr('U', (struct sockaddr *)&from, (*client)->conf);
658 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
661 p = checkconfaddr('U', (struct sockaddr *)&from, (*server)->conf);
663 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
666 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer %s, ignoring", addr2string((struct sockaddr *)&from, fromlen));
672 debug(DBG_ERR, "radudpget: malloc failed");
676 if (client && !*client) {
677 node = list_first(p->clients);
678 *client = node ? (struct client *)node->data : addclient(p);
683 } else if (server && !*server)
684 *server = p->servers;
688 memcpy(rad, buf, len);
694 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
695 int loc, i, l, n, r = 0;
698 STACK_OF(GENERAL_NAME) *alt;
701 debug(DBG_DBG, "subjectaltnameaddr");
703 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
707 ex = X509_get_ext(cert, loc);
708 alt = X509V3_EXT_d2i(ex);
712 n = sk_GENERAL_NAME_num(alt);
713 for (i = 0; i < n; i++) {
714 gn = sk_GENERAL_NAME_value(alt, i);
715 if (gn->type != GEN_IPADD)
718 v = (char *)ASN1_STRING_data(gn->d.ia5);
719 l = ASN1_STRING_length(gn->d.ia5);
720 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
721 && !memcmp(v, &addr, l)) {
726 GENERAL_NAMES_free(alt);
730 int cnregexp(X509 *cert, char *exact, regex_t *regex) {
737 nm = X509_get_subject_name(cert);
740 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
743 e = X509_NAME_get_entry(nm, loc);
744 t = X509_NAME_ENTRY_get_data(e);
745 v = (char *) ASN1_STRING_data(t);
746 l = ASN1_STRING_length(t);
750 if (l == strlen(exact) && !strncasecmp(exact, v, l))
753 s = stringcopy((char *)v, l);
755 debug(DBG_ERR, "malloc failed");
758 if (regexec(regex, s, 0, NULL, 0)) {
769 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
770 int loc, i, l, n, r = 0;
773 STACK_OF(GENERAL_NAME) *alt;
776 debug(DBG_DBG, "subjectaltnameregexp");
778 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
782 ex = X509_get_ext(cert, loc);
783 alt = X509V3_EXT_d2i(ex);
787 n = sk_GENERAL_NAME_num(alt);
788 for (i = 0; i < n; i++) {
789 gn = sk_GENERAL_NAME_value(alt, i);
790 if (gn->type != type)
793 v = (char *)ASN1_STRING_data(gn->d.ia5);
794 l = ASN1_STRING_length(gn->d.ia5);
798 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
801 if (memcmp(v, exact, l))
804 s = stringcopy((char *)v, l);
806 debug(DBG_ERR, "malloc failed");
809 if (regexec(regex, s, 0, NULL, 0)) {
818 GENERAL_NAMES_free(alt);
822 X509 *verifytlscert(SSL *ssl) {
826 if (SSL_get_verify_result(ssl) != X509_V_OK) {
827 debug(DBG_ERR, "verifytlscert: basic validation failed");
828 while ((error = ERR_get_error()))
829 debug(DBG_ERR, "verifytlscert: TLS: %s", ERR_error_string(error, NULL));
833 cert = SSL_get_peer_certificate(ssl);
835 debug(DBG_ERR, "verifytlscert: failed to obtain certificate");
839 int verifyconfcert(X509 *cert, struct clsrvconf *conf) {
841 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
842 struct in6_addr addr;
844 if (conf->certnamecheck && conf->prefixlen == 255) {
845 if (inet_pton(AF_INET, conf->host, &addr))
847 else if (inet_pton(AF_INET6, conf->host, &addr))
850 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
853 debug(DBG_WARN, "verifyconfcert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
856 debug(DBG_DBG, "verifyconfcert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
858 if (!cnregexp(cert, conf->host, NULL)) {
859 debug(DBG_WARN, "verifyconfcert: cn not matching host %s", conf->host);
862 debug(DBG_DBG, "verifyconfcert: Found cn matching host %s", conf->host);
865 if (conf->certcnregex) {
866 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
867 debug(DBG_WARN, "verifyconfcert: CN not matching regex");
870 debug(DBG_DBG, "verifyconfcert: CN matching regex");
872 if (conf->certuriregex) {
873 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
874 debug(DBG_WARN, "verifyconfcert: subjectaltname URI not matching regex");
877 debug(DBG_DBG, "verifyconfcert: subjectaltname URI matching regex");
882 int tlsconnect(struct server *server, struct timeval *when, int timeout, char *text) {
887 debug(DBG_DBG, "tlsconnect called from %s", text);
888 pthread_mutex_lock(&server->lock);
889 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
890 /* already reconnected, nothing to do */
891 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
892 pthread_mutex_unlock(&server->lock);
896 debug(DBG_DBG, "tlsconnect %s", text);
899 gettimeofday(&now, NULL);
900 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
901 if (timeout && server->lastconnecttry.tv_sec && elapsed > timeout) {
902 debug(DBG_DBG, "tlsconnect: timeout");
903 if (server->sock >= 0)
905 SSL_free(server->ssl);
907 pthread_mutex_unlock(&server->lock);
910 if (server->connectionok) {
911 server->connectionok = 0;
913 } else if (elapsed < 1)
915 else if (elapsed < 60) {
916 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
918 } else if (elapsed < 100000) {
919 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
922 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
923 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
924 if (server->sock >= 0)
926 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
927 debug(DBG_ERR, "tlsconnect: connecttcp failed");
931 SSL_free(server->ssl);
932 server->ssl = SSL_new(server->conf->ssl_ctx);
933 SSL_set_fd(server->ssl, server->sock);
934 if (SSL_connect(server->ssl) <= 0)
936 cert = verifytlscert(server->ssl);
939 if (verifyconfcert(cert, server->conf)) {
945 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
946 gettimeofday(&server->lastconnecttry, NULL);
947 pthread_mutex_unlock(&server->lock);
951 /* timeout in seconds, 0 means no timeout (blocking), returns when num bytes have been read, or timeout */
952 /* returns 0 on timeout, -1 on error and num if ok */
953 int sslreadtimeout(SSL *ssl, unsigned char *buf, int num, int timeout) {
954 int s, ndesc, cnt, len;
955 fd_set readfds, writefds;
956 struct timeval timer;
961 /* make socket non-blocking? */
962 for (len = 0; len < num; len += cnt) {
967 timer.tv_sec = timeout;
970 ndesc = select(s + 1, &readfds, &writefds, NULL, timeout ? &timer : NULL);
974 cnt = SSL_read(ssl, buf + len, num - len);
976 switch (SSL_get_error(ssl, cnt)) {
977 case SSL_ERROR_WANT_READ:
978 case SSL_ERROR_WANT_WRITE:
981 case SSL_ERROR_ZERO_RETURN:
982 /* remote end sent close_notify, send one back */
992 /* timeout in seconds, 0 means no timeout (blocking) */
993 unsigned char *radtlsget(SSL *ssl, int timeout) {
995 unsigned char buf[4], *rad;
998 cnt = sslreadtimeout(ssl, buf, 4, timeout);
1000 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1007 debug(DBG_ERR, "radtlsget: malloc failed");
1010 memcpy(rad, buf, 4);
1012 cnt = sslreadtimeout(ssl, rad + 4, len - 4, timeout);
1014 debug(DBG_DBG, cnt ? "radtlsget: connection lost" : "radtlsget: timeout");
1023 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
1026 debug(DBG_DBG, "radtlsget: got %d bytes", len);
1030 int clientradputudp(struct server *server, unsigned char *rad) {
1032 struct sockaddr_storage sa;
1033 struct sockaddr *sap;
1034 struct clsrvconf *conf = server->conf;
1035 in_port_t *port = NULL;
1039 if (*rad == RAD_Accounting_Request) {
1040 sap = (struct sockaddr *)&sa;
1041 memcpy(sap, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen);
1043 sap = conf->addrinfo->ai_addr;
1045 switch (sap->sa_family) {
1047 port = &((struct sockaddr_in *)sap)->sin_port;
1050 port = &((struct sockaddr_in6 *)sap)->sin6_port;
1056 if (*rad == RAD_Accounting_Request)
1057 *port = htons(ntohs(*port) + 1);
1059 if (sendto(server->sock, rad, len, 0, sap, conf->addrinfo->ai_addrlen) >= 0) {
1060 debug(DBG_DBG, "clienradputudp: sent UDP of length %d to %s port %d", len, conf->host, ntohs(*port));
1064 debug(DBG_WARN, "clientradputudp: send failed");
1068 int clientradputtls(struct server *server, unsigned char *rad) {
1071 unsigned long error;
1072 struct timeval lastconnecttry;
1073 struct clsrvconf *conf = server->conf;
1076 lastconnecttry = server->lastconnecttry;
1077 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
1078 while ((error = ERR_get_error()))
1079 debug(DBG_ERR, "clientradputtls: TLS: %s", ERR_error_string(error, NULL));
1080 if (server->dynamiclookuparg)
1082 tlsconnect(server, &lastconnecttry, 0, "clientradputtls");
1083 lastconnecttry = server->lastconnecttry;
1086 server->connectionok = 1;
1087 debug(DBG_DBG, "clientradputtls: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
1091 int clientradput(struct server *server, unsigned char *rad) {
1092 switch (server->conf->type) {
1094 return clientradputudp(server, rad);
1096 return clientradputtls(server, rad);
1101 int radsign(unsigned char *rad, unsigned char *sec) {
1102 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1103 static unsigned char first = 1;
1104 static EVP_MD_CTX mdctx;
1105 unsigned int md_len;
1108 pthread_mutex_lock(&lock);
1110 EVP_MD_CTX_init(&mdctx);
1114 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1115 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
1116 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1117 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
1119 pthread_mutex_unlock(&lock);
1123 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
1124 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1125 static unsigned char first = 1;
1126 static EVP_MD_CTX mdctx;
1127 unsigned char hash[EVP_MAX_MD_SIZE];
1131 pthread_mutex_lock(&lock);
1133 EVP_MD_CTX_init(&mdctx);
1139 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
1140 EVP_DigestUpdate(&mdctx, rad, 4) &&
1141 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
1142 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
1143 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
1144 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
1146 !memcmp(hash, rad + 4, 16));
1147 pthread_mutex_unlock(&lock);
1151 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
1152 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1153 static unsigned char first = 1;
1154 static HMAC_CTX hmacctx;
1155 unsigned int md_len;
1156 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
1158 pthread_mutex_lock(&lock);
1160 HMAC_CTX_init(&hmacctx);
1164 memcpy(auth, authattr, 16);
1165 memset(authattr, 0, 16);
1167 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1168 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1169 HMAC_Final(&hmacctx, hash, &md_len);
1170 memcpy(authattr, auth, 16);
1172 debug(DBG_WARN, "message auth computation failed");
1173 pthread_mutex_unlock(&lock);
1177 if (memcmp(auth, hash, 16)) {
1178 debug(DBG_WARN, "message authenticator, wrong value");
1179 pthread_mutex_unlock(&lock);
1183 pthread_mutex_unlock(&lock);
1187 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1188 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1189 static unsigned char first = 1;
1190 static HMAC_CTX hmacctx;
1191 unsigned int md_len;
1196 pthread_mutex_lock(&lock);
1198 HMAC_CTX_init(&hmacctx);
1202 memset(authattrval, 0, 16);
1204 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1205 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1206 HMAC_Final(&hmacctx, authattrval, &md_len);
1208 debug(DBG_WARN, "message auth computation failed");
1209 pthread_mutex_unlock(&lock);
1213 pthread_mutex_unlock(&lock);
1217 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1218 while (length > 1) {
1219 if (ATTRTYPE(attrs) == type)
1221 length -= ATTRLEN(attrs);
1222 attrs += ATTRLEN(attrs);
1227 void freerqdata(struct request *rq) {
1228 if (rq->origusername)
1229 free(rq->origusername);
1234 void sendrq(struct server *to, struct request *rq) {
1238 pthread_mutex_lock(&to->newrq_mutex);
1239 /* might simplify if only try nextid, might be ok */
1240 for (i = to->nextid; i < MAX_REQUESTS; i++)
1241 if (!to->requests[i].buf)
1243 if (i == MAX_REQUESTS) {
1244 for (i = 0; i < to->nextid; i++)
1245 if (!to->requests[i].buf)
1247 if (i == to->nextid) {
1248 debug(DBG_WARN, "sendrq: no room in queue, dropping request");
1254 rq->buf[1] = (char)i;
1256 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1257 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1262 if (*(uint8_t *)rq->buf == RAD_Accounting_Request) {
1263 if (!radsign(rq->buf, (unsigned char *)to->conf->secret)) {
1264 debug(DBG_WARN, "sendrq: failed to sign Accounting-Request message");
1270 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1271 to->requests[i] = *rq;
1276 debug(DBG_DBG, "sendrq: signalling client writer");
1277 pthread_cond_signal(&to->newrq_cond);
1280 pthread_mutex_unlock(&to->newrq_mutex);
1283 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa, int toudpsock) {
1284 struct reply *reply;
1287 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1289 debug(DBG_WARN, "sendreply: failed to sign message");
1293 reply = malloc(sizeof(struct reply));
1296 debug(DBG_ERR, "sendreply: malloc failed");
1299 memset(reply, 0, sizeof(struct reply));
1302 reply->tosa = *tosa;
1303 reply->toudpsock = toudpsock;
1305 pthread_mutex_lock(&to->replyq->mutex);
1307 first = list_first(to->replyq->replies) == NULL;
1309 if (!list_push(to->replyq->replies, reply)) {
1310 pthread_mutex_unlock(&to->replyq->mutex);
1313 debug(DBG_ERR, "sendreply: malloc failed");
1318 debug(DBG_DBG, "signalling server writer");
1319 pthread_cond_signal(&to->replyq->cond);
1321 pthread_mutex_unlock(&to->replyq->mutex);
1324 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1325 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1326 static unsigned char first = 1;
1327 static EVP_MD_CTX mdctx;
1328 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1329 unsigned int md_len;
1330 uint8_t i, offset = 0, out[128];
1332 pthread_mutex_lock(&lock);
1334 EVP_MD_CTX_init(&mdctx);
1340 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1341 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1342 !EVP_DigestUpdate(&mdctx, input, 16) ||
1343 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1345 pthread_mutex_unlock(&lock);
1348 for (i = 0; i < 16; i++)
1349 out[offset + i] = hash[i] ^ in[offset + i];
1350 input = out + offset - 16;
1355 memcpy(in, out, len);
1356 pthread_mutex_unlock(&lock);
1360 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1361 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1362 static unsigned char first = 1;
1363 static EVP_MD_CTX mdctx;
1364 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1365 unsigned int md_len;
1366 uint8_t i, offset = 0, out[128];
1368 pthread_mutex_lock(&lock);
1370 EVP_MD_CTX_init(&mdctx);
1376 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1377 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1378 !EVP_DigestUpdate(&mdctx, input, 16) ||
1379 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1381 pthread_mutex_unlock(&lock);
1384 for (i = 0; i < 16; i++)
1385 out[offset + i] = hash[i] ^ in[offset + i];
1386 input = in + offset;
1391 memcpy(in, out, len);
1392 pthread_mutex_unlock(&lock);
1396 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1397 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1398 static unsigned char first = 1;
1399 static EVP_MD_CTX mdctx;
1400 unsigned char hash[EVP_MAX_MD_SIZE];
1401 unsigned int md_len;
1404 pthread_mutex_lock(&lock);
1406 EVP_MD_CTX_init(&mdctx);
1411 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1412 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1413 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1416 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1417 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1418 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1419 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1420 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1421 pthread_mutex_unlock(&lock);
1426 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1429 for (i = 0; i < 16; i++)
1432 for (offset = 16; offset < len; offset += 16) {
1434 printf("text + offset - 16 c(%d): ", offset / 16);
1435 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1437 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1438 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1439 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1440 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1442 pthread_mutex_unlock(&lock);
1446 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1449 for (i = 0; i < 16; i++)
1450 text[offset + i] ^= hash[i];
1454 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1457 pthread_mutex_unlock(&lock);
1461 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1462 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1463 static unsigned char first = 1;
1464 static EVP_MD_CTX mdctx;
1465 unsigned char hash[EVP_MAX_MD_SIZE];
1466 unsigned int md_len;
1470 pthread_mutex_lock(&lock);
1472 EVP_MD_CTX_init(&mdctx);
1477 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1478 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1479 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1482 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1483 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1484 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1485 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1486 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1487 pthread_mutex_unlock(&lock);
1492 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1495 for (i = 0; i < 16; i++)
1496 plain[i] = text[i] ^ hash[i];
1498 for (offset = 16; offset < len; offset += 16) {
1500 printf("text + offset - 16 c(%d): ", offset / 16);
1501 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1503 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1504 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1505 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1506 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1508 pthread_mutex_unlock(&lock);
1512 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1515 for (i = 0; i < 16; i++)
1516 plain[offset + i] = text[offset + i] ^ hash[i];
1519 memcpy(text, plain, len);
1521 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1524 pthread_mutex_unlock(&lock);
1528 struct realm *id2realm(struct list *realmlist, char *id) {
1529 struct list_node *entry;
1530 struct realm *realm, *subrealm = NULL;
1532 /* need to do locking for subrealms and check subrealm timers */
1533 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1534 realm = (struct realm *)entry->data;
1535 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1536 pthread_mutex_lock(&realm->subrealms_mutex);
1537 if (realm->subrealms)
1538 subrealm = id2realm(realm->subrealms, id);
1539 pthread_mutex_unlock(&realm->subrealms_mutex);
1540 return subrealm ? subrealm : realm;
1546 /* helper function, only used by removeserversubrealms() */
1547 void _internal_removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1548 struct list_node *entry;
1549 struct realm *realm;
1551 for (entry = list_first(realmlist); entry;) {
1552 realm = (struct realm *)entry->data;
1553 entry = list_next(entry);
1554 if (realm->srvconfs) {
1555 list_removedata(realm->srvconfs, srv);
1556 if (!list_first(realm->srvconfs)) {
1557 list_destroy(realm->srvconfs);
1558 realm->srvconfs = NULL;
1561 if (realm->accsrvconfs) {
1562 list_removedata(realm->accsrvconfs, srv);
1563 if (!list_first(realm->accsrvconfs)) {
1564 list_destroy(realm->accsrvconfs);
1565 realm->accsrvconfs = NULL;
1569 /* remove subrealm if no servers */
1570 if (!realm->srvconfs && !realm->accsrvconfs) {
1571 list_removedata(realmlist, realm);
1577 void removeserversubrealms(struct list *realmlist, struct clsrvconf *srv) {
1578 struct list_node *entry;
1579 struct realm *realm;
1581 for (entry = list_first(realmlist); entry; entry = list_next(entry)) {
1582 realm = (struct realm *)entry->data;
1583 pthread_mutex_lock(&realm->subrealms_mutex);
1584 if (realm->subrealms) {
1585 _internal_removeserversubrealms(realm->subrealms, srv);
1586 if (!list_first(realm->subrealms)) {
1587 list_destroy(realm->subrealms);
1588 realm->subrealms = NULL;
1591 pthread_mutex_unlock(&realm->subrealms_mutex);
1595 int rqinqueue(struct server *to, struct client *from, uint8_t id, uint8_t code) {
1596 struct request *rq = to->requests, *end;
1598 pthread_mutex_lock(&to->newrq_mutex);
1599 for (end = rq + MAX_REQUESTS; rq < end; rq++)
1600 if (rq->buf && !rq->received && rq->origid == id && rq->from == from && *rq->buf == code)
1602 pthread_mutex_unlock(&to->newrq_mutex);
1607 int attrvalidate(unsigned char *attrs, int length) {
1608 while (length > 1) {
1609 if (ATTRLEN(attrs) < 2) {
1610 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1613 length -= ATTRLEN(attrs);
1615 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1618 attrs += ATTRLEN(attrs);
1621 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1625 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1626 if (len < 16 || len > 128 || len % 16) {
1627 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1631 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1632 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1636 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1638 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1639 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1645 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1648 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1649 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1652 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1653 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1659 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1660 char *oldsecret, char *newsecret) {
1661 unsigned char *attr;
1663 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1664 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1665 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1671 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1675 for (; attrs[0]; attrs += 2)
1676 if (attrs[0] == vendor && attrs[1] == subattr)
1681 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1682 uint8_t alen, sublen, rmlen = 0;
1683 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1686 if (!removevendorattrs)
1689 while (*removevendorattrs && *removevendorattrs != vendor)
1690 removevendorattrs += 2;
1691 if (!*removevendorattrs)
1694 alen = ATTRLEN(attrs);
1696 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1697 /* remove entire vendor attribute */
1698 memmove(attrs, attrs + alen, length - alen);
1703 subattrs = ATTRVAL(attrs) + 4;
1705 if (!attrvalidate(subattrs, sublen)) {
1706 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1711 while (sublen > 1) {
1712 alen = ATTRLEN(subattrs);
1715 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1716 memmove(subattrs, subattrs + alen, length);
1722 ATTRLEN(attrs) -= rmlen;
1726 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1727 uint8_t *attrs, alen;
1728 uint16_t len, rmlen = 0;
1730 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1733 len = RADLEN(buf) - 20;
1736 alen = ATTRLEN(attrs);
1738 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1739 memmove(attrs, attrs + alen, len);
1741 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1742 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1747 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1750 /* returns a pointer to the resized attribute value */
1751 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1752 uint8_t *attrs, *attr, vallen;
1756 len = RADLEN(*buf) - 20;
1759 attr = attrget(attrs, len, type);
1763 vallen = ATTRVALLEN(attr);
1764 if (vallen == newvallen)
1767 len += newvallen - vallen;
1768 if (newvallen > vallen) {
1769 new = realloc(*buf, len + 20);
1771 debug(DBG_ERR, "resizeattr: malloc failed");
1780 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1781 attr[1] = newvallen + 2;
1782 ((uint16_t *)*buf)[1] = htons(len + 20);
1786 int rewriteusername(struct request *rq, char *in) {
1787 size_t nmatch = 10, reslen = 0, start = 0;
1788 regmatch_t pmatch[10], *pfield;
1790 unsigned char *result;
1791 char *out = rq->from->conf->rewriteattrreplacement;
1793 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1794 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1798 rq->origusername = stringcopy(in, 0);
1799 if (!rq->origusername)
1802 for (i = start; out[i]; i++) {
1803 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1804 pfield = &pmatch[out[i + 1] - '0'];
1805 if (pfield->rm_so >= 0) {
1806 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1812 reslen += i - start;
1814 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1820 for (i = start; out[i]; i++) {
1821 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1822 pfield = &pmatch[out[i + 1] - '0'];
1823 if (pfield->rm_so >= 0) {
1824 memcpy(result + reslen, out + start, i - start);
1825 reslen += i - start;
1826 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1827 reslen += pfield->rm_eo - pfield->rm_so;
1834 memcpy(result + reslen, out + start, i - start);
1835 reslen += i - start;
1836 memcpy(in, result, reslen);
1841 const char *radmsgtype2string(uint8_t code) {
1842 static const char *rad_msg_names[] = {
1843 "", "Access-Request", "Access-Accept", "Access-Reject",
1844 "Accounting-Request", "Accounting-Response", "", "",
1845 "", "", "", "Access-Challenge",
1846 "Status-Server", "Status-Client"
1848 return code < 14 && *rad_msg_names[code] ? rad_msg_names[code] : "Unknown";
1851 void char2hex(char *h, unsigned char c) {
1852 static const char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
1853 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
1854 h[0] = hexdigits[c / 16];
1855 h[1] = hexdigits[c % 16];
1859 char *radattr2ascii(char *ascii, size_t len, unsigned char *attr) {
1863 if (!attr || len == 1) {
1868 l = ATTRVALLEN(attr);
1869 s = (char *)ATTRVAL(attr);
1872 for (i = 0; i < l; i++) {
1873 if (s[i] > 31 && s[i] < 127) {
1875 if (d - ascii == len - 1)
1878 if (d - ascii > len - 4)
1883 if (d - ascii == len - 1)
1891 void acclog(unsigned char *attrs, int length, char *host) {
1892 unsigned char *attr;
1895 attr = attrget(attrs, length, RAD_Attr_User_Name);
1897 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1900 radattr2ascii(username, sizeof(username), attr);
1901 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1904 void respondaccounting(struct request *rq) {
1905 unsigned char *resp;
1909 debug(DBG_ERR, "respondstatusserver: malloc failed");
1912 memcpy(resp, rq->buf, 20);
1913 resp[0] = RAD_Accounting_Response;
1916 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1917 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL, rq->fromudpsock);
1920 void respondstatusserver(struct request *rq) {
1921 unsigned char *resp;
1925 debug(DBG_ERR, "respondstatusserver: malloc failed");
1928 memcpy(resp, rq->buf, 20);
1929 resp[0] = RAD_Access_Accept;
1932 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1933 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL, rq->fromudpsock);
1936 void respondreject(struct request *rq, char *message) {
1937 unsigned char *resp;
1940 if (message && *message)
1941 len += 2 + strlen(message);
1945 debug(DBG_ERR, "respondreject: malloc failed");
1948 memcpy(resp, rq->buf, 20);
1949 resp[0] = RAD_Access_Reject;
1950 *(uint16_t *)(resp + 2) = htons(len);
1951 if (message && *message) {
1952 resp[20] = RAD_Attr_Reply_Message;
1953 resp[21] = len - 20;
1954 memcpy(resp + 22, message, len - 22);
1956 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL, rq->fromudpsock);
1959 struct clsrvconf *choosesrvconf(struct list *srvconfs) {
1960 struct list_node *entry;
1961 struct clsrvconf *server, *best = NULL, *first = NULL;
1963 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
1964 server = (struct clsrvconf *)entry->data;
1965 if (!server->servers)
1969 if (!server->servers->connectionok)
1971 if (!server->servers->lostrqs)
1977 if (server->servers->lostrqs < best->servers->lostrqs)
1980 return best ? best : first;
1983 struct server *findserver(struct realm **realm, char *id, uint8_t acc) {
1984 struct clsrvconf *srvconf;
1986 *realm = id2realm(realms, id);
1989 debug(DBG_DBG, "found matching realm: %s", (*realm)->name);
1990 srvconf = choosesrvconf(acc ? (*realm)->accsrvconfs : (*realm)->srvconfs);
1993 if (!acc && !srvconf->servers)
1994 adddynamicrealmserver(*realm, srvconf, id);
1995 return srvconf->servers;
1998 void radsrv(struct request *rq) {
1999 uint8_t code, id, *auth, *attrs, *attr;
2001 struct server *to = NULL;
2002 char username[254], userascii[760];
2003 unsigned char newauth[16];
2004 struct realm *realm = NULL;
2006 code = *(uint8_t *)rq->buf;
2007 id = *(uint8_t *)(rq->buf + 1);
2008 len = RADLEN(rq->buf);
2009 auth = (uint8_t *)(rq->buf + 4);
2011 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
2013 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
2014 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
2019 attrs = rq->buf + 20;
2021 if (!attrvalidate(attrs, len)) {
2022 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
2026 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2027 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
2028 debug(DBG_WARN, "radsrv: message authentication failed");
2032 if (code == RAD_Status_Server) {
2033 respondstatusserver(rq);
2037 /* below: code == RAD_Access_Request || code == RAD_Accounting_Request */
2039 if (code == RAD_Accounting_Request) {
2040 memset(newauth, 0, 16);
2041 if (!validauth(rq->buf, newauth, (unsigned char *)rq->from->conf->secret)) {
2042 debug(DBG_WARN, "radsrv: Accounting-Request message authentication failed");
2047 if (rq->from->conf->rewrite) {
2048 dorewrite(rq->buf, rq->from->conf->rewrite);
2049 len = RADLEN(rq->buf) - 20;
2052 attr = attrget(attrs, len, RAD_Attr_User_Name);
2054 if (code == RAD_Accounting_Request) {
2055 acclog(attrs, len, rq->from->conf->host);
2056 respondaccounting(rq);
2058 debug(DBG_WARN, "radsrv: ignoring access request, no username attribute");
2061 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
2062 username[ATTRVALLEN(attr)] = '\0';
2063 radattr2ascii(userascii, sizeof(userascii), attr);
2065 if (rq->from->conf->rewriteattrregex) {
2066 if (!rewriteusername(rq, username)) {
2067 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
2070 len = RADLEN(rq->buf) - 20;
2071 auth = (uint8_t *)(rq->buf + 4);
2072 attrs = rq->buf + 20;
2075 debug(DBG_DBG, "%s with username: %s", radmsgtype2string(code), userascii);
2077 to = findserver(&realm, username, code == RAD_Accounting_Request);
2079 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
2083 if (realm->message && code == RAD_Access_Request) {
2084 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, userascii);
2085 respondreject(rq, realm->message);
2086 } else if (realm->accresp && code == RAD_Accounting_Request) {
2087 acclog(attrs, len, rq->from->conf->host);
2088 respondaccounting(rq);
2093 if (options.loopprevention && !strcmp(rq->from->conf->name, to->conf->name)) {
2094 debug(DBG_INFO, "radsrv: Loop prevented, not forwarding request from client %s to server %s, discarding",
2095 rq->from->conf->name, to->conf->name);
2099 if (rqinqueue(to, rq->from, id, code)) {
2100 debug(DBG_INFO, "radsrv: already got %s from host %s with id %d, ignoring",
2101 radmsgtype2string(code), rq->from->conf->host, id);
2105 if (code != RAD_Accounting_Request) {
2106 if (!RAND_bytes(newauth, 16)) {
2107 debug(DBG_WARN, "radsrv: failed to generate random auth");
2113 printfchars(NULL, "auth", "%02x ", auth, 16);
2116 attr = attrget(attrs, len, RAD_Attr_User_Password);
2118 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
2119 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2123 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
2125 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
2126 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth))
2131 memcpy(rq->origauth, auth, 16);
2132 memcpy(auth, newauth, 16);
2140 int replyh(struct server *server, unsigned char *buf) {
2141 struct client *from;
2144 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
2145 struct sockaddr_storage fromsa;
2146 char tmp[760], stationid[760];
2148 server->connectionok = 1;
2149 server->lostrqs = 0;
2151 i = buf[1]; /* i is the id */
2153 if (*buf != RAD_Access_Accept && *buf != RAD_Access_Reject && *buf != RAD_Access_Challenge
2154 && *buf != RAD_Accounting_Response) {
2155 debug(DBG_INFO, "replyh: discarding message type %s, accepting only access accept, access reject, access challenge and accounting response messages", radmsgtype2string(*buf));
2158 debug(DBG_DBG, "got %s message with id %d", radmsgtype2string(*buf), i);
2160 rq = server->requests + i;
2162 pthread_mutex_lock(&server->newrq_mutex);
2163 if (!rq->buf || !rq->tries) {
2164 pthread_mutex_unlock(&server->newrq_mutex);
2165 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
2170 pthread_mutex_unlock(&server->newrq_mutex);
2171 debug(DBG_INFO, "replyh: already received, ignoring reply");
2175 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
2176 pthread_mutex_unlock(&server->newrq_mutex);
2177 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
2181 len = RADLEN(buf) - 20;
2184 if (!attrvalidate(attrs, len)) {
2185 pthread_mutex_unlock(&server->newrq_mutex);
2186 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
2190 /* Message Authenticator */
2191 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2193 if (ATTRVALLEN(messageauth) != 16) {
2194 pthread_mutex_unlock(&server->newrq_mutex);
2195 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
2198 memcpy(tmp, buf + 4, 16);
2199 memcpy(buf + 4, rq->buf + 4, 16);
2200 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
2201 pthread_mutex_unlock(&server->newrq_mutex);
2202 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
2205 memcpy(buf + 4, tmp, 16);
2206 debug(DBG_DBG, "replyh: message auth ok");
2209 if (*rq->buf == RAD_Status_Server) {
2211 pthread_mutex_unlock(&server->newrq_mutex);
2212 debug(DBG_DBG, "replyh: got status server response from %s", server->conf->host);
2216 gettimeofday(&server->lastreply, NULL);
2220 pthread_mutex_unlock(&server->newrq_mutex);
2221 debug(DBG_INFO, "replyh: client gone, ignoring reply");
2225 if (server->conf->rewrite) {
2226 dorewrite(buf, server->conf->rewrite);
2227 len = RADLEN(buf) - 20;
2231 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
2232 if (ATTRVALLEN(attr) <= 4)
2235 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
2238 sublen = ATTRVALLEN(attr) - 4;
2239 subattrs = ATTRVAL(attr) + 4;
2240 if (!attrvalidate(subattrs, sublen) ||
2241 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
2242 rq, server->conf->secret, from->conf->secret) ||
2243 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
2244 rq, server->conf->secret, from->conf->secret))
2248 pthread_mutex_unlock(&server->newrq_mutex);
2249 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
2253 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject || *buf == RAD_Accounting_Response) {
2254 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
2256 radattr2ascii(tmp, sizeof(tmp), attr);
2257 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Calling_Station_Id);
2259 radattr2ascii(stationid, sizeof(stationid), attr);
2260 debug(DBG_INFO, "%s for user %s stationid %s from %s",
2261 radmsgtype2string(*buf), tmp, stationid, server->conf->host);
2263 debug(DBG_INFO, "%s for user %s from %s", radmsgtype2string(*buf), tmp, server->conf->host);
2267 buf[1] = (char)rq->origid;
2268 memcpy(buf + 4, rq->origauth, 16);
2270 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
2273 if (rq->origusername) {
2274 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
2276 pthread_mutex_unlock(&server->newrq_mutex);
2277 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
2280 memcpy(username, rq->origusername, strlen(rq->origusername));
2281 len = RADLEN(buf) - 20;
2284 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
2288 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
2289 pthread_mutex_unlock(&server->newrq_mutex);
2290 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
2293 debug(DBG_DBG, "replyh: computed messageauthattr");
2296 if (from->conf->type == 'U')
2297 fromsa = rq->fromsa;
2298 /* once we set received = 1, rq may be reused */
2301 debug(DBG_INFO, "replyh: passing reply to client %s", from->conf->name);
2302 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL, rq->fromudpsock);
2303 pthread_mutex_unlock(&server->newrq_mutex);
2307 void *udpclientrd(void *arg) {
2308 struct server *server;
2310 int *s = (int *)arg;
2314 buf = radudpget(*s, NULL, &server, NULL);
2315 if (!replyh(server, buf))
2320 void *tlsclientrd(void *arg) {
2321 struct server *server = (struct server *)arg;
2323 struct timeval now, lastconnecttry;
2326 /* yes, lastconnecttry is really necessary */
2327 lastconnecttry = server->lastconnecttry;
2328 buf = radtlsget(server->ssl, server->dynamiclookuparg ? IDLE_TIMEOUT : 0);
2330 if (server->dynamiclookuparg)
2332 tlsconnect(server, &lastconnecttry, 0, "clientrd");
2336 if (!replyh(server, buf))
2338 if (server->dynamiclookuparg) {
2339 gettimeofday(&now, NULL);
2340 if (now.tv_sec - server->lastreply.tv_sec > IDLE_TIMEOUT) {
2341 debug(DBG_INFO, "clientrd: idle timeout for %s", server->conf->name);
2346 server->clientrdgone = 1;
2350 /* code for removing state not finished */
2351 void *clientwr(void *arg) {
2352 struct server *server = (struct server *)arg;
2354 pthread_t tlsclientrdth;
2355 int i, dynconffail = 0;
2357 struct timeval now, lastsend;
2358 struct timespec timeout;
2359 struct request statsrvrq;
2360 unsigned char statsrvbuf[38];
2361 struct clsrvconf *conf;
2363 conf = server->conf;
2365 if (server->dynamiclookuparg && !dynamicconfig(server)) {
2370 if (!conf->addrinfo && !resolvepeer(conf, 0)) {
2371 debug(DBG_WARN, "failed to resolve host %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2375 memset(&timeout, 0, sizeof(struct timespec));
2377 if (conf->statusserver) {
2378 memset(&statsrvrq, 0, sizeof(struct request));
2379 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2380 statsrvbuf[0] = RAD_Status_Server;
2382 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2383 statsrvbuf[21] = 18;
2384 gettimeofday(&lastsend, NULL);
2387 if (conf->type == 'U') {
2388 server->connectionok = 1;
2390 if (!tlsconnect(server, NULL, server->dynamiclookuparg ? 6 : 0, "clientwr"))
2392 server->connectionok = 1;
2393 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server)) {
2394 debug(DBG_ERR, "clientwr: pthread_create failed");
2400 pthread_mutex_lock(&server->newrq_mutex);
2401 if (!server->newrq) {
2402 gettimeofday(&now, NULL);
2403 /* random 0-7 seconds */
2404 RAND_bytes(&rnd, 1);
2406 if (conf->statusserver) {
2407 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2408 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2410 if (!timeout.tv_sec || timeout.tv_sec > now.tv_sec + STATUS_SERVER_PERIOD + rnd)
2411 timeout.tv_sec = now.tv_sec + STATUS_SERVER_PERIOD + rnd;
2414 if (timeout.tv_sec > now.tv_sec)
2415 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2417 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2420 if (server->newrq) {
2421 debug(DBG_DBG, "clientwr: got new request");
2426 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2428 pthread_mutex_unlock(&server->newrq_mutex);
2430 for (i = 0; i < MAX_REQUESTS; i++) {
2431 if (server->clientrdgone) {
2432 pthread_join(tlsclientrdth, NULL);
2435 pthread_mutex_lock(&server->newrq_mutex);
2436 while (i < MAX_REQUESTS && !server->requests[i].buf)
2438 if (i == MAX_REQUESTS) {
2439 pthread_mutex_unlock(&server->newrq_mutex);
2442 rq = server->requests + i;
2445 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2447 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2449 /* setting this to NULL means that it can be reused */
2452 pthread_mutex_unlock(&server->newrq_mutex);
2456 gettimeofday(&now, NULL);
2457 if (now.tv_sec < rq->expiry.tv_sec) {
2458 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2459 timeout.tv_sec = rq->expiry.tv_sec;
2460 pthread_mutex_unlock(&server->newrq_mutex);
2464 if (rq->tries == (*rq->buf == RAD_Status_Server || conf->type == 'T'
2465 ? 1 : conf->retrycount + 1)) {
2466 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2467 if (conf->statusserver) {
2468 if (*rq->buf == RAD_Status_Server) {
2469 debug(DBG_WARN, "clientwr: no status server response, %s dead?", conf->host);
2470 if (server->lostrqs < 255)
2474 debug(DBG_WARN, "clientwr: no server response, %s dead?", conf->host);
2475 if (server->lostrqs < 255)
2479 /* setting this to NULL means that it can be reused */
2481 pthread_mutex_unlock(&server->newrq_mutex);
2484 pthread_mutex_unlock(&server->newrq_mutex);
2486 rq->expiry.tv_sec = now.tv_sec +
2487 (*rq->buf == RAD_Status_Server || conf->type == 'T'
2488 ? conf->retrydelay * (conf->retrycount + 1) : conf->retrydelay);
2489 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2490 timeout.tv_sec = rq->expiry.tv_sec;
2492 clientradput(server, server->requests[i].buf);
2493 gettimeofday(&lastsend, NULL);
2495 if (conf->statusserver) {
2496 gettimeofday(&now, NULL);
2497 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2498 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2499 debug(DBG_WARN, "clientwr: failed to generate random auth");
2502 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2503 if (!statsrvrq.buf) {
2504 debug(DBG_ERR, "clientwr: malloc failed");
2507 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2508 debug(DBG_DBG, "clientwr: sending status server to %s", conf->host);
2509 lastsend.tv_sec = now.tv_sec;
2510 sendrq(server, &statsrvrq);
2515 conf->servers = NULL;
2516 if (server->dynamiclookuparg) {
2517 removeserversubrealms(realms, conf);
2521 freeclsrvconf(conf);
2523 freeserver(server, 1);
2527 void *udpserverwr(void *arg) {
2528 struct replyq *replyq = udp_server_replyq;
2529 struct reply *reply;
2532 pthread_mutex_lock(&replyq->mutex);
2533 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2534 debug(DBG_DBG, "udp server writer, waiting for signal");
2535 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2536 debug(DBG_DBG, "udp server writer, got signal");
2538 pthread_mutex_unlock(&replyq->mutex);
2540 if (sendto(reply->toudpsock, reply->buf, RADLEN(reply->buf), 0,
2541 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2542 debug(DBG_WARN, "sendudp: send failed");
2548 void *udpserverrd(void *arg) {
2550 struct udpserverrdarg *rdarg = (struct udpserverrdarg *)arg;
2553 memset(&rq, 0, sizeof(struct request));
2554 rq.buf = radudpget(rdarg->s, &rq.from, NULL, &rq.fromsa);
2555 if (rdarg->acconly && *(uint8_t *)rq.buf != RAD_Accounting_Request) {
2556 debug(DBG_INFO, "udpserverrd: got something other than accounting-request, ignoring");
2560 rq.fromudpsock = rdarg->s;
2565 void createudplisteners(char *arg, uint8_t acconly) {
2567 struct clsrvconf *listenres;
2568 struct udpserverrdarg *rdarg;
2570 rdarg = malloc(sizeof(struct udpserverrdarg));
2572 debugx(1, DBG_ERR, "malloc failed");
2574 listenres = resolve_hostport('U', arg, DEFAULT_UDP_PORT);
2575 if ((rdarg->s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2576 debugx(1, DBG_ERR, "createudplisteners: socket/bind failed");
2578 debug(DBG_WARN, "createudplisteners: listening for UDP on %s:%s",
2579 listenres->host ? listenres->host : "*", listenres->port);
2580 freeclsrvres(listenres);
2582 rdarg->acconly = acconly;
2583 if (pthread_create(&th, NULL, udpserverrd, (void *)rdarg))
2584 debugx(1, DBG_ERR, "pthread_create failed");
2588 void *tlsserverwr(void *arg) {
2590 unsigned long error;
2591 struct client *client = (struct client *)arg;
2592 struct replyq *replyq;
2593 struct reply *reply;
2595 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2596 replyq = client->replyq;
2598 pthread_mutex_lock(&replyq->mutex);
2599 while (!list_first(replyq->replies)) {
2601 debug(DBG_DBG, "tls server writer, waiting for signal");
2602 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2603 debug(DBG_DBG, "tls server writer, got signal");
2606 /* ssl might have changed while waiting */
2607 pthread_mutex_unlock(&replyq->mutex);
2608 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2612 reply = (struct reply *)list_shift(replyq->replies);
2613 pthread_mutex_unlock(&replyq->mutex);
2614 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2616 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2617 cnt, RADLEN(reply->buf));
2619 while ((error = ERR_get_error()))
2620 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2626 void tlsserverrd(struct client *client) {
2628 pthread_t tlsserverwrth;
2630 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2632 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2633 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2638 memset(&rq, 0, sizeof(struct request));
2639 rq.buf = radtlsget(client->ssl, 0);
2642 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2647 debug(DBG_ERR, "tlsserverrd: connection lost");
2648 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2650 pthread_mutex_lock(&client->replyq->mutex);
2651 pthread_cond_signal(&client->replyq->cond);
2652 pthread_mutex_unlock(&client->replyq->mutex);
2653 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2654 pthread_join(tlsserverwrth, NULL);
2655 removeclientrqs(client);
2656 debug(DBG_DBG, "tlsserverrd for %s exiting", client->conf->host);
2659 void *tlsservernew(void *arg) {
2661 struct sockaddr_storage from;
2662 size_t fromlen = sizeof(from);
2663 struct clsrvconf *conf;
2664 struct list_node *cur = NULL;
2667 unsigned long error;
2668 struct client *client;
2671 if (getpeername(s, (struct sockaddr *)&from, &fromlen)) {
2672 debug(DBG_DBG, "tlsserverrd: getpeername failed, exiting");
2675 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2677 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2679 ssl = SSL_new(conf->ssl_ctx);
2682 if (SSL_accept(ssl) <= 0) {
2683 while ((error = ERR_get_error()))
2684 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2685 debug(DBG_ERR, "SSL_accept failed");
2688 cert = verifytlscert(ssl);
2694 if (verifyconfcert(cert, conf)) {
2696 client = addclient(conf);
2699 tlsserverrd(client);
2700 removeclient(client);
2702 debug(DBG_WARN, "Failed to create new client instance");
2705 conf = find_conf('T', (struct sockaddr *)&from, clconfs, &cur);
2707 debug(DBG_WARN, "ignoring request, no matching TLS client");
2713 shutdown(s, SHUT_RDWR);
2719 pthread_t tlsserverth;
2721 struct sockaddr_storage from;
2722 size_t fromlen = sizeof(from);
2723 struct clsrvconf *listenres;
2725 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2726 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2727 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2729 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2730 freeclsrvres(listenres);
2734 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2736 debug(DBG_WARN, "accept failed");
2739 if (pthread_create(&tlsserverth, NULL, tlsservernew, (void *)&snew)) {
2740 debug(DBG_ERR, "tlslistener: pthread_create failed");
2741 shutdown(snew, SHUT_RDWR);
2745 pthread_detach(tlsserverth);
2750 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd, uint8_t crlcheck) {
2753 STACK_OF(X509_NAME) *calist;
2756 unsigned long error;
2758 if (!certfile || !certkeyfile)
2759 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2761 if (!cacertfile && !cacertpath)
2762 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2765 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2766 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2767 for (i = 0; i < CRYPTO_num_locks(); i++) {
2768 ssl_lock_count[i] = 0;
2769 pthread_mutex_init(&ssl_locks[i], NULL);
2771 CRYPTO_set_id_callback(ssl_thread_id);
2772 CRYPTO_set_locking_callback(ssl_locking_callback);
2774 SSL_load_error_strings();
2777 while (!RAND_status()) {
2778 time_t t = time(NULL);
2779 pid_t pid = getpid();
2780 RAND_seed((unsigned char *)&t, sizeof(time_t));
2781 RAND_seed((unsigned char *)&pid, sizeof(pid));
2784 ctx = SSL_CTX_new(TLSv1_method());
2786 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2787 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2789 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2790 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2791 !SSL_CTX_check_private_key(ctx) ||
2792 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2793 while ((error = ERR_get_error()))
2794 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2795 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2798 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2799 if (!cacertfile || calist) {
2802 calist = sk_X509_NAME_new_null();
2803 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2804 sk_X509_NAME_free(calist);
2810 while ((error = ERR_get_error()))
2811 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2812 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2814 SSL_CTX_set_client_CA_list(ctx, calist);
2816 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2817 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2820 x509_s = SSL_CTX_get_cert_store(ctx);
2821 X509_STORE_set_flags(x509_s, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
2824 new = malloc(sizeof(struct tls));
2825 if (!new || !list_push(tlsconfs, new))
2826 debugx(1, DBG_ERR, "malloc failed");
2828 memset(new, 0, sizeof(struct tls));
2829 new->name = stringcopy(value, 0);
2831 debugx(1, DBG_ERR, "malloc failed");
2833 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2836 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2837 struct list_node *entry;
2838 struct tls *t, *t1 = NULL, *t2 = NULL;
2840 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2841 t = (struct tls *)entry->data;
2842 if (!strcasecmp(t->name, alt1)) {
2846 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2856 struct list *addsrvconfs(char *value, char **names) {
2857 struct list *conflist;
2859 struct list_node *entry;
2860 struct clsrvconf *conf = NULL;
2862 if (!names || !*names)
2865 conflist = list_create();
2867 debug(DBG_ERR, "malloc failed");
2871 for (n = 0; names[n]; n++) {
2872 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2873 conf = (struct clsrvconf *)entry->data;
2874 if (!strcasecmp(names[n], conf->name))
2878 debug(DBG_ERR, "addsrvconfs failed for realm %s, no server named %s", value, names[n]);
2879 list_destroy(conflist);
2882 if (!list_push(conflist, conf)) {
2883 debug(DBG_ERR, "malloc failed");
2884 list_destroy(conflist);
2887 debug(DBG_DBG, "addsrvconfs: added server %s for realm %s", conf->name, value);
2892 void freerealm(struct realm *realm) {
2896 free(realm->message);
2897 regfree(&realm->regex);
2898 pthread_mutex_destroy(&realm->subrealms_mutex);
2899 if (realm->subrealms)
2900 list_destroy(realm->subrealms);
2901 if (realm->srvconfs) {
2902 /* emptying list without freeing data */
2903 while (list_shift(realm->srvconfs));
2904 list_destroy(realm->srvconfs);
2906 if (realm->accsrvconfs) {
2907 /* emptying list without freeing data */
2908 while (list_shift(realm->accsrvconfs));
2909 list_destroy(realm->accsrvconfs);
2914 struct realm *addrealm(struct list *realmlist, char *value, char **servers, char **accservers, char *message, uint8_t accresp) {
2916 struct realm *realm;
2917 char *s, *regex = NULL;
2919 if (*value == '/') {
2920 /* regexp, remove optional trailing / if present */
2921 if (value[strlen(value) - 1] == '/')
2922 value[strlen(value) - 1] = '\0';
2924 /* not a regexp, let us make it one */
2925 if (*value == '*' && !value[1])
2926 regex = stringcopy(".*", 0);
2928 for (n = 0, s = value; *s;)
2931 regex = malloc(strlen(value) + n + 3);
2934 for (n = 1, s = value; *s; s++) {
2944 debug(DBG_ERR, "malloc failed");
2948 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2951 realm = malloc(sizeof(struct realm));
2953 debug(DBG_ERR, "malloc failed");
2956 memset(realm, 0, sizeof(struct realm));
2958 if (pthread_mutex_init(&realm->subrealms_mutex, NULL)) {
2959 debug(DBG_ERR, "mutex init failed");
2965 realm->name = stringcopy(value, 0);
2967 debug(DBG_ERR, "malloc failed");
2970 if (message && strlen(message) > 253) {
2971 debug(DBG_ERR, "ReplyMessage can be at most 253 bytes");
2974 realm->message = message;
2975 realm->accresp = accresp;
2977 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB)) {
2978 debug(DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2982 if (servers && *servers) {
2983 realm->srvconfs = addsrvconfs(value, servers);
2984 if (!realm->srvconfs)
2988 if (accservers && *accservers) {
2989 realm->accsrvconfs = addsrvconfs(value, accservers);
2990 if (!realm->accsrvconfs)
2994 if (!list_push(realmlist, realm)) {
2995 debug(DBG_ERR, "malloc failed");
2996 pthread_mutex_destroy(&realm->subrealms_mutex);
3000 debug(DBG_DBG, "addrealm: added realm %s", value);
3010 for (n = 0; servers[n]; n++)
3015 for (n = 0; accservers[n]; n++)
3016 free(accservers[n]);
3022 void adddynamicrealmserver(struct realm *realm, struct clsrvconf *conf, char *id) {
3023 struct clsrvconf *srvconf;
3024 struct realm *newrealm = NULL;
3025 char *realmname, *s;
3028 if (!conf->dynamiclookupcommand)
3031 /* create dynamic for the realm (string after last @, exit if nothing after @ */
3032 realmname = strrchr(id, '@');
3038 for (s = realmname; *s; s++)
3039 if (*s != '.' && *s != '-' && !isalnum((int)*s))
3042 pthread_mutex_lock(&realm->subrealms_mutex);
3043 /* exit if we now already got a matching subrealm */
3044 if (id2realm(realm->subrealms, id))
3046 srvconf = malloc(sizeof(struct clsrvconf));
3048 debug(DBG_ERR, "malloc failed");
3052 if (!addserver(srvconf))
3055 if (!realm->subrealms)
3056 realm->subrealms = list_create();
3057 if (!realm->subrealms)
3059 newrealm = addrealm(realm->subrealms, realmname, NULL, NULL, NULL, 0);
3063 /* add server and accserver to newrealm */
3064 newrealm->srvconfs = list_create();
3065 if (!newrealm->srvconfs || !list_push(newrealm->srvconfs, srvconf)) {
3066 debug(DBG_ERR, "malloc failed");
3069 newrealm->accsrvconfs = list_create();
3070 if (!newrealm->accsrvconfs || !list_push(newrealm->accsrvconfs, srvconf)) {
3071 debug(DBG_ERR, "malloc failed");
3075 srvconf->servers->dynamiclookuparg = stringcopy(realmname, 0);
3077 if (pthread_create(&clientth, NULL, clientwr, (void *)(srvconf->servers))) {
3078 debug(DBG_ERR, "pthread_create failed");
3081 pthread_detach(clientth);
3086 list_removedata(realm->subrealms, newrealm);
3087 freerealm(newrealm);
3088 if (!list_first(realm->subrealms)) {
3089 list_destroy(realm->subrealms);
3090 realm->subrealms = NULL;
3093 freeserver(srvconf->servers, 1);
3095 debug(DBG_ERR, "failed to create dynamic server");
3098 pthread_mutex_unlock(&realm->subrealms_mutex);
3101 int dynamicconfig(struct server *server) {
3102 int ok, fd[2], status;
3104 struct clsrvconf *conf = server->conf;
3105 struct gconffile *cf = NULL;
3107 /* for now we only learn hostname/address */
3108 debug(DBG_DBG, "dynamicconfig: need dynamic server config for %s", server->dynamiclookuparg);
3111 debug(DBG_ERR, "dynamicconfig: pipe error");
3116 debug(DBG_ERR, "dynamicconfig: fork error");
3120 } else if (pid == 0) {
3123 if (fd[1] != STDOUT_FILENO) {
3124 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
3125 debugx(1, DBG_ERR, "dynamicconfig: dup2 error for command %s", conf->dynamiclookupcommand);
3128 if (execlp(conf->dynamiclookupcommand, conf->dynamiclookupcommand, server->dynamiclookuparg, NULL) < 0)
3129 debugx(1, DBG_ERR, "dynamicconfig: exec error for command %s", conf->dynamiclookupcommand);
3133 pushgconffile(&cf, fdopen(fd[0], "r"), conf->dynamiclookupcommand);
3134 ok = getgenericconfig(&cf, NULL,
3135 "Server", CONF_CBK, confserver_cb, (void *)conf,
3140 if (waitpid(pid, &status, 0) < 0) {
3141 debug(DBG_ERR, "dynamicconfig: wait error");
3146 debug(DBG_INFO, "dynamicconfig: command exited with status %d", WEXITSTATUS(status));
3154 debug(DBG_WARN, "dynamicconfig: failed to obtain dynamic server config");
3158 int addmatchcertattr(struct clsrvconf *conf) {
3162 if (!strncasecmp(conf->matchcertattr, "CN:/", 4)) {
3163 r = &conf->certcnregex;
3164 v = conf->matchcertattr + 4;
3165 } else if (!strncasecmp(conf->matchcertattr, "SubjectAltName:URI:/", 20)) {
3166 r = &conf->certuriregex;
3167 v = conf->matchcertattr + 20;
3172 /* regexp, remove optional trailing / if present */
3173 if (v[strlen(v) - 1] == '/')
3174 v[strlen(v) - 1] = '\0';
3178 *r = malloc(sizeof(regex_t));
3180 debug(DBG_ERR, "malloc failed");
3183 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
3186 debug(DBG_ERR, "failed to compile regular expression %s", v);
3192 int addrewriteattr(struct clsrvconf *conf) {
3195 v = conf->rewriteattr + 11;
3196 if (strncasecmp(conf->rewriteattr, "User-Name:/", 11) || !*v)
3198 /* regexp, remove optional trailing / if present */
3199 if (v[strlen(v) - 1] == '/')
3200 v[strlen(v) - 1] = '\0';
3208 conf->rewriteattrregex = malloc(sizeof(regex_t));
3209 if (!conf->rewriteattrregex) {
3210 debug(DBG_ERR, "malloc failed");
3214 conf->rewriteattrreplacement = stringcopy(w, 0);
3215 if (!conf->rewriteattrreplacement) {
3216 free(conf->rewriteattrregex);
3217 conf->rewriteattrregex = NULL;
3221 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
3222 free(conf->rewriteattrregex);
3223 conf->rewriteattrregex = NULL;
3224 free(conf->rewriteattrreplacement);
3225 conf->rewriteattrreplacement = NULL;
3226 debug(DBG_ERR, "failed to compile regular expression %s", v);
3233 /* should accept both names and numeric values, only numeric right now */
3234 uint8_t attrname2val(char *attrname) {
3237 val = atoi(attrname);
3238 return val > 0 && val < 256 ? val : 0;
3241 /* should accept both names and numeric values, only numeric right now */
3242 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
3245 *vendor = atoi(attrname);
3246 s = strchr(attrname, ':');
3251 *type = atoi(s + 1);
3252 return *type >= 0 && *type < 256;
3255 struct rewrite *getrewrite(char *alt1, char *alt2) {
3256 struct list_node *entry;
3257 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
3259 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
3260 r = (struct rewriteconf *)entry->data;
3261 if (!strcasecmp(r->name, alt1)) {
3265 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
3275 void addrewrite(char *value, char **attrs, char **vattrs) {
3276 struct rewriteconf *new;
3277 struct rewrite *rewrite = NULL;
3280 uint32_t *p, *va = NULL;
3284 for (; attrs[n]; n++);
3285 a = malloc((n + 1) * sizeof(uint8_t));
3287 debugx(1, DBG_ERR, "malloc failed");
3289 for (i = 0; i < n; i++) {
3290 if (!(a[i] = attrname2val(attrs[i])))
3291 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
3300 for (; vattrs[n]; n++);
3301 va = malloc((2 * n + 1) * sizeof(uint32_t));
3303 debugx(1, DBG_ERR, "malloc failed");
3305 for (p = va, i = 0; i < n; i++, p += 2) {
3306 if (!vattrname2val(vattrs[i], p, p + 1))
3307 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
3315 rewrite = malloc(sizeof(struct rewrite));
3317 debugx(1, DBG_ERR, "malloc failed");
3318 rewrite->removeattrs = a;
3319 rewrite->removevendorattrs = va;
3322 new = malloc(sizeof(struct rewriteconf));
3323 if (!new || !list_push(rewriteconfs, new))
3324 debugx(1, DBG_ERR, "malloc failed");
3326 memset(new, 0, sizeof(struct rewriteconf));
3327 new->name = stringcopy(value, 0);
3329 debugx(1, DBG_ERR, "malloc failed");
3331 new->rewrite = rewrite;
3332 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
3335 void freeclsrvconf(struct clsrvconf *conf) {
3337 free(conf->conftype);
3342 free(conf->matchcertattr);
3343 if (conf->certcnregex)
3344 regfree(conf->certcnregex);
3345 if (conf->certuriregex)
3346 regfree(conf->certuriregex);
3347 free(conf->confrewrite);
3348 free(conf->rewriteattr);
3349 if (conf->rewriteattrregex)
3350 regfree(conf->rewriteattrregex);
3351 free(conf->rewriteattrreplacement);
3352 free(conf->dynamiclookupcommand);
3353 free(conf->rewrite);
3355 freeaddrinfo(conf->addrinfo);
3356 /* not touching ssl_ctx, clients and servers */
3360 int mergeconfstring(char **dst, char **src) {
3369 t = stringcopy(*dst, 0);
3371 debug(DBG_ERR, "malloc failed");
3379 /* assumes dst is a shallow copy */
3380 int mergesrvconf(struct clsrvconf *dst, struct clsrvconf *src) {
3381 if (!mergeconfstring(&dst->name, &src->name) ||
3382 !mergeconfstring(&dst->conftype, &src->conftype) ||
3383 !mergeconfstring(&dst->host, &src->host) ||
3384 !mergeconfstring(&dst->port, &src->port) ||
3385 !mergeconfstring(&dst->secret, &src->secret) ||
3386 !mergeconfstring(&dst->tls, &src->tls) ||
3387 !mergeconfstring(&dst->matchcertattr, &src->matchcertattr) ||
3388 !mergeconfstring(&dst->confrewrite, &src->confrewrite) ||
3389 !mergeconfstring(&dst->dynamiclookupcommand, &src->dynamiclookupcommand))
3391 dst->statusserver = src->statusserver;
3392 dst->certnamecheck = src->certnamecheck;
3393 if (src->retrydelay != 255)
3394 dst->retrydelay = src->retrydelay;
3395 if (src->retrycount != 255)
3396 dst->retrycount = src->retrycount;
3400 int confclient_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3401 struct clsrvconf *conf;
3403 debug(DBG_DBG, "confclient_cb called for %s", block);
3405 conf = malloc(sizeof(struct clsrvconf));
3406 if (!conf || !list_push(clconfs, conf))
3407 debugx(1, DBG_ERR, "malloc failed");
3408 memset(conf, 0, sizeof(struct clsrvconf));
3409 conf->certnamecheck = 1;
3411 if (!getgenericconfig(cf, block,
3412 "type", CONF_STR, &conf->conftype,
3413 "host", CONF_STR, &conf->host,
3414 "secret", CONF_STR, &conf->secret,
3415 "tls", CONF_STR, &conf->tls,
3416 "matchcertificateattribute", CONF_STR, &conf->matchcertattr,
3417 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3418 "rewrite", CONF_STR, &conf->confrewrite,
3419 "rewriteattribute", CONF_STR, &conf->rewriteattr,
3422 debugx(1, DBG_ERR, "configuration error");
3424 conf->name = stringcopy(val, 0);
3426 conf->host = stringcopy(val, 0);
3428 if (conf->conftype && !strcasecmp(conf->conftype, "udp")) {
3431 } else if (conf->conftype && !strcasecmp(conf->conftype, "tls")) {
3432 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultclient", "default");
3434 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
3435 if (conf->matchcertattr && !addmatchcertattr(conf))
3436 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3440 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3442 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultclient", "default");
3444 if (conf->rewriteattr) {
3445 if (!addrewriteattr(conf))
3446 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
3449 if (!resolvepeer(conf, 0))
3450 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3452 if (!conf->secret) {
3453 if (conf->type == 'U')
3454 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3455 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3460 int compileserverconfig(struct clsrvconf *conf, const char *block) {
3461 switch (conf->type) {
3464 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
3467 conf->ssl_ctx = conf->tls ? tlsgetctx(conf->tls, NULL) : tlsgetctx("defaultserver", "default");
3468 if (!conf->ssl_ctx) {
3469 debug(DBG_ERR, "error in block %s, no tls context defined", block);
3472 if (conf->matchcertattr && !addmatchcertattr(conf)) {
3473 debug(DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
3477 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
3481 if (conf->retrydelay == 255)
3482 conf->retrydelay = REQUEST_RETRY_DELAY;
3483 if (conf->retrycount == 255)
3484 conf->retrycount = REQUEST_RETRY_COUNT;
3486 conf->rewrite = conf->confrewrite ? getrewrite(conf->confrewrite, NULL) : getrewrite("defaultserver", "default");
3488 if (!conf->secret) {
3489 if (conf->type == 'U')
3490 debug(DBG_ERR, "error in block %s, secret must be specified for UDP", block);
3491 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
3492 if (!conf->secret) {
3493 debug(DBG_ERR, "malloc failed");
3498 if (!conf->dynamiclookupcommand && !resolvepeer(conf, 0)) {
3499 debug(DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
3505 int confserver_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3506 struct clsrvconf *conf, *resconf;
3507 long int retrydelay = LONG_MIN, retrycount = LONG_MIN;
3509 debug(DBG_DBG, "confserver_cb called for %s", block);
3511 conf = malloc(sizeof(struct clsrvconf));
3513 debug(DBG_ERR, "malloc failed");
3516 memset(conf, 0, sizeof(struct clsrvconf));
3517 resconf = (struct clsrvconf *)arg;
3519 conf->statusserver = resconf->statusserver;
3520 conf->certnamecheck = resconf->certnamecheck;
3522 conf->certnamecheck = 1;
3524 if (!getgenericconfig(cf, block,
3525 "type", CONF_STR, &conf->conftype,
3526 "host", CONF_STR, &conf->host,
3527 "port", CONF_STR, &conf->port,
3528 "secret", CONF_STR, &conf->secret,
3529 "tls", CONF_STR, &conf->tls,
3530 "MatchCertificateAttribute", CONF_STR, &conf->matchcertattr,
3531 "rewrite", CONF_STR, &conf->confrewrite,
3532 "StatusServer", CONF_BLN, &conf->statusserver,
3533 "RetryDelay", CONF_LINT, &retrydelay,
3534 "RetryCount", CONF_LINT, &retrycount,
3535 "CertificateNameCheck", CONF_BLN, &conf->certnamecheck,
3536 "DynamicLookupCommand", CONF_STR, &conf->dynamiclookupcommand,
3539 debug(DBG_ERR, "configuration error");
3543 conf->name = stringcopy(val, 0);
3545 debug(DBG_ERR, "malloc failed");
3549 conf->host = stringcopy(val, 0);
3551 debug(DBG_ERR, "malloc failed");
3556 if (retrydelay != LONG_MIN) {
3557 if (retrydelay < 1 || retrydelay > 60) {
3558 debug(DBG_ERR, "error in block %s, value of option RetryDelay is %d, must be 1-60", block, retrydelay);
3561 conf->retrydelay = (uint8_t)retrydelay;
3563 conf->retrydelay = 255;
3565 if (retrycount != LONG_MIN) {
3566 if (retrycount < 0 || retrycount > 10) {
3567 debug(DBG_ERR, "error in block %s, value of option RetryCount is %d, must be 0-10", block, retrycount);
3570 conf->retrycount = (uint8_t)retrycount;
3572 conf->retrycount = 255;
3575 if (!mergesrvconf(resconf, conf))
3579 if (conf->dynamiclookupcommand) {
3580 free(conf->dynamiclookupcommand);
3581 conf->dynamiclookupcommand = NULL;
3585 if (conf->conftype && !strcasecmp(conf->conftype, "udp"))
3587 else if (conf->conftype && !strcasecmp(conf->conftype, "tls"))
3590 debug(DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
3594 if (resconf || !conf->dynamiclookupcommand) {
3595 if (!compileserverconfig(conf, block))
3602 switch (conf->type) {
3613 if (!list_push(srvconfs, conf)) {
3614 debug(DBG_ERR, "malloc failed");
3620 freeclsrvconf(conf);
3624 int confrealm_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3625 char **servers = NULL, **accservers = NULL, *msg = NULL;
3626 uint8_t accresp = 0;
3628 debug(DBG_DBG, "confrealm_cb called for %s", block);
3630 if (!getgenericconfig(cf, block,
3631 "server", CONF_MSTR, &servers,
3632 "accountingServer", CONF_MSTR, &accservers,
3633 "ReplyMessage", CONF_STR, &msg,
3634 "AccountingResponse", CONF_BLN, &accresp,
3637 debugx(1, DBG_ERR, "configuration error");
3639 addrealm(realms, val, servers, accservers, msg, accresp);
3643 int conftls_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3644 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
3645 uint8_t crlcheck = 0;
3647 debug(DBG_DBG, "conftls_cb called for %s", block);
3649 if (!getgenericconfig(cf, block,
3650 "CACertificateFile", CONF_STR, &cacertfile,
3651 "CACertificatePath", CONF_STR, &cacertpath,
3652 "CertificateFile", CONF_STR, &certfile,
3653 "CertificateKeyFile", CONF_STR, &certkeyfile,
3654 "CertificateKeyPassword", CONF_STR, &certkeypwd,
3655 "CRLCheck", CONF_BLN, &crlcheck,
3658 debugx(1, DBG_ERR, "configuration error");
3660 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd, crlcheck);
3669 int confrewrite_cb(struct gconffile **cf, void *arg, char *block, char *opt, char *val) {
3670 char **attrs = NULL, **vattrs = NULL;
3672 debug(DBG_DBG, "confrewrite_cb called for %s", block);
3674 if (!getgenericconfig(cf, block,
3675 "removeAttribute", CONF_MSTR, &attrs,
3676 "removeVendorAttribute", CONF_MSTR, &vattrs,
3679 debugx(1, DBG_ERR, "configuration error");
3680 addrewrite(val, attrs, vattrs);
3684 void getmainconfig(const char *configfile) {
3685 long int loglevel = LONG_MIN;
3686 struct gconffile *cfs;
3688 cfs = openconfigfile(configfile);
3689 memset(&options, 0, sizeof(options));
3691 clconfs = list_create();
3693 debugx(1, DBG_ERR, "malloc failed");
3695 srvconfs = list_create();
3697 debugx(1, DBG_ERR, "malloc failed");
3699 realms = list_create();
3701 debugx(1, DBG_ERR, "malloc failed");
3703 tlsconfs = list_create();
3705 debugx(1, DBG_ERR, "malloc failed");
3707 rewriteconfs = list_create();
3709 debugx(1, DBG_ERR, "malloc failed");
3711 if (!getgenericconfig(&cfs, NULL,
3712 "ListenUDP", CONF_STR, &options.listenudp,
3713 "ListenTCP", CONF_STR, &options.listentcp,
3714 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
3715 "SourceUDP", CONF_STR, &options.sourceudp,
3716 "SourceTCP", CONF_STR, &options.sourcetcp,
3717 "LogLevel", CONF_LINT, &loglevel,
3718 "LogDestination", CONF_STR, &options.logdestination,
3719 "LoopPrevention", CONF_BLN, &options.loopprevention,
3720 "Client", CONF_CBK, confclient_cb, NULL,
3721 "Server", CONF_CBK, confserver_cb, NULL,
3722 "Realm", CONF_CBK, confrealm_cb, NULL,
3723 "TLS", CONF_CBK, conftls_cb, NULL,
3724 "Rewrite", CONF_CBK, confrewrite_cb, NULL,
3727 debugx(1, DBG_ERR, "configuration error");
3729 if (loglevel != LONG_MIN) {
3730 if (loglevel < 1 || loglevel > 4)
3731 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %d, must be 1, 2, 3 or 4", configfile, loglevel);
3732 options.loglevel = (uint8_t)loglevel;
3736 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3739 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3742 *configfile = optarg;
3745 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3746 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3747 *loglevel = *optarg - '0';
3756 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3761 if (!(argc - optind))
3765 debugx(1, DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3769 int daemon(int a, int b) {
3777 for (i = 0; i < 3; i++) {
3779 open("/dev/null", O_RDWR);
3785 void *sighandler(void *arg) {
3790 sigemptyset(&sigset);
3791 sigaddset(&sigset, SIGPIPE);
3792 sigwait(&sigset, &sig);
3793 /* only get SIGPIPE right now, so could simplify below code */
3796 /* completely ignoring this */
3799 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3802 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3807 int main(int argc, char **argv) {
3808 pthread_t sigth, udpclient4rdth, udpclient6rdth, udpserverwrth;
3810 struct list_node *entry;
3811 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3812 char *configfile = NULL;
3813 struct clsrvconf *srvconf;
3815 debug_init("radsecproxy");
3816 debug_set_level(DEBUG_LEVEL);
3817 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3819 debug_set_level(loglevel);
3820 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3822 options.loglevel = loglevel;
3823 else if (options.loglevel)
3824 debug_set_level(options.loglevel);
3826 debug_set_destination(options.logdestination ? options.logdestination : "x-syslog:///");
3827 free(options.logdestination);
3829 if (!list_first(clconfs))
3830 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3831 if (!list_first(srvconfs))
3832 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3833 if (!list_first(realms))
3834 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3837 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3839 if (!foreground && (daemon(0, 0) < 0))
3840 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3842 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3844 sigemptyset(&sigset);
3845 /* exit on all but SIGPIPE, ignore more? */
3846 sigaddset(&sigset, SIGPIPE);
3847 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3848 pthread_create(&sigth, NULL, sighandler, NULL);
3850 if (client_udp_count) {
3851 udp_server_replyq = newreplyq();
3852 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
3853 debugx(1, DBG_ERR, "pthread_create failed");
3854 createudplisteners(options.listenudp, 0);
3855 if (options.listenaccudp)
3856 createudplisteners(options.listenaccudp, 1);
3859 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3860 srvconf = (struct clsrvconf *)entry->data;
3861 if (srvconf->dynamiclookupcommand)
3863 if (!addserver(srvconf))
3864 debugx(1, DBG_ERR, "failed to add server");
3865 if (pthread_create(&srvconf->servers->clientth, NULL, clientwr,
3866 (void *)(srvconf->servers)))
3867 debugx(1, DBG_ERR, "pthread_create failed");
3869 /* srcudpres no longer needed, while srctcpres is needed later */
3871 freeaddrinfo(srcudpres);
3874 if (udp_client4_sock >= 0)
3875 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3876 debugx(1, DBG_ERR, "pthread_create failed");
3877 if (udp_client6_sock >= 0)
3878 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3879 debugx(1, DBG_ERR, "pthread_create failed");
3881 if (client_tls_count)
3882 return tlslistener();
3884 /* just hang around doing nothing, anything to do here? */