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>
42 #include <sys/types.h>
43 #include <arpa/inet.h>
47 #include <openssl/ssl.h>
48 #include <openssl/rand.h>
49 #include <openssl/err.h>
50 #include <openssl/md5.h>
51 #include <openssl/hmac.h>
52 #include <openssl/x509v3.h>
57 #include "radsecproxy.h"
59 static struct options options;
60 struct list *clconfs, *srvconfs, *realms, *tlsconfs, *rewriteconfs;
62 static int client_udp_count = 0;
63 static int client_tls_count = 0;
64 static int server_udp_count = 0;
65 static int server_tls_count = 0;
67 static struct clsrvconf *srcudpres = NULL;
68 static struct clsrvconf *srctcpres = NULL;
70 static struct replyq *udp_server_replyq = NULL;
71 static int udp_server_sock = -1;
72 static int udp_accserver_sock = -1;
73 static int udp_client4_sock = -1;
74 static int udp_client6_sock = -1;
75 static pthread_mutex_t *ssl_locks;
76 static long *ssl_lock_count;
80 /* callbacks for making OpenSSL thread safe */
81 unsigned long ssl_thread_id() {
82 return (unsigned long)pthread_self();
85 void ssl_locking_callback(int mode, int type, const char *file, int line) {
86 if (mode & CRYPTO_LOCK) {
87 pthread_mutex_lock(&ssl_locks[type]);
88 ssl_lock_count[type]++;
90 pthread_mutex_unlock(&ssl_locks[type]);
93 static int pem_passwd_cb(char *buf, int size, int rwflag, void *userdata) {
94 int pwdlen = strlen(userdata);
95 if (rwflag != 0 || pwdlen > size) /* not for decryption or too large */
97 memcpy(buf, userdata, pwdlen);
101 static int verify_cb(int ok, X509_STORE_CTX *ctx) {
106 err_cert = X509_STORE_CTX_get_current_cert(ctx);
107 err = X509_STORE_CTX_get_error(ctx);
108 depth = X509_STORE_CTX_get_error_depth(ctx);
110 if (depth > MAX_CERT_DEPTH) {
112 err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
113 X509_STORE_CTX_set_error(ctx, err);
117 X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
118 debug(DBG_WARN, "verify error: num=%d:%s:depth=%d:%s", err, X509_verify_cert_error_string(err), depth, buf);
121 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
122 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
123 debug(DBG_WARN, "\tIssuer=%s", buf);
125 case X509_V_ERR_CERT_NOT_YET_VALID:
126 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
127 debug(DBG_WARN, "\tCertificate not yet valid");
129 case X509_V_ERR_CERT_HAS_EXPIRED:
130 debug(DBG_WARN, "Certificate has expired");
132 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
133 debug(DBG_WARN, "Certificate no longer valid (after notAfter)");
138 printf("certificate verify returns %d\n", ok);
143 int resolvepeer(struct clsrvconf *conf, int ai_flags) {
144 struct addrinfo hints, *addrinfo, *res;
148 slash = conf->host ? strchr(conf->host, '/') : NULL;
152 debug(DBG_WARN, "resolvepeer: prefix length must be specified after the / in %s", conf->host);
156 if (*s < '0' || *s > '9') {
157 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
160 plen = atoi(slash + 1);
161 if (plen < 0 || plen > 128) {
162 debug(DBG_WARN, "resolvepeer: %s in %s is not a valid prefix length", slash + 1, conf->host);
167 memset(&hints, 0, sizeof(hints));
168 hints.ai_socktype = (conf->type == 'T' ? SOCK_STREAM : SOCK_DGRAM);
169 hints.ai_family = AF_UNSPEC;
170 hints.ai_flags = ai_flags;
171 if (!conf->host && !conf->port) {
172 /* getaddrinfo() doesn't like host and port to be NULL */
173 if (getaddrinfo(conf->host, DEFAULT_UDP_PORT, &hints, &addrinfo)) {
174 debug(DBG_WARN, "resolvepeer: can't resolve (null) port (null)");
177 for (res = addrinfo; res; res = res->ai_next) {
178 switch (res->ai_family) {
180 ((struct sockaddr_in *)res->ai_addr)->sin_port = 0;
183 ((struct sockaddr_in6 *)res->ai_addr)->sin6_port = 0;
189 hints.ai_flags |= AI_NUMERICHOST;
190 if (getaddrinfo(conf->host, conf->port, &hints, &addrinfo)) {
191 debug(DBG_WARN, "resolvepeer: can't resolve %s port %s", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
196 switch (addrinfo->ai_family) {
199 debug(DBG_WARN, "resolvepeer: prefix length must be <= 32 in %s", conf->host);
200 freeaddrinfo(addrinfo);
207 debug(DBG_WARN, "resolvepeer: prefix must be IPv4 or IPv6 in %s", conf->host);
208 freeaddrinfo(addrinfo);
211 conf->prefixlen = plen;
213 conf->prefixlen = 255;
216 freeaddrinfo(conf->addrinfo);
217 conf->addrinfo = addrinfo;
221 int bindtoaddr(struct addrinfo *addrinfo, int family, int reuse, int v6only) {
223 struct addrinfo *res;
225 for (res = addrinfo; res; res = res->ai_next) {
226 if (family != AF_UNSPEC && family != res->ai_family)
228 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
230 debug(DBG_WARN, "bindtoaddr: socket failed");
234 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
237 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
240 if (!bind(s, res->ai_addr, res->ai_addrlen))
242 debug(DBG_WARN, "bindtoaddr: bind failed");
248 char *parsehostport(char *s, struct clsrvconf *conf, char *default_port) {
253 /* allow literal addresses and port, e.g. [2001:db8::1]:1812 */
257 for (; *p && *p != ']' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
259 debugx(1, DBG_ERR, "no ] matching initial [");
263 for (; *p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n'; p++);
266 debugx(1, DBG_ERR, "missing host/address");
268 conf->host = stringcopy(field, p - field);
271 if (*p && *p != ':' && *p != ' ' && *p != '\t' && *p != '\n')
272 debugx(1, DBG_ERR, "unexpected character after ]");
275 /* port number or service name is specified */;
277 for (; *p && *p != ' ' && *p != '\t' && *p != '\n'; p++);
279 debugx(1, DBG_ERR, "syntax error, : but no following port");
280 conf->port = stringcopy(field, p - field);
282 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
286 struct clsrvconf *resolve_hostport(char type, char *lconf, char *default_port) {
287 struct clsrvconf *conf;
289 conf = malloc(sizeof(struct clsrvconf));
291 debugx(1, DBG_ERR, "malloc failed");
292 memset(conf, 0, sizeof(struct clsrvconf));
295 parsehostport(lconf, conf, default_port);
296 if (!strcmp(conf->host, "*")) {
301 conf->port = default_port ? stringcopy(default_port, 0) : NULL;
302 if (!resolvepeer(conf, AI_PASSIVE))
303 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
307 int connecttcp(struct addrinfo *addrinfo) {
309 struct addrinfo *res;
312 for (res = addrinfo; res; res = res->ai_next) {
313 s = bindtoaddr(srctcpres->addrinfo, res->ai_family, 1, 1);
315 debug(DBG_WARN, "connecttoserver: socket failed");
318 if (connect(s, res->ai_addr, res->ai_addrlen) == 0)
320 debug(DBG_WARN, "connecttoserver: connect failed");
327 /* returns 1 if the len first bits are equal, else 0 */
328 int prefixmatch(void *a1, void *a2, uint8_t len) {
329 static uint8_t mask[] = { 0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe };
331 if (l && memcmp(a1, a2, l))
336 return (((uint8_t *)a1)[l] & mask[r]) == (((uint8_t *)a2)[l] & mask[r]);
339 /* returns the config with matching address, or NULL */
340 /* if conf argument is not NULL, we only check that one */
341 struct clsrvconf *find_conf(char type, struct sockaddr *addr, struct list *confs, struct clsrvconf *conf) {
342 struct sockaddr_in6 *sa6 = NULL;
343 struct in_addr *a4 = NULL;
344 struct addrinfo *res;
345 struct list_node *entry;
347 if (addr->sa_family == AF_INET6) {
348 sa6 = (struct sockaddr_in6 *)addr;
349 if (IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr)) {
350 a4 = (struct in_addr *)&sa6->sin6_addr.s6_addr[12];
354 a4 = &((struct sockaddr_in *)addr)->sin_addr;
357 if (conf->type == type) {
358 if (conf->prefixlen == 255) {
359 for (res = conf->addrinfo; res; res = res->ai_next)
360 if ((a4 && res->ai_family == AF_INET &&
361 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
362 (sa6 && res->ai_family == AF_INET6 &&
363 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
366 res = conf->addrinfo;
368 ((a4 && res->ai_family == AF_INET &&
369 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
370 (sa6 && res->ai_family == AF_INET6 &&
371 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
378 for (entry = list_first(confs); entry; entry = list_next(entry)) {
379 conf = (struct clsrvconf *)entry->data;
380 if (conf->type == type) {
381 if (conf->prefixlen == 255) {
382 for (res = conf->addrinfo; res; res = res->ai_next)
383 if ((a4 && res->ai_family == AF_INET &&
384 !memcmp(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, 4)) ||
385 (sa6 && res->ai_family == AF_INET6 &&
386 !memcmp(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, 16)))
389 res = conf->addrinfo;
391 ((a4 && res->ai_family == AF_INET &&
392 prefixmatch(a4, &((struct sockaddr_in *)res->ai_addr)->sin_addr, conf->prefixlen)) ||
393 (sa6 && res->ai_family == AF_INET6 &&
394 prefixmatch(&sa6->sin6_addr, &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, conf->prefixlen))))
402 struct replyq *newreplyq() {
403 struct replyq *replyq;
405 replyq = malloc(sizeof(struct replyq));
407 debugx(1, DBG_ERR, "malloc failed");
408 replyq->replies = list_create();
409 if (!replyq->replies)
410 debugx(1, DBG_ERR, "malloc failed");
411 pthread_mutex_init(&replyq->mutex, NULL);
412 pthread_cond_init(&replyq->cond, NULL);
416 struct client *addclient(struct clsrvconf *conf) {
417 struct client *new = malloc(sizeof(struct client));
420 debug(DBG_ERR, "malloc failed");
423 if (!conf->clients) {
424 conf->clients = list_create();
425 if (!conf->clients) {
426 debug(DBG_ERR, "malloc failed");
431 memset(new, 0, sizeof(struct client));
433 new->replyq = conf->type == 'T' ? newreplyq() : udp_server_replyq;
435 list_push(conf->clients, new);
439 void removeclient(struct client *client) {
440 struct list_node *entry;
442 if (!client || !client->conf->clients)
445 pthread_mutex_lock(&client->replyq->mutex);
446 for (entry = list_first(client->replyq->replies); entry; entry = list_next(entry))
447 free(((struct reply *)entry)->buf);
448 list_destroy(client->replyq->replies);
449 pthread_mutex_unlock(&client->replyq->mutex);
450 list_removedata(client->conf->clients, client);
454 void removeclientrqs(struct client *client) {
455 struct list_node *entry;
456 struct server *server;
460 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
461 server = ((struct clsrvconf *)entry->data)->servers;
462 pthread_mutex_lock(&server->newrq_mutex);
463 for (i = 0; i < MAX_REQUESTS; i++) {
464 rq = server->requests + i;
465 if (rq->from == client)
468 pthread_mutex_unlock(&server->newrq_mutex);
472 void addserver(struct clsrvconf *conf) {
474 debugx(1, DBG_ERR, "addserver: currently works with just one server per conf");
476 conf->servers = malloc(sizeof(struct server));
478 debugx(1, DBG_ERR, "malloc failed");
479 memset(conf->servers, 0, sizeof(struct server));
480 conf->servers->conf = conf;
482 if (conf->type == 'U') {
484 srcudpres = resolve_hostport('U', options.sourceudp, NULL);
485 switch (conf->addrinfo->ai_family) {
487 if (udp_client4_sock < 0) {
488 udp_client4_sock = bindtoaddr(srcudpres->addrinfo, AF_INET, 0, 1);
489 if (udp_client4_sock < 0)
490 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
492 conf->servers->sock = udp_client4_sock;
495 if (udp_client6_sock < 0) {
496 udp_client6_sock = bindtoaddr(srcudpres->addrinfo, AF_INET6, 0, 1);
497 if (udp_client6_sock < 0)
498 debugx(1, DBG_ERR, "addserver: failed to create client socket for server %s", conf->host);
500 conf->servers->sock = udp_client6_sock;
503 debugx(1, DBG_ERR, "addserver: unsupported address family");
508 srctcpres = resolve_hostport('T', options.sourcetcp, NULL);
509 conf->servers->sock = -1;
512 pthread_mutex_init(&conf->servers->lock, NULL);
513 conf->servers->requests = calloc(MAX_REQUESTS, sizeof(struct request));
514 if (!conf->servers->requests)
515 debugx(1, DBG_ERR, "malloc failed");
516 conf->servers->newrq = 0;
517 pthread_mutex_init(&conf->servers->newrq_mutex, NULL);
518 pthread_cond_init(&conf->servers->newrq_cond, NULL);
521 /* exactly one of client and server must be non-NULL */
522 /* should probably take peer list (client(s) or server(s)) as argument instead */
523 /* if *peer == NULL we return who we received from, else require it to be from peer */
524 /* return from in sa if not NULL */
525 unsigned char *radudpget(int s, struct client **client, struct server **server, struct sockaddr_storage *sa) {
527 unsigned char buf[65536], *rad;
528 struct sockaddr_storage from;
529 socklen_t fromlen = sizeof(from);
531 struct list_node *node;
534 cnt = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fromlen);
536 debug(DBG_WARN, "radudpget: recv failed");
539 debug(DBG_DBG, "radudpget: got %d bytes from %s", cnt, addr2string((struct sockaddr *)&from, fromlen));
542 debug(DBG_WARN, "radudpget: packet too small");
548 debug(DBG_WARN, "radudpget: length too small");
553 debug(DBG_WARN, "radudpget: packet smaller than length field in radius header");
557 debug(DBG_DBG, "radudpget: packet was padded with %d bytes", cnt - len);
561 p = find_conf('U', (struct sockaddr *)&from, NULL, (*client)->conf);
563 p = find_conf('U', (struct sockaddr *)&from, clconfs, NULL);
566 p = find_conf('U', (struct sockaddr *)&from, NULL, (*server)->conf);
568 p = find_conf('U', (struct sockaddr *)&from, srvconfs, NULL);
571 debug(DBG_WARN, "radudpget: got packet from wrong or unknown UDP peer, ignoring");
577 debug(DBG_ERR, "radudpget: malloc failed");
581 if (client && !*client) {
582 node = list_first(p->clients);
583 *client = node ? (struct client *)node->data : addclient(p);
588 } else if (server && !*server)
589 *server = p->servers;
593 memcpy(rad, buf, len);
599 int subjectaltnameaddr(X509 *cert, int family, struct in6_addr *addr) {
600 int loc, i, l, n, r = 0;
603 STACK_OF(GENERAL_NAME) *alt;
606 debug(DBG_DBG, "subjectaltnameaddr");
608 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
612 ex = X509_get_ext(cert, loc);
613 alt = X509V3_EXT_d2i(ex);
617 n = sk_GENERAL_NAME_num(alt);
618 for (i = 0; i < n; i++) {
619 gn = sk_GENERAL_NAME_value(alt, i);
620 if (gn->type != GEN_IPADD)
623 v = (char *)ASN1_STRING_data(gn->d.ia5);
624 l = ASN1_STRING_length(gn->d.ia5);
625 if (((family == AF_INET && l == sizeof(struct in_addr)) || (family == AF_INET6 && l == sizeof(struct in6_addr)))
626 && !memcmp(v, &addr, l)) {
631 GENERAL_NAMES_free(alt);
635 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
636 int loc, i, l, n, r = 0;
639 STACK_OF(GENERAL_NAME) *alt;
642 debug(DBG_DBG, "subjectaltnameregexp");
644 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
648 ex = X509_get_ext(cert, loc);
649 alt = X509V3_EXT_d2i(ex);
653 n = sk_GENERAL_NAME_num(alt);
654 for (i = 0; i < n; i++) {
655 gn = sk_GENERAL_NAME_value(alt, i);
656 if (gn->type != type)
659 v = (char *)ASN1_STRING_data(gn->d.ia5);
660 l = ASN1_STRING_length(gn->d.ia5);
664 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
667 if (memcmp(v, exact, l))
670 s = stringcopy((char *)v, l);
672 debug(DBG_ERR, "malloc failed");
675 if (regexec(regex, s, 0, NULL, 0)) {
684 GENERAL_NAMES_free(alt);
688 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
695 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
697 struct in6_addr addr;
699 if (SSL_get_verify_result(ssl) != X509_V_OK) {
700 debug(DBG_ERR, "tlsverifycert: basic validation failed");
701 while ((error = ERR_get_error()))
702 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
706 cert = SSL_get_peer_certificate(ssl);
708 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
712 if (conf->prefixlen == 255) {
713 if (inet_pton(AF_INET, conf->host, &addr))
715 else if (inet_pton(AF_INET6, conf->host, &addr))
718 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
722 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
725 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
727 nm = X509_get_subject_name(cert);
730 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
733 e = X509_NAME_get_entry(nm, loc);
734 s = X509_NAME_ENTRY_get_data(e);
735 v = (char *) ASN1_STRING_data(s);
736 l = ASN1_STRING_length(s);
740 printfchars(NULL, "cn", NULL, v, l);
742 if (l == strlen(conf->host) && !strncasecmp(conf->host, v, l)) {
744 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
750 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
755 if (conf->certuriregex) {
756 r = subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex);
758 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
762 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
768 void tlsconnect(struct server *server, struct timeval *when, char *text) {
772 debug(DBG_DBG, "tlsconnect called from %s", text);
773 pthread_mutex_lock(&server->lock);
774 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
775 /* already reconnected, nothing to do */
776 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
777 pthread_mutex_unlock(&server->lock);
781 debug(DBG_DBG, "tlsconnect %s", text);
784 gettimeofday(&now, NULL);
785 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
786 if (server->connectionok) {
787 server->connectionok = 0;
789 } else if (elapsed < 1)
791 else if (elapsed < 60) {
792 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
794 } else if (elapsed < 100000) {
795 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
798 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
799 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
800 if (server->sock >= 0)
802 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
803 debug(DBG_ERR, "tlsconnect: connecttcp failed");
807 SSL_free(server->ssl);
808 server->ssl = SSL_new(server->conf->ssl_ctx);
809 SSL_set_fd(server->ssl, server->sock);
810 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
813 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
814 gettimeofday(&server->lastconnecttry, NULL);
815 pthread_mutex_unlock(&server->lock);
818 unsigned char *radtlsget(SSL *ssl) {
820 unsigned char buf[4], *rad;
823 for (total = 0; total < 4; total += cnt) {
824 cnt = SSL_read(ssl, buf + total, 4 - total);
826 debug(DBG_ERR, "radtlsget: connection lost");
827 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
828 /* remote end sent close_notify, send one back */
838 debug(DBG_ERR, "radtlsget: malloc failed");
843 for (; total < len; total += cnt) {
844 cnt = SSL_read(ssl, rad + total, len - total);
846 debug(DBG_ERR, "radtlsget: connection lost");
847 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
848 /* remote end sent close_notify, send one back */
860 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
863 debug(DBG_DBG, "radtlsget: got %d bytes", total);
867 int clientradput(struct server *server, unsigned char *rad) {
871 struct timeval lastconnecttry;
872 struct clsrvconf *conf = server->conf;
875 if (conf->type == 'U') {
876 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
877 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
880 debug(DBG_WARN, "clientradput: send failed");
884 lastconnecttry = server->lastconnecttry;
885 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
886 while ((error = ERR_get_error()))
887 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
888 tlsconnect(server, &lastconnecttry, "clientradput");
889 lastconnecttry = server->lastconnecttry;
892 server->connectionok = 1;
893 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
897 int radsign(unsigned char *rad, unsigned char *sec) {
898 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
899 static unsigned char first = 1;
900 static EVP_MD_CTX mdctx;
904 pthread_mutex_lock(&lock);
906 EVP_MD_CTX_init(&mdctx);
910 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
911 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
912 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
913 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
915 pthread_mutex_unlock(&lock);
919 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
920 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
921 static unsigned char first = 1;
922 static EVP_MD_CTX mdctx;
923 unsigned char hash[EVP_MAX_MD_SIZE];
927 pthread_mutex_lock(&lock);
929 EVP_MD_CTX_init(&mdctx);
935 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
936 EVP_DigestUpdate(&mdctx, rad, 4) &&
937 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
938 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
939 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
940 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
942 !memcmp(hash, rad + 4, 16));
943 pthread_mutex_unlock(&lock);
947 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
948 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
949 static unsigned char first = 1;
950 static HMAC_CTX hmacctx;
952 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
954 pthread_mutex_lock(&lock);
956 HMAC_CTX_init(&hmacctx);
960 memcpy(auth, authattr, 16);
961 memset(authattr, 0, 16);
963 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
964 HMAC_Update(&hmacctx, rad, RADLEN(rad));
965 HMAC_Final(&hmacctx, hash, &md_len);
966 memcpy(authattr, auth, 16);
968 debug(DBG_WARN, "message auth computation failed");
969 pthread_mutex_unlock(&lock);
973 if (memcmp(auth, hash, 16)) {
974 debug(DBG_WARN, "message authenticator, wrong value");
975 pthread_mutex_unlock(&lock);
979 pthread_mutex_unlock(&lock);
983 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
984 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
985 static unsigned char first = 1;
986 static HMAC_CTX hmacctx;
992 pthread_mutex_lock(&lock);
994 HMAC_CTX_init(&hmacctx);
998 memset(authattrval, 0, 16);
1000 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1001 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1002 HMAC_Final(&hmacctx, authattrval, &md_len);
1004 debug(DBG_WARN, "message auth computation failed");
1005 pthread_mutex_unlock(&lock);
1009 pthread_mutex_unlock(&lock);
1013 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1014 while (length > 1) {
1015 if (ATTRTYPE(attrs) == type)
1017 length -= ATTRLEN(attrs);
1018 attrs += ATTRLEN(attrs);
1023 void freerqdata(struct request *rq) {
1024 if (rq->origusername)
1025 free(rq->origusername);
1030 void sendrq(struct server *to, struct request *rq) {
1034 pthread_mutex_lock(&to->newrq_mutex);
1035 /* might simplify if only try nextid, might be ok */
1036 for (i = to->nextid; i < MAX_REQUESTS; i++)
1037 if (!to->requests[i].buf)
1039 if (i == MAX_REQUESTS) {
1040 for (i = 0; i < to->nextid; i++)
1041 if (!to->requests[i].buf)
1043 if (i == to->nextid) {
1044 debug(DBG_WARN, "No room in queue, dropping request");
1046 pthread_mutex_unlock(&to->newrq_mutex);
1051 rq->buf[1] = (char)i;
1053 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1054 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1056 pthread_mutex_unlock(&to->newrq_mutex);
1060 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1061 to->requests[i] = *rq;
1066 debug(DBG_DBG, "signalling client writer");
1067 pthread_cond_signal(&to->newrq_cond);
1069 pthread_mutex_unlock(&to->newrq_mutex);
1072 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1073 struct reply *reply;
1076 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1078 debug(DBG_WARN, "sendreply: failed to sign message");
1082 reply = malloc(sizeof(struct reply));
1085 debug(DBG_ERR, "sendreply: malloc failed");
1088 memset(reply, 0, sizeof(struct reply));
1091 reply->tosa = *tosa;
1093 pthread_mutex_lock(&to->replyq->mutex);
1095 first = list_first(to->replyq->replies) == NULL;
1097 if (!list_push(to->replyq->replies, reply)) {
1098 pthread_mutex_unlock(&to->replyq->mutex);
1101 debug(DBG_ERR, "sendreply: malloc failed");
1106 debug(DBG_DBG, "signalling server writer");
1107 pthread_cond_signal(&to->replyq->cond);
1109 pthread_mutex_unlock(&to->replyq->mutex);
1112 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1113 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1114 static unsigned char first = 1;
1115 static EVP_MD_CTX mdctx;
1116 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1117 unsigned int md_len;
1118 uint8_t i, offset = 0, out[128];
1120 pthread_mutex_lock(&lock);
1122 EVP_MD_CTX_init(&mdctx);
1128 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1129 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1130 !EVP_DigestUpdate(&mdctx, input, 16) ||
1131 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1133 pthread_mutex_unlock(&lock);
1136 for (i = 0; i < 16; i++)
1137 out[offset + i] = hash[i] ^ in[offset + i];
1138 input = out + offset - 16;
1143 memcpy(in, out, len);
1144 pthread_mutex_unlock(&lock);
1148 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1149 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1150 static unsigned char first = 1;
1151 static EVP_MD_CTX mdctx;
1152 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1153 unsigned int md_len;
1154 uint8_t i, offset = 0, out[128];
1156 pthread_mutex_lock(&lock);
1158 EVP_MD_CTX_init(&mdctx);
1164 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1165 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1166 !EVP_DigestUpdate(&mdctx, input, 16) ||
1167 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1169 pthread_mutex_unlock(&lock);
1172 for (i = 0; i < 16; i++)
1173 out[offset + i] = hash[i] ^ in[offset + i];
1174 input = in + offset;
1179 memcpy(in, out, len);
1180 pthread_mutex_unlock(&lock);
1184 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1185 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1186 static unsigned char first = 1;
1187 static EVP_MD_CTX mdctx;
1188 unsigned char hash[EVP_MAX_MD_SIZE];
1189 unsigned int md_len;
1192 pthread_mutex_lock(&lock);
1194 EVP_MD_CTX_init(&mdctx);
1199 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1200 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1201 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1204 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1205 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1206 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1207 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1208 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1209 pthread_mutex_unlock(&lock);
1214 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1217 for (i = 0; i < 16; i++)
1220 for (offset = 16; offset < len; offset += 16) {
1222 printf("text + offset - 16 c(%d): ", offset / 16);
1223 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1225 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1226 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1227 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1228 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1230 pthread_mutex_unlock(&lock);
1234 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1237 for (i = 0; i < 16; i++)
1238 text[offset + i] ^= hash[i];
1242 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1245 pthread_mutex_unlock(&lock);
1249 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1250 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1251 static unsigned char first = 1;
1252 static EVP_MD_CTX mdctx;
1253 unsigned char hash[EVP_MAX_MD_SIZE];
1254 unsigned int md_len;
1258 pthread_mutex_lock(&lock);
1260 EVP_MD_CTX_init(&mdctx);
1265 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1266 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1267 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1270 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1271 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1272 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1273 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1274 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1275 pthread_mutex_unlock(&lock);
1280 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1283 for (i = 0; i < 16; i++)
1284 plain[i] = text[i] ^ hash[i];
1286 for (offset = 16; offset < len; offset += 16) {
1288 printf("text + offset - 16 c(%d): ", offset / 16);
1289 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1291 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1292 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1293 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1294 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1296 pthread_mutex_unlock(&lock);
1300 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1303 for (i = 0; i < 16; i++)
1304 plain[offset + i] = text[offset + i] ^ hash[i];
1307 memcpy(text, plain, len);
1309 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1312 pthread_mutex_unlock(&lock);
1316 struct realm *id2realm(char *id, uint8_t len) {
1317 struct list_node *entry;
1318 struct realm *realm;
1320 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1321 realm = (struct realm *)entry->data;
1322 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1323 debug(DBG_DBG, "found matching realm: %s", realm->name);
1330 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1333 pthread_mutex_lock(&to->newrq_mutex);
1334 for (i = 0; i < MAX_REQUESTS; i++)
1335 if (to->requests[i].buf && !to->requests[i].received && to->requests[i].origid == id && to->requests[i].from == from)
1337 pthread_mutex_unlock(&to->newrq_mutex);
1339 return i < MAX_REQUESTS;
1342 int attrvalidate(unsigned char *attrs, int length) {
1343 while (length > 1) {
1344 if (ATTRLEN(attrs) < 2) {
1345 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1348 length -= ATTRLEN(attrs);
1350 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1353 attrs += ATTRLEN(attrs);
1356 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1360 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1361 if (len < 16 || len > 128 || len % 16) {
1362 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1366 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1367 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1371 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1373 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1374 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1380 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1383 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1384 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1387 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1388 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1394 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1395 char *oldsecret, char *newsecret) {
1396 unsigned char *attr;
1398 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1399 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1400 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1406 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1410 for (; attrs[0]; attrs += 2)
1411 if (attrs[0] == vendor && attrs[1] == subattr)
1416 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1417 uint8_t alen, sublen, rmlen = 0;
1418 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1421 if (!removevendorattrs)
1424 while (*removevendorattrs && *removevendorattrs != vendor)
1425 removevendorattrs += 2;
1426 if (!*removevendorattrs)
1429 alen = ATTRLEN(attrs);
1431 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1432 /* remove entire vendor attribute */
1433 memmove(attrs, attrs + alen, length - alen);
1438 subattrs = ATTRVAL(attrs) + 4;
1440 if (!attrvalidate(subattrs, sublen)) {
1441 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1446 while (sublen > 1) {
1447 alen = ATTRLEN(subattrs);
1450 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1451 memmove(subattrs, subattrs + alen, length);
1457 ATTRLEN(attrs) -= rmlen;
1461 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1462 uint8_t *attrs, alen;
1463 uint16_t len, rmlen = 0;
1465 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1468 len = RADLEN(buf) - 20;
1471 alen = ATTRLEN(attrs);
1473 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1474 memmove(attrs, attrs + alen, len);
1476 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1477 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1482 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1485 /* returns a pointer to the resized attribute value */
1486 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1487 uint8_t *attrs, *attr, vallen;
1491 len = RADLEN(*buf) - 20;
1494 attr = attrget(attrs, len, type);
1498 vallen = ATTRVALLEN(attr);
1499 if (vallen == newvallen)
1502 len += newvallen - vallen;
1503 if (newvallen > vallen) {
1504 new = realloc(*buf, len + 20);
1506 debug(DBG_ERR, "resizeattr: malloc failed");
1515 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1516 attr[1] = newvallen + 2;
1517 ((uint16_t *)*buf)[1] = htons(len + 20);
1521 int rewriteusername(struct request *rq, char *in) {
1522 size_t nmatch = 10, reslen = 0, start = 0;
1523 regmatch_t pmatch[10], *pfield;
1525 unsigned char *result;
1526 char *out = rq->from->conf->rewriteattrreplacement;
1528 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1529 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1533 rq->origusername = stringcopy(in, 0);
1534 if (!rq->origusername)
1537 for (i = start; out[i]; i++) {
1538 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1539 pfield = &pmatch[out[i + 1] - '0'];
1540 if (pfield->rm_so >= 0) {
1541 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1547 reslen += i - start;
1549 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1555 for (i = start; out[i]; i++) {
1556 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1557 pfield = &pmatch[out[i + 1] - '0'];
1558 if (pfield->rm_so >= 0) {
1559 memcpy(result + reslen, out + start, i - start);
1560 reslen += i - start;
1561 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1562 reslen += pfield->rm_eo - pfield->rm_so;
1569 memcpy(result + reslen, out + start, i - start);
1570 reslen += i - start;
1571 memcpy(in, result, reslen);
1576 void acclog(unsigned char *attrs, int length, char *host) {
1577 unsigned char *attr;
1580 attr = attrget(attrs, length, RAD_Attr_User_Name);
1582 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1585 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1586 username[ATTRVALLEN(attr)] = '\0';
1587 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1590 void respondaccounting(struct request *rq) {
1591 unsigned char *resp;
1595 debug(DBG_ERR, "respondstatusserver: malloc failed");
1598 memcpy(resp, rq->buf, 20);
1599 resp[0] = RAD_Accounting_Response;
1602 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1603 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1606 void respondstatusserver(struct request *rq) {
1607 unsigned char *resp;
1611 debug(DBG_ERR, "respondstatusserver: malloc failed");
1614 memcpy(resp, rq->buf, 20);
1615 resp[0] = RAD_Access_Accept;
1618 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1619 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1622 void respondreject(struct request *rq, char *message) {
1623 unsigned char *resp;
1626 if (message && *message)
1627 len += 2 + strlen(message);
1631 debug(DBG_ERR, "respondreject: malloc failed");
1634 memcpy(resp, rq->buf, 20);
1635 resp[0] = RAD_Access_Reject;
1636 *(uint16_t *)(resp + 2) = htons(len);
1637 if (message && *message) {
1638 resp[20] = RAD_Attr_Reply_Message;
1639 resp[21] = len - 20;
1640 memcpy(resp + 22, message, len - 22);
1642 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1645 struct server *realm2server(struct realm *realm) {
1646 struct list_node *entry;
1647 struct server *server, *best = NULL, *first = NULL;
1649 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1650 server = ((struct clsrvconf *)entry->data)->servers;
1653 if (!server->connectionok)
1655 if (!server->loststatsrv)
1661 if (server->loststatsrv < best->loststatsrv)
1664 return best ? best : first;
1667 void radsrv(struct request *rq) {
1668 uint8_t code, id, *auth, *attrs, *attr;
1670 struct server *to = NULL;
1672 unsigned char newauth[16];
1673 struct realm *realm = NULL;
1675 code = *(uint8_t *)rq->buf;
1676 id = *(uint8_t *)(rq->buf + 1);
1677 len = RADLEN(rq->buf);
1678 auth = (uint8_t *)(rq->buf + 4);
1680 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1682 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1683 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1689 attrs = rq->buf + 20;
1691 if (!attrvalidate(attrs, len)) {
1692 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1697 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1698 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1699 debug(DBG_WARN, "radsrv: message authentication failed");
1704 if (code != RAD_Access_Request) {
1706 case RAD_Accounting_Request:
1707 /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
1708 acclog(attrs, len, rq->from->conf->host);
1709 respondaccounting(rq);
1711 case RAD_Status_Server:
1712 respondstatusserver(rq);
1719 /* code == RAD_Access_Request */
1720 if (rq->from->conf->rewrite) {
1721 dorewrite(rq->buf, rq->from->conf->rewrite);
1722 len = RADLEN(rq->buf) - 20;
1725 attr = attrget(attrs, len, RAD_Attr_User_Name);
1727 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1731 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1732 username[ATTRVALLEN(attr)] = '\0';
1734 if (rq->from->conf->rewriteattrregex) {
1735 if (!rewriteusername(rq, username)) {
1736 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1740 len = RADLEN(rq->buf) - 20;
1741 auth = (uint8_t *)(rq->buf + 4);
1742 attrs = rq->buf + 20;
1745 if (rq->origusername)
1746 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1748 debug(DBG_DBG, "Access Request with username: %s", username);
1750 realm = id2realm(username, strlen(username));
1752 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1757 to = realm2server(realm);
1758 if (to && rqinqueue(to, rq->from, id)) {
1759 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1765 if (realm->message) {
1766 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1767 respondreject(rq, realm->message);
1773 if (!RAND_bytes(newauth, 16)) {
1774 debug(DBG_WARN, "radsrv: failed to generate random auth");
1780 printfchars(NULL, "auth", "%02x ", auth, 16);
1783 attr = attrget(attrs, len, RAD_Attr_User_Password);
1785 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1786 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1792 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1794 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1795 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1802 memcpy(rq->origauth, auth, 16);
1803 memcpy(auth, newauth, 16);
1807 int replyh(struct server *server, unsigned char *buf) {
1808 struct client *from;
1811 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1812 struct sockaddr_storage fromsa;
1815 server->connectionok = 1;
1816 server->loststatsrv = 0;
1818 i = buf[1]; /* i is the id */
1821 case RAD_Access_Accept:
1822 debug(DBG_DBG, "got Access Accept with id %d", i);
1824 case RAD_Access_Reject:
1825 debug(DBG_DBG, "got Access Reject with id %d", i);
1827 case RAD_Access_Challenge:
1828 debug(DBG_DBG, "got Access Challenge with id %d", i);
1831 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1835 rq = server->requests + i;
1837 pthread_mutex_lock(&server->newrq_mutex);
1838 if (!rq->buf || !rq->tries) {
1839 pthread_mutex_unlock(&server->newrq_mutex);
1840 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1845 pthread_mutex_unlock(&server->newrq_mutex);
1846 debug(DBG_INFO, "replyh: already received, ignoring reply");
1850 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1851 pthread_mutex_unlock(&server->newrq_mutex);
1852 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1856 len = RADLEN(buf) - 20;
1859 if (!attrvalidate(attrs, len)) {
1860 pthread_mutex_unlock(&server->newrq_mutex);
1861 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1865 /* Message Authenticator */
1866 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1868 if (ATTRVALLEN(messageauth) != 16) {
1869 pthread_mutex_unlock(&server->newrq_mutex);
1870 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1873 memcpy(tmp, buf + 4, 16);
1874 memcpy(buf + 4, rq->buf + 4, 16);
1875 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1876 pthread_mutex_unlock(&server->newrq_mutex);
1877 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1880 memcpy(buf + 4, tmp, 16);
1881 debug(DBG_DBG, "replyh: message auth ok");
1884 if (*rq->buf == RAD_Status_Server) {
1886 pthread_mutex_unlock(&server->newrq_mutex);
1887 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1893 pthread_mutex_unlock(&server->newrq_mutex);
1894 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1898 if (server->conf->rewrite) {
1899 dorewrite(buf, server->conf->rewrite);
1900 len = RADLEN(buf) - 20;
1904 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1905 if (ATTRVALLEN(attr) <= 4)
1908 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1911 sublen = ATTRVALLEN(attr) - 4;
1912 subattrs = ATTRVAL(attr) + 4;
1913 if (!attrvalidate(subattrs, sublen) ||
1914 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1915 rq, server->conf->secret, from->conf->secret) ||
1916 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1917 rq, server->conf->secret, from->conf->secret))
1921 pthread_mutex_unlock(&server->newrq_mutex);
1922 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1926 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1927 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1928 /* we know the attribute exists */
1929 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1930 tmp[ATTRVALLEN(attr)] = '\0';
1932 case RAD_Access_Accept:
1933 if (rq->origusername)
1934 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1936 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1938 case RAD_Access_Reject:
1939 if (rq->origusername)
1940 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1942 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1947 buf[1] = (char)rq->origid;
1948 memcpy(buf + 4, rq->origauth, 16);
1950 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1953 if (rq->origusername) {
1954 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1956 pthread_mutex_unlock(&server->newrq_mutex);
1957 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1960 memcpy(username, rq->origusername, strlen(rq->origusername));
1961 len = RADLEN(buf) - 20;
1964 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1968 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1969 pthread_mutex_unlock(&server->newrq_mutex);
1970 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1973 debug(DBG_DBG, "replyh: computed messageauthattr");
1976 if (from->conf->type == 'U')
1977 fromsa = rq->fromsa;
1978 /* once we set received = 1, rq may be reused */
1981 debug(DBG_DBG, "replyh: passing reply to client %s", from->conf->name);
1982 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
1983 pthread_mutex_unlock(&server->newrq_mutex);
1987 void *udpclientrd(void *arg) {
1988 struct server *server;
1990 int *s = (int *)arg;
1994 buf = radudpget(*s, NULL, &server, NULL);
1995 if (!replyh(server, buf))
2000 void *tlsclientrd(void *arg) {
2001 struct server *server = (struct server *)arg;
2003 struct timeval lastconnecttry;
2006 /* yes, lastconnecttry is really necessary */
2007 lastconnecttry = server->lastconnecttry;
2008 buf = radtlsget(server->ssl);
2010 tlsconnect(server, &lastconnecttry, "clientrd");
2014 if (!replyh(server, buf))
2019 void *clientwr(void *arg) {
2020 struct server *server = (struct server *)arg;
2022 pthread_t tlsclientrdth;
2025 struct timeval now, lastsend;
2026 struct timespec timeout;
2027 struct request statsrvrq;
2028 unsigned char statsrvbuf[38];
2030 memset(&timeout, 0, sizeof(struct timespec));
2032 if (server->conf->statusserver) {
2033 memset(&statsrvrq, 0, sizeof(struct request));
2034 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2035 statsrvbuf[0] = RAD_Status_Server;
2037 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2038 statsrvbuf[21] = 18;
2039 gettimeofday(&lastsend, NULL);
2042 if (server->conf->type == 'U') {
2043 server->connectionok = 1;
2045 tlsconnect(server, NULL, "new client");
2046 server->connectionok = 1;
2047 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2048 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2052 pthread_mutex_lock(&server->newrq_mutex);
2053 if (!server->newrq) {
2054 gettimeofday(&now, NULL);
2055 if (server->conf->statusserver) {
2056 /* random 0-7 seconds */
2057 RAND_bytes(&rnd, 1);
2059 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2060 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2062 if (timeout.tv_sec) {
2063 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2064 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2067 debug(DBG_DBG, "clientwr: waiting for new request");
2068 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2071 if (server->newrq) {
2072 debug(DBG_DBG, "clientwr: got new request");
2075 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2076 pthread_mutex_unlock(&server->newrq_mutex);
2078 for (i = 0; i < MAX_REQUESTS; i++) {
2079 pthread_mutex_lock(&server->newrq_mutex);
2080 while (i < MAX_REQUESTS && !server->requests[i].buf)
2082 if (i == MAX_REQUESTS) {
2083 pthread_mutex_unlock(&server->newrq_mutex);
2086 rq = server->requests + i;
2089 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2091 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2093 /* setting this to NULL means that it can be reused */
2096 pthread_mutex_unlock(&server->newrq_mutex);
2100 gettimeofday(&now, NULL);
2101 if (now.tv_sec < rq->expiry.tv_sec) {
2102 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2103 timeout.tv_sec = rq->expiry.tv_sec;
2104 pthread_mutex_unlock(&server->newrq_mutex);
2108 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2109 ? 1 : REQUEST_RETRIES)) {
2110 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2111 if (*rq->buf == RAD_Status_Server) {
2112 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2113 if (server->loststatsrv < 255)
2114 server->loststatsrv++;
2117 /* setting this to NULL means that it can be reused */
2119 pthread_mutex_unlock(&server->newrq_mutex);
2122 pthread_mutex_unlock(&server->newrq_mutex);
2124 rq->expiry.tv_sec = now.tv_sec +
2125 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2126 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2127 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2128 timeout.tv_sec = rq->expiry.tv_sec;
2130 clientradput(server, server->requests[i].buf);
2131 gettimeofday(&lastsend, NULL);
2133 if (server->conf->statusserver) {
2134 gettimeofday(&now, NULL);
2135 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2136 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2137 debug(DBG_WARN, "clientwr: failed to generate random auth");
2140 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2141 if (!statsrvrq.buf) {
2142 debug(DBG_ERR, "clientwr: malloc failed");
2145 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2146 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2147 lastsend.tv_sec = now.tv_sec;
2148 sendrq(server, &statsrvrq);
2154 void *udpserverwr(void *arg) {
2155 struct replyq *replyq = udp_server_replyq;
2156 struct reply *reply;
2159 pthread_mutex_lock(&replyq->mutex);
2160 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2161 debug(DBG_DBG, "udp server writer, waiting for signal");
2162 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2163 debug(DBG_DBG, "udp server writer, got signal");
2165 pthread_mutex_unlock(&replyq->mutex);
2167 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2168 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2169 debug(DBG_WARN, "sendudp: send failed");
2175 void *udpserverrd(void *arg) {
2177 pthread_t udpserverwrth;
2178 struct clsrvconf *listenres;
2180 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2181 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2182 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2184 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2185 listenres->host ? listenres->host : "*", listenres->port);
2188 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2189 debugx(1, DBG_ERR, "pthread_create failed");
2192 memset(&rq, 0, sizeof(struct request));
2193 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2198 void *udpaccserverrd(void *arg) {
2200 struct clsrvconf *listenres;
2202 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2203 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2204 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2206 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2207 listenres->host ? listenres->host : "*", listenres->port);
2211 memset(&rq, 0, sizeof(struct request));
2212 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2213 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2217 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2222 void *tlsserverwr(void *arg) {
2224 unsigned long error;
2225 struct client *client = (struct client *)arg;
2226 struct replyq *replyq;
2227 struct reply *reply;
2229 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2230 replyq = client->replyq;
2232 pthread_mutex_lock(&replyq->mutex);
2233 while (!list_first(replyq->replies)) {
2235 debug(DBG_DBG, "tls server writer, waiting for signal");
2236 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2237 debug(DBG_DBG, "tls server writer, got signal");
2240 /* ssl might have changed while waiting */
2241 pthread_mutex_unlock(&replyq->mutex);
2242 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2246 reply = (struct reply *)list_shift(replyq->replies);
2247 pthread_mutex_unlock(&replyq->mutex);
2248 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2250 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2251 cnt, RADLEN(reply->buf));
2253 while ((error = ERR_get_error()))
2254 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2260 void *tlsserverrd(void *arg) {
2262 unsigned long error;
2264 struct client *client = (struct client *)arg;
2265 pthread_t tlsserverwrth;
2268 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2271 if (SSL_accept(ssl) <= 0) {
2272 while ((error = ERR_get_error()))
2273 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2274 debug(DBG_ERR, "SSL_accept failed");
2277 if (tlsverifycert(client->ssl, client->conf)) {
2278 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2279 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2283 memset(&rq, 0, sizeof(struct request));
2284 rq.buf = radtlsget(client->ssl);
2287 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2291 debug(DBG_ERR, "tlsserverrd: connection lost");
2292 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2294 pthread_mutex_lock(&client->replyq->mutex);
2295 pthread_cond_signal(&client->replyq->cond);
2296 pthread_mutex_unlock(&client->replyq->mutex);
2297 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2298 pthread_join(tlsserverwrth, NULL);
2302 s = SSL_get_fd(ssl);
2304 shutdown(s, SHUT_RDWR);
2306 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2307 removeclientrqs(client);
2308 removeclient(client);
2313 pthread_t tlsserverth;
2315 struct sockaddr_storage from;
2316 size_t fromlen = sizeof(from);
2317 struct clsrvconf *conf;
2318 struct client *client;
2319 struct clsrvconf *listenres;
2321 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2322 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2323 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2326 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2330 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2332 debug(DBG_WARN, "accept failed");
2335 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2337 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2339 debug(DBG_WARN, "ignoring request, not a known TLS client");
2340 shutdown(snew, SHUT_RDWR);
2345 client = addclient(conf);
2348 debug(DBG_WARN, "Failed to create new client instance");
2349 shutdown(snew, SHUT_RDWR);
2353 client->ssl = SSL_new(client->conf->ssl_ctx);
2354 SSL_set_fd(client->ssl, snew);
2355 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2356 debug(DBG_ERR, "tlslistener: pthread_create failed");
2357 SSL_free(client->ssl);
2358 removeclient(client);
2359 shutdown(snew, SHUT_RDWR);
2363 pthread_detach(tlsserverth);
2368 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2371 STACK_OF(X509_NAME) *calist;
2373 unsigned long error;
2375 if (!certfile || !certkeyfile)
2376 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2378 if (!cacertfile && !cacertpath)
2379 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2382 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2383 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2384 for (i = 0; i < CRYPTO_num_locks(); i++) {
2385 ssl_lock_count[i] = 0;
2386 pthread_mutex_init(&ssl_locks[i], NULL);
2388 CRYPTO_set_id_callback(ssl_thread_id);
2389 CRYPTO_set_locking_callback(ssl_locking_callback);
2391 SSL_load_error_strings();
2394 while (!RAND_status()) {
2395 time_t t = time(NULL);
2396 pid_t pid = getpid();
2397 RAND_seed((unsigned char *)&t, sizeof(time_t));
2398 RAND_seed((unsigned char *)&pid, sizeof(pid));
2401 ctx = SSL_CTX_new(TLSv1_method());
2403 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2404 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2406 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2407 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2408 !SSL_CTX_check_private_key(ctx) ||
2409 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2410 while ((error = ERR_get_error()))
2411 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2412 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2415 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2416 if (!cacertfile || calist) {
2419 calist = sk_X509_NAME_new_null();
2420 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2421 sk_X509_NAME_free(calist);
2427 while ((error = ERR_get_error()))
2428 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2429 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2431 SSL_CTX_set_client_CA_list(ctx, calist);
2433 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2434 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2436 new = malloc(sizeof(struct tls));
2437 if (!new || !list_push(tlsconfs, new))
2438 debugx(1, DBG_ERR, "malloc failed");
2440 memset(new, 0, sizeof(struct tls));
2441 new->name = stringcopy(value, 0);
2443 debugx(1, DBG_ERR, "malloc failed");
2446 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2450 struct list_node *entry;
2453 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2454 t = (struct tls *)entry->data;
2458 SSL_CTX_free(t->ctx);
2460 list_destroy(tlsconfs);
2464 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2465 struct list_node *entry;
2466 struct tls *t, *t1 = NULL, *t2 = NULL;
2468 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2469 t = (struct tls *)entry->data;
2470 if (!strcasecmp(t->name, alt1)) {
2474 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2485 void addrealm(char *value, char **servers, char *message) {
2487 struct realm *realm;
2488 char *s, *regex = NULL;
2489 struct list_node *entry;
2490 struct clsrvconf *conf;
2492 if (*value == '/') {
2493 /* regexp, remove optional trailing / if present */
2494 if (value[strlen(value) - 1] == '/')
2495 value[strlen(value) - 1] = '\0';
2497 /* not a regexp, let us make it one */
2498 if (*value == '*' && !value[1])
2499 regex = stringcopy(".*", 0);
2501 for (n = 0, s = value; *s;)
2504 regex = malloc(strlen(value) + n + 3);
2507 for (n = 1, s = value; *s; s++) {
2517 debugx(1, DBG_ERR, "malloc failed");
2518 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2521 realm = malloc(sizeof(struct realm));
2523 debugx(1, DBG_ERR, "malloc failed");
2525 memset(realm, 0, sizeof(struct realm));
2526 realm->name = stringcopy(value, 0);
2528 debugx(1, DBG_ERR, "malloc failed");
2529 if (message && strlen(message) > 253)
2530 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2531 realm->message = message;
2533 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2534 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2538 if (servers && *servers) {
2539 realm->srvconfs = list_create();
2540 if (!realm->srvconfs)
2541 debugx(1, DBG_ERR, "malloc failed");
2542 for (n = 0; servers[n]; n++) {
2543 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2544 conf = (struct clsrvconf *)entry->data;
2545 if (!strcasecmp(servers[n], conf->name))
2549 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2550 if (!list_push(realm->srvconfs, conf))
2551 debugx(1, DBG_ERR, "malloc failed");
2552 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2555 realm->srvconfs = NULL;
2557 if (!list_push(realms, realm))
2558 debugx(1, DBG_ERR, "malloc failed");
2559 debug(DBG_DBG, "addrealm: added realm %s", value);
2562 struct gconffile *openconfigfile(const char *filename) {
2564 char pathname[100], *base = NULL;
2565 struct gconffile *cf = NULL;
2567 f = pushgconffile(&cf, filename);
2569 debug(DBG_DBG, "reading config file %s", filename);
2573 if (strlen(filename) + 1 <= sizeof(pathname)) {
2574 /* basename() might modify the string */
2575 strcpy(pathname, filename);
2576 base = basename(pathname);
2577 f = pushgconffile(&cf, base);
2581 debugx(1, DBG_ERR, "could not read config file %s nor %s\n%s", filename, base, strerror(errno));
2583 debug(DBG_DBG, "reading config file %s", base);
2587 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2590 v = matchcertattr + 20;
2591 if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20) || !*v)
2593 /* regexp, remove optional trailing / if present */
2594 if (v[strlen(v) - 1] == '/')
2595 v[strlen(v) - 1] = '\0';
2599 conf->certuriregex = malloc(sizeof(regex_t));
2600 if (!conf->certuriregex) {
2601 debug(DBG_ERR, "malloc failed");
2604 if (regcomp(conf->certuriregex, v, REG_ICASE | REG_NOSUB)) {
2605 free(conf->certuriregex);
2606 conf->certuriregex = NULL;
2607 debug(DBG_ERR, "failed to compile regular expression %s", v);
2613 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2616 v = rewriteattr + 11;
2617 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2619 /* regexp, remove optional trailing / if present */
2620 if (v[strlen(v) - 1] == '/')
2621 v[strlen(v) - 1] = '\0';
2629 conf->rewriteattrregex = malloc(sizeof(regex_t));
2630 if (!conf->rewriteattrregex) {
2631 debug(DBG_ERR, "malloc failed");
2635 conf->rewriteattrreplacement = stringcopy(w, 0);
2636 if (!conf->rewriteattrreplacement) {
2637 free(conf->rewriteattrregex);
2638 conf->rewriteattrregex = NULL;
2642 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2643 free(conf->rewriteattrregex);
2644 conf->rewriteattrregex = NULL;
2645 free(conf->rewriteattrreplacement);
2646 conf->rewriteattrreplacement = NULL;
2647 debug(DBG_ERR, "failed to compile regular expression %s", v);
2654 /* should accept both names and numeric values, only numeric right now */
2655 uint8_t attrname2val(char *attrname) {
2658 val = atoi(attrname);
2659 return val > 0 && val < 256 ? val : 0;
2662 /* should accept both names and numeric values, only numeric right now */
2663 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2666 *vendor = atoi(attrname);
2667 s = strchr(attrname, ':');
2672 *type = atoi(s + 1);
2673 return *type >= 0 && *type < 256;
2676 void rewritefree() {
2677 struct list_node *entry;
2678 struct rewriteconf *r;
2680 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2681 r = (struct rewriteconf *)entry->data;
2687 list_destroy(rewriteconfs);
2688 rewriteconfs = NULL;
2691 struct rewrite *getrewrite(char *alt1, char *alt2) {
2692 struct list_node *entry;
2693 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2695 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2696 r = (struct rewriteconf *)entry->data;
2697 if (!strcasecmp(r->name, alt1)) {
2701 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2712 void addrewrite(char *value, char **attrs, char **vattrs) {
2713 struct rewriteconf *new;
2714 struct rewrite *rewrite = NULL;
2717 uint32_t *p, *va = NULL;
2721 for (; attrs[n]; n++);
2722 a = malloc((n + 1) * sizeof(uint8_t));
2724 debugx(1, DBG_ERR, "malloc failed");
2726 for (i = 0; i < n; i++)
2727 if (!(a[i] = attrname2val(attrs[i])))
2728 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2734 for (; vattrs[n]; n++);
2735 va = malloc((2 * n + 1) * sizeof(uint32_t));
2737 debugx(1, DBG_ERR, "malloc failed");
2739 for (p = va, i = 0; i < n; i++, p += 2)
2740 if (!vattrname2val(vattrs[i], p, p + 1))
2741 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2746 rewrite = malloc(sizeof(struct rewrite));
2748 debugx(1, DBG_ERR, "malloc failed");
2749 rewrite->removeattrs = a;
2750 rewrite->removevendorattrs = va;
2753 new = malloc(sizeof(struct rewriteconf));
2754 if (!new || !list_push(rewriteconfs, new))
2755 debugx(1, DBG_ERR, "malloc failed");
2757 memset(new, 0, sizeof(struct rewriteconf));
2758 new->name = stringcopy(value, 0);
2760 debugx(1, DBG_ERR, "malloc failed");
2762 new->rewrite = rewrite;
2763 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2766 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2767 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2768 struct clsrvconf *conf;
2770 debug(DBG_DBG, "confclient_cb called for %s", block);
2772 conf = malloc(sizeof(struct clsrvconf));
2773 if (!conf || !list_push(clconfs, conf))
2774 debugx(1, DBG_ERR, "malloc failed");
2775 memset(conf, 0, sizeof(struct clsrvconf));
2777 getgenericconfig(cf, block,
2778 "type", CONF_STR, &type,
2779 "host", CONF_STR, &conf->host,
2780 "secret", CONF_STR, &conf->secret,
2781 "tls", CONF_STR, &tls,
2782 "matchcertificateattribute", CONF_STR, &matchcertattr,
2783 "rewrite", CONF_STR, &rewrite,
2784 "rewriteattribute", CONF_STR, &rewriteattr,
2788 /* leave conf->name to be NULL for clients */
2790 conf->host = stringcopy(val, 0);
2792 if (type && !strcasecmp(type, "udp")) {
2795 } else if (type && !strcasecmp(type, "tls")) {
2796 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2798 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2799 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2800 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2804 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2809 free(matchcertattr);
2811 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2814 if (!addrewriteattr(conf, rewriteattr))
2815 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2819 if (!resolvepeer(conf, 0))
2820 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2822 if (!conf->secret) {
2823 if (conf->type == 'U')
2824 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2825 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2829 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2830 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
2831 struct clsrvconf *conf;
2833 debug(DBG_DBG, "confserver_cb called for %s", block);
2835 conf = malloc(sizeof(struct clsrvconf));
2836 if (!conf || !list_push(srvconfs, conf))
2837 debugx(1, DBG_ERR, "malloc failed");
2838 memset(conf, 0, sizeof(struct clsrvconf));
2840 getgenericconfig(cf, block,
2841 "type", CONF_STR, &type,
2842 "host", CONF_STR, &conf->host,
2843 "port", CONF_STR, &conf->port,
2844 "secret", CONF_STR, &conf->secret,
2845 "tls", CONF_STR, &tls,
2846 "matchcertificateattribute", CONF_STR, &matchcertattr,
2847 "rewrite", CONF_STR, &rewrite,
2848 "StatusServer", CONF_STR, &statusserver,
2852 conf->name = stringcopy(val, 0);
2854 conf->host = stringcopy(val, 0);
2856 if (type && !strcasecmp(type, "udp")) {
2860 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2861 } else if (type && !strcasecmp(type, "tls")) {
2862 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2864 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2865 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2866 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2868 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2872 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2877 free(matchcertattr);
2879 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
2881 if (!resolvepeer(conf, 0))
2882 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2884 if (!conf->secret) {
2885 if (conf->type == 'U')
2886 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2887 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2891 if (!strcasecmp(statusserver, "on"))
2892 conf->statusserver = 1;
2893 else if (strcasecmp(statusserver, "off"))
2894 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2899 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2900 char **servers = NULL, *msg = NULL;
2902 debug(DBG_DBG, "confrealm_cb called for %s", block);
2904 getgenericconfig(cf, block,
2905 "server", CONF_MSTR, &servers,
2906 "ReplyMessage", CONF_STR, &msg,
2910 addrealm(val, servers, msg);
2914 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2915 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2917 debug(DBG_DBG, "conftls_cb called for %s", block);
2919 getgenericconfig(cf, block,
2920 "CACertificateFile", CONF_STR, &cacertfile,
2921 "CACertificatePath", CONF_STR, &cacertpath,
2922 "CertificateFile", CONF_STR, &certfile,
2923 "CertificateKeyFile", CONF_STR, &certkeyfile,
2924 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2928 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2936 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2937 char **attrs = NULL, **vattrs = NULL;
2939 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2941 getgenericconfig(cf, block,
2942 "removeAttribute", CONF_MSTR, &attrs,
2943 "removeVendorAttribute", CONF_MSTR, &vattrs,
2946 addrewrite(val, attrs, vattrs);
2951 void getmainconfig(const char *configfile) {
2952 char *loglevel = NULL;
2953 struct gconffile *cfs;
2955 cfs = openconfigfile(configfile);
2956 memset(&options, 0, sizeof(options));
2958 clconfs = list_create();
2960 debugx(1, DBG_ERR, "malloc failed");
2962 srvconfs = list_create();
2964 debugx(1, DBG_ERR, "malloc failed");
2966 realms = list_create();
2968 debugx(1, DBG_ERR, "malloc failed");
2970 tlsconfs = list_create();
2972 debugx(1, DBG_ERR, "malloc failed");
2974 rewriteconfs = list_create();
2976 debugx(1, DBG_ERR, "malloc failed");
2978 getgenericconfig(&cfs, NULL,
2979 "ListenUDP", CONF_STR, &options.listenudp,
2980 "ListenTCP", CONF_STR, &options.listentcp,
2981 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2982 "SourceUDP", CONF_STR, &options.sourceudp,
2983 "SourceTCP", CONF_STR, &options.sourcetcp,
2984 "LogLevel", CONF_STR, &loglevel,
2985 "LogDestination", CONF_STR, &options.logdestination,
2986 "Client", CONF_CBK, confclient_cb,
2987 "Server", CONF_CBK, confserver_cb,
2988 "Realm", CONF_CBK, confrealm_cb,
2989 "TLS", CONF_CBK, conftls_cb,
2990 "Rewrite", CONF_CBK, confrewrite_cb,
2998 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
2999 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3000 options.loglevel = *loglevel - '0';
3005 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3008 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3011 *configfile = optarg;
3014 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3015 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3016 *loglevel = *optarg - '0';
3025 debugx(0, DBG_ERR, "radsecproxy 1.1-prebeta");
3030 if (!(argc - optind))
3034 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3039 int daemon(int a, int b) {
3047 for (i = 0; i < 3; i++) {
3049 open("/dev/null", O_RDWR);
3055 void *sighandler(void *arg) {
3060 sigemptyset(&sigset);
3061 sigaddset(&sigset, SIGPIPE);
3062 sigwait(&sigset, &sig);
3063 /* only get SIGPIPE right now, so could simplify below code */
3066 /* completely ignoring this */
3069 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3072 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3077 int main(int argc, char **argv) {
3078 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3080 struct list_node *entry;
3081 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3082 char *configfile = NULL;
3084 debug_init("radsecproxy");
3085 debug_set_level(DEBUG_LEVEL);
3086 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3088 debug_set_level(loglevel);
3089 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3091 options.loglevel = loglevel;
3092 else if (options.loglevel)
3093 debug_set_level(options.loglevel);
3095 options.logdestination = NULL;
3097 if (!options.logdestination)
3098 options.logdestination = "x-syslog:///";
3099 debug_set_destination(options.logdestination);
3103 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3105 if (!list_first(clconfs))
3106 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3107 if (!list_first(srvconfs))
3108 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3109 if (!list_first(realms))
3110 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3112 if (!foreground && (daemon(0, 0) < 0))
3113 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3115 debug(DBG_INFO, "radsecproxy 1.1-prebeta starting");
3117 sigemptyset(&sigset);
3118 /* exit on all but SIGPIPE, ignore more? */
3119 sigaddset(&sigset, SIGPIPE);
3120 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3121 pthread_create(&sigth, NULL, sighandler, NULL);
3123 if (client_udp_count) {
3124 udp_server_replyq = newreplyq();
3125 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3126 debugx(1, DBG_ERR, "pthread_create failed");
3127 if (options.listenaccudp)
3128 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3129 debugx(1, DBG_ERR, "pthread_create failed");
3132 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3133 addserver((struct clsrvconf *)entry->data);
3134 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3135 (void *)((struct clsrvconf *)entry->data)->servers))
3136 debugx(1, DBG_ERR, "pthread_create failed");
3138 /* srcudpres no longer needed, while srctcpres is needed later */
3143 if (udp_client4_sock >= 0)
3144 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3145 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3146 if (udp_client6_sock >= 0)
3147 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3148 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3150 if (client_tls_count)
3151 return tlslistener();
3153 /* just hang around doing nothing, anything to do here? */