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 cnregexp(X509 *cert, char *exact, regex_t *regex) {
642 nm = X509_get_subject_name(cert);
645 loc = X509_NAME_get_index_by_NID(nm, NID_commonName, loc);
648 e = X509_NAME_get_entry(nm, loc);
649 t = X509_NAME_ENTRY_get_data(e);
650 v = (char *) ASN1_STRING_data(t);
651 l = ASN1_STRING_length(t);
655 if (l == strlen(exact) && !strncasecmp(exact, v, l))
658 s = stringcopy((char *)v, l);
660 debug(DBG_ERR, "malloc failed");
663 if (regexec(regex, s, 0, NULL, 0)) {
674 int subjectaltnameregexp(X509 *cert, int type, char *exact, regex_t *regex) {
675 int loc, i, l, n, r = 0;
678 STACK_OF(GENERAL_NAME) *alt;
681 debug(DBG_DBG, "subjectaltnameregexp");
683 loc = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
687 ex = X509_get_ext(cert, loc);
688 alt = X509V3_EXT_d2i(ex);
692 n = sk_GENERAL_NAME_num(alt);
693 for (i = 0; i < n; i++) {
694 gn = sk_GENERAL_NAME_value(alt, i);
695 if (gn->type != type)
698 v = (char *)ASN1_STRING_data(gn->d.ia5);
699 l = ASN1_STRING_length(gn->d.ia5);
703 printfchars(NULL, gn->type == GEN_DNS ? "dns" : "uri", NULL, v, l);
706 if (memcmp(v, exact, l))
709 s = stringcopy((char *)v, l);
711 debug(DBG_ERR, "malloc failed");
714 if (regexec(regex, s, 0, NULL, 0)) {
723 GENERAL_NAMES_free(alt);
727 int tlsverifycert(SSL *ssl, struct clsrvconf *conf) {
730 uint8_t type = 0; /* 0 for DNS, AF_INET for IPv4, AF_INET6 for IPv6 */
732 struct in6_addr addr;
734 if (SSL_get_verify_result(ssl) != X509_V_OK) {
735 debug(DBG_ERR, "tlsverifycert: basic validation failed");
736 while ((error = ERR_get_error()))
737 debug(DBG_ERR, "tlsverifycert: TLS: %s", ERR_error_string(error, NULL));
741 cert = SSL_get_peer_certificate(ssl);
743 debug(DBG_ERR, "tlsverifycert: failed to obtain certificate");
747 if (conf->prefixlen == 255) {
748 if (inet_pton(AF_INET, conf->host, &addr))
750 else if (inet_pton(AF_INET6, conf->host, &addr))
753 r = type ? subjectaltnameaddr(cert, type, &addr) : subjectaltnameregexp(cert, GEN_DNS, conf->host, NULL);
756 debug(DBG_DBG, "tlsverifycert: No subjectaltname matching %s %s", type ? "address" : "host", conf->host);
759 debug(DBG_DBG, "tlsverifycert: Found subjectaltname matching %s %s", type ? "address" : "host", conf->host);
761 if (!cnregexp(cert, conf->host, NULL)) {
762 debug(DBG_ERR, "tlsverifycert: cn not matching host %s", conf->host);
765 debug(DBG_DBG, "tlsverifycert: Found cn matching host %s", conf->host);
768 if (conf->certcnregex) {
769 if (cnregexp(cert, NULL, conf->certcnregex) < 1) {
770 debug(DBG_DBG, "tlsverifycert: CN not matching regex");
773 debug(DBG_DBG, "tlsverifycert: CN matching regex");
775 if (conf->certuriregex) {
776 if (subjectaltnameregexp(cert, GEN_URI, NULL, conf->certuriregex) < 1) {
777 debug(DBG_DBG, "tlsverifycert: subjectaltname URI not matching regex");
780 debug(DBG_DBG, "tlsverifycert: subjectaltname URI matching regex");
790 void tlsconnect(struct server *server, struct timeval *when, char *text) {
794 debug(DBG_DBG, "tlsconnect called from %s", text);
795 pthread_mutex_lock(&server->lock);
796 if (when && memcmp(&server->lastconnecttry, when, sizeof(struct timeval))) {
797 /* already reconnected, nothing to do */
798 debug(DBG_DBG, "tlsconnect(%s): seems already reconnected", text);
799 pthread_mutex_unlock(&server->lock);
803 debug(DBG_DBG, "tlsconnect %s", text);
806 gettimeofday(&now, NULL);
807 elapsed = now.tv_sec - server->lastconnecttry.tv_sec;
808 if (server->connectionok) {
809 server->connectionok = 0;
811 } else if (elapsed < 1)
813 else if (elapsed < 60) {
814 debug(DBG_INFO, "tlsconnect: sleeping %lds", elapsed);
816 } else if (elapsed < 100000) {
817 debug(DBG_INFO, "tlsconnect: sleeping %ds", 60);
820 server->lastconnecttry.tv_sec = now.tv_sec; /* no sleep at startup */
821 debug(DBG_WARN, "tlsconnect: trying to open TLS connection to %s port %s", server->conf->host, server->conf->port);
822 if (server->sock >= 0)
824 if ((server->sock = connecttcp(server->conf->addrinfo)) < 0) {
825 debug(DBG_ERR, "tlsconnect: connecttcp failed");
829 SSL_free(server->ssl);
830 server->ssl = SSL_new(server->conf->ssl_ctx);
831 SSL_set_fd(server->ssl, server->sock);
832 if (SSL_connect(server->ssl) > 0 && tlsverifycert(server->ssl, server->conf))
835 debug(DBG_WARN, "tlsconnect: TLS connection to %s port %s up", server->conf->host, server->conf->port);
836 gettimeofday(&server->lastconnecttry, NULL);
837 pthread_mutex_unlock(&server->lock);
840 unsigned char *radtlsget(SSL *ssl) {
842 unsigned char buf[4], *rad;
845 for (total = 0; total < 4; total += cnt) {
846 cnt = SSL_read(ssl, buf + total, 4 - total);
848 debug(DBG_ERR, "radtlsget: connection lost");
849 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
850 /* remote end sent close_notify, send one back */
860 debug(DBG_ERR, "radtlsget: malloc failed");
865 for (; total < len; total += cnt) {
866 cnt = SSL_read(ssl, rad + total, len - total);
868 debug(DBG_ERR, "radtlsget: connection lost");
869 if (SSL_get_error(ssl, cnt) == SSL_ERROR_ZERO_RETURN) {
870 /* remote end sent close_notify, send one back */
882 debug(DBG_WARN, "radtlsget: packet smaller than minimum radius size");
885 debug(DBG_DBG, "radtlsget: got %d bytes", total);
889 int clientradput(struct server *server, unsigned char *rad) {
893 struct timeval lastconnecttry;
894 struct clsrvconf *conf = server->conf;
897 if (conf->type == 'U') {
898 if (sendto(server->sock, rad, len, 0, conf->addrinfo->ai_addr, conf->addrinfo->ai_addrlen) >= 0) {
899 debug(DBG_DBG, "clienradput: sent UDP of length %d to %s port %s", len, conf->host, conf->port);
902 debug(DBG_WARN, "clientradput: send failed");
906 lastconnecttry = server->lastconnecttry;
907 while ((cnt = SSL_write(server->ssl, rad, len)) <= 0) {
908 while ((error = ERR_get_error()))
909 debug(DBG_ERR, "clientradput: TLS: %s", ERR_error_string(error, NULL));
910 tlsconnect(server, &lastconnecttry, "clientradput");
911 lastconnecttry = server->lastconnecttry;
914 server->connectionok = 1;
915 debug(DBG_DBG, "clientradput: Sent %d bytes, Radius packet of length %d to TLS peer %s", cnt, len, conf->host);
919 int radsign(unsigned char *rad, unsigned char *sec) {
920 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
921 static unsigned char first = 1;
922 static EVP_MD_CTX mdctx;
926 pthread_mutex_lock(&lock);
928 EVP_MD_CTX_init(&mdctx);
932 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
933 EVP_DigestUpdate(&mdctx, rad, RADLEN(rad)) &&
934 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
935 EVP_DigestFinal_ex(&mdctx, rad + 4, &md_len) &&
937 pthread_mutex_unlock(&lock);
941 int validauth(unsigned char *rad, unsigned char *reqauth, unsigned char *sec) {
942 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
943 static unsigned char first = 1;
944 static EVP_MD_CTX mdctx;
945 unsigned char hash[EVP_MAX_MD_SIZE];
949 pthread_mutex_lock(&lock);
951 EVP_MD_CTX_init(&mdctx);
957 result = (EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) &&
958 EVP_DigestUpdate(&mdctx, rad, 4) &&
959 EVP_DigestUpdate(&mdctx, reqauth, 16) &&
960 (len <= 20 || EVP_DigestUpdate(&mdctx, rad + 20, len - 20)) &&
961 EVP_DigestUpdate(&mdctx, sec, strlen((char *)sec)) &&
962 EVP_DigestFinal_ex(&mdctx, hash, &len) &&
964 !memcmp(hash, rad + 4, 16));
965 pthread_mutex_unlock(&lock);
969 int checkmessageauth(unsigned char *rad, uint8_t *authattr, char *secret) {
970 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
971 static unsigned char first = 1;
972 static HMAC_CTX hmacctx;
974 uint8_t auth[16], hash[EVP_MAX_MD_SIZE];
976 pthread_mutex_lock(&lock);
978 HMAC_CTX_init(&hmacctx);
982 memcpy(auth, authattr, 16);
983 memset(authattr, 0, 16);
985 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
986 HMAC_Update(&hmacctx, rad, RADLEN(rad));
987 HMAC_Final(&hmacctx, hash, &md_len);
988 memcpy(authattr, auth, 16);
990 debug(DBG_WARN, "message auth computation failed");
991 pthread_mutex_unlock(&lock);
995 if (memcmp(auth, hash, 16)) {
996 debug(DBG_WARN, "message authenticator, wrong value");
997 pthread_mutex_unlock(&lock);
1001 pthread_mutex_unlock(&lock);
1005 int createmessageauth(unsigned char *rad, unsigned char *authattrval, char *secret) {
1006 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1007 static unsigned char first = 1;
1008 static HMAC_CTX hmacctx;
1009 unsigned int md_len;
1014 pthread_mutex_lock(&lock);
1016 HMAC_CTX_init(&hmacctx);
1020 memset(authattrval, 0, 16);
1022 HMAC_Init_ex(&hmacctx, secret, strlen(secret), EVP_md5(), NULL);
1023 HMAC_Update(&hmacctx, rad, RADLEN(rad));
1024 HMAC_Final(&hmacctx, authattrval, &md_len);
1026 debug(DBG_WARN, "message auth computation failed");
1027 pthread_mutex_unlock(&lock);
1031 pthread_mutex_unlock(&lock);
1035 unsigned char *attrget(unsigned char *attrs, int length, uint8_t type) {
1036 while (length > 1) {
1037 if (ATTRTYPE(attrs) == type)
1039 length -= ATTRLEN(attrs);
1040 attrs += ATTRLEN(attrs);
1045 void freerqdata(struct request *rq) {
1046 if (rq->origusername)
1047 free(rq->origusername);
1052 void sendrq(struct server *to, struct request *rq) {
1056 pthread_mutex_lock(&to->newrq_mutex);
1057 /* might simplify if only try nextid, might be ok */
1058 for (i = to->nextid; i < MAX_REQUESTS; i++)
1059 if (!to->requests[i].buf)
1061 if (i == MAX_REQUESTS) {
1062 for (i = 0; i < to->nextid; i++)
1063 if (!to->requests[i].buf)
1065 if (i == to->nextid) {
1066 debug(DBG_WARN, "No room in queue, dropping request");
1068 pthread_mutex_unlock(&to->newrq_mutex);
1073 rq->buf[1] = (char)i;
1075 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_Message_Authenticator);
1076 if (attr && !createmessageauth(rq->buf, ATTRVAL(attr), to->conf->secret)) {
1078 pthread_mutex_unlock(&to->newrq_mutex);
1082 debug(DBG_DBG, "sendrq: inserting packet with id %d in queue for %s", i, to->conf->host);
1083 to->requests[i] = *rq;
1088 debug(DBG_DBG, "signalling client writer");
1089 pthread_cond_signal(&to->newrq_cond);
1091 pthread_mutex_unlock(&to->newrq_mutex);
1094 void sendreply(struct client *to, unsigned char *buf, struct sockaddr_storage *tosa) {
1095 struct reply *reply;
1098 if (!radsign(buf, (unsigned char *)to->conf->secret)) {
1100 debug(DBG_WARN, "sendreply: failed to sign message");
1104 reply = malloc(sizeof(struct reply));
1107 debug(DBG_ERR, "sendreply: malloc failed");
1110 memset(reply, 0, sizeof(struct reply));
1113 reply->tosa = *tosa;
1115 pthread_mutex_lock(&to->replyq->mutex);
1117 first = list_first(to->replyq->replies) == NULL;
1119 if (!list_push(to->replyq->replies, reply)) {
1120 pthread_mutex_unlock(&to->replyq->mutex);
1123 debug(DBG_ERR, "sendreply: malloc failed");
1128 debug(DBG_DBG, "signalling server writer");
1129 pthread_cond_signal(&to->replyq->cond);
1131 pthread_mutex_unlock(&to->replyq->mutex);
1134 int pwdencrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1135 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1136 static unsigned char first = 1;
1137 static EVP_MD_CTX mdctx;
1138 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1139 unsigned int md_len;
1140 uint8_t i, offset = 0, out[128];
1142 pthread_mutex_lock(&lock);
1144 EVP_MD_CTX_init(&mdctx);
1150 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1151 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1152 !EVP_DigestUpdate(&mdctx, input, 16) ||
1153 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1155 pthread_mutex_unlock(&lock);
1158 for (i = 0; i < 16; i++)
1159 out[offset + i] = hash[i] ^ in[offset + i];
1160 input = out + offset - 16;
1165 memcpy(in, out, len);
1166 pthread_mutex_unlock(&lock);
1170 int pwddecrypt(uint8_t *in, uint8_t len, char *shared, uint8_t sharedlen, uint8_t *auth) {
1171 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1172 static unsigned char first = 1;
1173 static EVP_MD_CTX mdctx;
1174 unsigned char hash[EVP_MAX_MD_SIZE], *input;
1175 unsigned int md_len;
1176 uint8_t i, offset = 0, out[128];
1178 pthread_mutex_lock(&lock);
1180 EVP_MD_CTX_init(&mdctx);
1186 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1187 !EVP_DigestUpdate(&mdctx, (uint8_t *)shared, sharedlen) ||
1188 !EVP_DigestUpdate(&mdctx, input, 16) ||
1189 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1191 pthread_mutex_unlock(&lock);
1194 for (i = 0; i < 16; i++)
1195 out[offset + i] = hash[i] ^ in[offset + i];
1196 input = in + offset;
1201 memcpy(in, out, len);
1202 pthread_mutex_unlock(&lock);
1206 int msmppencrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1207 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1208 static unsigned char first = 1;
1209 static EVP_MD_CTX mdctx;
1210 unsigned char hash[EVP_MAX_MD_SIZE];
1211 unsigned int md_len;
1214 pthread_mutex_lock(&lock);
1216 EVP_MD_CTX_init(&mdctx);
1221 printfchars(NULL, "msppencrypt auth in", "%02x ", auth, 16);
1222 printfchars(NULL, "msppencrypt salt in", "%02x ", salt, 2);
1223 printfchars(NULL, "msppencrypt in", "%02x ", text, len);
1226 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1227 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1228 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1229 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1230 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1231 pthread_mutex_unlock(&lock);
1236 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1239 for (i = 0; i < 16; i++)
1242 for (offset = 16; offset < len; offset += 16) {
1244 printf("text + offset - 16 c(%d): ", offset / 16);
1245 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1247 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1248 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1249 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1250 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1252 pthread_mutex_unlock(&lock);
1256 printfchars(NULL, "msppencrypt hash", "%02x ", hash, 16);
1259 for (i = 0; i < 16; i++)
1260 text[offset + i] ^= hash[i];
1264 printfchars(NULL, "msppencrypt out", "%02x ", text, len);
1267 pthread_mutex_unlock(&lock);
1271 int msmppdecrypt(uint8_t *text, uint8_t len, uint8_t *shared, uint8_t sharedlen, uint8_t *auth, uint8_t *salt) {
1272 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
1273 static unsigned char first = 1;
1274 static EVP_MD_CTX mdctx;
1275 unsigned char hash[EVP_MAX_MD_SIZE];
1276 unsigned int md_len;
1280 pthread_mutex_lock(&lock);
1282 EVP_MD_CTX_init(&mdctx);
1287 printfchars(NULL, "msppdecrypt auth in", "%02x ", auth, 16);
1288 printfchars(NULL, "msppdecrypt salt in", "%02x ", salt, 2);
1289 printfchars(NULL, "msppdecrypt in", "%02x ", text, len);
1292 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1293 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1294 !EVP_DigestUpdate(&mdctx, auth, 16) ||
1295 !EVP_DigestUpdate(&mdctx, salt, 2) ||
1296 !EVP_DigestFinal_ex(&mdctx, hash, &md_len)) {
1297 pthread_mutex_unlock(&lock);
1302 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1305 for (i = 0; i < 16; i++)
1306 plain[i] = text[i] ^ hash[i];
1308 for (offset = 16; offset < len; offset += 16) {
1310 printf("text + offset - 16 c(%d): ", offset / 16);
1311 printfchars(NULL, NULL, "%02x ", text + offset - 16, 16);
1313 if (!EVP_DigestInit_ex(&mdctx, EVP_md5(), NULL) ||
1314 !EVP_DigestUpdate(&mdctx, shared, sharedlen) ||
1315 !EVP_DigestUpdate(&mdctx, text + offset - 16, 16) ||
1316 !EVP_DigestFinal_ex(&mdctx, hash, &md_len) ||
1318 pthread_mutex_unlock(&lock);
1322 printfchars(NULL, "msppdecrypt hash", "%02x ", hash, 16);
1325 for (i = 0; i < 16; i++)
1326 plain[offset + i] = text[offset + i] ^ hash[i];
1329 memcpy(text, plain, len);
1331 printfchars(NULL, "msppdecrypt out", "%02x ", text, len);
1334 pthread_mutex_unlock(&lock);
1338 struct realm *id2realm(char *id, uint8_t len) {
1339 struct list_node *entry;
1340 struct realm *realm;
1342 for (entry = list_first(realms); entry; entry = list_next(entry)) {
1343 realm = (struct realm *)entry->data;
1344 if (!regexec(&realm->regex, id, 0, NULL, 0)) {
1345 debug(DBG_DBG, "found matching realm: %s", realm->name);
1352 int rqinqueue(struct server *to, struct client *from, uint8_t id) {
1355 pthread_mutex_lock(&to->newrq_mutex);
1356 for (i = 0; i < MAX_REQUESTS; i++)
1357 if (to->requests[i].buf && to->requests[i].origid == id && to->requests[i].from == from)
1359 pthread_mutex_unlock(&to->newrq_mutex);
1361 return i < MAX_REQUESTS;
1364 int attrvalidate(unsigned char *attrs, int length) {
1365 while (length > 1) {
1366 if (ATTRLEN(attrs) < 2) {
1367 debug(DBG_WARN, "attrvalidate: invalid attribute length %d", ATTRLEN(attrs));
1370 length -= ATTRLEN(attrs);
1372 debug(DBG_WARN, "attrvalidate: attribute length %d exceeds packet length", ATTRLEN(attrs));
1375 attrs += ATTRLEN(attrs);
1378 debug(DBG_WARN, "attrvalidate: malformed packet? remaining byte after last attribute");
1382 int pwdrecrypt(uint8_t *pwd, uint8_t len, char *oldsecret, char *newsecret, uint8_t *oldauth, uint8_t *newauth) {
1383 if (len < 16 || len > 128 || len % 16) {
1384 debug(DBG_WARN, "pwdrecrypt: invalid password length");
1388 if (!pwddecrypt(pwd, len, oldsecret, strlen(oldsecret), oldauth)) {
1389 debug(DBG_WARN, "pwdrecrypt: cannot decrypt password");
1393 printfchars(NULL, "pwdrecrypt: password", "%02x ", pwd, len);
1395 if (!pwdencrypt(pwd, len, newsecret, strlen(newsecret), newauth)) {
1396 debug(DBG_WARN, "pwdrecrypt: cannot encrypt password");
1402 int msmpprecrypt(uint8_t *msmpp, uint8_t len, char *oldsecret, char *newsecret, unsigned char *oldauth, char *newauth) {
1405 if (!msmppdecrypt(msmpp + 2, len - 2, (unsigned char *)oldsecret, strlen(oldsecret), oldauth, msmpp)) {
1406 debug(DBG_WARN, "msmpprecrypt: failed to decrypt msppe key");
1409 if (!msmppencrypt(msmpp + 2, len - 2, (unsigned char *)newsecret, strlen(newsecret), (unsigned char *)newauth, msmpp)) {
1410 debug(DBG_WARN, "msmpprecrypt: failed to encrypt msppe key");
1416 int msmppe(unsigned char *attrs, int length, uint8_t type, char *attrtxt, struct request *rq,
1417 char *oldsecret, char *newsecret) {
1418 unsigned char *attr;
1420 for (attr = attrs; (attr = attrget(attr, length - (attr - attrs), type)); attr += ATTRLEN(attr)) {
1421 debug(DBG_DBG, "msmppe: Got %s", attrtxt);
1422 if (!msmpprecrypt(ATTRVAL(attr), ATTRVALLEN(attr), oldsecret, newsecret, rq->buf + 4, rq->origauth))
1428 int findvendorsubattr(uint32_t *attrs, uint32_t vendor, uint8_t subattr) {
1432 for (; attrs[0]; attrs += 2)
1433 if (attrs[0] == vendor && attrs[1] == subattr)
1438 int dovendorrewrite(uint8_t *attrs, uint16_t length, uint32_t *removevendorattrs) {
1439 uint8_t alen, sublen, rmlen = 0;
1440 uint32_t vendor = *(uint32_t *)ATTRVAL(attrs);
1443 if (!removevendorattrs)
1446 while (*removevendorattrs && *removevendorattrs != vendor)
1447 removevendorattrs += 2;
1448 if (!*removevendorattrs)
1451 alen = ATTRLEN(attrs);
1453 if (findvendorsubattr(removevendorattrs, vendor, -1)) {
1454 /* remove entire vendor attribute */
1455 memmove(attrs, attrs + alen, length - alen);
1460 subattrs = ATTRVAL(attrs) + 4;
1462 if (!attrvalidate(subattrs, sublen)) {
1463 debug(DBG_WARN, "dovendorrewrite: vendor attribute validation failed, no rewrite");
1468 while (sublen > 1) {
1469 alen = ATTRLEN(subattrs);
1472 if (findvendorsubattr(removevendorattrs, vendor, ATTRTYPE(subattrs))) {
1473 memmove(subattrs, subattrs + alen, length);
1479 ATTRLEN(attrs) -= rmlen;
1483 void dorewrite(uint8_t *buf, struct rewrite *rewrite) {
1484 uint8_t *attrs, alen;
1485 uint16_t len, rmlen = 0;
1487 if (!rewrite || (!rewrite->removeattrs && !rewrite->removevendorattrs))
1490 len = RADLEN(buf) - 20;
1493 alen = ATTRLEN(attrs);
1495 if (rewrite->removeattrs && strchr((char *)rewrite->removeattrs, ATTRTYPE(attrs))) {
1496 memmove(attrs, attrs + alen, len);
1498 } else if (ATTRTYPE(attrs) == RAD_Attr_Vendor_Specific && rewrite->removevendorattrs)
1499 rmlen += dovendorrewrite(attrs, len, rewrite->removevendorattrs);
1504 ((uint16_t *)buf)[1] = htons(RADLEN(buf) - rmlen);
1507 /* returns a pointer to the resized attribute value */
1508 uint8_t *resizeattr(uint8_t **buf, uint8_t newvallen, uint8_t type) {
1509 uint8_t *attrs, *attr, vallen;
1513 len = RADLEN(*buf) - 20;
1516 attr = attrget(attrs, len, type);
1520 vallen = ATTRVALLEN(attr);
1521 if (vallen == newvallen)
1524 len += newvallen - vallen;
1525 if (newvallen > vallen) {
1526 new = realloc(*buf, len + 20);
1528 debug(DBG_ERR, "resizeattr: malloc failed");
1537 memmove(attr + 2 + newvallen, attr + 2 + vallen, len - (attr - attrs + newvallen));
1538 attr[1] = newvallen + 2;
1539 ((uint16_t *)*buf)[1] = htons(len + 20);
1543 int rewriteusername(struct request *rq, char *in) {
1544 size_t nmatch = 10, reslen = 0, start = 0;
1545 regmatch_t pmatch[10], *pfield;
1547 unsigned char *result;
1548 char *out = rq->from->conf->rewriteattrreplacement;
1550 if (regexec(rq->from->conf->rewriteattrregex, in, nmatch, pmatch, 0)) {
1551 debug(DBG_DBG, "rewriteattr: username not matching, no rewrite");
1555 rq->origusername = stringcopy(in, 0);
1556 if (!rq->origusername)
1559 for (i = start; out[i]; i++) {
1560 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1561 pfield = &pmatch[out[i + 1] - '0'];
1562 if (pfield->rm_so >= 0) {
1563 reslen += i - start + pfield->rm_eo - pfield->rm_so;
1569 reslen += i - start;
1571 result = resizeattr(&rq->buf, reslen, RAD_Attr_User_Name);
1577 for (i = start; out[i]; i++) {
1578 if (out[i] == '\\' && out[i + 1] >= '1' && out[i + 1] <= '9') {
1579 pfield = &pmatch[out[i + 1] - '0'];
1580 if (pfield->rm_so >= 0) {
1581 memcpy(result + reslen, out + start, i - start);
1582 reslen += i - start;
1583 memcpy(result + reslen, in + pfield->rm_so, pfield->rm_eo - pfield->rm_so);
1584 reslen += pfield->rm_eo - pfield->rm_so;
1591 memcpy(result + reslen, out + start, i - start);
1592 reslen += i - start;
1593 memcpy(in, result, reslen);
1598 void acclog(unsigned char *attrs, int length, char *host) {
1599 unsigned char *attr;
1602 attr = attrget(attrs, length, RAD_Attr_User_Name);
1604 debug(DBG_INFO, "acclog: accounting-request from %s without username attribute", host);
1607 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1608 username[ATTRVALLEN(attr)] = '\0';
1609 debug(DBG_INFO, "acclog: accounting-request from %s with username: %s", host, username);
1612 void respondaccounting(struct request *rq) {
1613 unsigned char *resp;
1617 debug(DBG_ERR, "respondstatusserver: malloc failed");
1620 memcpy(resp, rq->buf, 20);
1621 resp[0] = RAD_Accounting_Response;
1624 debug(DBG_DBG, "respondaccounting: responding to %s", rq->from->conf->host);
1625 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1628 void respondstatusserver(struct request *rq) {
1629 unsigned char *resp;
1633 debug(DBG_ERR, "respondstatusserver: malloc failed");
1636 memcpy(resp, rq->buf, 20);
1637 resp[0] = RAD_Access_Accept;
1640 debug(DBG_DBG, "respondstatusserver: responding to %s", rq->from->conf->host);
1641 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1644 void respondreject(struct request *rq, char *message) {
1645 unsigned char *resp;
1648 if (message && *message)
1649 len += 2 + strlen(message);
1653 debug(DBG_ERR, "respondreject: malloc failed");
1656 memcpy(resp, rq->buf, 20);
1657 resp[0] = RAD_Access_Reject;
1658 *(uint16_t *)(resp + 2) = htons(len);
1659 if (message && *message) {
1660 resp[20] = RAD_Attr_Reply_Message;
1661 resp[21] = len - 20;
1662 memcpy(resp + 22, message, len - 22);
1664 sendreply(rq->from, resp, rq->from->conf->type == 'U' ? &rq->fromsa : NULL);
1667 struct server *realm2server(struct realm *realm) {
1668 struct list_node *entry;
1669 struct server *server, *best = NULL, *first = NULL;
1671 for (entry = list_first(realm->srvconfs); entry; entry = list_next(entry)) {
1672 server = ((struct clsrvconf *)entry->data)->servers;
1675 if (!server->connectionok)
1677 if (!server->loststatsrv)
1683 if (server->loststatsrv < best->loststatsrv)
1686 return best ? best : first;
1689 void radsrv(struct request *rq) {
1690 uint8_t code, id, *auth, *attrs, *attr;
1692 struct server *to = NULL;
1694 unsigned char newauth[16];
1695 struct realm *realm = NULL;
1697 code = *(uint8_t *)rq->buf;
1698 id = *(uint8_t *)(rq->buf + 1);
1699 len = RADLEN(rq->buf);
1700 auth = (uint8_t *)(rq->buf + 4);
1702 debug(DBG_DBG, "radsrv: code %d, id %d, length %d", code, id, len);
1704 if (code != RAD_Access_Request && code != RAD_Status_Server && code != RAD_Accounting_Request) {
1705 debug(DBG_INFO, "radsrv: server currently accepts only access-requests, accounting-requests and status-server, ignoring");
1711 attrs = rq->buf + 20;
1713 if (!attrvalidate(attrs, len)) {
1714 debug(DBG_WARN, "radsrv: attribute validation failed, ignoring packet");
1719 attr = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1720 if (attr && (ATTRVALLEN(attr) != 16 || !checkmessageauth(rq->buf, ATTRVAL(attr), rq->from->conf->secret))) {
1721 debug(DBG_WARN, "radsrv: message authentication failed");
1726 if (code != RAD_Access_Request) {
1728 case RAD_Accounting_Request:
1729 /* when forwarding accounting, also filter attributes, call removeattrs(rq) */
1730 acclog(attrs, len, rq->from->conf->host);
1731 respondaccounting(rq);
1733 case RAD_Status_Server:
1734 respondstatusserver(rq);
1741 /* code == RAD_Access_Request */
1742 if (rq->from->conf->rewrite) {
1743 dorewrite(rq->buf, rq->from->conf->rewrite);
1744 len = RADLEN(rq->buf) - 20;
1747 attr = attrget(attrs, len, RAD_Attr_User_Name);
1749 debug(DBG_WARN, "radsrv: ignoring request, no username attribute");
1753 memcpy(username, ATTRVAL(attr), ATTRVALLEN(attr));
1754 username[ATTRVALLEN(attr)] = '\0';
1756 if (rq->from->conf->rewriteattrregex) {
1757 if (!rewriteusername(rq, username)) {
1758 debug(DBG_WARN, "radsrv: username malloc failed, ignoring request");
1762 len = RADLEN(rq->buf) - 20;
1763 auth = (uint8_t *)(rq->buf + 4);
1764 attrs = rq->buf + 20;
1767 if (rq->origusername)
1768 debug(DBG_DBG, "Access Request with username: %s (originally %s)", username, rq->origusername);
1770 debug(DBG_DBG, "Access Request with username: %s", username);
1772 realm = id2realm(username, strlen(username));
1774 debug(DBG_INFO, "radsrv: ignoring request, don't know where to send it");
1779 to = realm2server(realm);
1780 if (to && rqinqueue(to, rq->from, id)) {
1781 debug(DBG_INFO, "radsrv: already got request from host %s with id %d, ignoring", rq->from->conf->host, id);
1787 if (realm->message) {
1788 debug(DBG_INFO, "radsrv: sending reject to %s for %s", rq->from->conf->host, username);
1789 respondreject(rq, realm->message);
1795 if (!RAND_bytes(newauth, 16)) {
1796 debug(DBG_WARN, "radsrv: failed to generate random auth");
1802 printfchars(NULL, "auth", "%02x ", auth, 16);
1805 attr = attrget(attrs, len, RAD_Attr_User_Password);
1807 debug(DBG_DBG, "radsrv: found userpwdattr with value length %d", ATTRVALLEN(attr));
1808 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1814 attr = attrget(attrs, len, RAD_Attr_Tunnel_Password);
1816 debug(DBG_DBG, "radsrv: found tunnelpwdattr with value length %d", ATTRVALLEN(attr));
1817 if (!pwdrecrypt(ATTRVAL(attr), ATTRVALLEN(attr), rq->from->conf->secret, to->conf->secret, auth, newauth)) {
1824 memcpy(rq->origauth, auth, 16);
1825 memcpy(auth, newauth, 16);
1829 int replyh(struct server *server, unsigned char *buf) {
1830 struct client *from;
1833 unsigned char *messageauth, *subattrs, *attrs, *attr, *username;
1834 struct sockaddr_storage fromsa;
1837 server->connectionok = 1;
1838 server->loststatsrv = 0;
1840 i = buf[1]; /* i is the id */
1843 case RAD_Access_Accept:
1844 debug(DBG_DBG, "got Access Accept with id %d", i);
1846 case RAD_Access_Reject:
1847 debug(DBG_DBG, "got Access Reject with id %d", i);
1849 case RAD_Access_Challenge:
1850 debug(DBG_DBG, "got Access Challenge with id %d", i);
1853 debug(DBG_INFO, "replyh: discarding, only accept access accept, access reject and access challenge messages");
1857 rq = server->requests + i;
1859 pthread_mutex_lock(&server->newrq_mutex);
1860 if (!rq->buf || !rq->tries) {
1861 pthread_mutex_unlock(&server->newrq_mutex);
1862 debug(DBG_INFO, "replyh: no matching request sent with this id, ignoring reply");
1867 pthread_mutex_unlock(&server->newrq_mutex);
1868 debug(DBG_INFO, "replyh: already received, ignoring reply");
1872 if (!validauth(buf, rq->buf + 4, (unsigned char *)server->conf->secret)) {
1873 pthread_mutex_unlock(&server->newrq_mutex);
1874 debug(DBG_WARN, "replyh: invalid auth, ignoring reply");
1878 len = RADLEN(buf) - 20;
1881 if (!attrvalidate(attrs, len)) {
1882 pthread_mutex_unlock(&server->newrq_mutex);
1883 debug(DBG_WARN, "replyh: attribute validation failed, ignoring reply");
1887 /* Message Authenticator */
1888 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1890 if (ATTRVALLEN(messageauth) != 16) {
1891 pthread_mutex_unlock(&server->newrq_mutex);
1892 debug(DBG_WARN, "replyh: illegal message auth attribute length, ignoring reply");
1895 memcpy(tmp, buf + 4, 16);
1896 memcpy(buf + 4, rq->buf + 4, 16);
1897 if (!checkmessageauth(buf, ATTRVAL(messageauth), server->conf->secret)) {
1898 pthread_mutex_unlock(&server->newrq_mutex);
1899 debug(DBG_WARN, "replyh: message authentication failed, ignoring reply");
1902 memcpy(buf + 4, tmp, 16);
1903 debug(DBG_DBG, "replyh: message auth ok");
1906 if (*rq->buf == RAD_Status_Server) {
1908 pthread_mutex_unlock(&server->newrq_mutex);
1909 debug(DBG_INFO, "replyh: got status server response from %s", server->conf->host);
1915 pthread_mutex_unlock(&server->newrq_mutex);
1916 debug(DBG_INFO, "replyh: client gone, ignoring reply");
1920 if (server->conf->rewrite) {
1921 dorewrite(buf, server->conf->rewrite);
1922 len = RADLEN(buf) - 20;
1926 for (attr = attrs; (attr = attrget(attr, len - (attr - attrs), RAD_Attr_Vendor_Specific)); attr += ATTRLEN(attr)) {
1927 if (ATTRVALLEN(attr) <= 4)
1930 if (attr[2] != 0 || attr[3] != 0 || attr[4] != 1 || attr[5] != 55) /* 311 == MS */
1933 sublen = ATTRVALLEN(attr) - 4;
1934 subattrs = ATTRVAL(attr) + 4;
1935 if (!attrvalidate(subattrs, sublen) ||
1936 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Send_Key, "MS MPPE Send Key",
1937 rq, server->conf->secret, from->conf->secret) ||
1938 !msmppe(subattrs, sublen, RAD_VS_ATTR_MS_MPPE_Recv_Key, "MS MPPE Recv Key",
1939 rq, server->conf->secret, from->conf->secret))
1943 pthread_mutex_unlock(&server->newrq_mutex);
1944 debug(DBG_WARN, "replyh: MS attribute handling failed, ignoring reply");
1948 if (*buf == RAD_Access_Accept || *buf == RAD_Access_Reject) {
1949 attr = attrget(rq->buf + 20, RADLEN(rq->buf) - 20, RAD_Attr_User_Name);
1950 /* we know the attribute exists */
1951 memcpy(tmp, ATTRVAL(attr), ATTRVALLEN(attr));
1952 tmp[ATTRVALLEN(attr)] = '\0';
1954 case RAD_Access_Accept:
1955 if (rq->origusername)
1956 debug(DBG_INFO, "Access Accept for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1958 debug(DBG_INFO, "Access Accept for %s from %s", tmp, server->conf->host);
1960 case RAD_Access_Reject:
1961 if (rq->origusername)
1962 debug(DBG_INFO, "Access Reject for %s (originally %s) from %s", tmp, rq->origusername, server->conf->host);
1964 debug(DBG_INFO, "Access Reject for %s from %s", tmp, server->conf->host);
1969 buf[1] = (char)rq->origid;
1970 memcpy(buf + 4, rq->origauth, 16);
1972 printfchars(NULL, "origauth/buf+4", "%02x ", buf + 4, 16);
1975 if (rq->origusername) {
1976 username = resizeattr(&buf, strlen(rq->origusername), RAD_Attr_User_Name);
1978 pthread_mutex_unlock(&server->newrq_mutex);
1979 debug(DBG_WARN, "replyh: malloc failed, ignoring reply");
1982 memcpy(username, rq->origusername, strlen(rq->origusername));
1983 len = RADLEN(buf) - 20;
1986 messageauth = attrget(attrs, len, RAD_Attr_Message_Authenticator);
1990 if (!createmessageauth(buf, ATTRVAL(messageauth), from->conf->secret)) {
1991 pthread_mutex_unlock(&server->newrq_mutex);
1992 debug(DBG_WARN, "replyh: failed to create authenticator, malloc failed?, ignoring reply");
1995 debug(DBG_DBG, "replyh: computed messageauthattr");
1998 if (from->conf->type == 'U')
1999 fromsa = rq->fromsa;
2000 /* once we set received = 1, rq may be reused */
2003 debug(DBG_DBG, "replyh: giving packet back to where it came from");
2004 sendreply(from, buf, from->conf->type == 'U' ? &fromsa : NULL);
2005 pthread_mutex_unlock(&server->newrq_mutex);
2009 void *udpclientrd(void *arg) {
2010 struct server *server;
2012 int *s = (int *)arg;
2016 buf = radudpget(*s, NULL, &server, NULL);
2017 if (!replyh(server, buf))
2022 void *tlsclientrd(void *arg) {
2023 struct server *server = (struct server *)arg;
2025 struct timeval lastconnecttry;
2028 /* yes, lastconnecttry is really necessary */
2029 lastconnecttry = server->lastconnecttry;
2030 buf = radtlsget(server->ssl);
2032 tlsconnect(server, &lastconnecttry, "clientrd");
2036 if (!replyh(server, buf))
2041 void *clientwr(void *arg) {
2042 struct server *server = (struct server *)arg;
2044 pthread_t tlsclientrdth;
2047 struct timeval now, lastsend;
2048 struct timespec timeout;
2049 struct request statsrvrq;
2050 unsigned char statsrvbuf[38];
2052 memset(&timeout, 0, sizeof(struct timespec));
2054 if (server->conf->statusserver) {
2055 memset(&statsrvrq, 0, sizeof(struct request));
2056 memset(statsrvbuf, 0, sizeof(statsrvbuf));
2057 statsrvbuf[0] = RAD_Status_Server;
2059 statsrvbuf[20] = RAD_Attr_Message_Authenticator;
2060 statsrvbuf[21] = 18;
2061 gettimeofday(&lastsend, NULL);
2064 if (server->conf->type == 'U') {
2065 server->connectionok = 1;
2067 tlsconnect(server, NULL, "new client");
2068 server->connectionok = 1;
2069 if (pthread_create(&tlsclientrdth, NULL, tlsclientrd, (void *)server))
2070 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
2074 pthread_mutex_lock(&server->newrq_mutex);
2075 if (!server->newrq) {
2076 gettimeofday(&now, NULL);
2077 if (server->conf->statusserver) {
2078 /* random 0-7 seconds */
2079 RAND_bytes(&rnd, 1);
2081 if (!timeout.tv_sec || timeout.tv_sec > lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd)
2082 timeout.tv_sec = lastsend.tv_sec + STATUS_SERVER_PERIOD + rnd;
2084 if (timeout.tv_sec) {
2085 debug(DBG_DBG, "clientwr: waiting up to %ld secs for new request", timeout.tv_sec - now.tv_sec);
2086 pthread_cond_timedwait(&server->newrq_cond, &server->newrq_mutex, &timeout);
2089 debug(DBG_DBG, "clientwr: waiting for new request");
2090 pthread_cond_wait(&server->newrq_cond, &server->newrq_mutex);
2093 if (server->newrq) {
2094 debug(DBG_DBG, "clientwr: got new request");
2097 debug(DBG_DBG, "clientwr: request timer expired, processing request queue");
2098 pthread_mutex_unlock(&server->newrq_mutex);
2100 for (i = 0; i < MAX_REQUESTS; i++) {
2101 pthread_mutex_lock(&server->newrq_mutex);
2102 while (i < MAX_REQUESTS && !server->requests[i].buf)
2104 if (i == MAX_REQUESTS) {
2105 pthread_mutex_unlock(&server->newrq_mutex);
2108 rq = server->requests + i;
2111 debug(DBG_DBG, "clientwr: packet %d in queue is marked as received", i);
2113 debug(DBG_DBG, "clientwr: freeing received packet %d from queue", i);
2115 /* setting this to NULL means that it can be reused */
2118 pthread_mutex_unlock(&server->newrq_mutex);
2122 gettimeofday(&now, NULL);
2123 if (now.tv_sec < rq->expiry.tv_sec) {
2124 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2125 timeout.tv_sec = rq->expiry.tv_sec;
2126 pthread_mutex_unlock(&server->newrq_mutex);
2130 if (rq->tries == (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2131 ? 1 : REQUEST_RETRIES)) {
2132 debug(DBG_DBG, "clientwr: removing expired packet from queue");
2133 if (*rq->buf == RAD_Status_Server) {
2134 debug(DBG_WARN, "clientwr: no status server response, %s dead?", server->conf->host);
2135 if (server->loststatsrv < 255)
2136 server->loststatsrv++;
2139 /* setting this to NULL means that it can be reused */
2141 pthread_mutex_unlock(&server->newrq_mutex);
2144 pthread_mutex_unlock(&server->newrq_mutex);
2146 rq->expiry.tv_sec = now.tv_sec +
2147 (*rq->buf == RAD_Status_Server || server->conf->type == 'T'
2148 ? REQUEST_EXPIRY : REQUEST_EXPIRY / REQUEST_RETRIES);
2149 if (!timeout.tv_sec || rq->expiry.tv_sec < timeout.tv_sec)
2150 timeout.tv_sec = rq->expiry.tv_sec;
2152 clientradput(server, server->requests[i].buf);
2153 gettimeofday(&lastsend, NULL);
2155 if (server->conf->statusserver) {
2156 gettimeofday(&now, NULL);
2157 if (now.tv_sec - lastsend.tv_sec >= STATUS_SERVER_PERIOD) {
2158 if (!RAND_bytes(statsrvbuf + 4, 16)) {
2159 debug(DBG_WARN, "clientwr: failed to generate random auth");
2162 statsrvrq.buf = malloc(sizeof(statsrvbuf));
2163 if (!statsrvrq.buf) {
2164 debug(DBG_ERR, "clientwr: malloc failed");
2167 memcpy(statsrvrq.buf, statsrvbuf, sizeof(statsrvbuf));
2168 debug(DBG_DBG, "clientwr: sending status server to %s", server->conf->host);
2169 lastsend.tv_sec = now.tv_sec;
2170 sendrq(server, &statsrvrq);
2176 void *udpserverwr(void *arg) {
2177 struct replyq *replyq = udp_server_replyq;
2178 struct reply *reply;
2181 pthread_mutex_lock(&replyq->mutex);
2182 while (!(reply = (struct reply *)list_shift(replyq->replies))) {
2183 debug(DBG_DBG, "udp server writer, waiting for signal");
2184 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2185 debug(DBG_DBG, "udp server writer, got signal");
2187 pthread_mutex_unlock(&replyq->mutex);
2189 if (sendto(udp_server_sock, reply->buf, RADLEN(reply->buf), 0,
2190 (struct sockaddr *)&reply->tosa, SOCKADDR_SIZE(reply->tosa)) < 0)
2191 debug(DBG_WARN, "sendudp: send failed");
2197 void *udpserverrd(void *arg) {
2199 pthread_t udpserverwrth;
2200 struct clsrvconf *listenres;
2202 listenres = resolve_hostport('U', options.listenudp, DEFAULT_UDP_PORT);
2203 if ((udp_server_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2204 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2206 debug(DBG_WARN, "udpserverrd: listening for UDP on %s:%s",
2207 listenres->host ? listenres->host : "*", listenres->port);
2210 if (pthread_create(&udpserverwrth, NULL, udpserverwr, NULL))
2211 debugx(1, DBG_ERR, "pthread_create failed");
2214 memset(&rq, 0, sizeof(struct request));
2215 rq.buf = radudpget(udp_server_sock, &rq.from, NULL, &rq.fromsa);
2220 void *udpaccserverrd(void *arg) {
2222 struct clsrvconf *listenres;
2224 listenres = resolve_hostport('U', options.listenaccudp, DEFAULT_UDP_PORT);
2225 if ((udp_accserver_sock = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2226 debugx(1, DBG_ERR, "udpserverrd: socket/bind failed");
2228 debug(DBG_WARN, "udpaccserverrd: listening for UDP on %s:%s",
2229 listenres->host ? listenres->host : "*", listenres->port);
2233 memset(&rq, 0, sizeof(struct request));
2234 rq.buf = radudpget(udp_accserver_sock, &rq.from, NULL, &rq.fromsa);
2235 if (*(uint8_t *)rq.buf == RAD_Accounting_Request) {
2239 debug(DBG_INFO, "udpaccserverrd: got something other than accounting-request, ignoring");
2244 void *tlsserverwr(void *arg) {
2246 unsigned long error;
2247 struct client *client = (struct client *)arg;
2248 struct replyq *replyq;
2249 struct reply *reply;
2251 debug(DBG_DBG, "tlsserverwr starting for %s", client->conf->host);
2252 replyq = client->replyq;
2254 pthread_mutex_lock(&replyq->mutex);
2255 while (!list_first(replyq->replies)) {
2257 debug(DBG_DBG, "tls server writer, waiting for signal");
2258 pthread_cond_wait(&replyq->cond, &replyq->mutex);
2259 debug(DBG_DBG, "tls server writer, got signal");
2262 /* ssl might have changed while waiting */
2263 pthread_mutex_unlock(&replyq->mutex);
2264 debug(DBG_DBG, "tlsserverwr: exiting as requested");
2268 reply = (struct reply *)list_shift(replyq->replies);
2269 pthread_mutex_unlock(&replyq->mutex);
2270 cnt = SSL_write(client->ssl, reply->buf, RADLEN(reply->buf));
2272 debug(DBG_DBG, "tlsserverwr: Sent %d bytes, Radius packet of length %d",
2273 cnt, RADLEN(reply->buf));
2275 while ((error = ERR_get_error()))
2276 debug(DBG_ERR, "tlsserverwr: SSL: %s", ERR_error_string(error, NULL));
2282 void *tlsserverrd(void *arg) {
2284 unsigned long error;
2286 struct client *client = (struct client *)arg;
2287 pthread_t tlsserverwrth;
2290 debug(DBG_DBG, "tlsserverrd starting for %s", client->conf->host);
2293 if (SSL_accept(ssl) <= 0) {
2294 while ((error = ERR_get_error()))
2295 debug(DBG_ERR, "tlsserverrd: SSL: %s", ERR_error_string(error, NULL));
2296 debug(DBG_ERR, "SSL_accept failed");
2299 if (tlsverifycert(client->ssl, client->conf)) {
2300 if (pthread_create(&tlsserverwrth, NULL, tlsserverwr, (void *)client)) {
2301 debug(DBG_ERR, "tlsserverrd: pthread_create failed");
2305 memset(&rq, 0, sizeof(struct request));
2306 rq.buf = radtlsget(client->ssl);
2309 debug(DBG_DBG, "tlsserverrd: got Radius message from %s", client->conf->host);
2313 debug(DBG_ERR, "tlsserverrd: connection lost");
2314 /* stop writer by setting ssl to NULL and give signal in case waiting for data */
2316 pthread_mutex_lock(&client->replyq->mutex);
2317 pthread_cond_signal(&client->replyq->cond);
2318 pthread_mutex_unlock(&client->replyq->mutex);
2319 debug(DBG_DBG, "tlsserverrd: waiting for writer to end");
2320 pthread_join(tlsserverwrth, NULL);
2324 s = SSL_get_fd(ssl);
2326 shutdown(s, SHUT_RDWR);
2328 debug(DBG_DBG, "tlsserverrd thread for %s exiting", client->conf->host);
2329 removeclientrqs(client);
2330 removeclient(client);
2335 pthread_t tlsserverth;
2337 struct sockaddr_storage from;
2338 size_t fromlen = sizeof(from);
2339 struct clsrvconf *conf;
2340 struct client *client;
2341 struct clsrvconf *listenres;
2343 listenres = resolve_hostport('T', options.listentcp, DEFAULT_TLS_PORT);
2344 if ((s = bindtoaddr(listenres->addrinfo, AF_UNSPEC, 1, 0)) < 0)
2345 debugx(1, DBG_ERR, "tlslistener: socket/bind failed");
2348 debug(DBG_WARN, "listening for incoming TCP on %s:%s", listenres->host ? listenres->host : "*", listenres->port);
2352 snew = accept(s, (struct sockaddr *)&from, &fromlen);
2354 debug(DBG_WARN, "accept failed");
2357 debug(DBG_WARN, "incoming TLS connection from %s", addr2string((struct sockaddr *)&from, fromlen));
2359 conf = find_conf('T', (struct sockaddr *)&from, clconfs, NULL);
2361 debug(DBG_WARN, "ignoring request, not a known TLS client");
2362 shutdown(snew, SHUT_RDWR);
2367 client = addclient(conf);
2370 debug(DBG_WARN, "Failed to create new client instance");
2371 shutdown(snew, SHUT_RDWR);
2375 client->ssl = SSL_new(client->conf->ssl_ctx);
2376 SSL_set_fd(client->ssl, snew);
2377 if (pthread_create(&tlsserverth, NULL, tlsserverrd, (void *)client)) {
2378 debug(DBG_ERR, "tlslistener: pthread_create failed");
2379 SSL_free(client->ssl);
2380 removeclient(client);
2381 shutdown(snew, SHUT_RDWR);
2385 pthread_detach(tlsserverth);
2390 void tlsadd(char *value, char *cacertfile, char *cacertpath, char *certfile, char *certkeyfile, char *certkeypwd) {
2393 STACK_OF(X509_NAME) *calist;
2395 unsigned long error;
2397 if (!certfile || !certkeyfile)
2398 debugx(1, DBG_ERR, "TLSCertificateFile and TLSCertificateKeyFile must be specified in TLS context %s", value);
2400 if (!cacertfile && !cacertpath)
2401 debugx(1, DBG_ERR, "CA Certificate file or path need to be specified in TLS context %s", value);
2404 ssl_locks = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
2405 ssl_lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
2406 for (i = 0; i < CRYPTO_num_locks(); i++) {
2407 ssl_lock_count[i] = 0;
2408 pthread_mutex_init(&ssl_locks[i], NULL);
2410 CRYPTO_set_id_callback(ssl_thread_id);
2411 CRYPTO_set_locking_callback(ssl_locking_callback);
2413 SSL_load_error_strings();
2416 while (!RAND_status()) {
2417 time_t t = time(NULL);
2418 pid_t pid = getpid();
2419 RAND_seed((unsigned char *)&t, sizeof(time_t));
2420 RAND_seed((unsigned char *)&pid, sizeof(pid));
2423 ctx = SSL_CTX_new(TLSv1_method());
2425 SSL_CTX_set_default_passwd_cb_userdata(ctx, certkeypwd);
2426 SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
2428 if (!SSL_CTX_use_certificate_chain_file(ctx, certfile) ||
2429 !SSL_CTX_use_PrivateKey_file(ctx, certkeyfile, SSL_FILETYPE_PEM) ||
2430 !SSL_CTX_check_private_key(ctx) ||
2431 !SSL_CTX_load_verify_locations(ctx, cacertfile, cacertpath)) {
2432 while ((error = ERR_get_error()))
2433 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2434 debugx(1, DBG_ERR, "Error initialising SSL/TLS in TLS context %s", value);
2437 calist = cacertfile ? SSL_load_client_CA_file(cacertfile) : NULL;
2438 if (!cacertfile || calist) {
2441 calist = sk_X509_NAME_new_null();
2442 if (!SSL_add_dir_cert_subjects_to_stack(calist, cacertpath)) {
2443 sk_X509_NAME_free(calist);
2449 while ((error = ERR_get_error()))
2450 debug(DBG_ERR, "SSL: %s", ERR_error_string(error, NULL));
2451 debugx(1, DBG_ERR, "Error adding CA subjects in TLS context %s", value);
2453 SSL_CTX_set_client_CA_list(ctx, calist);
2455 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
2456 SSL_CTX_set_verify_depth(ctx, MAX_CERT_DEPTH + 1);
2458 new = malloc(sizeof(struct tls));
2459 if (!new || !list_push(tlsconfs, new))
2460 debugx(1, DBG_ERR, "malloc failed");
2462 memset(new, 0, sizeof(struct tls));
2463 new->name = stringcopy(value, 0);
2465 debugx(1, DBG_ERR, "malloc failed");
2468 debug(DBG_DBG, "tlsadd: added TLS context %s", value);
2472 struct list_node *entry;
2475 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2476 t = (struct tls *)entry->data;
2480 SSL_CTX_free(t->ctx);
2482 list_destroy(tlsconfs);
2486 SSL_CTX *tlsgetctx(char *alt1, char *alt2) {
2487 struct list_node *entry;
2488 struct tls *t, *t1 = NULL, *t2 = NULL;
2490 for (entry = list_first(tlsconfs); entry; entry = list_next(entry)) {
2491 t = (struct tls *)entry->data;
2492 if (!strcasecmp(t->name, alt1)) {
2496 if (!t2 && alt2 && !strcasecmp(t->name, alt2))
2507 void addrealm(char *value, char **servers, char *message) {
2509 struct realm *realm;
2510 char *s, *regex = NULL;
2511 struct list_node *entry;
2512 struct clsrvconf *conf;
2514 if (*value == '/') {
2515 /* regexp, remove optional trailing / if present */
2516 if (value[strlen(value) - 1] == '/')
2517 value[strlen(value) - 1] = '\0';
2519 /* not a regexp, let us make it one */
2520 if (*value == '*' && !value[1])
2521 regex = stringcopy(".*", 0);
2523 for (n = 0, s = value; *s;)
2526 regex = malloc(strlen(value) + n + 3);
2529 for (n = 1, s = value; *s; s++) {
2539 debugx(1, DBG_ERR, "malloc failed");
2540 debug(DBG_DBG, "addrealm: constructed regexp %s from %s", regex, value);
2543 realm = malloc(sizeof(struct realm));
2545 debugx(1, DBG_ERR, "malloc failed");
2547 memset(realm, 0, sizeof(struct realm));
2548 realm->name = stringcopy(value, 0);
2550 debugx(1, DBG_ERR, "malloc failed");
2551 if (message && strlen(message) > 253)
2552 debugx(1, DBG_ERR, "ReplyMessage can be at most 253 bytes");
2553 realm->message = message;
2555 if (regcomp(&realm->regex, regex ? regex : value + 1, REG_ICASE | REG_NOSUB))
2556 debugx(1, DBG_ERR, "addrealm: failed to compile regular expression %s", regex ? regex : value + 1);
2560 if (servers && *servers) {
2561 realm->srvconfs = list_create();
2562 if (!realm->srvconfs)
2563 debugx(1, DBG_ERR, "malloc failed");
2564 for (n = 0; servers[n]; n++) {
2565 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
2566 conf = (struct clsrvconf *)entry->data;
2567 if (!strcasecmp(servers[n], conf->name))
2571 debugx(1, DBG_ERR, "addrealm failed, no server %s", servers[n]);
2572 if (!list_push(realm->srvconfs, conf))
2573 debugx(1, DBG_ERR, "malloc failed");
2574 debug(DBG_DBG, "addrealm: added server %s for realm %s", conf->name, value);
2577 realm->srvconfs = NULL;
2579 if (!list_push(realms, realm))
2580 debugx(1, DBG_ERR, "malloc failed");
2581 debug(DBG_DBG, "addrealm: added realm %s", value);
2584 struct gconffile *openconfigfile(const char *file) {
2585 struct gconffile *cf = NULL;
2587 if (!pushgconffile(&cf, file))
2588 debugx(1, DBG_ERR, "could not read config file %s\n%s", file, strerror(errno));
2589 debug(DBG_DBG, "reading config file %s", file);
2593 int addmatchcertattr(struct clsrvconf *conf, char *matchcertattr) {
2597 if (strncasecmp(matchcertattr, "CN:/", 4)) {
2598 r = &conf->certcnregex;
2599 v = matchcertattr + 4;
2600 } else if (strncasecmp(matchcertattr, "SubjectAltName:URI:/", 20)) {
2601 r = &conf->certuriregex;
2602 v = matchcertattr + 20;
2607 /* regexp, remove optional trailing / if present */
2608 if (v[strlen(v) - 1] == '/')
2609 v[strlen(v) - 1] = '\0';
2613 *r = malloc(sizeof(regex_t));
2615 debug(DBG_ERR, "malloc failed");
2618 if (regcomp(*r, v, REG_ICASE | REG_NOSUB)) {
2621 debug(DBG_ERR, "failed to compile regular expression %s", v);
2627 int addrewriteattr(struct clsrvconf *conf, char *rewriteattr) {
2630 v = rewriteattr + 11;
2631 if (strncasecmp(rewriteattr, "User-Name:/", 11) || !*v)
2633 /* regexp, remove optional trailing / if present */
2634 if (v[strlen(v) - 1] == '/')
2635 v[strlen(v) - 1] = '\0';
2643 conf->rewriteattrregex = malloc(sizeof(regex_t));
2644 if (!conf->rewriteattrregex) {
2645 debug(DBG_ERR, "malloc failed");
2649 conf->rewriteattrreplacement = stringcopy(w, 0);
2650 if (!conf->rewriteattrreplacement) {
2651 free(conf->rewriteattrregex);
2652 conf->rewriteattrregex = NULL;
2656 if (regcomp(conf->rewriteattrregex, v, REG_ICASE | REG_EXTENDED)) {
2657 free(conf->rewriteattrregex);
2658 conf->rewriteattrregex = NULL;
2659 free(conf->rewriteattrreplacement);
2660 conf->rewriteattrreplacement = NULL;
2661 debug(DBG_ERR, "failed to compile regular expression %s", v);
2668 /* should accept both names and numeric values, only numeric right now */
2669 uint8_t attrname2val(char *attrname) {
2672 val = atoi(attrname);
2673 return val > 0 && val < 256 ? val : 0;
2676 /* should accept both names and numeric values, only numeric right now */
2677 int vattrname2val(char *attrname, uint32_t *vendor, uint32_t *type) {
2680 *vendor = atoi(attrname);
2681 s = strchr(attrname, ':');
2686 *type = atoi(s + 1);
2687 return *type >= 0 && *type < 256;
2690 void rewritefree() {
2691 struct list_node *entry;
2692 struct rewriteconf *r;
2694 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2695 r = (struct rewriteconf *)entry->data;
2701 list_destroy(rewriteconfs);
2702 rewriteconfs = NULL;
2705 struct rewrite *getrewrite(char *alt1, char *alt2) {
2706 struct list_node *entry;
2707 struct rewriteconf *r, *r1 = NULL, *r2 = NULL;
2709 for (entry = list_first(rewriteconfs); entry; entry = list_next(entry)) {
2710 r = (struct rewriteconf *)entry->data;
2711 if (!strcasecmp(r->name, alt1)) {
2715 if (!r2 && alt2 && !strcasecmp(r->name, alt2))
2726 void addrewrite(char *value, char **attrs, char **vattrs) {
2727 struct rewriteconf *new;
2728 struct rewrite *rewrite = NULL;
2731 uint32_t *p, *va = NULL;
2735 for (; attrs[n]; n++);
2736 a = malloc((n + 1) * sizeof(uint8_t));
2738 debugx(1, DBG_ERR, "malloc failed");
2740 for (i = 0; i < n; i++)
2741 if (!(a[i] = attrname2val(attrs[i])))
2742 debugx(1, DBG_ERR, "addrewrite: invalid attribute %s", attrs[i]);
2748 for (; vattrs[n]; n++);
2749 va = malloc((2 * n + 1) * sizeof(uint32_t));
2751 debugx(1, DBG_ERR, "malloc failed");
2753 for (p = va, i = 0; i < n; i++, p += 2)
2754 if (!vattrname2val(vattrs[i], p, p + 1))
2755 debugx(1, DBG_ERR, "addrewrite: invalid vendor attribute %s", vattrs[i]);
2760 rewrite = malloc(sizeof(struct rewrite));
2762 debugx(1, DBG_ERR, "malloc failed");
2763 rewrite->removeattrs = a;
2764 rewrite->removevendorattrs = va;
2767 new = malloc(sizeof(struct rewriteconf));
2768 if (!new || !list_push(rewriteconfs, new))
2769 debugx(1, DBG_ERR, "malloc failed");
2771 memset(new, 0, sizeof(struct rewriteconf));
2772 new->name = stringcopy(value, 0);
2774 debugx(1, DBG_ERR, "malloc failed");
2776 new->rewrite = rewrite;
2777 debug(DBG_DBG, "addrewrite: added rewrite block %s", value);
2780 void confclient_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2781 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *rewrite = NULL, *rewriteattr = NULL;
2782 struct clsrvconf *conf;
2784 debug(DBG_DBG, "confclient_cb called for %s", block);
2786 conf = malloc(sizeof(struct clsrvconf));
2787 if (!conf || !list_push(clconfs, conf))
2788 debugx(1, DBG_ERR, "malloc failed");
2789 memset(conf, 0, sizeof(struct clsrvconf));
2791 getgenericconfig(cf, block,
2792 "type", CONF_STR, &type,
2793 "host", CONF_STR, &conf->host,
2794 "secret", CONF_STR, &conf->secret,
2795 "tls", CONF_STR, &tls,
2796 "matchcertificateattribute", CONF_STR, &matchcertattr,
2797 "rewrite", CONF_STR, &rewrite,
2798 "rewriteattribute", CONF_STR, &rewriteattr,
2802 /* leave conf->name to be NULL for clients */
2804 conf->host = stringcopy(val, 0);
2806 if (type && !strcasecmp(type, "udp")) {
2809 } else if (type && !strcasecmp(type, "tls")) {
2810 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultclient", "default");
2812 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2813 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2814 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2818 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2823 free(matchcertattr);
2825 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultclient", "default");
2828 if (!addrewriteattr(conf, rewriteattr))
2829 debugx(1, DBG_ERR, "error in block %s, invalid RewriteAttributeValue", block);
2833 if (!resolvepeer(conf, 0))
2834 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2836 if (!conf->secret) {
2837 if (conf->type == 'U')
2838 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2839 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2843 void confserver_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2844 char *type = NULL, *tls = NULL, *matchcertattr = NULL, *statusserver = NULL, *rewrite = NULL;
2845 struct clsrvconf *conf;
2847 debug(DBG_DBG, "confserver_cb called for %s", block);
2849 conf = malloc(sizeof(struct clsrvconf));
2850 if (!conf || !list_push(srvconfs, conf))
2851 debugx(1, DBG_ERR, "malloc failed");
2852 memset(conf, 0, sizeof(struct clsrvconf));
2854 getgenericconfig(cf, block,
2855 "type", CONF_STR, &type,
2856 "host", CONF_STR, &conf->host,
2857 "port", CONF_STR, &conf->port,
2858 "secret", CONF_STR, &conf->secret,
2859 "tls", CONF_STR, &tls,
2860 "matchcertificateattribute", CONF_STR, &matchcertattr,
2861 "rewrite", CONF_STR, &rewrite,
2862 "StatusServer", CONF_STR, &statusserver,
2866 conf->name = stringcopy(val, 0);
2868 conf->host = stringcopy(val, 0);
2870 if (type && !strcasecmp(type, "udp")) {
2874 conf->port = stringcopy(DEFAULT_UDP_PORT, 0);
2875 } else if (type && !strcasecmp(type, "tls")) {
2876 conf->ssl_ctx = tls ? tlsgetctx(tls, NULL) : tlsgetctx("defaultserver", "default");
2878 debugx(1, DBG_ERR, "error in block %s, no tls context defined", block);
2879 if (matchcertattr && !addmatchcertattr(conf, matchcertattr))
2880 debugx(1, DBG_ERR, "error in block %s, invalid MatchCertificateAttributeValue", block);
2882 conf->port = stringcopy(DEFAULT_TLS_PORT, 0);
2886 debugx(1, DBG_ERR, "error in block %s, type must be set to UDP or TLS", block);
2891 free(matchcertattr);
2893 conf->rewrite = rewrite ? getrewrite(rewrite, NULL) : getrewrite("defaultserver", "default");
2895 if (!resolvepeer(conf, 0))
2896 debugx(1, DBG_ERR, "failed to resolve host %s port %s, exiting", conf->host ? conf->host : "(null)", conf->port ? conf->port : "(null)");
2898 if (!conf->secret) {
2899 if (conf->type == 'U')
2900 debugx(1, DBG_ERR, "error in block %s, secret must be specified for UDP", block);
2901 conf->secret = stringcopy(DEFAULT_TLS_SECRET, 0);
2905 if (!strcasecmp(statusserver, "on"))
2906 conf->statusserver = 1;
2907 else if (strcasecmp(statusserver, "off"))
2908 debugx(1, DBG_ERR, "error in block %s, StatusServer is %s, must be on or off", block, statusserver);
2913 void confrealm_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2914 char **servers = NULL, *msg = NULL;
2916 debug(DBG_DBG, "confrealm_cb called for %s", block);
2918 getgenericconfig(cf, block,
2919 "server", CONF_MSTR, &servers,
2920 "ReplyMessage", CONF_STR, &msg,
2924 addrealm(val, servers, msg);
2928 void conftls_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2929 char *cacertfile = NULL, *cacertpath = NULL, *certfile = NULL, *certkeyfile = NULL, *certkeypwd = NULL;
2931 debug(DBG_DBG, "conftls_cb called for %s", block);
2933 getgenericconfig(cf, block,
2934 "CACertificateFile", CONF_STR, &cacertfile,
2935 "CACertificatePath", CONF_STR, &cacertpath,
2936 "CertificateFile", CONF_STR, &certfile,
2937 "CertificateKeyFile", CONF_STR, &certkeyfile,
2938 "CertificateKeyPassword", CONF_STR, &certkeypwd,
2942 tlsadd(val, cacertfile, cacertpath, certfile, certkeyfile, certkeypwd);
2950 void confrewrite_cb(struct gconffile **cf, char *block, char *opt, char *val) {
2951 char **attrs = NULL, **vattrs = NULL;
2953 debug(DBG_DBG, "confrewrite_cb called for %s", block);
2955 getgenericconfig(cf, block,
2956 "removeAttribute", CONF_MSTR, &attrs,
2957 "removeVendorAttribute", CONF_MSTR, &vattrs,
2960 addrewrite(val, attrs, vattrs);
2965 void getmainconfig(const char *configfile) {
2966 char *loglevel = NULL;
2967 struct gconffile *cfs;
2969 cfs = openconfigfile(configfile);
2970 memset(&options, 0, sizeof(options));
2972 clconfs = list_create();
2974 debugx(1, DBG_ERR, "malloc failed");
2976 srvconfs = list_create();
2978 debugx(1, DBG_ERR, "malloc failed");
2980 realms = list_create();
2982 debugx(1, DBG_ERR, "malloc failed");
2984 tlsconfs = list_create();
2986 debugx(1, DBG_ERR, "malloc failed");
2988 rewriteconfs = list_create();
2990 debugx(1, DBG_ERR, "malloc failed");
2992 getgenericconfig(&cfs, NULL,
2993 "ListenUDP", CONF_STR, &options.listenudp,
2994 "ListenTCP", CONF_STR, &options.listentcp,
2995 "ListenAccountingUDP", CONF_STR, &options.listenaccudp,
2996 "SourceUDP", CONF_STR, &options.sourceudp,
2997 "SourceTCP", CONF_STR, &options.sourcetcp,
2998 "LogLevel", CONF_STR, &loglevel,
2999 "LogDestination", CONF_STR, &options.logdestination,
3000 "Client", CONF_CBK, confclient_cb,
3001 "Server", CONF_CBK, confserver_cb,
3002 "Realm", CONF_CBK, confrealm_cb,
3003 "TLS", CONF_CBK, conftls_cb,
3004 "Rewrite", CONF_CBK, confrewrite_cb,
3011 if (strlen(loglevel) != 1 || *loglevel < '1' || *loglevel > '4')
3012 debugx(1, DBG_ERR, "error in %s, value of option LogLevel is %s, must be 1, 2, 3 or 4", configfile, loglevel);
3013 options.loglevel = *loglevel - '0';
3018 void getargs(int argc, char **argv, uint8_t *foreground, uint8_t *pretend, uint8_t *loglevel, char **configfile) {
3021 while ((c = getopt(argc, argv, "c:d:fpv")) != -1) {
3024 *configfile = optarg;
3027 if (strlen(optarg) != 1 || *optarg < '1' || *optarg > '4')
3028 debugx(1, DBG_ERR, "Debug level must be 1, 2, 3 or 4, not %s", optarg);
3029 *loglevel = *optarg - '0';
3038 debugx(0, DBG_ERR, "radsecproxy revision $Rev$");
3043 if (!(argc - optind))
3047 debug(DBG_ERR, "Usage:\n%s [ -c configfile ] [ -d debuglevel ] [ -f ] [ -p ] [ -v ]", argv[0]);
3052 int daemon(int a, int b) {
3060 for (i = 0; i < 3; i++) {
3062 open("/dev/null", O_RDWR);
3068 void *sighandler(void *arg) {
3073 sigfillset(&sigset);
3074 sigwait(&sigset, &sig);
3077 /* completely ignoring this */
3080 debug(DBG_WARN, "sighandler: got SIGPIPE, TLS write error?");
3083 debug(DBG_WARN, "sighandler: ignoring signal %d", sig);
3088 int main(int argc, char **argv) {
3089 pthread_t sigth, udpserverth, udpaccserverth, udpclient4rdth, udpclient6rdth;
3091 struct list_node *entry;
3092 uint8_t foreground = 0, pretend = 0, loglevel = 0;
3093 char *configfile = NULL;
3095 debug_init("radsecproxy");
3096 debug_set_level(DEBUG_LEVEL);
3097 getargs(argc, argv, &foreground, &pretend, &loglevel, &configfile);
3099 debug_set_level(loglevel);
3100 getmainconfig(configfile ? configfile : CONFIG_MAIN);
3102 options.loglevel = loglevel;
3103 else if (options.loglevel)
3104 debug_set_level(options.loglevel);
3106 options.logdestination = NULL;
3108 if (!options.logdestination)
3109 options.logdestination = "x-syslog:///";
3110 debug_set_destination(options.logdestination);
3114 debugx(0, DBG_ERR, "All OK so far; exiting since only pretending");
3116 if (!list_first(clconfs))
3117 debugx(1, DBG_ERR, "No clients configured, nothing to do, exiting");
3118 if (!list_first(srvconfs))
3119 debugx(1, DBG_ERR, "No servers configured, nothing to do, exiting");
3120 if (!list_first(realms))
3121 debugx(1, DBG_ERR, "No realms configured, nothing to do, exiting");
3123 if (!foreground && (daemon(0, 0) < 0))
3124 debugx(1, DBG_ERR, "daemon() failed: %s", strerror(errno));
3126 debug(DBG_INFO, "radsecproxy revision $Rev$ starting");
3128 sigemptyset(&sigset);
3129 /* exit on all but SIGPIPE, ignore more? */
3130 sigaddset(&sigset, SIGPIPE);
3131 pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3132 pthread_create(&sigth, NULL, sighandler, NULL);
3134 if (client_udp_count) {
3135 udp_server_replyq = newreplyq();
3136 if (pthread_create(&udpserverth, NULL, udpserverrd, NULL))
3137 debugx(1, DBG_ERR, "pthread_create failed");
3138 if (options.listenaccudp)
3139 if (pthread_create(&udpaccserverth, NULL, udpaccserverrd, NULL))
3140 debugx(1, DBG_ERR, "pthread_create failed");
3143 for (entry = list_first(srvconfs); entry; entry = list_next(entry)) {
3144 addserver((struct clsrvconf *)entry->data);
3145 if (pthread_create(&((struct clsrvconf *)entry->data)->servers->clientth, NULL, clientwr,
3146 (void *)((struct clsrvconf *)entry->data)->servers))
3147 debugx(1, DBG_ERR, "pthread_create failed");
3149 /* srcudpres no longer needed, while srctcpres is needed later */
3154 if (udp_client4_sock >= 0)
3155 if (pthread_create(&udpclient4rdth, NULL, udpclientrd, (void *)&udp_client4_sock))
3156 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3157 if (udp_client6_sock >= 0)
3158 if (pthread_create(&udpclient6rdth, NULL, udpclientrd, (void *)&udp_client6_sock))
3159 debugx(1, DBG_ERR, "clientwr: pthread_create failed");
3161 if (client_tls_count)
3162 return tlslistener();
3164 /* just hang around doing nothing, anything to do here? */